@crawlee/core 4.0.0-beta.24 → 4.0.0-beta.240

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 (265) hide show
  1. package/README.md +15 -15
  2. package/byte-utils.d.ts +17 -0
  3. package/byte-utils.js +42 -0
  4. package/configuration.d.ts +77 -235
  5. package/configuration.js +157 -227
  6. package/debug.d.ts +36 -0
  7. package/debug.js +70 -0
  8. package/errors.d.ts +45 -18
  9. package/errors.js +58 -27
  10. package/events/event-manager.d.ts +78 -0
  11. package/events/{event_manager.js → event-manager.js} +12 -13
  12. package/events/index.d.ts +3 -3
  13. package/events/index.js +2 -3
  14. package/events/local-event-manager.d.ts +32 -0
  15. package/events/local-event-manager.js +101 -0
  16. package/events/system-info.d.ts +38 -0
  17. package/events/system-info.js +1 -0
  18. package/index.d.ts +9 -12
  19. package/index.js +10 -11
  20. package/internal.d.ts +8 -0
  21. package/internal.js +9 -0
  22. package/iterables.d.ts +79 -0
  23. package/iterables.js +134 -0
  24. package/log.d.ts +77 -1
  25. package/log.js +134 -1
  26. package/memory-storage/consts.d.ts +4 -0
  27. package/memory-storage/consts.js +4 -0
  28. package/memory-storage/index.d.ts +1 -0
  29. package/memory-storage/index.js +1 -0
  30. package/memory-storage/memory-storage.d.ts +43 -0
  31. package/memory-storage/memory-storage.js +158 -0
  32. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  33. package/memory-storage/resource-clients/common/base-client.js +6 -0
  34. package/memory-storage/resource-clients/dataset.d.ts +35 -0
  35. package/memory-storage/resource-clients/dataset.js +105 -0
  36. package/memory-storage/resource-clients/key-value-store.d.ts +54 -0
  37. package/memory-storage/resource-clients/key-value-store.js +179 -0
  38. package/memory-storage/resource-clients/request-queue.d.ts +55 -0
  39. package/memory-storage/resource-clients/request-queue.js +413 -0
  40. package/memory-storage/utils.d.ts +16 -0
  41. package/memory-storage/utils.js +41 -0
  42. package/owned-or-injected.d.ts +58 -0
  43. package/owned-or-injected.js +98 -0
  44. package/package.json +20 -20
  45. package/proxy-configuration.d.ts +118 -0
  46. package/proxy-configuration.js +141 -0
  47. package/recoverable-state.d.ts +177 -0
  48. package/recoverable-state.js +268 -0
  49. package/request.d.ts +48 -93
  50. package/request.js +112 -230
  51. package/serialization.d.ts +0 -1
  52. package/serialization.js +18 -18
  53. package/service-locator.d.ts +168 -0
  54. package/service-locator.js +255 -0
  55. package/storages/batched-adds.d.ts +37 -0
  56. package/storages/batched-adds.js +73 -0
  57. package/storages/dataset.d.ts +105 -58
  58. package/storages/dataset.js +292 -150
  59. package/storages/index.d.ts +11 -12
  60. package/storages/index.js +7 -12
  61. package/storages/key-value-store-codec.d.ts +32 -0
  62. package/storages/key-value-store-codec.js +108 -0
  63. package/storages/{key_value_store.d.ts → key-value-store.d.ts} +169 -72
  64. package/storages/key-value-store.js +767 -0
  65. package/storages/request-dedup-cache.d.ts +20 -0
  66. package/storages/request-dedup-cache.js +48 -0
  67. package/storages/{request_list.d.ts → request-list.d.ts} +33 -173
  68. package/storages/{request_list.js → request-list.js} +276 -255
  69. package/storages/request-loader.d.ts +127 -0
  70. package/storages/request-loader.js +36 -0
  71. package/storages/request-manager-tandem.d.ts +82 -0
  72. package/storages/request-manager-tandem.js +200 -0
  73. package/storages/request-manager.d.ts +119 -0
  74. package/storages/request-manager.js +1 -0
  75. package/storages/{request_provider.d.ts → request-queue.d.ts} +128 -159
  76. package/storages/request-queue.js +870 -0
  77. package/storages/storage-instance-manager.d.ts +86 -0
  78. package/storages/storage-instance-manager.js +256 -0
  79. package/storages/storage-stats.d.ts +48 -0
  80. package/storages/storage-stats.js +29 -0
  81. package/storages/transaction.d.ts +270 -0
  82. package/storages/transaction.js +296 -0
  83. package/storages/utils.d.ts +59 -11
  84. package/storages/utils.js +76 -16
  85. package/system-info/cpu-info.d.ts +67 -0
  86. package/system-info/cpu-info.js +216 -0
  87. package/system-info/memory-info.d.ts +31 -0
  88. package/system-info/memory-info.js +115 -0
  89. package/system-info/ps-tree.d.ts +17 -0
  90. package/system-info/ps-tree.js +144 -0
  91. package/system-info/runtime.d.ts +14 -0
  92. package/system-info/runtime.js +80 -0
  93. package/typedefs.d.ts +0 -6
  94. package/typedefs.js +0 -1
  95. package/url.d.ts +9 -0
  96. package/url.js +11 -0
  97. package/validators.d.ts +23 -18
  98. package/validators.js +14 -18
  99. package/autoscaling/autoscaled_pool.d.ts +0 -300
  100. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  101. package/autoscaling/autoscaled_pool.js +0 -533
  102. package/autoscaling/autoscaled_pool.js.map +0 -1
  103. package/autoscaling/index.d.ts +0 -4
  104. package/autoscaling/index.d.ts.map +0 -1
  105. package/autoscaling/index.js +0 -4
  106. package/autoscaling/index.js.map +0 -1
  107. package/autoscaling/snapshotter.d.ts +0 -189
  108. package/autoscaling/snapshotter.d.ts.map +0 -1
  109. package/autoscaling/snapshotter.js +0 -285
  110. package/autoscaling/snapshotter.js.map +0 -1
  111. package/autoscaling/system_status.d.ts +0 -181
  112. package/autoscaling/system_status.d.ts.map +0 -1
  113. package/autoscaling/system_status.js +0 -169
  114. package/autoscaling/system_status.js.map +0 -1
  115. package/configuration.d.ts.map +0 -1
  116. package/configuration.js.map +0 -1
  117. package/cookie_utils.d.ts +0 -43
  118. package/cookie_utils.d.ts.map +0 -1
  119. package/cookie_utils.js +0 -111
  120. package/cookie_utils.js.map +0 -1
  121. package/crawlers/context_pipeline.d.ts +0 -61
  122. package/crawlers/context_pipeline.d.ts.map +0 -1
  123. package/crawlers/context_pipeline.js +0 -99
  124. package/crawlers/context_pipeline.js.map +0 -1
  125. package/crawlers/crawler_commons.d.ts +0 -191
  126. package/crawlers/crawler_commons.d.ts.map +0 -1
  127. package/crawlers/crawler_commons.js +0 -108
  128. package/crawlers/crawler_commons.js.map +0 -1
  129. package/crawlers/crawler_utils.d.ts +0 -10
  130. package/crawlers/crawler_utils.d.ts.map +0 -1
  131. package/crawlers/crawler_utils.js +0 -12
  132. package/crawlers/crawler_utils.js.map +0 -1
  133. package/crawlers/error_snapshotter.d.ts +0 -60
  134. package/crawlers/error_snapshotter.d.ts.map +0 -1
  135. package/crawlers/error_snapshotter.js +0 -118
  136. package/crawlers/error_snapshotter.js.map +0 -1
  137. package/crawlers/error_tracker.d.ts +0 -55
  138. package/crawlers/error_tracker.d.ts.map +0 -1
  139. package/crawlers/error_tracker.js +0 -309
  140. package/crawlers/error_tracker.js.map +0 -1
  141. package/crawlers/index.d.ts +0 -7
  142. package/crawlers/index.d.ts.map +0 -1
  143. package/crawlers/index.js +0 -7
  144. package/crawlers/index.js.map +0 -1
  145. package/crawlers/internals/types.d.ts +0 -8
  146. package/crawlers/internals/types.d.ts.map +0 -1
  147. package/crawlers/internals/types.js +0 -2
  148. package/crawlers/internals/types.js.map +0 -1
  149. package/crawlers/statistics.d.ts +0 -213
  150. package/crawlers/statistics.d.ts.map +0 -1
  151. package/crawlers/statistics.js +0 -349
  152. package/crawlers/statistics.js.map +0 -1
  153. package/enqueue_links/enqueue_links.d.ts +0 -249
  154. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  155. package/enqueue_links/enqueue_links.js +0 -269
  156. package/enqueue_links/enqueue_links.js.map +0 -1
  157. package/enqueue_links/index.d.ts +0 -3
  158. package/enqueue_links/index.d.ts.map +0 -1
  159. package/enqueue_links/index.js +0 -3
  160. package/enqueue_links/index.js.map +0 -1
  161. package/enqueue_links/shared.d.ts +0 -73
  162. package/enqueue_links/shared.d.ts.map +0 -1
  163. package/enqueue_links/shared.js +0 -212
  164. package/enqueue_links/shared.js.map +0 -1
  165. package/errors.d.ts.map +0 -1
  166. package/errors.js.map +0 -1
  167. package/events/event_manager.d.ts +0 -52
  168. package/events/event_manager.d.ts.map +0 -1
  169. package/events/event_manager.js.map +0 -1
  170. package/events/index.d.ts.map +0 -1
  171. package/events/index.js.map +0 -1
  172. package/events/local_event_manager.d.ts +0 -27
  173. package/events/local_event_manager.d.ts.map +0 -1
  174. package/events/local_event_manager.js +0 -75
  175. package/events/local_event_manager.js.map +0 -1
  176. package/index.d.ts.map +0 -1
  177. package/index.js.map +0 -1
  178. package/log.d.ts.map +0 -1
  179. package/log.js.map +0 -1
  180. package/proxy_configuration.d.ts +0 -169
  181. package/proxy_configuration.d.ts.map +0 -1
  182. package/proxy_configuration.js +0 -247
  183. package/proxy_configuration.js.map +0 -1
  184. package/recoverable_state.d.ts +0 -123
  185. package/recoverable_state.d.ts.map +0 -1
  186. package/recoverable_state.js +0 -140
  187. package/recoverable_state.js.map +0 -1
  188. package/request.d.ts.map +0 -1
  189. package/request.js.map +0 -1
  190. package/router.d.ts +0 -134
  191. package/router.d.ts.map +0 -1
  192. package/router.js +0 -164
  193. package/router.js.map +0 -1
  194. package/serialization.d.ts.map +0 -1
  195. package/serialization.js.map +0 -1
  196. package/session_pool/consts.d.ts +0 -4
  197. package/session_pool/consts.d.ts.map +0 -1
  198. package/session_pool/consts.js +0 -4
  199. package/session_pool/consts.js.map +0 -1
  200. package/session_pool/errors.d.ts +0 -8
  201. package/session_pool/errors.d.ts.map +0 -1
  202. package/session_pool/errors.js +0 -12
  203. package/session_pool/errors.js.map +0 -1
  204. package/session_pool/events.d.ts +0 -3
  205. package/session_pool/events.d.ts.map +0 -1
  206. package/session_pool/events.js +0 -3
  207. package/session_pool/events.js.map +0 -1
  208. package/session_pool/index.d.ts +0 -6
  209. package/session_pool/index.d.ts.map +0 -1
  210. package/session_pool/index.js +0 -6
  211. package/session_pool/index.js.map +0 -1
  212. package/session_pool/session.d.ts +0 -186
  213. package/session_pool/session.d.ts.map +0 -1
  214. package/session_pool/session.js +0 -278
  215. package/session_pool/session.js.map +0 -1
  216. package/session_pool/session_pool.d.ts +0 -258
  217. package/session_pool/session_pool.d.ts.map +0 -1
  218. package/session_pool/session_pool.js +0 -387
  219. package/session_pool/session_pool.js.map +0 -1
  220. package/storages/access_checking.d.ts +0 -13
  221. package/storages/access_checking.d.ts.map +0 -1
  222. package/storages/access_checking.js +0 -14
  223. package/storages/access_checking.js.map +0 -1
  224. package/storages/dataset.d.ts.map +0 -1
  225. package/storages/dataset.js.map +0 -1
  226. package/storages/index.d.ts.map +0 -1
  227. package/storages/index.js.map +0 -1
  228. package/storages/key_value_store.d.ts.map +0 -1
  229. package/storages/key_value_store.js +0 -512
  230. package/storages/key_value_store.js.map +0 -1
  231. package/storages/request_list.d.ts.map +0 -1
  232. package/storages/request_list.js.map +0 -1
  233. package/storages/request_list_adapter.d.ts +0 -58
  234. package/storages/request_list_adapter.d.ts.map +0 -1
  235. package/storages/request_list_adapter.js +0 -81
  236. package/storages/request_list_adapter.js.map +0 -1
  237. package/storages/request_manager_tandem.d.ts +0 -68
  238. package/storages/request_manager_tandem.d.ts.map +0 -1
  239. package/storages/request_manager_tandem.js +0 -124
  240. package/storages/request_manager_tandem.js.map +0 -1
  241. package/storages/request_provider.d.ts.map +0 -1
  242. package/storages/request_provider.js +0 -591
  243. package/storages/request_provider.js.map +0 -1
  244. package/storages/request_queue.d.ts +0 -128
  245. package/storages/request_queue.d.ts.map +0 -1
  246. package/storages/request_queue.js +0 -320
  247. package/storages/request_queue.js.map +0 -1
  248. package/storages/request_queue_v2.d.ts +0 -87
  249. package/storages/request_queue_v2.d.ts.map +0 -1
  250. package/storages/request_queue_v2.js +0 -438
  251. package/storages/request_queue_v2.js.map +0 -1
  252. package/storages/sitemap_request_list.d.ts +0 -250
  253. package/storages/sitemap_request_list.d.ts.map +0 -1
  254. package/storages/sitemap_request_list.js +0 -431
  255. package/storages/sitemap_request_list.js.map +0 -1
  256. package/storages/storage_manager.d.ts +0 -62
  257. package/storages/storage_manager.d.ts.map +0 -1
  258. package/storages/storage_manager.js +0 -105
  259. package/storages/storage_manager.js.map +0 -1
  260. package/storages/utils.d.ts.map +0 -1
  261. package/storages/utils.js.map +0 -1
  262. package/typedefs.d.ts.map +0 -1
  263. package/typedefs.js.map +0 -1
  264. package/validators.d.ts.map +0 -1
  265. package/validators.js.map +0 -1
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,5 +1,81 @@
1
+ import type { CrawleeLogger, CrawleeLoggerOptions, LogOptions } from '@crawlee/types';
1
2
  import type { LoggerOptions } from '@apify/log';
2
3
  import log, { Log, Logger, LoggerJson, LoggerText, LogLevel } from '@apify/log';
4
+ export type { CrawleeLogger, CrawleeLoggerOptions, LogOptions };
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;
37
+ constructor(options?: Partial<CrawleeLoggerOptions>);
38
+ /**
39
+ * Core logging method. Subclasses must implement this to dispatch log messages
40
+ * to the underlying logger (Winston, Pino, console, etc.).
41
+ *
42
+ * Level filtering is the responsibility of the underlying library — this method
43
+ * is called for every message regardless of the current level.
44
+ *
45
+ * @param level Crawlee log level (use {@link LogLevel} constants)
46
+ * @param message The log message
47
+ * @param data Optional structured data to attach to the log entry
48
+ */
49
+ abstract logWithLevel(level: number, message: string, data?: Record<string, unknown>): void;
50
+ /**
51
+ * Creates a child logger instance. Subclasses must implement this to define
52
+ * how child loggers are created for the underlying logger.
53
+ */
54
+ protected abstract createChild(options: Partial<CrawleeLoggerOptions>): CrawleeLogger;
55
+ getOptions(): CrawleeLoggerOptions;
56
+ setOptions(options: Partial<CrawleeLoggerOptions>): void;
57
+ child(options: Partial<CrawleeLoggerOptions>): CrawleeLogger;
58
+ error(message: string, data?: Record<string, unknown>, options?: LogOptions): void;
59
+ exception(exception: Error, message: string, data?: Record<string, unknown>): void;
60
+ softFail(message: string, data?: Record<string, unknown>, options?: LogOptions): void;
61
+ warning(message: string, data?: Record<string, unknown>, options?: LogOptions): void;
62
+ warningOnce(message: string): void;
63
+ info(message: string, data?: Record<string, unknown>, options?: LogOptions): void;
64
+ debug(message: string, data?: Record<string, unknown>, options?: LogOptions): void;
65
+ perf(message: string, data?: Record<string, unknown>, options?: LogOptions): void;
66
+ deprecated(message: string): void;
67
+ }
68
+ /**
69
+ * Adapter that wraps `@apify/log`'s {@link Log} instance to implement the {@link CrawleeLogger} interface.
70
+ *
71
+ * This is the default logger used by Crawlee when no custom logger is configured.
72
+ * Users who want to use a different logging library should implement {@link BaseCrawleeLogger} directly.
73
+ */
74
+ export declare class ApifyLogAdapter extends BaseCrawleeLogger {
75
+ #private;
76
+ constructor(apifyLog: Log, options?: Partial<CrawleeLoggerOptions>);
77
+ logWithLevel(level: number, message: string, data?: Record<string, unknown>): void;
78
+ protected createChild(options: Partial<CrawleeLoggerOptions>): CrawleeLogger;
79
+ }
3
80
  export { log, Log, LogLevel, Logger, LoggerJson, LoggerText };
4
81
  export type { LoggerOptions };
5
- //# sourceMappingURL=log.d.ts.map
package/log.js CHANGED
@@ -1,3 +1,136 @@
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
+ // Note: If wrapping logger in a Proxy, unbound methods calling #-fields throw TypeError
34
+ // unless bound to the target (see createLogProxy in adaptive-playwright-crawler.ts).
35
+ #options;
36
+ #loggedOnce = 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
+ /**
50
+ * Whether `once` suppresses this message. Keyed by level as well as text, so that a message logged once as
51
+ * `info` does not swallow the same text logged as a `warning`.
52
+ *
53
+ * Handled here rather than in {@link BaseCrawleeLogger.logWithLevel} so that every logger gets it, instead
54
+ * of each implementation having to dedupe for itself.
55
+ */
56
+ #suppressedAsRepeat(level, message, options) {
57
+ if (!options?.once) {
58
+ return false;
59
+ }
60
+ const key = `${level}:${message}`;
61
+ if (this.#loggedOnce.has(key)) {
62
+ return true;
63
+ }
64
+ this.#loggedOnce.add(key);
65
+ return false;
66
+ }
67
+ error(message, data, options) {
68
+ if (this.#suppressedAsRepeat(LogLevel.ERROR, message, options))
69
+ return;
70
+ this.logWithLevel(LogLevel.ERROR, message, data);
71
+ }
72
+ exception(exception, message, data) {
73
+ this.logWithLevel(LogLevel.ERROR, `${message}: ${exception.message}`, {
74
+ ...data,
75
+ stack: exception.stack,
76
+ exception,
77
+ });
78
+ }
79
+ softFail(message, data, options) {
80
+ if (this.#suppressedAsRepeat(LogLevel.SOFT_FAIL, message, options))
81
+ return;
82
+ this.logWithLevel(LogLevel.SOFT_FAIL, message, data);
83
+ }
84
+ warning(message, data, options) {
85
+ if (this.#suppressedAsRepeat(LogLevel.WARNING, message, options))
86
+ return;
87
+ this.logWithLevel(LogLevel.WARNING, message, data);
88
+ }
89
+ warningOnce(message) {
90
+ // Gates before delegating, so that a suppressed repeat is not even a `warning()` call.
91
+ if (this.#suppressedAsRepeat(LogLevel.WARNING, message, { once: true }))
92
+ return;
93
+ this.warning(message);
94
+ }
95
+ info(message, data, options) {
96
+ if (this.#suppressedAsRepeat(LogLevel.INFO, message, options))
97
+ return;
98
+ this.logWithLevel(LogLevel.INFO, message, data);
99
+ }
100
+ debug(message, data, options) {
101
+ if (this.#suppressedAsRepeat(LogLevel.DEBUG, message, options))
102
+ return;
103
+ this.logWithLevel(LogLevel.DEBUG, message, data);
104
+ }
105
+ perf(message, data, options) {
106
+ if (this.#suppressedAsRepeat(LogLevel.PERF, message, options))
107
+ return;
108
+ this.logWithLevel(LogLevel.PERF, `[PERF] ${message}`, data);
109
+ }
110
+ deprecated(message) {
111
+ this.warningOnce(`[DEPRECATED] ${message}`);
112
+ }
113
+ }
114
+ /**
115
+ * Adapter that wraps `@apify/log`'s {@link Log} instance to implement the {@link CrawleeLogger} interface.
116
+ *
117
+ * This is the default logger used by Crawlee when no custom logger is configured.
118
+ * Users who want to use a different logging library should implement {@link BaseCrawleeLogger} directly.
119
+ */
120
+ export class ApifyLogAdapter extends BaseCrawleeLogger {
121
+ #apifyLog;
122
+ constructor(apifyLog, options) {
123
+ super(options ?? {});
124
+ this.#apifyLog = apifyLog;
125
+ }
126
+ logWithLevel(level, message, data) {
127
+ this.#apifyLog.internal(level, message, data);
128
+ }
129
+ createChild(options) {
130
+ return new ApifyLogAdapter(this.#apifyLog.child({ prefix: options.prefix ?? null }), {
131
+ ...this.getOptions(),
132
+ ...options,
133
+ });
134
+ }
135
+ }
2
136
  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,43 @@
1
+ import type * as storage from '@crawlee/types';
2
+ import type { CrawleeLogger } from '@crawlee/types';
3
+ export interface MemoryStorageOptions {
4
+ /**
5
+ * Optional logger for MemoryStorageBackend warnings.
6
+ */
7
+ logger?: CrawleeLogger;
8
+ }
9
+ export declare class MemoryStorageBackend implements storage.StorageBackend {
10
+ #private;
11
+ readonly logger?: CrawleeLogger;
12
+ constructor(options?: MemoryStorageOptions);
13
+ /**
14
+ * Return a per-instance unique cache key so that distinct `MemoryStorageBackend` instances get separate
15
+ * cache partitions in the storage backend cache.
16
+ */
17
+ getStorageBackendCacheKey(): string;
18
+ /**
19
+ * Evict a cached backend so that a dropped storage is no longer resolved by `createXBackend`,
20
+ * reported by `storageExists` or visited by `purge`. Returns whether the backend was cached, which
21
+ * tells the caller whether it still owns in-memory state worth clearing.
22
+ *
23
+ * The resource clients own their own entry's lifetime but must not reach into the caches directly.
24
+ * Because a client is only ever constructed by `createXBackend`, which caches it immediately, the
25
+ * entry matching `id` is always the caller itself.
26
+ * @internal
27
+ */
28
+ evictBackend(type: 'Dataset' | 'KeyValueStore' | 'RequestQueue', id: string): boolean;
29
+ createDatasetBackend(options?: storage.StorageIdentifier): Promise<storage.DatasetBackend>;
30
+ createKeyValueStoreBackend(options?: storage.StorageIdentifier): Promise<storage.KeyValueStoreBackend>;
31
+ createRequestQueueBackend(options?: storage.StorageIdentifier): Promise<storage.RequestQueueBackend>;
32
+ storageExists(id: string, type: 'Dataset' | 'KeyValueStore' | 'RequestQueue'): Promise<boolean>;
33
+ /**
34
+ * Cleans up the run-scoped storages before the run starts. For the in-memory storage this simply
35
+ * resets the in-memory state of the cached backends.
36
+ */
37
+ purge(): Promise<void>;
38
+ /**
39
+ * This method should be called at the end of the process. The in-memory storage holds no resources
40
+ * that outlive the process (no file handles, no cross-process locks), so there is nothing to do.
41
+ */
42
+ teardown(): Promise<void>;
43
+ }
@@ -0,0 +1,158 @@
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
+ /** The alias the default (unnamed) storage is opened under. */
6
+ const DEFAULT_STORAGE_ALIAS = '__default__';
7
+ export class MemoryStorageBackend {
8
+ logger;
9
+ /**
10
+ * Unique per-instance cache partition key. Mirrors the way `FileSystemStorageBackend` partitions its
11
+ * cache by storage directory: two distinct `MemoryStorageBackend` instances must not share cached backends.
12
+ */
13
+ #instanceCacheKey = `MemoryStorageBackend:${randomUUID()}`;
14
+ #keyValueStoreBackendCache = [];
15
+ #datasetBackendCache = [];
16
+ #requestQueueBackendCache = [];
17
+ constructor(options = {}) {
18
+ this.logger = options.logger;
19
+ }
20
+ /**
21
+ * Return a per-instance unique cache key so that distinct `MemoryStorageBackend` instances get separate
22
+ * cache partitions in the storage backend cache.
23
+ */
24
+ getStorageBackendCacheKey() {
25
+ return this.#instanceCacheKey;
26
+ }
27
+ /**
28
+ * Evict a cached backend so that a dropped storage is no longer resolved by `createXBackend`,
29
+ * reported by `storageExists` or visited by `purge`. Returns whether the backend was cached, which
30
+ * tells the caller whether it still owns in-memory state worth clearing.
31
+ *
32
+ * The resource clients own their own entry's lifetime but must not reach into the caches directly.
33
+ * Because a client is only ever constructed by `createXBackend`, which caches it immediately, the
34
+ * entry matching `id` is always the caller itself.
35
+ * @internal
36
+ */
37
+ evictBackend(type, id) {
38
+ let cache;
39
+ switch (type) {
40
+ case 'Dataset':
41
+ cache = this.#datasetBackendCache;
42
+ break;
43
+ case 'KeyValueStore':
44
+ cache = this.#keyValueStoreBackendCache;
45
+ break;
46
+ case 'RequestQueue':
47
+ cache = this.#requestQueueBackendCache;
48
+ break;
49
+ }
50
+ const index = cache.findIndex((entry) => entry.id === id);
51
+ if (index === -1) {
52
+ return false;
53
+ }
54
+ cache.splice(index, 1);
55
+ return true;
56
+ }
57
+ static #resolveStorageKey(options) {
58
+ // No identifier at all means the default storage, which is opened under the reserved alias —
59
+ // same rule as `resolveStorageIdentifier` in the storage frontends, so that a backend used
60
+ // directly lands on the very storage the frontends would have opened.
61
+ const alias = options.alias || (!options.id && !options.name ? DEFAULT_STORAGE_ALIAS : undefined);
62
+ // `alias` covers the identifier-less case, so one of the three is always set.
63
+ const rawKey = alias ?? options.name ?? options.id;
64
+ // Normalize the internal __default__ alias to the user-facing 'default' name.
65
+ const cacheKey = rawKey === DEFAULT_STORAGE_ALIAS ? 'default' : rawKey;
66
+ return { isAlias: alias !== undefined, cacheKey };
67
+ }
68
+ async createDatasetBackend(options = {}) {
69
+ const { isAlias, cacheKey } = MemoryStorageBackend.#resolveStorageKey(options);
70
+ const found = this.#datasetBackendCache.find((store) => store.id === cacheKey ||
71
+ store.name?.toLowerCase() === cacheKey.toLowerCase() ||
72
+ store.cacheKey.toLowerCase() === cacheKey.toLowerCase());
73
+ if (found) {
74
+ return found;
75
+ }
76
+ const newStore = new DatasetBackend({
77
+ name: isAlias ? undefined : cacheKey,
78
+ cacheKey,
79
+ storageBackend: this,
80
+ });
81
+ this.#datasetBackendCache.push(newStore);
82
+ return newStore;
83
+ }
84
+ async createKeyValueStoreBackend(options = {}) {
85
+ const { isAlias, cacheKey } = MemoryStorageBackend.#resolveStorageKey(options);
86
+ const found = this.#keyValueStoreBackendCache.find((store) => store.id === cacheKey ||
87
+ store.name?.toLowerCase() === cacheKey.toLowerCase() ||
88
+ store.cacheKey.toLowerCase() === cacheKey.toLowerCase());
89
+ if (found) {
90
+ return found;
91
+ }
92
+ const newStore = new KeyValueStoreBackend({
93
+ name: isAlias ? undefined : cacheKey,
94
+ cacheKey,
95
+ storageBackend: this,
96
+ });
97
+ this.#keyValueStoreBackendCache.push(newStore);
98
+ return newStore;
99
+ }
100
+ async createRequestQueueBackend(options = {}) {
101
+ const { isAlias, cacheKey } = MemoryStorageBackend.#resolveStorageKey(options);
102
+ const found = this.#requestQueueBackendCache.find((queue) => queue.id === cacheKey ||
103
+ queue.name?.toLowerCase() === cacheKey.toLowerCase() ||
104
+ queue.cacheKey.toLowerCase() === cacheKey.toLowerCase());
105
+ if (found) {
106
+ return found;
107
+ }
108
+ const newStore = new RequestQueueBackend({
109
+ name: isAlias ? undefined : cacheKey,
110
+ cacheKey,
111
+ storageBackend: this,
112
+ });
113
+ this.#requestQueueBackendCache.push(newStore);
114
+ return newStore;
115
+ }
116
+ async storageExists(id, type) {
117
+ let backends;
118
+ switch (type) {
119
+ case 'Dataset':
120
+ backends = this.#datasetBackendCache;
121
+ break;
122
+ case 'KeyValueStore':
123
+ backends = this.#keyValueStoreBackendCache;
124
+ break;
125
+ case 'RequestQueue':
126
+ backends = this.#requestQueueBackendCache;
127
+ break;
128
+ default:
129
+ return false;
130
+ }
131
+ // In-memory storage only knows about backends in its cache.
132
+ return backends.some((store) => store.id === id);
133
+ }
134
+ /**
135
+ * Cleans up the run-scoped storages before the run starts. For the in-memory storage this simply
136
+ * resets the in-memory state of the cached backends.
137
+ */
138
+ async purge() {
139
+ // `#resolveStorageKey` leaves `name` unset for the default and alias-keyed storages, which is what
140
+ // marks them as run-scoped. `'default'` is the exception — it collapses onto the default storage.
141
+ const isRunScoped = (store) => store.name === undefined || store.name === 'default';
142
+ const purgeRunScoped = async (cache, purgeStore) => {
143
+ await Promise.all(cache.filter(isRunScoped).map(async (store) => purgeStore(store)));
144
+ };
145
+ await Promise.all([
146
+ purgeRunScoped(this.#keyValueStoreBackendCache, async (store) => store.purge()),
147
+ purgeRunScoped(this.#datasetBackendCache, async (store) => store.purge()),
148
+ purgeRunScoped(this.#requestQueueBackendCache, async (store) => store.purge()),
149
+ ]);
150
+ }
151
+ /**
152
+ * This method should be called at the end of the process. The in-memory storage holds no resources
153
+ * that outlive the process (no file handles, no cross-process locks), so there is nothing to do.
154
+ */
155
+ async teardown() {
156
+ // Nothing to tear down for in-memory storage.
157
+ }
158
+ }
@@ -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,35 @@
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
+ constructor(options: DatasetBackendOptions);
29
+ getMetadata(): Promise<storage.DatasetInfo>;
30
+ drop(): Promise<void>;
31
+ purge(): Promise<void>;
32
+ getData(options?: storage.DatasetBackendListOptions): Promise<storage.PaginatedList<Data>>;
33
+ pushData(items: Data[]): Promise<void>;
34
+ toDatasetInfo(): storage.DatasetInfo;
35
+ }