@crawlee/core 4.0.0-beta.11 → 4.0.0-beta.111

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 (271) hide show
  1. package/README.md +17 -13
  2. package/autoscaling/autoscaled_pool.d.ts +67 -172
  3. package/autoscaling/autoscaled_pool.js +165 -320
  4. package/autoscaling/client_load_signal.d.ts +55 -0
  5. package/autoscaling/client_load_signal.js +73 -0
  6. package/autoscaling/concurrency_system.d.ts +268 -0
  7. package/autoscaling/concurrency_system.js +351 -0
  8. package/autoscaling/cpu_load_signal.d.ts +43 -0
  9. package/autoscaling/cpu_load_signal.js +46 -0
  10. package/autoscaling/event_loop_load_signal.d.ts +51 -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 +104 -0
  16. package/autoscaling/memory_load_signal.d.ts +47 -0
  17. package/autoscaling/memory_load_signal.js +105 -0
  18. package/autoscaling/snapshotter.d.ts +58 -163
  19. package/autoscaling/snapshotter.js +45 -263
  20. package/autoscaling/system_status.d.ts +62 -84
  21. package/autoscaling/system_status.js +92 -122
  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 -223
  27. package/configuration.js +170 -222
  28. package/cookie_utils.d.ts +4 -3
  29. package/cookie_utils.js +22 -13
  30. package/crawlers/context_pipeline.d.ts +10 -1
  31. package/crawlers/context_pipeline.js +31 -8
  32. package/crawlers/crawler_commons.d.ts +90 -83
  33. package/crawlers/crawler_commons.js +1 -116
  34. package/crawlers/error_snapshotter.d.ts +1 -4
  35. package/crawlers/error_snapshotter.js +3 -6
  36. package/crawlers/error_tracker.d.ts +0 -1
  37. package/crawlers/error_tracker.js +0 -1
  38. package/crawlers/index.d.ts +1 -3
  39. package/crawlers/index.js +0 -3
  40. package/crawlers/internals/types.d.ts +0 -1
  41. package/crawlers/internals/types.js +0 -1
  42. package/crawlers/statistics.d.ts +91 -41
  43. package/crawlers/statistics.js +83 -72
  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 +40 -27
  51. package/enqueue_links/shared.js +90 -68
  52. package/errors.d.ts +41 -4
  53. package/errors.js +50 -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 -3
  59. package/events/local_event_manager.js +37 -11
  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 +106 -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 +42 -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 +114 -0
  76. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  77. package/memory-storage/resource-clients/key-value-store.js +204 -0
  78. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  79. package/memory-storage/resource-clients/request-queue.js +422 -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 +58 -0
  83. package/owned_or_injected.js +98 -0
  84. package/package.json +13 -12
  85. package/proxy_configuration.d.ts +27 -152
  86. package/proxy_configuration.js +27 -179
  87. package/recoverable_state.d.ts +111 -0
  88. package/recoverable_state.js +143 -0
  89. package/request.d.ts +86 -17
  90. package/request.js +117 -41
  91. package/router.d.ts +193 -21
  92. package/router.js +188 -43
  93. package/serialization.d.ts +0 -1
  94. package/serialization.js +9 -11
  95. package/service_locator.d.ts +147 -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 -86
  106. package/session_pool/session.js +85 -138
  107. package/session_pool/session_pool.d.ts +77 -91
  108. package/session_pool/session_pool.js +159 -147
  109. package/storages/dataset.d.ts +114 -54
  110. package/storages/dataset.js +285 -144
  111. package/storages/index.d.ts +9 -8
  112. package/storages/index.js +7 -8
  113. package/storages/key_value_store.d.ts +185 -42
  114. package/storages/key_value_store.js +424 -151
  115. package/storages/key_value_store_codec.d.ts +32 -0
  116. package/storages/key_value_store_codec.js +113 -0
  117. package/storages/request_dedup_cache.d.ts +22 -0
  118. package/storages/request_dedup_cache.js +48 -0
  119. package/storages/request_list.d.ts +52 -116
  120. package/storages/request_list.js +158 -133
  121. package/storages/request_loader.d.ts +96 -0
  122. package/storages/request_loader.js +1 -0
  123. package/storages/request_manager.d.ts +33 -0
  124. package/storages/request_manager.js +1 -0
  125. package/storages/request_manager_tandem.d.ts +97 -0
  126. package/storages/request_manager_tandem.js +197 -0
  127. package/storages/request_queue.d.ts +290 -47
  128. package/storages/request_queue.js +825 -216
  129. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +37 -88
  130. package/storages/{sitemap_request_list.js → sitemap_request_loader.js} +136 -143
  131. package/storages/storage_instance_manager.d.ts +87 -0
  132. package/storages/storage_instance_manager.js +256 -0
  133. package/storages/storage_stats.d.ts +48 -0
  134. package/storages/storage_stats.js +29 -0
  135. package/storages/transaction.d.ts +252 -0
  136. package/storages/transaction.js +251 -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/context_pipeline.d.ts.map +0 -1
  164. package/crawlers/context_pipeline.js.map +0 -1
  165. package/crawlers/crawler_commons.d.ts.map +0 -1
  166. package/crawlers/crawler_commons.js.map +0 -1
  167. package/crawlers/crawler_utils.d.ts +0 -10
  168. package/crawlers/crawler_utils.d.ts.map +0 -1
  169. package/crawlers/crawler_utils.js +0 -12
  170. package/crawlers/crawler_utils.js.map +0 -1
  171. package/crawlers/error_snapshotter.d.ts.map +0 -1
  172. package/crawlers/error_snapshotter.js.map +0 -1
  173. package/crawlers/error_tracker.d.ts.map +0 -1
  174. package/crawlers/error_tracker.js.map +0 -1
  175. package/crawlers/index.d.ts.map +0 -1
  176. package/crawlers/index.js.map +0 -1
  177. package/crawlers/internals/types.d.ts.map +0 -1
  178. package/crawlers/internals/types.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 +0 -13
  238. package/storages/access_checking.d.ts.map +0 -1
  239. package/storages/access_checking.js +0 -14
  240. package/storages/access_checking.js.map +0 -1
  241. package/storages/dataset.d.ts.map +0 -1
  242. package/storages/dataset.js.map +0 -1
  243. package/storages/index.d.ts.map +0 -1
  244. package/storages/index.js.map +0 -1
  245. package/storages/key_value_store.d.ts.map +0 -1
  246. package/storages/key_value_store.js.map +0 -1
  247. package/storages/request_list.d.ts.map +0 -1
  248. package/storages/request_list.js.map +0 -1
  249. package/storages/request_provider.d.ts +0 -308
  250. package/storages/request_provider.d.ts.map +0 -1
  251. package/storages/request_provider.js +0 -555
  252. package/storages/request_provider.js.map +0 -1
  253. package/storages/request_queue.d.ts.map +0 -1
  254. package/storages/request_queue.js.map +0 -1
  255. package/storages/request_queue_v2.d.ts +0 -87
  256. package/storages/request_queue_v2.d.ts.map +0 -1
  257. package/storages/request_queue_v2.js +0 -438
  258. package/storages/request_queue_v2.js.map +0 -1
  259. package/storages/sitemap_request_list.d.ts.map +0 -1
  260. package/storages/sitemap_request_list.js.map +0 -1
  261. package/storages/storage_manager.d.ts +0 -58
  262. package/storages/storage_manager.d.ts.map +0 -1
  263. package/storages/storage_manager.js +0 -105
  264. package/storages/storage_manager.js.map +0 -1
  265. package/storages/utils.d.ts.map +0 -1
  266. package/storages/utils.js.map +0 -1
  267. package/tsconfig.build.tsbuildinfo +0 -1
  268. package/typedefs.d.ts.map +0 -1
  269. package/typedefs.js.map +0 -1
  270. package/validators.d.ts.map +0 -1
  271. package/validators.js.map +0 -1
package/iterables.d.ts ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Converts any iterable or async iterable to an async iterable.
3
+ * @internal
4
+ *
5
+ * @yields Each item from the input iterable
6
+ *
7
+ * **Example usage:**
8
+ * ```ts
9
+ * const syncArray = [1, 2, 3];
10
+ * for await (const item of asyncifyIterable(syncArray)) {
11
+ * console.log(item); // 1, 2, 3
12
+ * }
13
+ * ```
14
+ */
15
+ export declare function asyncifyIterable<T>(iterable: Iterable<T> | AsyncIterable<T>): AsyncIterable<T>;
16
+ /**
17
+ * Lazily splits the input async iterable into chunks of specified size.
18
+ * The last chunk may contain fewer items if the total number of items
19
+ * is not evenly divisible by the chunk size.
20
+ * @internal
21
+ *
22
+ * @yields Arrays of items, each containing up to chunkSize items
23
+ *
24
+ * **Example usage:**
25
+ * ```ts
26
+ * const numbers = async function* () {
27
+ * for (let i = 1; i <= 10; i++) yield i;
28
+ * };
29
+ *
30
+ * for await (const chunk of chunkedAsyncIterable(numbers(), 3)) {
31
+ * console.log(chunk); // [1, 2, 3], [4, 5, 6], [7, 8, 9], [10]
32
+ * }
33
+ * ```
34
+ */
35
+ export declare function chunkedAsyncIterable<T>(iterable: AsyncIterable<T> | Iterable<T>, chunkSize: number | (() => number)): AsyncIterable<T[]>;
36
+ /**
37
+ * An async iterator that also supports peeking at the next value without consuming it.
38
+ * Extends both AsyncIterator and AsyncIterable interfaces.
39
+ * @internal
40
+ */
41
+ export interface PeekableAsyncIterator<T> extends AsyncIterator<T>, AsyncIterable<T> {
42
+ /**
43
+ * Peeks at the next value without consuming it from the iterator.
44
+ * Subsequent calls to peek() will return the same value until next() is called.
45
+ *
46
+ * @returns Promise that resolves to the next value, or undefined if the iterator is exhausted
47
+ */
48
+ peek(): Promise<T | undefined>;
49
+ }
50
+ /**
51
+ * An async iterable that yields peekable async iterators.
52
+ * @internal
53
+ */
54
+ export interface PeekableAsyncIterable<T> extends AsyncIterable<T> {
55
+ [Symbol.asyncIterator](): PeekableAsyncIterator<T>;
56
+ }
57
+ /**
58
+ * Wraps an async iterable to provide peek functionality, allowing you to look at
59
+ * the next value without consuming it from the iterator.
60
+ * @internal
61
+ *
62
+ * @param iterable - The async iterable to make peekable
63
+ *
64
+ * **Example usage:**
65
+ * ```ts
66
+ * const numbers = async function* () {
67
+ * yield 1; yield 2; yield 3;
68
+ * };
69
+ *
70
+ * const peekable = peekableAsyncIterable(numbers());
71
+ * const iterator = peekable[Symbol.asyncIterator]();
72
+ *
73
+ * console.log(await iterator.peek()); // 1 (doesn't consume)
74
+ * console.log(await iterator.peek()); // 1 (still doesn't consume)
75
+ * console.log(await iterator.next()); // { value: 1, done: false } (now consumed)
76
+ * console.log(await iterator.peek()); // 2 (next value)
77
+ * ```
78
+ */
79
+ export declare function peekableAsyncIterable<T>(iterable: AsyncIterable<T> | Iterable<T>): PeekableAsyncIterable<T>;
package/iterables.js ADDED
@@ -0,0 +1,134 @@
1
+ import { inspect } from 'node:util';
2
+ /**
3
+ * Converts any iterable or async iterable to an async iterable.
4
+ * @internal
5
+ *
6
+ * @yields Each item from the input iterable
7
+ *
8
+ * **Example usage:**
9
+ * ```ts
10
+ * const syncArray = [1, 2, 3];
11
+ * for await (const item of asyncifyIterable(syncArray)) {
12
+ * console.log(item); // 1, 2, 3
13
+ * }
14
+ * ```
15
+ */
16
+ export async function* asyncifyIterable(iterable) {
17
+ yield* iterable;
18
+ }
19
+ /**
20
+ * Lazily splits the input async iterable into chunks of specified size.
21
+ * The last chunk may contain fewer items if the total number of items
22
+ * is not evenly divisible by the chunk size.
23
+ * @internal
24
+ *
25
+ * @yields Arrays of items, each containing up to chunkSize items
26
+ *
27
+ * **Example usage:**
28
+ * ```ts
29
+ * const numbers = async function* () {
30
+ * for (let i = 1; i <= 10; i++) yield i;
31
+ * };
32
+ *
33
+ * for await (const chunk of chunkedAsyncIterable(numbers(), 3)) {
34
+ * console.log(chunk); // [1, 2, 3], [4, 5, 6], [7, 8, 9], [10]
35
+ * }
36
+ * ```
37
+ */
38
+ export async function* chunkedAsyncIterable(iterable, chunkSize) {
39
+ const getChunkSize = typeof chunkSize === 'function' ? chunkSize : () => chunkSize;
40
+ if (typeof chunkSize === 'number' && chunkSize < 1) {
41
+ throw new Error(`Chunk size must be a positive number (${inspect(chunkSize)}) received`);
42
+ }
43
+ const iterator = Symbol.asyncIterator in iterable
44
+ ? iterable[Symbol.asyncIterator]()
45
+ : iterable[Symbol.iterator]();
46
+ while (true) {
47
+ const currentSize = getChunkSize();
48
+ if (currentSize < 1)
49
+ break;
50
+ const chunk = [];
51
+ for (let i = 0; i < currentSize; i++) {
52
+ const next = await iterator.next();
53
+ if (next.done) {
54
+ break;
55
+ }
56
+ chunk.push(next.value);
57
+ }
58
+ if (chunk.length === 0)
59
+ break;
60
+ yield chunk;
61
+ }
62
+ }
63
+ /**
64
+ * Wraps an async iterable to provide peek functionality, allowing you to look at
65
+ * the next value without consuming it from the iterator.
66
+ * @internal
67
+ *
68
+ * @param iterable - The async iterable to make peekable
69
+ *
70
+ * **Example usage:**
71
+ * ```ts
72
+ * const numbers = async function* () {
73
+ * yield 1; yield 2; yield 3;
74
+ * };
75
+ *
76
+ * const peekable = peekableAsyncIterable(numbers());
77
+ * const iterator = peekable[Symbol.asyncIterator]();
78
+ *
79
+ * console.log(await iterator.peek()); // 1 (doesn't consume)
80
+ * console.log(await iterator.peek()); // 1 (still doesn't consume)
81
+ * console.log(await iterator.next()); // { value: 1, done: false } (now consumed)
82
+ * console.log(await iterator.peek()); // 2 (next value)
83
+ * ```
84
+ */
85
+ export function peekableAsyncIterable(iterable) {
86
+ const iterator = asyncifyIterable(iterable)[Symbol.asyncIterator]();
87
+ let peekedValue;
88
+ let isExhausted = false;
89
+ const peekableIterator = {
90
+ async next() {
91
+ // If we have peeked a value, return it and clear the peek
92
+ if (peekedValue !== undefined) {
93
+ const result = peekedValue;
94
+ peekedValue = undefined;
95
+ if (result.done) {
96
+ isExhausted = true;
97
+ return { done: true, value: undefined };
98
+ }
99
+ return { done: false, value: result.value };
100
+ }
101
+ if (isExhausted) {
102
+ return { done: true, value: undefined };
103
+ }
104
+ const result = await iterator.next();
105
+ if (result.done) {
106
+ isExhausted = true;
107
+ }
108
+ return result;
109
+ },
110
+ async peek() {
111
+ if (peekedValue !== undefined) {
112
+ return peekedValue.done ? undefined : peekedValue.value;
113
+ }
114
+ if (isExhausted) {
115
+ return undefined;
116
+ }
117
+ const result = await iterator.next();
118
+ peekedValue = { done: result.done ?? false, value: result.value };
119
+ if (result.done) {
120
+ isExhausted = true;
121
+ return undefined;
122
+ }
123
+ return result.value;
124
+ },
125
+ [Symbol.asyncIterator]() {
126
+ return this;
127
+ },
128
+ };
129
+ return {
130
+ [Symbol.asyncIterator]() {
131
+ return peekableIterator;
132
+ },
133
+ };
134
+ }
package/log.d.ts CHANGED
@@ -1,3 +1,82 @@
1
- import log, { Log, Logger, LoggerJson, LoggerOptions, LoggerText, LogLevel } from '@apify/log';
2
- export { log, Log, LoggerOptions, LogLevel, Logger, LoggerJson, LoggerText };
3
- //# sourceMappingURL=log.d.ts.map
1
+ import type { CrawleeLogger, CrawleeLoggerOptions } from '@crawlee/types';
2
+ import type { LoggerOptions } from '@apify/log';
3
+ import log, { Log, Logger, LoggerJson, LoggerText, LogLevel } from '@apify/log';
4
+ export type { CrawleeLogger, CrawleeLoggerOptions };
5
+ /**
6
+ * Abstract base class for custom Crawlee logger implementations.
7
+ *
8
+ * Subclasses must implement two methods:
9
+ * - {@link BaseCrawleeLogger.logWithLevel} — the core logging dispatch
10
+ * - {@link BaseCrawleeLogger.createChild} — how to create a child logger instance
11
+ *
12
+ * All other `CrawleeLogger` methods (`error`, `warning`, `info`, `debug`, etc.)
13
+ * are derived automatically. Level filtering is entirely the responsibility of the
14
+ * underlying library — `logWithLevel()` is called for every message.
15
+ *
16
+ * **Example — Winston adapter:**
17
+ * ```typescript
18
+ * const CRAWLEE_TO_WINSTON = { 1: 'error', 2: 'warn', 3: 'warn', 4: 'info', 5: 'debug', 6: 'debug' };
19
+ *
20
+ * class WinstonAdapter extends BaseCrawleeLogger {
21
+ * constructor(private logger: winston.Logger, options?: Partial<CrawleeLoggerOptions>) {
22
+ * super(options);
23
+ * }
24
+ *
25
+ * logWithLevel(level: number, message: string, data?: Record<string, unknown>): void {
26
+ * this.logger.log(CRAWLEE_TO_WINSTON[level] ?? 'info', message, data);
27
+ * }
28
+ *
29
+ * protected createChild(options: Partial<CrawleeLoggerOptions>): CrawleeLogger {
30
+ * return new WinstonAdapter(this.logger.child({ prefix: options.prefix }), { ...this.getOptions(), ...options });
31
+ * }
32
+ * }
33
+ * ```
34
+ */
35
+ export declare abstract class BaseCrawleeLogger implements CrawleeLogger {
36
+ private options;
37
+ private readonly warningsLogged;
38
+ constructor(options?: Partial<CrawleeLoggerOptions>);
39
+ /**
40
+ * Core logging method. Subclasses must implement this to dispatch log messages
41
+ * to the underlying logger (Winston, Pino, console, etc.).
42
+ *
43
+ * Level filtering is the responsibility of the underlying library — this method
44
+ * is called for every message regardless of the current level.
45
+ *
46
+ * @param level Crawlee log level (use {@link LogLevel} constants)
47
+ * @param message The log message
48
+ * @param data Optional structured data to attach to the log entry
49
+ */
50
+ abstract logWithLevel(level: number, message: string, data?: Record<string, unknown>): void;
51
+ /**
52
+ * Creates a child logger instance. Subclasses must implement this to define
53
+ * how child loggers are created for the underlying logger.
54
+ */
55
+ protected abstract createChild(options: Partial<CrawleeLoggerOptions>): CrawleeLogger;
56
+ getOptions(): CrawleeLoggerOptions;
57
+ setOptions(options: Partial<CrawleeLoggerOptions>): void;
58
+ child(options: Partial<CrawleeLoggerOptions>): CrawleeLogger;
59
+ error(message: string, data?: Record<string, unknown>): void;
60
+ exception(exception: Error, message: string, data?: Record<string, unknown>): void;
61
+ softFail(message: string, data?: Record<string, unknown>): void;
62
+ warning(message: string, data?: Record<string, unknown>): void;
63
+ warningOnce(message: string): void;
64
+ info(message: string, data?: Record<string, unknown>): void;
65
+ debug(message: string, data?: Record<string, unknown>): void;
66
+ perf(message: string, data?: Record<string, unknown>): void;
67
+ deprecated(message: string): void;
68
+ }
69
+ /**
70
+ * Adapter that wraps `@apify/log`'s {@link Log} instance to implement the {@link CrawleeLogger} interface.
71
+ *
72
+ * This is the default logger used by Crawlee when no custom logger is configured.
73
+ * Users who want to use a different logging library should implement {@link BaseCrawleeLogger} directly.
74
+ */
75
+ export declare class ApifyLogAdapter extends BaseCrawleeLogger {
76
+ private readonly apifyLog;
77
+ constructor(apifyLog: Log, options?: Partial<CrawleeLoggerOptions>);
78
+ logWithLevel(level: number, message: string, data?: Record<string, unknown>): void;
79
+ protected createChild(options: Partial<CrawleeLoggerOptions>): CrawleeLogger;
80
+ }
81
+ export { log, Log, LogLevel, Logger, LoggerJson, LoggerText };
82
+ export type { LoggerOptions };
package/log.js CHANGED
@@ -1,3 +1,108 @@
1
1
  import log, { Log, Logger, LoggerJson, LoggerText, LogLevel } from '@apify/log';
2
+ /**
3
+ * Abstract base class for custom Crawlee logger implementations.
4
+ *
5
+ * Subclasses must implement two methods:
6
+ * - {@link BaseCrawleeLogger.logWithLevel} — the core logging dispatch
7
+ * - {@link BaseCrawleeLogger.createChild} — how to create a child logger instance
8
+ *
9
+ * All other `CrawleeLogger` methods (`error`, `warning`, `info`, `debug`, etc.)
10
+ * are derived automatically. Level filtering is entirely the responsibility of the
11
+ * underlying library — `logWithLevel()` is called for every message.
12
+ *
13
+ * **Example — Winston adapter:**
14
+ * ```typescript
15
+ * const CRAWLEE_TO_WINSTON = { 1: 'error', 2: 'warn', 3: 'warn', 4: 'info', 5: 'debug', 6: 'debug' };
16
+ *
17
+ * class WinstonAdapter extends BaseCrawleeLogger {
18
+ * constructor(private logger: winston.Logger, options?: Partial<CrawleeLoggerOptions>) {
19
+ * super(options);
20
+ * }
21
+ *
22
+ * logWithLevel(level: number, message: string, data?: Record<string, unknown>): void {
23
+ * this.logger.log(CRAWLEE_TO_WINSTON[level] ?? 'info', message, data);
24
+ * }
25
+ *
26
+ * protected createChild(options: Partial<CrawleeLoggerOptions>): CrawleeLogger {
27
+ * return new WinstonAdapter(this.logger.child({ prefix: options.prefix }), { ...this.getOptions(), ...options });
28
+ * }
29
+ * }
30
+ * ```
31
+ */
32
+ export class BaseCrawleeLogger {
33
+ // kept as TS-private: the adaptive crawler's log proxy calls non-intercepted methods with `this === proxy`,
34
+ // where `#`-field access would throw at runtime
35
+ options;
36
+ warningsLogged = new Set();
37
+ constructor(options = {}) {
38
+ this.options = options;
39
+ }
40
+ getOptions() {
41
+ return this.options;
42
+ }
43
+ setOptions(options) {
44
+ this.options = { ...this.options, ...options };
45
+ }
46
+ child(options) {
47
+ return this.createChild(options);
48
+ }
49
+ error(message, data) {
50
+ this.logWithLevel(LogLevel.ERROR, message, data);
51
+ }
52
+ exception(exception, message, data) {
53
+ this.logWithLevel(LogLevel.ERROR, `${message}: ${exception.message}`, {
54
+ ...data,
55
+ stack: exception.stack,
56
+ exception,
57
+ });
58
+ }
59
+ softFail(message, data) {
60
+ this.logWithLevel(LogLevel.SOFT_FAIL, message, data);
61
+ }
62
+ warning(message, data) {
63
+ this.logWithLevel(LogLevel.WARNING, message, data);
64
+ }
65
+ warningOnce(message) {
66
+ if (!this.warningsLogged.has(message)) {
67
+ this.warningsLogged.add(message);
68
+ this.warning(message);
69
+ }
70
+ }
71
+ info(message, data) {
72
+ this.logWithLevel(LogLevel.INFO, message, data);
73
+ }
74
+ debug(message, data) {
75
+ this.logWithLevel(LogLevel.DEBUG, message, data);
76
+ }
77
+ perf(message, data) {
78
+ this.logWithLevel(LogLevel.PERF, `[PERF] ${message}`, data);
79
+ }
80
+ deprecated(message) {
81
+ this.warningOnce(`[DEPRECATED] ${message}`);
82
+ }
83
+ }
84
+ /**
85
+ * Adapter that wraps `@apify/log`'s {@link Log} instance to implement the {@link CrawleeLogger} interface.
86
+ *
87
+ * This is the default logger used by Crawlee when no custom logger is configured.
88
+ * Users who want to use a different logging library should implement {@link BaseCrawleeLogger} directly.
89
+ */
90
+ export class ApifyLogAdapter extends BaseCrawleeLogger {
91
+ apifyLog;
92
+ constructor(
93
+ // kept as a TS-private parameter property: reached through the adaptive crawler's log proxy, see above
94
+ apifyLog, options) {
95
+ super(options ?? {});
96
+ this.apifyLog = apifyLog;
97
+ }
98
+ logWithLevel(level, message, data) {
99
+ this.apifyLog.internal(level, message, data);
100
+ }
101
+ createChild(options) {
102
+ return new ApifyLogAdapter(this.apifyLog.child({ prefix: options.prefix ?? null }), {
103
+ ...this.getOptions(),
104
+ ...options,
105
+ });
106
+ }
107
+ }
2
108
  export { log, Log, LogLevel, Logger, LoggerJson, LoggerText };
3
- //# sourceMappingURL=log.js.map
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Length of id property of a Request instance in characters.
3
+ */
4
+ export declare const REQUEST_ID_LENGTH = 15;
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Length of id property of a Request instance in characters.
3
+ */
4
+ export const REQUEST_ID_LENGTH = 15;
@@ -0,0 +1 @@
1
+ export * from './memory-storage.js';
@@ -0,0 +1 @@
1
+ export * from './memory-storage.js';
@@ -0,0 +1,42 @@
1
+ import type * as storage from '@crawlee/types';
2
+ import type { CrawleeLogger } from '@crawlee/types';
3
+ import { DatasetBackend } from './resource-clients/dataset.js';
4
+ import { KeyValueStoreBackend } from './resource-clients/key-value-store.js';
5
+ import { RequestQueueBackend } from './resource-clients/request-queue.js';
6
+ export interface MemoryStorageOptions {
7
+ /**
8
+ * Optional logger for MemoryStorageBackend warnings.
9
+ */
10
+ logger?: CrawleeLogger;
11
+ }
12
+ export declare class MemoryStorageBackend implements storage.StorageBackend {
13
+ #private;
14
+ readonly logger?: CrawleeLogger;
15
+ readonly keyValueStoreBackendCache: KeyValueStoreBackend[];
16
+ readonly datasetBackendCache: DatasetBackend[];
17
+ readonly requestQueueBackendCache: RequestQueueBackend[];
18
+ constructor(options?: MemoryStorageOptions);
19
+ /**
20
+ * Return a per-instance unique cache key so that distinct `MemoryStorageBackend` instances get separate
21
+ * cache partitions in the storage backend cache.
22
+ */
23
+ getStorageBackendCacheKey(): string;
24
+ private static resolveStorageKey;
25
+ createDatasetBackend(options?: storage.StorageIdentifier): Promise<storage.DatasetBackend>;
26
+ createKeyValueStoreBackend(options?: storage.StorageIdentifier): Promise<storage.KeyValueStoreBackend>;
27
+ createRequestQueueBackend(options?: storage.StorageIdentifier): Promise<RequestQueueBackend>;
28
+ storageExists(id: string, type: 'Dataset' | 'KeyValueStore' | 'RequestQueue'): Promise<boolean>;
29
+ /**
30
+ * Cleans up the default storages before the run starts. For the in-memory storage this simply
31
+ * resets the in-memory state of the cached default dataset, key-value store and request queue.
32
+ *
33
+ * As with `FileSystemStorageBackend`, the run's input (the `INPUT` key in the default key-value
34
+ * store) is preserved — only the rest of the default storages is cleared.
35
+ */
36
+ purge(): Promise<void>;
37
+ /**
38
+ * This method should be called at the end of the process. The in-memory storage holds no resources
39
+ * that outlive the process (no file handles, no cross-process locks), so there is nothing to do.
40
+ */
41
+ teardown(): Promise<void>;
42
+ }
@@ -0,0 +1,136 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { DatasetBackend } from './resource-clients/dataset.js';
3
+ import { KeyValueStoreBackend } from './resource-clients/key-value-store.js';
4
+ import { RequestQueueBackend } from './resource-clients/request-queue.js';
5
+ export class MemoryStorageBackend {
6
+ logger;
7
+ /**
8
+ * Unique per-instance cache partition key. Mirrors the way `FileSystemStorageBackend` partitions its
9
+ * cache by storage directory: two distinct `MemoryStorageBackend` instances must not share cached backends.
10
+ */
11
+ #instanceCacheKey = `MemoryStorageBackend:${randomUUID()}`;
12
+ keyValueStoreBackendCache = [];
13
+ datasetBackendCache = [];
14
+ requestQueueBackendCache = [];
15
+ constructor(options = {}) {
16
+ this.logger = options.logger;
17
+ }
18
+ /**
19
+ * Return a per-instance unique cache key so that distinct `MemoryStorageBackend` instances get separate
20
+ * cache partitions in the storage backend cache.
21
+ */
22
+ getStorageBackendCacheKey() {
23
+ return this.#instanceCacheKey;
24
+ }
25
+ static resolveStorageKey(options) {
26
+ const isAlias = 'alias' in options && !!options.alias;
27
+ const rawKey = isAlias ? options.alias : (options.name ?? options.id);
28
+ // Normalize the internal __default__ alias to the user-facing 'default' name.
29
+ const cacheKey = rawKey === '__default__' ? 'default' : rawKey;
30
+ return { isAlias, cacheKey };
31
+ }
32
+ async createDatasetBackend(options = {}) {
33
+ const { isAlias, cacheKey } = MemoryStorageBackend.resolveStorageKey(options);
34
+ if (cacheKey) {
35
+ const found = this.datasetBackendCache.find((store) => store.id === cacheKey ||
36
+ store.name?.toLowerCase() === cacheKey.toLowerCase() ||
37
+ store.cacheKey.toLowerCase() === cacheKey.toLowerCase());
38
+ if (found) {
39
+ return found;
40
+ }
41
+ }
42
+ const newStore = new DatasetBackend({
43
+ name: isAlias ? undefined : cacheKey,
44
+ cacheKey,
45
+ storageBackend: this,
46
+ });
47
+ this.datasetBackendCache.push(newStore);
48
+ return newStore;
49
+ }
50
+ async createKeyValueStoreBackend(options = {}) {
51
+ const { isAlias, cacheKey } = MemoryStorageBackend.resolveStorageKey(options);
52
+ if (cacheKey) {
53
+ const found = this.keyValueStoreBackendCache.find((store) => store.id === cacheKey ||
54
+ store.name?.toLowerCase() === cacheKey.toLowerCase() ||
55
+ store.cacheKey.toLowerCase() === cacheKey.toLowerCase());
56
+ if (found) {
57
+ return found;
58
+ }
59
+ }
60
+ const newStore = new KeyValueStoreBackend({
61
+ name: isAlias ? undefined : cacheKey,
62
+ cacheKey,
63
+ storageBackend: this,
64
+ });
65
+ this.keyValueStoreBackendCache.push(newStore);
66
+ return newStore;
67
+ }
68
+ async createRequestQueueBackend(options = {}) {
69
+ const { isAlias, cacheKey } = MemoryStorageBackend.resolveStorageKey(options);
70
+ if (cacheKey) {
71
+ const found = this.requestQueueBackendCache.find((queue) => queue.id === cacheKey ||
72
+ queue.name?.toLowerCase() === cacheKey.toLowerCase() ||
73
+ queue.cacheKey.toLowerCase() === cacheKey.toLowerCase());
74
+ if (found) {
75
+ return found;
76
+ }
77
+ }
78
+ const newStore = new RequestQueueBackend({
79
+ name: isAlias ? undefined : cacheKey,
80
+ cacheKey,
81
+ storageBackend: this,
82
+ });
83
+ this.requestQueueBackendCache.push(newStore);
84
+ return newStore;
85
+ }
86
+ async storageExists(id, type) {
87
+ let backends;
88
+ switch (type) {
89
+ case 'Dataset':
90
+ backends = this.datasetBackendCache;
91
+ break;
92
+ case 'KeyValueStore':
93
+ backends = this.keyValueStoreBackendCache;
94
+ break;
95
+ case 'RequestQueue':
96
+ backends = this.requestQueueBackendCache;
97
+ break;
98
+ default:
99
+ return false;
100
+ }
101
+ // In-memory storage only knows about backends in its cache.
102
+ return backends.some((store) => store.id === id);
103
+ }
104
+ /**
105
+ * Cleans up the default storages before the run starts. For the in-memory storage this simply
106
+ * resets the in-memory state of the cached default dataset, key-value store and request queue.
107
+ *
108
+ * As with `FileSystemStorageBackend`, the run's input (the `INPUT` key in the default key-value
109
+ * store) is preserved — only the rest of the default storages is cleared.
110
+ */
111
+ async purge() {
112
+ // The run default is opened via `{ alias: '__default__' }`, which `resolveStorageKey`
113
+ // normalizes to `cacheKey === 'default'` (with `name === undefined`) — that is the clause
114
+ // that actually matches it. The `name === 'default'` clause additionally covers a store a user
115
+ // explicitly opened via `{ name: 'default' }`. (`'__default__'` never reaches `cacheKey`,
116
+ // as it is always normalized to `'default'` first, so it does not need to be checked here.)
117
+ const isDefault = (store) => store.name === 'default' || store.cacheKey === 'default';
118
+ const purgeDefaults = async (cache, purgeStore) => {
119
+ await Promise.all(cache.filter(isDefault).map(async (store) => purgeStore(store)));
120
+ };
121
+ await Promise.all([
122
+ // Preserve the run input (INPUT) when purging the default key-value store, matching
123
+ // `FileSystemStorageBackend`.
124
+ purgeDefaults(this.keyValueStoreBackendCache, async (store) => store.purgeExceptInput()),
125
+ purgeDefaults(this.datasetBackendCache, async (store) => store.purge()),
126
+ purgeDefaults(this.requestQueueBackendCache, async (store) => store.purge()),
127
+ ]);
128
+ }
129
+ /**
130
+ * This method should be called at the end of the process. The in-memory storage holds no resources
131
+ * that outlive the process (no file handles, no cross-process locks), so there is nothing to do.
132
+ */
133
+ async teardown() {
134
+ // Nothing to tear down for in-memory storage.
135
+ }
136
+ }
@@ -0,0 +1,4 @@
1
+ export declare class BaseClient {
2
+ id: string;
3
+ constructor(id: string);
4
+ }
@@ -0,0 +1,6 @@
1
+ export class BaseClient {
2
+ id;
3
+ constructor(id) {
4
+ this.id = id;
5
+ }
6
+ }
@@ -0,0 +1,40 @@
1
+ import type * as storage from '@crawlee/types';
2
+ import type { Dictionary } from '@crawlee/types';
3
+ import type { MemoryStorageBackend } from '../memory-storage.js';
4
+ import { BaseClient } from './common/base-client.js';
5
+ export interface DatasetBackendOptions {
6
+ id?: string;
7
+ name?: string;
8
+ /**
9
+ * The key used for cache lookup. When provided, takes precedence over `name` and `id`.
10
+ * This allows alias-opened storages to have a cache key that differs from their
11
+ * metadata `name` (which is `undefined` for unnamed storages).
12
+ */
13
+ cacheKey?: string;
14
+ storageBackend: MemoryStorageBackend;
15
+ }
16
+ export declare class DatasetBackend<Data extends Dictionary = Dictionary> extends BaseClient implements storage.DatasetBackend<Data> {
17
+ #private;
18
+ name?: string;
19
+ /**
20
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
21
+ * storages, this is the alias string. Falls back to id.
22
+ */
23
+ cacheKey: string;
24
+ createdAt: Date;
25
+ accessedAt: Date;
26
+ modifiedAt: Date;
27
+ itemCount: number;
28
+ private readonly storageBackend;
29
+ constructor(options: DatasetBackendOptions);
30
+ getMetadata(): Promise<storage.DatasetInfo>;
31
+ drop(): Promise<void>;
32
+ purge(): Promise<void>;
33
+ getData(options?: storage.DatasetBackendListOptions): Promise<storage.PaginatedList<Data>>;
34
+ private getDataPage;
35
+ pushData(items: Data[]): Promise<void>;
36
+ toDatasetInfo(): storage.DatasetInfo;
37
+ private generateLocalEntryName;
38
+ private getStartAndEndIndexes;
39
+ private updateTimestamps;
40
+ }