@crawlee/core 4.0.0-beta.28 → 4.0.0-beta.280

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 (266) 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 +75 -167
  5. package/configuration.js +164 -140
  6. package/debug.d.ts +36 -0
  7. package/debug.js +70 -0
  8. package/errors.d.ts +40 -19
  9. package/errors.js +52 -30
  10. package/events/{event_manager.d.ts → event-manager.d.ts} +29 -6
  11. package/events/{event_manager.js → event-manager.js} +10 -9
  12. package/events/index.d.ts +3 -3
  13. package/events/index.js +2 -3
  14. package/events/{local_event_manager.d.ts → local-event-manager.d.ts} +3 -10
  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 -13
  19. package/index.js +10 -12
  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 +108 -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 +23 -23
  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 -101
  50. package/request.js +139 -249
  51. package/serialization.d.ts +0 -1
  52. package/serialization.js +18 -18
  53. package/{service_locator.d.ts → service-locator.d.ts} +66 -37
  54. package/service-locator.js +255 -0
  55. package/storages/batched-adds.d.ts +39 -0
  56. package/storages/batched-adds.js +81 -0
  57. package/storages/dataset.d.ts +105 -58
  58. package/storages/dataset.js +292 -151
  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} +32 -171
  68. package/storages/{request_list.js → request-list.js} +276 -253
  69. package/storages/request-loader.d.ts +127 -0
  70. package/storages/request-loader.js +34 -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} +127 -161
  76. package/storages/request-queue.js +871 -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 -17
  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 -298
  100. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  101. package/autoscaling/autoscaled_pool.js +0 -527
  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 -179
  108. package/autoscaling/snapshotter.d.ts.map +0 -1
  109. package/autoscaling/snapshotter.js +0 -279
  110. package/autoscaling/snapshotter.js.map +0 -1
  111. package/autoscaling/system_status.d.ts +0 -178
  112. package/autoscaling/system_status.d.ts.map +0 -1
  113. package/autoscaling/system_status.js +0 -168
  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 -204
  150. package/crawlers/statistics.d.ts.map +0 -1
  151. package/crawlers/statistics.js +0 -350
  152. package/crawlers/statistics.js.map +0 -1
  153. package/enqueue_links/enqueue_links.d.ts +0 -254
  154. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  155. package/enqueue_links/enqueue_links.js +0 -268
  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 -84
  162. package/enqueue_links/shared.d.ts.map +0 -1
  163. package/enqueue_links/shared.js +0 -219
  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.map +0 -1
  168. package/events/event_manager.js.map +0 -1
  169. package/events/index.d.ts.map +0 -1
  170. package/events/index.js.map +0 -1
  171. package/events/local_event_manager.d.ts.map +0 -1
  172. package/events/local_event_manager.js +0 -93
  173. package/events/local_event_manager.js.map +0 -1
  174. package/index.d.ts.map +0 -1
  175. package/index.js.map +0 -1
  176. package/log.d.ts.map +0 -1
  177. package/log.js.map +0 -1
  178. package/proxy_configuration.d.ts +0 -169
  179. package/proxy_configuration.d.ts.map +0 -1
  180. package/proxy_configuration.js +0 -247
  181. package/proxy_configuration.js.map +0 -1
  182. package/recoverable_state.d.ts +0 -122
  183. package/recoverable_state.d.ts.map +0 -1
  184. package/recoverable_state.js +0 -138
  185. package/recoverable_state.js.map +0 -1
  186. package/request.d.ts.map +0 -1
  187. package/request.js.map +0 -1
  188. package/router.d.ts +0 -134
  189. package/router.d.ts.map +0 -1
  190. package/router.js +0 -164
  191. package/router.js.map +0 -1
  192. package/serialization.d.ts.map +0 -1
  193. package/serialization.js.map +0 -1
  194. package/service_locator.d.ts.map +0 -1
  195. package/service_locator.js +0 -252
  196. package/service_locator.js.map +0 -1
  197. package/session_pool/consts.d.ts +0 -4
  198. package/session_pool/consts.d.ts.map +0 -1
  199. package/session_pool/consts.js +0 -4
  200. package/session_pool/consts.js.map +0 -1
  201. package/session_pool/errors.d.ts +0 -8
  202. package/session_pool/errors.d.ts.map +0 -1
  203. package/session_pool/errors.js +0 -12
  204. package/session_pool/errors.js.map +0 -1
  205. package/session_pool/events.d.ts +0 -3
  206. package/session_pool/events.d.ts.map +0 -1
  207. package/session_pool/events.js +0 -3
  208. package/session_pool/events.js.map +0 -1
  209. package/session_pool/index.d.ts +0 -6
  210. package/session_pool/index.d.ts.map +0 -1
  211. package/session_pool/index.js +0 -6
  212. package/session_pool/index.js.map +0 -1
  213. package/session_pool/session.d.ts +0 -186
  214. package/session_pool/session.d.ts.map +0 -1
  215. package/session_pool/session.js +0 -278
  216. package/session_pool/session.js.map +0 -1
  217. package/session_pool/session_pool.d.ts +0 -256
  218. package/session_pool/session_pool.d.ts.map +0 -1
  219. package/session_pool/session_pool.js +0 -386
  220. package/session_pool/session_pool.js.map +0 -1
  221. package/storages/access_checking.d.ts +0 -13
  222. package/storages/access_checking.d.ts.map +0 -1
  223. package/storages/access_checking.js +0 -14
  224. package/storages/access_checking.js.map +0 -1
  225. package/storages/dataset.d.ts.map +0 -1
  226. package/storages/dataset.js.map +0 -1
  227. package/storages/index.d.ts.map +0 -1
  228. package/storages/index.js.map +0 -1
  229. package/storages/key_value_store.d.ts.map +0 -1
  230. package/storages/key_value_store.js +0 -513
  231. package/storages/key_value_store.js.map +0 -1
  232. package/storages/request_list.d.ts.map +0 -1
  233. package/storages/request_list.js.map +0 -1
  234. package/storages/request_list_adapter.d.ts +0 -58
  235. package/storages/request_list_adapter.d.ts.map +0 -1
  236. package/storages/request_list_adapter.js +0 -81
  237. package/storages/request_list_adapter.js.map +0 -1
  238. package/storages/request_manager_tandem.d.ts +0 -68
  239. package/storages/request_manager_tandem.d.ts.map +0 -1
  240. package/storages/request_manager_tandem.js +0 -124
  241. package/storages/request_manager_tandem.js.map +0 -1
  242. package/storages/request_provider.d.ts.map +0 -1
  243. package/storages/request_provider.js +0 -592
  244. package/storages/request_provider.js.map +0 -1
  245. package/storages/request_queue.d.ts +0 -128
  246. package/storages/request_queue.d.ts.map +0 -1
  247. package/storages/request_queue.js +0 -320
  248. package/storages/request_queue.js.map +0 -1
  249. package/storages/request_queue_v2.d.ts +0 -87
  250. package/storages/request_queue_v2.d.ts.map +0 -1
  251. package/storages/request_queue_v2.js +0 -437
  252. package/storages/request_queue_v2.js.map +0 -1
  253. package/storages/sitemap_request_list.d.ts +0 -245
  254. package/storages/sitemap_request_list.d.ts.map +0 -1
  255. package/storages/sitemap_request_list.js +0 -431
  256. package/storages/sitemap_request_list.js.map +0 -1
  257. package/storages/storage_manager.d.ts +0 -60
  258. package/storages/storage_manager.d.ts.map +0 -1
  259. package/storages/storage_manager.js +0 -95
  260. package/storages/storage_manager.js.map +0 -1
  261. package/storages/utils.d.ts.map +0 -1
  262. package/storages/utils.js.map +0 -1
  263. package/typedefs.d.ts.map +0 -1
  264. package/typedefs.js.map +0 -1
  265. package/validators.d.ts.map +0 -1
  266. package/validators.js.map +0 -1
@@ -0,0 +1,108 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { parseArgument, schemas } from '@crawlee/utils/internal';
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
+ if (this.#storageBackend.evictBackend('Dataset', this.id)) {
39
+ this.itemCount = 0;
40
+ this.#datasetEntries.clear();
41
+ }
42
+ }
43
+ async purge() {
44
+ this.itemCount = 0;
45
+ this.#datasetEntries.clear();
46
+ this.#updateTimestamps(true);
47
+ }
48
+ getData(options = {}) {
49
+ const { desc, limit, offset } = parseArgument(options, schemas.datasetListItemsOptions);
50
+ return this.#getDataPage({
51
+ desc,
52
+ offset: offset ?? 0,
53
+ limit: Math.min(limit ?? LIST_ITEMS_LIMIT, LIST_ITEMS_LIMIT),
54
+ });
55
+ }
56
+ async #getDataPage(options = {}) {
57
+ const { limit = LIST_ITEMS_LIMIT, offset = 0, desc } = options;
58
+ // In descending order, the window ends `offset` items before the newest one, so it can be shorter than `limit`.
59
+ const windowStart = desc ? Math.max(this.itemCount - offset - limit, 0) : offset;
60
+ const windowEnd = desc ? Math.max(this.itemCount - offset, 0) : offset + limit;
61
+ const [start, end] = this.#getStartAndEndIndexes(windowStart, windowEnd - windowStart);
62
+ const items = [];
63
+ for (let idx = start; idx < end; idx++) {
64
+ const entryNumber = this.#generateLocalEntryName(idx);
65
+ items.push(this.#datasetEntries.get(entryNumber));
66
+ }
67
+ this.#updateTimestamps(false);
68
+ return {
69
+ count: items.length,
70
+ desc: desc ?? false,
71
+ items: desc ? items.reverse() : items,
72
+ limit,
73
+ offset,
74
+ total: this.itemCount,
75
+ };
76
+ }
77
+ async pushData(items) {
78
+ for (const entry of items) {
79
+ const idx = this.#generateLocalEntryName(++this.itemCount);
80
+ this.#datasetEntries.set(idx, JSON.parse(JSON.stringify(entry)));
81
+ }
82
+ this.#updateTimestamps(true);
83
+ }
84
+ toDatasetInfo() {
85
+ return {
86
+ id: this.id,
87
+ accessedAt: this.accessedAt,
88
+ createdAt: this.createdAt,
89
+ itemCount: this.itemCount,
90
+ modifiedAt: this.modifiedAt,
91
+ name: this.name,
92
+ };
93
+ }
94
+ #generateLocalEntryName(idx) {
95
+ return idx.toString().padStart(LOCAL_ENTRY_NAME_DIGITS, '0');
96
+ }
97
+ #getStartAndEndIndexes(offset, limit = this.itemCount) {
98
+ const start = offset + 1;
99
+ const end = Math.min(offset + limit, this.itemCount) + 1;
100
+ return [start, end];
101
+ }
102
+ #updateTimestamps(hasBeenModified) {
103
+ this.accessedAt = new Date();
104
+ if (hasBeenModified) {
105
+ this.modifiedAt = new Date();
106
+ }
107
+ }
108
+ }
@@ -0,0 +1,54 @@
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
+ #private;
23
+ name?: string;
24
+ /**
25
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
26
+ * storages, this is the alias string. Falls back to id.
27
+ */
28
+ cacheKey: string;
29
+ createdAt: Date;
30
+ accessedAt: Date;
31
+ modifiedAt: Date;
32
+ constructor(options: KeyValueStoreBackendOptions);
33
+ getMetadata(): Promise<storage.KeyValueStoreInfo>;
34
+ drop(): Promise<void>;
35
+ purge(): Promise<void>;
36
+ listKeys(options?: storage.KeyValueStoreListKeysOptions): Promise<storage.KeyValueStoreListKeysResult>;
37
+ /**
38
+ * In-memory records are not file-backed, so there is no public file URL to return.
39
+ * Always resolves to `undefined`.
40
+ * @param key The key of the record to generate the public URL for.
41
+ */
42
+ getPublicUrl(key: string): Promise<string | undefined>;
43
+ /**
44
+ * Tests whether a record with the given key exists in the key-value store without retrieving its value.
45
+ *
46
+ * @param key The queried record key.
47
+ * @returns `true` if the record exists, `false` if it does not.
48
+ */
49
+ recordExists(key: string): Promise<boolean>;
50
+ getValue(key: string): Promise<storage.KeyValueStoreRecord | undefined>;
51
+ setValue(record: storage.KeyValueStoreInputRecord): Promise<void>;
52
+ deleteValue(key: string): Promise<void>;
53
+ toKeyValueStoreInfo(): storage.KeyValueStoreInfo;
54
+ }
@@ -0,0 +1,179 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { parseArgument, schemas } from '@crawlee/utils/internal';
3
+ import { z } from 'zod';
4
+ import { isStream, toBuffer } from '../utils.js';
5
+ import { BaseClient } from './common/base-client.js';
6
+ import mime from 'mime-types';
7
+ const DEFAULT_LOCAL_FILE_EXTENSION = 'bin';
8
+ const keySchema = z.string();
9
+ const inputRecordSchema = z.object({
10
+ key: z.string().min(1),
11
+ value: z.union([
12
+ z.null(),
13
+ z.string(),
14
+ z.number(),
15
+ z.instanceof(Buffer),
16
+ z.instanceof(ArrayBuffer),
17
+ schemas.typedArray,
18
+ // only checks the value is an actual object, not null, nor array
19
+ schemas.plainObject,
20
+ ]),
21
+ contentType: z.string().min(1).optional(),
22
+ });
23
+ export class KeyValueStoreBackend extends BaseClient {
24
+ name;
25
+ /**
26
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
27
+ * storages, this is the alias string. Falls back to id.
28
+ */
29
+ cacheKey;
30
+ createdAt = new Date();
31
+ accessedAt = new Date();
32
+ modifiedAt = new Date();
33
+ #keyValueEntries = new Map();
34
+ #storageBackend;
35
+ constructor(options) {
36
+ super(options.id ?? randomUUID());
37
+ this.name = options.name;
38
+ this.cacheKey = options.cacheKey ?? this.name ?? this.id;
39
+ this.#storageBackend = options.storageBackend;
40
+ }
41
+ async getMetadata() {
42
+ this.#updateTimestamps(false);
43
+ return this.toKeyValueStoreInfo();
44
+ }
45
+ async drop() {
46
+ if (this.#storageBackend.evictBackend('KeyValueStore', this.id)) {
47
+ this.#keyValueEntries.clear();
48
+ }
49
+ }
50
+ async purge() {
51
+ this.#keyValueEntries.clear();
52
+ this.#updateTimestamps(true);
53
+ }
54
+ async listKeys(options = {}) {
55
+ const { prefix, exclusiveStartKey, limit } = parseArgument(options, schemas.keyValueStoreListKeysOptions);
56
+ const items = [];
57
+ for (const record of this.#keyValueEntries.values()) {
58
+ const size = Buffer.byteLength(record.value);
59
+ items.push({
60
+ key: record.key,
61
+ size,
62
+ contentType: record.contentType ?? 'application/octet-stream',
63
+ });
64
+ }
65
+ // Lexically sort to emulate API.
66
+ items.sort((a, b) => a.key.localeCompare(b.key));
67
+ let filteredItems = items.filter((item) => !prefix || item.key.startsWith(prefix));
68
+ if (exclusiveStartKey) {
69
+ const keyPos = filteredItems.findIndex((item) => item.key === exclusiveStartKey);
70
+ if (keyPos === -1) {
71
+ throw new Error(`exclusiveStartKey "${exclusiveStartKey}" was not found in the key-value store. ` +
72
+ `This is likely a bug — the key may have been deleted between paginated listKeys calls.`);
73
+ }
74
+ filteredItems = filteredItems.slice(keyPos + 1);
75
+ }
76
+ const isTruncated = limit !== undefined && filteredItems.length > limit;
77
+ const pageItems = isTruncated ? filteredItems.slice(0, limit) : filteredItems;
78
+ const nextExclusiveStartKey = isTruncated ? pageItems[pageItems.length - 1].key : undefined;
79
+ this.#updateTimestamps(false);
80
+ return {
81
+ items: pageItems,
82
+ count: pageItems.length,
83
+ limit: limit ?? pageItems.length,
84
+ exclusiveStartKey,
85
+ isTruncated,
86
+ nextExclusiveStartKey,
87
+ };
88
+ }
89
+ /**
90
+ * In-memory records are not file-backed, so there is no public file URL to return.
91
+ * Always resolves to `undefined`.
92
+ * @param key The key of the record to generate the public URL for.
93
+ */
94
+ async getPublicUrl(key) {
95
+ parseArgument(key, keySchema);
96
+ return undefined;
97
+ }
98
+ /**
99
+ * Tests whether a record with the given key exists in the key-value store without retrieving its value.
100
+ *
101
+ * @param key The queried record key.
102
+ * @returns `true` if the record exists, `false` if it does not.
103
+ */
104
+ async recordExists(key) {
105
+ parseArgument(key, keySchema);
106
+ return this.#keyValueEntries.has(key);
107
+ }
108
+ async getValue(key) {
109
+ parseArgument(key, keySchema);
110
+ const entry = this.#keyValueEntries.get(key);
111
+ if (!entry) {
112
+ return undefined;
113
+ }
114
+ // Return raw bytes + verbatim content type. Parsing is the frontend's job (see the
115
+ // KeyValueStore codec). The mime fallback reconstructs the content type for on-disk records.
116
+ const record = {
117
+ key: entry.key,
118
+ value: entry.value,
119
+ // mime.contentType returns `false` for unknown extensions; fall back to undefined so the
120
+ // frontend treats it as "no content type" rather than a bogus value.
121
+ contentType: entry.contentType ?? (mime.contentType(entry.extension) || undefined),
122
+ };
123
+ this.#updateTimestamps(false);
124
+ return record;
125
+ }
126
+ async setValue(record) {
127
+ parseArgument(record, inputRecordSchema);
128
+ const { key } = record;
129
+ let { value } = record;
130
+ // The frontend (KeyValueStore codec) serializes the value and resolves its content type
131
+ // before it reaches the backend. We only need it here for on-disk extension bookkeeping.
132
+ const contentType = record.contentType ?? 'application/octet-stream';
133
+ const extension = mime.extension(contentType) || DEFAULT_LOCAL_FILE_EXTENSION;
134
+ // Draining a stream into a Buffer for storage is the backend's responsibility.
135
+ if (isStream(value)) {
136
+ const chunks = [];
137
+ for await (const chunk of value) {
138
+ chunks.push(chunk);
139
+ }
140
+ value = Buffer.concat(chunks);
141
+ }
142
+ // This backend is a byte transport: it stores and returns raw bytes regardless of the input
143
+ // shape. Streams were drained above; encode strings to UTF-8 bytes and normalize
144
+ // ArrayBuffer / typed-array views to a Buffer over the same memory.
145
+ const normalizedValue = typeof value === 'string'
146
+ ? Buffer.from(value, 'utf-8')
147
+ : toBuffer(value);
148
+ const normalizedRecord = {
149
+ extension,
150
+ key,
151
+ value: normalizedValue,
152
+ contentType,
153
+ };
154
+ this.#keyValueEntries.set(key, normalizedRecord);
155
+ this.#updateTimestamps(true);
156
+ }
157
+ async deleteValue(key) {
158
+ parseArgument(key, keySchema);
159
+ if (this.#keyValueEntries.has(key)) {
160
+ this.#keyValueEntries.delete(key);
161
+ this.#updateTimestamps(true);
162
+ }
163
+ }
164
+ toKeyValueStoreInfo() {
165
+ return {
166
+ id: this.id,
167
+ name: this.name,
168
+ accessedAt: this.accessedAt,
169
+ createdAt: this.createdAt,
170
+ modifiedAt: this.modifiedAt,
171
+ };
172
+ }
173
+ #updateTimestamps(hasBeenModified) {
174
+ this.accessedAt = new Date();
175
+ if (hasBeenModified) {
176
+ this.modifiedAt = new Date();
177
+ }
178
+ }
179
+ }
@@ -0,0 +1,55 @@
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 RequestQueueBackendOptions {
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 InternalRequest {
16
+ id: string;
17
+ orderNo: number | null;
18
+ url: string;
19
+ uniqueKey: string;
20
+ method: storage.RequestSchema['method'];
21
+ retryCount: number;
22
+ json: string;
23
+ }
24
+ export declare class RequestQueueBackend extends BaseClient implements storage.RequestQueueBackend {
25
+ #private;
26
+ name?: string;
27
+ /**
28
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
29
+ * storages, this is the alias string. Falls back to id.
30
+ */
31
+ cacheKey: string;
32
+ createdAt: Date;
33
+ accessedAt: Date;
34
+ modifiedAt: Date;
35
+ handledRequestCount: number;
36
+ pendingRequestCount: number;
37
+ constructor(options: RequestQueueBackendOptions);
38
+ getMetadata(): Promise<storage.RequestQueueInfo>;
39
+ drop(): Promise<void>;
40
+ purge(): Promise<void>;
41
+ fetchNextRequest(): Promise<storage.UpdateRequestSchema | undefined>;
42
+ addBatchOfRequests(requests: storage.RequestSchema[], options?: storage.RequestQueueOperationOptions): Promise<storage.BatchAddRequestsResult>;
43
+ getRequest(uniqueKey: string): Promise<storage.UpdateRequestSchema | undefined>;
44
+ markRequestAsHandled(request: storage.UpdateRequestSchema): Promise<storage.QueueOperationInfo | undefined>;
45
+ reclaimRequest(request: storage.UpdateRequestSchema, options?: storage.RequestQueueOperationOptions): Promise<storage.QueueOperationInfo | undefined>;
46
+ isEmpty(): Promise<boolean>;
47
+ isFinished(): Promise<boolean>;
48
+ /**
49
+ * Returns all pending (not yet handled, not currently in progress) requests in the queue, ordered
50
+ * the same way {@link fetchNextRequest} would hand them out. This does not mutate the queue,
51
+ * nothing is marked in progress.
52
+ */
53
+ listItems(): Promise<storage.UpdateRequestSchema[]>;
54
+ toRequestQueueInfo(): storage.RequestQueueInfo;
55
+ }