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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (257) hide show
  1. package/README.md +17 -13
  2. package/autoscaling/autoscaled_pool.d.ts +5 -6
  3. package/autoscaling/autoscaled_pool.js +12 -11
  4. package/autoscaling/client_load_signal.d.ts +25 -0
  5. package/autoscaling/client_load_signal.js +36 -0
  6. package/autoscaling/cpu_load_signal.d.ts +28 -0
  7. package/autoscaling/cpu_load_signal.js +24 -0
  8. package/autoscaling/event_loop_load_signal.d.ts +23 -0
  9. package/autoscaling/event_loop_load_signal.js +35 -0
  10. package/autoscaling/index.d.ts +5 -1
  11. package/autoscaling/index.js +5 -1
  12. package/autoscaling/load_signal.d.ts +99 -0
  13. package/autoscaling/load_signal.js +135 -0
  14. package/autoscaling/memory_load_signal.d.ts +43 -0
  15. package/autoscaling/memory_load_signal.js +102 -0
  16. package/autoscaling/snapshotter.d.ts +35 -72
  17. package/autoscaling/snapshotter.js +78 -181
  18. package/autoscaling/system_status.d.ts +21 -36
  19. package/autoscaling/system_status.js +46 -84
  20. package/configuration.d.ts +88 -228
  21. package/configuration.js +162 -224
  22. package/cookie_utils.d.ts +4 -3
  23. package/cookie_utils.js +20 -13
  24. package/crawlers/context_pipeline.d.ts +70 -0
  25. package/crawlers/context_pipeline.js +122 -0
  26. package/crawlers/crawler_commons.d.ts +20 -30
  27. package/crawlers/crawler_commons.js +12 -21
  28. package/crawlers/crawler_utils.d.ts +2 -3
  29. package/crawlers/crawler_utils.js +1 -2
  30. package/crawlers/error_snapshotter.d.ts +3 -3
  31. package/crawlers/error_snapshotter.js +2 -3
  32. package/crawlers/error_tracker.d.ts +2 -2
  33. package/crawlers/error_tracker.js +0 -1
  34. package/crawlers/index.d.ts +1 -2
  35. package/crawlers/index.js +1 -2
  36. package/crawlers/internals/types.d.ts +7 -0
  37. package/crawlers/internals/types.js +1 -0
  38. package/crawlers/statistics.d.ts +22 -17
  39. package/crawlers/statistics.js +30 -26
  40. package/enqueue_links/enqueue_links.d.ts +44 -22
  41. package/enqueue_links/enqueue_links.js +51 -30
  42. package/enqueue_links/index.d.ts +0 -1
  43. package/enqueue_links/index.js +0 -1
  44. package/enqueue_links/shared.d.ts +25 -9
  45. package/enqueue_links/shared.js +69 -38
  46. package/errors.d.ts +53 -4
  47. package/errors.js +70 -5
  48. package/events/event_manager.d.ts +34 -8
  49. package/events/event_manager.js +8 -10
  50. package/events/index.d.ts +0 -1
  51. package/events/index.js +0 -1
  52. package/events/local_event_manager.d.ts +15 -5
  53. package/events/local_event_manager.js +37 -40
  54. package/index.d.ts +4 -3
  55. package/index.js +3 -2
  56. package/log.d.ts +82 -3
  57. package/log.js +102 -1
  58. package/memory-storage/consts.d.ts +4 -0
  59. package/memory-storage/consts.js +4 -0
  60. package/memory-storage/index.d.ts +1 -0
  61. package/memory-storage/index.js +1 -0
  62. package/memory-storage/memory-storage.d.ts +46 -0
  63. package/memory-storage/memory-storage.js +136 -0
  64. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  65. package/memory-storage/resource-clients/common/base-client.js +6 -0
  66. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  67. package/memory-storage/resource-clients/dataset.js +113 -0
  68. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  69. package/memory-storage/resource-clients/key-value-store.js +203 -0
  70. package/memory-storage/resource-clients/request-queue.d.ts +96 -0
  71. package/memory-storage/resource-clients/request-queue.js +421 -0
  72. package/memory-storage/utils.d.ts +17 -0
  73. package/memory-storage/utils.js +42 -0
  74. package/package.json +12 -10
  75. package/proxy_configuration.d.ts +14 -149
  76. package/proxy_configuration.js +19 -168
  77. package/recoverable_state.d.ts +120 -0
  78. package/recoverable_state.js +141 -0
  79. package/request.d.ts +84 -13
  80. package/request.js +107 -28
  81. package/router.d.ts +117 -15
  82. package/router.js +124 -30
  83. package/serialization.d.ts +0 -1
  84. package/serialization.js +1 -2
  85. package/service_locator.d.ts +156 -0
  86. package/service_locator.js +238 -0
  87. package/session_pool/consts.d.ts +1 -2
  88. package/session_pool/consts.js +1 -2
  89. package/session_pool/errors.d.ts +0 -1
  90. package/session_pool/errors.js +0 -1
  91. package/session_pool/fingerprint.d.ts +9 -0
  92. package/session_pool/fingerprint.js +30 -0
  93. package/session_pool/index.d.ts +0 -2
  94. package/session_pool/index.js +0 -2
  95. package/session_pool/session.d.ts +35 -73
  96. package/session_pool/session.js +46 -99
  97. package/session_pool/session_pool.d.ts +71 -72
  98. package/session_pool/session_pool.js +111 -100
  99. package/storages/access_checking.d.ts +0 -1
  100. package/storages/access_checking.js +5 -2
  101. package/storages/dataset.d.ts +101 -51
  102. package/storages/dataset.js +168 -126
  103. package/storages/index.d.ts +8 -7
  104. package/storages/index.js +6 -7
  105. package/storages/key_value_store.d.ts +165 -36
  106. package/storages/key_value_store.js +269 -122
  107. package/storages/key_value_store_codec.d.ts +32 -0
  108. package/storages/key_value_store_codec.js +113 -0
  109. package/storages/request_dedup_cache.d.ts +23 -0
  110. package/storages/request_dedup_cache.js +48 -0
  111. package/storages/request_list.d.ts +38 -82
  112. package/storages/request_list.js +65 -41
  113. package/storages/request_loader.d.ts +96 -0
  114. package/storages/request_loader.js +1 -0
  115. package/storages/request_manager.d.ts +33 -0
  116. package/storages/request_manager.js +1 -0
  117. package/storages/request_manager_tandem.d.ts +106 -0
  118. package/storages/request_manager_tandem.js +197 -0
  119. package/storages/request_queue.d.ts +303 -46
  120. package/storages/request_queue.js +629 -214
  121. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +28 -24
  122. package/storages/{sitemap_request_list.js → sitemap_request_loader.js} +49 -46
  123. package/storages/storage_instance_manager.d.ts +91 -0
  124. package/storages/storage_instance_manager.js +258 -0
  125. package/storages/storage_stats.d.ts +48 -0
  126. package/storages/storage_stats.js +29 -0
  127. package/storages/utils.d.ts +51 -6
  128. package/storages/utils.js +60 -9
  129. package/system-info/cpu-info.d.ts +67 -0
  130. package/system-info/cpu-info.js +216 -0
  131. package/system-info/memory-info.d.ts +31 -0
  132. package/system-info/memory-info.js +115 -0
  133. package/system-info/ps-tree.d.ts +17 -0
  134. package/system-info/ps-tree.js +144 -0
  135. package/system-info/runtime.d.ts +14 -0
  136. package/system-info/runtime.js +80 -0
  137. package/typedefs.d.ts +1 -2
  138. package/typedefs.js +0 -1
  139. package/validators.d.ts +8 -1
  140. package/validators.js +8 -1
  141. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  142. package/autoscaling/autoscaled_pool.js.map +0 -1
  143. package/autoscaling/index.d.ts.map +0 -1
  144. package/autoscaling/index.js.map +0 -1
  145. package/autoscaling/snapshotter.d.ts.map +0 -1
  146. package/autoscaling/snapshotter.js.map +0 -1
  147. package/autoscaling/system_status.d.ts.map +0 -1
  148. package/autoscaling/system_status.js.map +0 -1
  149. package/configuration.d.ts.map +0 -1
  150. package/configuration.js.map +0 -1
  151. package/cookie_utils.d.ts.map +0 -1
  152. package/cookie_utils.js.map +0 -1
  153. package/crawlers/crawler_commons.d.ts.map +0 -1
  154. package/crawlers/crawler_commons.js.map +0 -1
  155. package/crawlers/crawler_extension.d.ts +0 -12
  156. package/crawlers/crawler_extension.d.ts.map +0 -1
  157. package/crawlers/crawler_extension.js +0 -14
  158. package/crawlers/crawler_extension.js.map +0 -1
  159. package/crawlers/crawler_utils.d.ts.map +0 -1
  160. package/crawlers/crawler_utils.js.map +0 -1
  161. package/crawlers/error_snapshotter.d.ts.map +0 -1
  162. package/crawlers/error_snapshotter.js.map +0 -1
  163. package/crawlers/error_tracker.d.ts.map +0 -1
  164. package/crawlers/error_tracker.js.map +0 -1
  165. package/crawlers/index.d.ts.map +0 -1
  166. package/crawlers/index.js.map +0 -1
  167. package/crawlers/statistics.d.ts.map +0 -1
  168. package/crawlers/statistics.js.map +0 -1
  169. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  170. package/enqueue_links/enqueue_links.js.map +0 -1
  171. package/enqueue_links/index.d.ts.map +0 -1
  172. package/enqueue_links/index.js.map +0 -1
  173. package/enqueue_links/shared.d.ts.map +0 -1
  174. package/enqueue_links/shared.js.map +0 -1
  175. package/errors.d.ts.map +0 -1
  176. package/errors.js.map +0 -1
  177. package/events/event_manager.d.ts.map +0 -1
  178. package/events/event_manager.js.map +0 -1
  179. package/events/index.d.ts.map +0 -1
  180. package/events/index.js.map +0 -1
  181. package/events/local_event_manager.d.ts.map +0 -1
  182. package/events/local_event_manager.js.map +0 -1
  183. package/http_clients/base-http-client.d.ts +0 -134
  184. package/http_clients/base-http-client.d.ts.map +0 -1
  185. package/http_clients/base-http-client.js +0 -33
  186. package/http_clients/base-http-client.js.map +0 -1
  187. package/http_clients/form-data-like.d.ts +0 -67
  188. package/http_clients/form-data-like.d.ts.map +0 -1
  189. package/http_clients/form-data-like.js +0 -5
  190. package/http_clients/form-data-like.js.map +0 -1
  191. package/http_clients/got-scraping-http-client.d.ts +0 -15
  192. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  193. package/http_clients/got-scraping-http-client.js +0 -69
  194. package/http_clients/got-scraping-http-client.js.map +0 -1
  195. package/http_clients/index.d.ts +0 -3
  196. package/http_clients/index.d.ts.map +0 -1
  197. package/http_clients/index.js +0 -3
  198. package/http_clients/index.js.map +0 -1
  199. package/index.d.ts.map +0 -1
  200. package/index.js.map +0 -1
  201. package/log.d.ts.map +0 -1
  202. package/log.js.map +0 -1
  203. package/proxy_configuration.d.ts.map +0 -1
  204. package/proxy_configuration.js.map +0 -1
  205. package/request.d.ts.map +0 -1
  206. package/request.js.map +0 -1
  207. package/router.d.ts.map +0 -1
  208. package/router.js.map +0 -1
  209. package/serialization.d.ts.map +0 -1
  210. package/serialization.js.map +0 -1
  211. package/session_pool/consts.d.ts.map +0 -1
  212. package/session_pool/consts.js.map +0 -1
  213. package/session_pool/errors.d.ts.map +0 -1
  214. package/session_pool/errors.js.map +0 -1
  215. package/session_pool/events.d.ts +0 -3
  216. package/session_pool/events.d.ts.map +0 -1
  217. package/session_pool/events.js +0 -3
  218. package/session_pool/events.js.map +0 -1
  219. package/session_pool/index.d.ts.map +0 -1
  220. package/session_pool/index.js.map +0 -1
  221. package/session_pool/session.d.ts.map +0 -1
  222. package/session_pool/session.js.map +0 -1
  223. package/session_pool/session_pool.d.ts.map +0 -1
  224. package/session_pool/session_pool.js.map +0 -1
  225. package/storages/access_checking.d.ts.map +0 -1
  226. package/storages/access_checking.js.map +0 -1
  227. package/storages/dataset.d.ts.map +0 -1
  228. package/storages/dataset.js.map +0 -1
  229. package/storages/index.d.ts.map +0 -1
  230. package/storages/index.js.map +0 -1
  231. package/storages/key_value_store.d.ts.map +0 -1
  232. package/storages/key_value_store.js.map +0 -1
  233. package/storages/request_list.d.ts.map +0 -1
  234. package/storages/request_list.js.map +0 -1
  235. package/storages/request_provider.d.ts +0 -307
  236. package/storages/request_provider.d.ts.map +0 -1
  237. package/storages/request_provider.js +0 -555
  238. package/storages/request_provider.js.map +0 -1
  239. package/storages/request_queue.d.ts.map +0 -1
  240. package/storages/request_queue.js.map +0 -1
  241. package/storages/request_queue_v2.d.ts +0 -87
  242. package/storages/request_queue_v2.d.ts.map +0 -1
  243. package/storages/request_queue_v2.js +0 -438
  244. package/storages/request_queue_v2.js.map +0 -1
  245. package/storages/sitemap_request_list.d.ts.map +0 -1
  246. package/storages/sitemap_request_list.js.map +0 -1
  247. package/storages/storage_manager.d.ts +0 -58
  248. package/storages/storage_manager.d.ts.map +0 -1
  249. package/storages/storage_manager.js +0 -105
  250. package/storages/storage_manager.js.map +0 -1
  251. package/storages/utils.d.ts.map +0 -1
  252. package/storages/utils.js.map +0 -1
  253. package/tsconfig.build.tsbuildinfo +0 -1
  254. package/typedefs.d.ts.map +0 -1
  255. package/typedefs.js.map +0 -1
  256. package/validators.d.ts.map +0 -1
  257. package/validators.js.map +0 -1
package/log.js CHANGED
@@ -1,3 +1,104 @@
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
+ options;
34
+ warningsLogged = new Set();
35
+ constructor(options = {}) {
36
+ this.options = options;
37
+ }
38
+ getOptions() {
39
+ return this.options;
40
+ }
41
+ setOptions(options) {
42
+ this.options = { ...this.options, ...options };
43
+ }
44
+ child(options) {
45
+ return this.createChild(options);
46
+ }
47
+ error(message, data) {
48
+ this.logWithLevel(LogLevel.ERROR, message, data);
49
+ }
50
+ exception(exception, message, data) {
51
+ this.logWithLevel(LogLevel.ERROR, `${message}: ${exception.message}`, {
52
+ ...data,
53
+ stack: exception.stack,
54
+ exception,
55
+ });
56
+ }
57
+ softFail(message, data) {
58
+ this.logWithLevel(LogLevel.SOFT_FAIL, message, data);
59
+ }
60
+ warning(message, data) {
61
+ this.logWithLevel(LogLevel.WARNING, message, data);
62
+ }
63
+ warningOnce(message) {
64
+ if (!this.warningsLogged.has(message)) {
65
+ this.warningsLogged.add(message);
66
+ this.warning(message);
67
+ }
68
+ }
69
+ info(message, data) {
70
+ this.logWithLevel(LogLevel.INFO, message, data);
71
+ }
72
+ debug(message, data) {
73
+ this.logWithLevel(LogLevel.DEBUG, message, data);
74
+ }
75
+ perf(message, data) {
76
+ this.logWithLevel(LogLevel.PERF, `[PERF] ${message}`, data);
77
+ }
78
+ deprecated(message) {
79
+ this.warningOnce(`[DEPRECATED] ${message}`);
80
+ }
81
+ }
82
+ /**
83
+ * Adapter that wraps `@apify/log`'s {@link Log} instance to implement the {@link CrawleeLogger} interface.
84
+ *
85
+ * This is the default logger used by Crawlee when no custom logger is configured.
86
+ * Users who want to use a different logging library should implement {@link BaseCrawleeLogger} directly.
87
+ */
88
+ export class ApifyLogAdapter extends BaseCrawleeLogger {
89
+ apifyLog;
90
+ constructor(apifyLog, options) {
91
+ super(options ?? {});
92
+ this.apifyLog = apifyLog;
93
+ }
94
+ logWithLevel(level, message, data) {
95
+ this.apifyLog.internal(level, message, data);
96
+ }
97
+ createChild(options) {
98
+ return new ApifyLogAdapter(this.apifyLog.child({ prefix: options.prefix ?? null }), {
99
+ ...this.getOptions(),
100
+ ...options,
101
+ });
102
+ }
103
+ }
2
104
  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,46 @@
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
+ readonly logger?: CrawleeLogger;
14
+ /**
15
+ * Unique per-instance cache partition key. Mirrors the way `FileSystemStorageBackend` partitions its
16
+ * cache by storage directory: two distinct `MemoryStorageBackend` instances must not share cached backends.
17
+ */
18
+ private readonly instanceCacheKey;
19
+ readonly keyValueStoreBackendCache: KeyValueStoreBackend[];
20
+ readonly datasetBackendCache: DatasetBackend[];
21
+ readonly requestQueueBackendCache: RequestQueueBackend[];
22
+ constructor(options?: MemoryStorageOptions);
23
+ /**
24
+ * Return a per-instance unique cache key so that distinct `MemoryStorageBackend` instances get separate
25
+ * cache partitions in the storage backend cache.
26
+ */
27
+ getStorageBackendCacheKey(): string;
28
+ private static resolveStorageKey;
29
+ createDatasetBackend(options?: storage.StorageIdentifier): Promise<storage.DatasetBackend>;
30
+ createKeyValueStoreBackend(options?: storage.StorageIdentifier): Promise<storage.KeyValueStoreBackend>;
31
+ createRequestQueueBackend(options?: storage.StorageIdentifier): Promise<RequestQueueBackend>;
32
+ storageExists(id: string, type: 'Dataset' | 'KeyValueStore' | 'RequestQueue'): Promise<boolean>;
33
+ /**
34
+ * Cleans up the default storages before the run starts. For the in-memory storage this simply
35
+ * resets the in-memory state of the cached default dataset, key-value store and request queue.
36
+ *
37
+ * As with `FileSystemStorageBackend`, the run's input (the `INPUT` key in the default key-value
38
+ * store) is preserved — only the rest of the default storages is cleared.
39
+ */
40
+ purge(): Promise<void>;
41
+ /**
42
+ * This method should be called at the end of the process. The in-memory storage holds no resources
43
+ * that outlive the process (no file handles, no cross-process locks), so there is nothing to do.
44
+ */
45
+ teardown(): Promise<void>;
46
+ }
@@ -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
+ name?: string;
18
+ /**
19
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
20
+ * storages, this is the alias string. Falls back to id.
21
+ */
22
+ cacheKey: string;
23
+ createdAt: Date;
24
+ accessedAt: Date;
25
+ modifiedAt: Date;
26
+ itemCount: number;
27
+ private readonly datasetEntries;
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
+ }
@@ -0,0 +1,113 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { s } from '@sapphire/shapeshift';
3
+ import { BaseClient } from './common/base-client.js';
4
+ /**
5
+ * This is what API returns in the x-apify-pagination-limit
6
+ * header when no limit query parameter is used.
7
+ */
8
+ const LIST_ITEMS_LIMIT = 999_999_999_999;
9
+ /**
10
+ * Number of characters of the dataset item entry names.
11
+ * E.g.: 000000019 - 9 digits
12
+ */
13
+ const LOCAL_ENTRY_NAME_DIGITS = 9;
14
+ export class DatasetBackend extends BaseClient {
15
+ name;
16
+ /**
17
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
18
+ * storages, this is the alias string. Falls back to id.
19
+ */
20
+ cacheKey;
21
+ createdAt = new Date();
22
+ accessedAt = new Date();
23
+ modifiedAt = new Date();
24
+ itemCount = 0;
25
+ datasetEntries = new Map();
26
+ storageBackend;
27
+ constructor(options) {
28
+ super(options.id ?? randomUUID());
29
+ this.name = options.name;
30
+ this.cacheKey = options.cacheKey ?? this.name ?? this.id;
31
+ this.storageBackend = options.storageBackend;
32
+ }
33
+ async getMetadata() {
34
+ this.updateTimestamps(false);
35
+ return this.toDatasetInfo();
36
+ }
37
+ async drop() {
38
+ const storeIndex = this.storageBackend.datasetBackendCache.findIndex((store) => store.id === this.id);
39
+ if (storeIndex !== -1) {
40
+ const [oldBackend] = this.storageBackend.datasetBackendCache.splice(storeIndex, 1);
41
+ oldBackend.itemCount = 0;
42
+ oldBackend.datasetEntries.clear();
43
+ }
44
+ }
45
+ async purge() {
46
+ this.itemCount = 0;
47
+ this.datasetEntries.clear();
48
+ this.updateTimestamps(true);
49
+ }
50
+ getData(options = {}) {
51
+ const { desc, limit, offset } = s
52
+ .object({
53
+ desc: s.boolean().optional(),
54
+ limit: s.number().int().optional(),
55
+ offset: s.number().int().optional(),
56
+ })
57
+ .parse(options);
58
+ return this.getDataPage({
59
+ desc,
60
+ offset: offset ?? 0,
61
+ limit: Math.min(limit ?? LIST_ITEMS_LIMIT, LIST_ITEMS_LIMIT),
62
+ });
63
+ }
64
+ async getDataPage(options = {}) {
65
+ const { limit = LIST_ITEMS_LIMIT, offset = 0, desc } = options;
66
+ const [start, end] = this.getStartAndEndIndexes(desc ? Math.max(this.itemCount - offset - limit, 0) : offset, limit);
67
+ const items = [];
68
+ for (let idx = start; idx < end; idx++) {
69
+ const entryNumber = this.generateLocalEntryName(idx);
70
+ items.push(this.datasetEntries.get(entryNumber));
71
+ }
72
+ this.updateTimestamps(false);
73
+ return {
74
+ count: items.length,
75
+ desc: desc ?? false,
76
+ items: desc ? items.reverse() : items,
77
+ limit,
78
+ offset,
79
+ total: this.itemCount,
80
+ };
81
+ }
82
+ async pushData(items) {
83
+ for (const entry of items) {
84
+ const idx = this.generateLocalEntryName(++this.itemCount);
85
+ this.datasetEntries.set(idx, JSON.parse(JSON.stringify(entry)));
86
+ }
87
+ this.updateTimestamps(true);
88
+ }
89
+ toDatasetInfo() {
90
+ return {
91
+ id: this.id,
92
+ accessedAt: this.accessedAt,
93
+ createdAt: this.createdAt,
94
+ itemCount: this.itemCount,
95
+ modifiedAt: this.modifiedAt,
96
+ name: this.name,
97
+ };
98
+ }
99
+ generateLocalEntryName(idx) {
100
+ return idx.toString().padStart(LOCAL_ENTRY_NAME_DIGITS, '0');
101
+ }
102
+ getStartAndEndIndexes(offset, limit = this.itemCount) {
103
+ const start = offset + 1;
104
+ const end = Math.min(offset + limit, this.itemCount) + 1;
105
+ return [start, end];
106
+ }
107
+ updateTimestamps(hasBeenModified) {
108
+ this.accessedAt = new Date();
109
+ if (hasBeenModified) {
110
+ this.modifiedAt = new Date();
111
+ }
112
+ }
113
+ }
@@ -0,0 +1,63 @@
1
+ import type * as storage from '@crawlee/types';
2
+ import type { MemoryStorageBackend } from '../memory-storage.js';
3
+ import { BaseClient } from './common/base-client.js';
4
+ export interface KeyValueStoreBackendOptions {
5
+ name?: string;
6
+ id?: string;
7
+ /**
8
+ * The key used for cache lookup. When provided, takes precedence over `name` and `id`.
9
+ * This allows alias-opened storages to have a cache key that differs from their
10
+ * metadata `name` (which is `undefined` for unnamed storages).
11
+ */
12
+ cacheKey?: string;
13
+ storageBackend: MemoryStorageBackend;
14
+ }
15
+ export interface InternalKeyRecord {
16
+ key: string;
17
+ value: Buffer;
18
+ contentType?: string;
19
+ extension: string;
20
+ }
21
+ export declare class KeyValueStoreBackend extends BaseClient implements storage.KeyValueStoreBackend {
22
+ name?: string;
23
+ /**
24
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
25
+ * storages, this is the alias string. Falls back to id.
26
+ */
27
+ cacheKey: string;
28
+ createdAt: Date;
29
+ accessedAt: Date;
30
+ modifiedAt: Date;
31
+ private readonly keyValueEntries;
32
+ private readonly storageBackend;
33
+ constructor(options: KeyValueStoreBackendOptions);
34
+ getMetadata(): Promise<storage.KeyValueStoreInfo>;
35
+ drop(): Promise<void>;
36
+ purge(): Promise<void>;
37
+ /**
38
+ * Purges every record except the run's input. Used by {@link MemoryStorageBackend.purge} for the
39
+ * default key-value store, mirroring `FileSystemStorageBackend`, which preserves `INPUT` (and its
40
+ * extension variants) when purging the default store. The in-memory key has no extension, so we
41
+ * preserve the bare `INPUT` key only.
42
+ */
43
+ purgeExceptInput(): Promise<void>;
44
+ listKeys(options?: storage.KeyValueStoreListKeysOptions): Promise<storage.KeyValueStoreListKeysResult>;
45
+ /**
46
+ * In-memory records are not file-backed, so there is no public file URL to return.
47
+ * Always resolves to `undefined`.
48
+ * @param key The key of the record to generate the public URL for.
49
+ */
50
+ getPublicUrl(key: string): Promise<string | undefined>;
51
+ /**
52
+ * Tests whether a record with the given key exists in the key-value store without retrieving its value.
53
+ *
54
+ * @param key The queried record key.
55
+ * @returns `true` if the record exists, `false` if it does not.
56
+ */
57
+ recordExists(key: string): Promise<boolean>;
58
+ getValue(key: string): Promise<storage.KeyValueStoreRecord | undefined>;
59
+ setValue(record: storage.KeyValueStoreInputRecord): Promise<void>;
60
+ deleteValue(key: string): Promise<void>;
61
+ toKeyValueStoreInfo(): storage.KeyValueStoreInfo;
62
+ private updateTimestamps;
63
+ }