@crawlee/core 4.0.0-beta.16 → 4.0.0-beta.160

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 (287) hide show
  1. package/README.md +14 -14
  2. package/autoscaling/autoscaled_pool.d.ts +73 -177
  3. package/autoscaling/autoscaled_pool.js +182 -329
  4. package/autoscaling/concurrency_system.d.ts +268 -0
  5. package/autoscaling/concurrency_system.js +364 -0
  6. package/autoscaling/cpu_load_signal.d.ts +43 -0
  7. package/autoscaling/cpu_load_signal.js +47 -0
  8. package/autoscaling/event_loop_load_signal.d.ts +51 -0
  9. package/autoscaling/event_loop_load_signal.js +60 -0
  10. package/autoscaling/index.d.ts +6 -1
  11. package/autoscaling/index.js +6 -1
  12. package/autoscaling/load_signal.d.ts +98 -0
  13. package/autoscaling/load_signal.js +103 -0
  14. package/autoscaling/memory_load_signal.d.ts +47 -0
  15. package/autoscaling/memory_load_signal.js +106 -0
  16. package/autoscaling/snapshotter.d.ts +58 -163
  17. package/autoscaling/snapshotter.js +45 -263
  18. package/autoscaling/storage_backend_load_signal.d.ts +56 -0
  19. package/autoscaling/storage_backend_load_signal.js +73 -0
  20. package/autoscaling/system_status.d.ts +67 -89
  21. package/autoscaling/system_status.js +92 -122
  22. package/autoscaling/weighted_avg.d.ts +5 -0
  23. package/autoscaling/weighted_avg.js +14 -0
  24. package/byte_utils.d.ts +17 -0
  25. package/byte_utils.js +42 -0
  26. package/configuration.d.ts +96 -223
  27. package/configuration.js +170 -222
  28. package/cookie_utils.d.ts +3 -2
  29. package/cookie_utils.js +18 -7
  30. package/crawlers/context_pipeline.d.ts +10 -1
  31. package/crawlers/context_pipeline.js +31 -8
  32. package/crawlers/crawler_commons.d.ts +90 -126
  33. package/crawlers/crawler_commons.js +1 -108
  34. package/crawlers/error_snapshotter.d.ts +2 -5
  35. package/crawlers/error_snapshotter.js +7 -8
  36. package/crawlers/error_tracker.d.ts +0 -1
  37. package/crawlers/error_tracker.js +0 -1
  38. package/crawlers/index.d.ts +1 -3
  39. package/crawlers/index.js +0 -3
  40. package/crawlers/internals/types.d.ts +0 -1
  41. package/crawlers/internals/types.js +0 -1
  42. package/crawlers/statistics.d.ts +187 -64
  43. package/crawlers/statistics.js +354 -165
  44. package/debug.d.ts +36 -0
  45. package/debug.js +70 -0
  46. package/enqueue_links/enqueue_links.d.ts +61 -154
  47. package/enqueue_links/enqueue_links.js +40 -232
  48. package/enqueue_links/index.d.ts +0 -1
  49. package/enqueue_links/index.js +0 -1
  50. package/enqueue_links/shared.d.ts +55 -28
  51. package/enqueue_links/shared.js +116 -69
  52. package/errors.d.ts +72 -4
  53. package/errors.js +89 -5
  54. package/events/event_manager.d.ts +35 -9
  55. package/events/event_manager.js +12 -13
  56. package/events/index.d.ts +0 -1
  57. package/events/index.js +0 -1
  58. package/events/local_event_manager.d.ts +15 -3
  59. package/events/local_event_manager.js +39 -13
  60. package/http.d.ts +9 -0
  61. package/http.js +28 -0
  62. package/index.d.ts +7 -5
  63. package/index.js +8 -4
  64. package/iterables.d.ts +79 -0
  65. package/iterables.js +134 -0
  66. package/log.d.ts +77 -1
  67. package/log.js +104 -1
  68. package/memory-storage/consts.d.ts +4 -0
  69. package/memory-storage/consts.js +4 -0
  70. package/memory-storage/index.d.ts +1 -0
  71. package/memory-storage/index.js +1 -0
  72. package/memory-storage/memory-storage.d.ts +44 -0
  73. package/memory-storage/memory-storage.js +160 -0
  74. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  75. package/memory-storage/resource-clients/common/base-client.js +6 -0
  76. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  77. package/memory-storage/resource-clients/dataset.js +106 -0
  78. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  79. package/memory-storage/resource-clients/key-value-store.js +199 -0
  80. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  81. package/memory-storage/resource-clients/request-queue.js +407 -0
  82. package/memory-storage/utils.d.ts +16 -0
  83. package/memory-storage/utils.js +41 -0
  84. package/owned_or_injected.d.ts +58 -0
  85. package/owned_or_injected.js +98 -0
  86. package/package.json +13 -12
  87. package/proxy_configuration.d.ts +22 -128
  88. package/proxy_configuration.js +32 -144
  89. package/recoverable_state.d.ts +83 -51
  90. package/recoverable_state.js +163 -72
  91. package/request.d.ts +57 -16
  92. package/request.js +130 -69
  93. package/router.d.ts +193 -21
  94. package/router.js +188 -43
  95. package/serialization.d.ts +0 -1
  96. package/serialization.js +15 -15
  97. package/service_locator.d.ts +165 -0
  98. package/service_locator.js +253 -0
  99. package/session_pool/consts.d.ts +1 -2
  100. package/session_pool/consts.js +1 -2
  101. package/session_pool/errors.d.ts +0 -1
  102. package/session_pool/errors.js +0 -1
  103. package/session_pool/fingerprint.d.ts +9 -0
  104. package/session_pool/fingerprint.js +30 -0
  105. package/session_pool/index.d.ts +0 -2
  106. package/session_pool/index.js +0 -2
  107. package/session_pool/session.d.ts +39 -89
  108. package/session_pool/session.js +102 -159
  109. package/session_pool/session_pool.d.ts +67 -91
  110. package/session_pool/session_pool.js +196 -187
  111. package/storages/batched_adds.d.ts +37 -0
  112. package/storages/batched_adds.js +73 -0
  113. package/storages/dataset.d.ts +114 -56
  114. package/storages/dataset.js +292 -149
  115. package/storages/index.d.ts +9 -9
  116. package/storages/index.js +7 -9
  117. package/storages/key_value_store.d.ts +190 -48
  118. package/storages/key_value_store.js +456 -171
  119. package/storages/key_value_store_codec.d.ts +32 -0
  120. package/storages/key_value_store_codec.js +113 -0
  121. package/storages/request_dedup_cache.d.ts +22 -0
  122. package/storages/request_dedup_cache.js +48 -0
  123. package/storages/request_list.d.ts +53 -115
  124. package/storages/request_list.js +194 -167
  125. package/storages/request_loader.d.ts +133 -0
  126. package/storages/request_loader.js +36 -0
  127. package/storages/request_manager.d.ts +109 -0
  128. package/storages/request_manager.js +1 -0
  129. package/storages/request_manager_tandem.d.ts +55 -23
  130. package/storages/request_manager_tandem.js +139 -57
  131. package/storages/request_queue.d.ts +286 -48
  132. package/storages/request_queue.js +757 -218
  133. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +43 -91
  134. package/storages/sitemap_request_loader.js +439 -0
  135. package/storages/storage_instance_manager.d.ts +87 -0
  136. package/storages/storage_instance_manager.js +256 -0
  137. package/storages/storage_stats.d.ts +48 -0
  138. package/storages/storage_stats.js +29 -0
  139. package/storages/throttling_request_manager.d.ts +223 -0
  140. package/storages/throttling_request_manager.js +835 -0
  141. package/storages/transaction.d.ts +252 -0
  142. package/storages/transaction.js +251 -0
  143. package/storages/utils.d.ts +59 -11
  144. package/storages/utils.js +75 -15
  145. package/system-info/cpu-info.d.ts +67 -0
  146. package/system-info/cpu-info.js +216 -0
  147. package/system-info/memory-info.d.ts +31 -0
  148. package/system-info/memory-info.js +115 -0
  149. package/system-info/ps-tree.d.ts +17 -0
  150. package/system-info/ps-tree.js +144 -0
  151. package/system-info/runtime.d.ts +14 -0
  152. package/system-info/runtime.js +80 -0
  153. package/typedefs.d.ts +0 -6
  154. package/typedefs.js +0 -1
  155. package/url.d.ts +9 -0
  156. package/url.js +11 -0
  157. package/validators.d.ts +22 -18
  158. package/validators.js +13 -18
  159. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  160. package/autoscaling/autoscaled_pool.js.map +0 -1
  161. package/autoscaling/index.d.ts.map +0 -1
  162. package/autoscaling/index.js.map +0 -1
  163. package/autoscaling/snapshotter.d.ts.map +0 -1
  164. package/autoscaling/snapshotter.js.map +0 -1
  165. package/autoscaling/system_status.d.ts.map +0 -1
  166. package/autoscaling/system_status.js.map +0 -1
  167. package/configuration.d.ts.map +0 -1
  168. package/configuration.js.map +0 -1
  169. package/cookie_utils.d.ts.map +0 -1
  170. package/cookie_utils.js.map +0 -1
  171. package/crawlers/context_pipeline.d.ts.map +0 -1
  172. package/crawlers/context_pipeline.js.map +0 -1
  173. package/crawlers/crawler_commons.d.ts.map +0 -1
  174. package/crawlers/crawler_commons.js.map +0 -1
  175. package/crawlers/crawler_utils.d.ts +0 -10
  176. package/crawlers/crawler_utils.d.ts.map +0 -1
  177. package/crawlers/crawler_utils.js +0 -12
  178. package/crawlers/crawler_utils.js.map +0 -1
  179. package/crawlers/error_snapshotter.d.ts.map +0 -1
  180. package/crawlers/error_snapshotter.js.map +0 -1
  181. package/crawlers/error_tracker.d.ts.map +0 -1
  182. package/crawlers/error_tracker.js.map +0 -1
  183. package/crawlers/index.d.ts.map +0 -1
  184. package/crawlers/index.js.map +0 -1
  185. package/crawlers/internals/types.d.ts.map +0 -1
  186. package/crawlers/internals/types.js.map +0 -1
  187. package/crawlers/statistics.d.ts.map +0 -1
  188. package/crawlers/statistics.js.map +0 -1
  189. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  190. package/enqueue_links/enqueue_links.js.map +0 -1
  191. package/enqueue_links/index.d.ts.map +0 -1
  192. package/enqueue_links/index.js.map +0 -1
  193. package/enqueue_links/shared.d.ts.map +0 -1
  194. package/enqueue_links/shared.js.map +0 -1
  195. package/errors.d.ts.map +0 -1
  196. package/errors.js.map +0 -1
  197. package/events/event_manager.d.ts.map +0 -1
  198. package/events/event_manager.js.map +0 -1
  199. package/events/index.d.ts.map +0 -1
  200. package/events/index.js.map +0 -1
  201. package/events/local_event_manager.d.ts.map +0 -1
  202. package/events/local_event_manager.js.map +0 -1
  203. package/http_clients/base-http-client.d.ts +0 -140
  204. package/http_clients/base-http-client.d.ts.map +0 -1
  205. package/http_clients/base-http-client.js +0 -40
  206. package/http_clients/base-http-client.js.map +0 -1
  207. package/http_clients/form-data-like.d.ts +0 -67
  208. package/http_clients/form-data-like.d.ts.map +0 -1
  209. package/http_clients/form-data-like.js +0 -5
  210. package/http_clients/form-data-like.js.map +0 -1
  211. package/http_clients/got-scraping-http-client.d.ts +0 -20
  212. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  213. package/http_clients/got-scraping-http-client.js +0 -85
  214. package/http_clients/got-scraping-http-client.js.map +0 -1
  215. package/http_clients/index.d.ts +0 -3
  216. package/http_clients/index.d.ts.map +0 -1
  217. package/http_clients/index.js +0 -3
  218. package/http_clients/index.js.map +0 -1
  219. package/index.d.ts.map +0 -1
  220. package/index.js.map +0 -1
  221. package/log.d.ts.map +0 -1
  222. package/log.js.map +0 -1
  223. package/proxy_configuration.d.ts.map +0 -1
  224. package/proxy_configuration.js.map +0 -1
  225. package/recoverable_state.d.ts.map +0 -1
  226. package/recoverable_state.js.map +0 -1
  227. package/request.d.ts.map +0 -1
  228. package/request.js.map +0 -1
  229. package/router.d.ts.map +0 -1
  230. package/router.js.map +0 -1
  231. package/serialization.d.ts.map +0 -1
  232. package/serialization.js.map +0 -1
  233. package/session_pool/consts.d.ts.map +0 -1
  234. package/session_pool/consts.js.map +0 -1
  235. package/session_pool/errors.d.ts.map +0 -1
  236. package/session_pool/errors.js.map +0 -1
  237. package/session_pool/events.d.ts +0 -3
  238. package/session_pool/events.d.ts.map +0 -1
  239. package/session_pool/events.js +0 -3
  240. package/session_pool/events.js.map +0 -1
  241. package/session_pool/index.d.ts.map +0 -1
  242. package/session_pool/index.js.map +0 -1
  243. package/session_pool/session.d.ts.map +0 -1
  244. package/session_pool/session.js.map +0 -1
  245. package/session_pool/session_pool.d.ts.map +0 -1
  246. package/session_pool/session_pool.js.map +0 -1
  247. package/storages/access_checking.d.ts +0 -13
  248. package/storages/access_checking.d.ts.map +0 -1
  249. package/storages/access_checking.js +0 -14
  250. package/storages/access_checking.js.map +0 -1
  251. package/storages/dataset.d.ts.map +0 -1
  252. package/storages/dataset.js.map +0 -1
  253. package/storages/index.d.ts.map +0 -1
  254. package/storages/index.js.map +0 -1
  255. package/storages/key_value_store.d.ts.map +0 -1
  256. package/storages/key_value_store.js.map +0 -1
  257. package/storages/request_list.d.ts.map +0 -1
  258. package/storages/request_list.js.map +0 -1
  259. package/storages/request_list_adapter.d.ts +0 -58
  260. package/storages/request_list_adapter.d.ts.map +0 -1
  261. package/storages/request_list_adapter.js +0 -81
  262. package/storages/request_list_adapter.js.map +0 -1
  263. package/storages/request_manager_tandem.d.ts.map +0 -1
  264. package/storages/request_manager_tandem.js.map +0 -1
  265. package/storages/request_provider.d.ts +0 -371
  266. package/storages/request_provider.d.ts.map +0 -1
  267. package/storages/request_provider.js +0 -585
  268. package/storages/request_provider.js.map +0 -1
  269. package/storages/request_queue.d.ts.map +0 -1
  270. package/storages/request_queue.js.map +0 -1
  271. package/storages/request_queue_v2.d.ts +0 -87
  272. package/storages/request_queue_v2.d.ts.map +0 -1
  273. package/storages/request_queue_v2.js +0 -438
  274. package/storages/request_queue_v2.js.map +0 -1
  275. package/storages/sitemap_request_list.d.ts.map +0 -1
  276. package/storages/sitemap_request_list.js +0 -430
  277. package/storages/sitemap_request_list.js.map +0 -1
  278. package/storages/storage_manager.d.ts +0 -58
  279. package/storages/storage_manager.d.ts.map +0 -1
  280. package/storages/storage_manager.js +0 -105
  281. package/storages/storage_manager.js.map +0 -1
  282. package/storages/utils.d.ts.map +0 -1
  283. package/storages/utils.js.map +0 -1
  284. package/typedefs.d.ts.map +0 -1
  285. package/typedefs.js.map +0 -1
  286. package/validators.d.ts.map +0 -1
  287. package/validators.js.map +0 -1
@@ -1,42 +1,31 @@
1
- import { readFile } from 'node:fs/promises';
2
- import { join } from 'node:path';
3
- import JSON5 from 'json5';
4
- import ow, { ArgumentError } from 'ow';
1
+ import { z } from 'zod';
5
2
  import { KEY_VALUE_STORE_KEY_REGEX } from '@apify/consts';
6
- import log from '@apify/log';
7
- import { jsonStringifyExtended } from '@apify/utilities';
3
+ import { tryCancel } from '@apify/timeout';
8
4
  import { Configuration } from '../configuration.js';
9
- import { checkStorageAccess } from './access_checking.js';
10
- import { StorageManager } from './storage_manager.js';
11
- import { purgeDefaultStorages } from './utils.js';
12
- /**
13
- * Helper function to possibly stringify value if options.contentType is not set.
14
- *
15
- * @ignore
16
- */
17
- export const maybeStringify = (value, options) => {
18
- // If contentType is missing, value will be stringified to JSON
19
- if (options.contentType === null || options.contentType === undefined) {
20
- options.contentType = 'application/json; charset=utf-8';
21
- try {
22
- // Format JSON to simplify debugging, the overheads with compression is negligible
23
- value = jsonStringifyExtended(value, null, 2);
24
- }
25
- catch (e) {
26
- const error = e;
27
- // Give more meaningful error message
28
- if (error.message?.includes('Invalid string length')) {
29
- error.message = 'Object is too large';
30
- }
31
- throw new Error(`The "value" parameter cannot be stringified to JSON: ${error.message}`);
32
- }
33
- if (value === undefined) {
34
- throw new Error('The "value" parameter was stringified to JSON and returned undefined. ' +
35
- "Make sure you're not trying to stringify an undefined value.");
36
- }
37
- }
38
- return value;
39
- };
5
+ import { serviceLocator } from '../service_locator.js';
6
+ import { parseArgument, schemas, validators } from '../validators.js';
7
+ import { activeStorageTransaction, operationRejectedInTransaction, rejectOperationInTransaction, snapshotValue, withDirectStorageAccess, } from './transaction.js';
8
+ import { parseValue, serializeValue } from './key_value_store_codec.js';
9
+ import { StorageStatsTracker } from './storage_stats.js';
10
+ import { resolveStorageIdentifier } from './storage_instance_manager.js';
11
+ import { createDualIterable, purgeDefaultStorages } from './utils.js';
12
+ import { isBuffer, isStream } from '../byte_utils.js';
13
+ /** @internal */
14
+ const KVS_KEYS_DEFAULT_LIMIT = 1000;
15
+ const keySchema = z.string().nonempty();
16
+ const setValueKeySchema = z.string().nonempty().regex(KEY_VALUE_STORE_KEY_REGEX, {
17
+ message: `The "key" argument must be at most 256 characters long and only contain the following characters: a-zA-Z0-9!-_.'()`,
18
+ });
19
+ const recordOptionsSchema = z.strictObject({
20
+ contentType: z.string().nonempty().optional(),
21
+ });
22
+ const iteratorOptionsSchema = z.strictObject({
23
+ prefix: z.string().optional(),
24
+ });
25
+ const openOptionsSchema = z.strictObject({
26
+ configuration: z.instanceof(Configuration).optional(),
27
+ storageBackend: validators.storageBackend.optional(),
28
+ });
40
29
  /**
41
30
  * The `KeyValueStore` class represents a key-value store, a simple data storage that is used
42
31
  * for saving and reading data records or files. Each data record is
@@ -94,23 +83,34 @@ export const maybeStringify = (value, options) => {
94
83
  * @category Result Stores
95
84
  */
96
85
  export class KeyValueStore {
97
- config;
86
+ configuration;
98
87
  id;
99
88
  name;
100
- storageObject;
101
- client;
102
- persistStateEventStarted = false;
89
+ backend;
90
+ #persistStateEventStarted = false;
103
91
  /** Cache for persistent (auto-saved) values. When we try to set such value, the cache will be updated automatically. */
104
- cache = new Map();
92
+ #cache = new Map();
93
+ #statsTracker = new StorageStatsTracker({
94
+ readCount: 0,
95
+ writeCount: 0,
96
+ deleteCount: 0,
97
+ listCount: 0,
98
+ });
105
99
  /**
106
100
  * @internal
107
101
  */
108
- constructor(options, config = Configuration.getGlobalConfig()) {
109
- this.config = config;
110
- this.id = options.id;
111
- this.name = options.name;
112
- this.storageObject = options.storageObject;
113
- this.client = options.client.keyValueStore(this.id);
102
+ constructor(options, configuration = Configuration.getGlobalConfiguration()) {
103
+ this.configuration = configuration;
104
+ this.id = options.metadata.id;
105
+ this.name = options.metadata.name;
106
+ this.backend = options.backend;
107
+ }
108
+ /**
109
+ * Backend-independent usage counters tracked for this key-value store (read / write / delete /
110
+ * list operations issued to the underlying storage backend). Counted per backend call.
111
+ */
112
+ get stats() {
113
+ return this.#statsTracker.current;
114
114
  }
115
115
  /**
116
116
  * Gets a value from the key-value store.
@@ -145,10 +145,93 @@ export class KeyValueStore {
145
145
  * on the MIME content type of the record, or `null` if the key is missing from the store.
146
146
  */
147
147
  async getValue(key, defaultValue) {
148
- checkStorageAccess();
149
- ow(key, ow.string.nonEmpty);
150
- const record = await this.client.getRecord(key);
151
- return record?.value ?? defaultValue ?? null;
148
+ tryCancel();
149
+ parseArgument(key, keySchema);
150
+ const record = await this.readRecord(key);
151
+ // A missing record falls back to the default; a record that parses to a falsy value (including
152
+ // a stored literal `null`) is returned verbatim, so callers can tell "stored null" from "absent".
153
+ if (!record) {
154
+ return defaultValue ?? null;
155
+ }
156
+ // Storage backends are byte transports — the value is raw bytes; the frontend parses it here.
157
+ return parseValue(record.value, record.contentType ?? null);
158
+ }
159
+ /**
160
+ * The active transaction's last buffered write per key for this store, derived from its journal.
161
+ * An entry with a `null` value is a tombstone (an in-transaction deletion).
162
+ */
163
+ bufferedJournalEntries() {
164
+ const transaction = activeStorageTransaction();
165
+ if (!transaction)
166
+ return undefined;
167
+ const lastWritePerKey = new Map();
168
+ for (const entry of transaction.journal) {
169
+ if (entry.type === 'keyValueStore' && entry.participant === this) {
170
+ lastWritePerKey.set(entry.key, entry);
171
+ }
172
+ }
173
+ return lastWritePerKey;
174
+ }
175
+ /**
176
+ * The single transaction-aware record read shared by `getValue`, `getRecord`, `recordExists` and the
177
+ * listing paths: buffered key → serialized through the standard codec (same fidelity as a real
178
+ * round-trip); tombstoned key → `null`; otherwise the backend.
179
+ *
180
+ * The per-key buffered lookup requires the whole journal to be reduced to a last-write-per-key map,
181
+ * which is O(journal). Single-record callers let it default (rebuilt per call); the listing paths,
182
+ * which read many keys, pass a map built once so the read stays O(1) per key instead of O(journal).
183
+ */
184
+ async readRecord(key, buffered = this.bufferedJournalEntries()) {
185
+ const entry = buffered?.get(key);
186
+ if (entry) {
187
+ if (entry.value === null) {
188
+ return null;
189
+ }
190
+ const serialized = serializeValue(entry.value, entry.options?.contentType);
191
+ return {
192
+ value: normalizeSerializedValue(serialized.value),
193
+ contentType: serialized.contentType ?? null,
194
+ };
195
+ }
196
+ this.#statsTracker.add('readCount');
197
+ const record = await this.backend.getValue(key);
198
+ if (!record)
199
+ return null;
200
+ return {
201
+ value: record.value,
202
+ contentType: record.contentType ?? null,
203
+ };
204
+ }
205
+ /**
206
+ * Reads a record from the key-value store without parsing the value.
207
+ *
208
+ * Use this when you need the raw bytes and the content type — for example, to run your own
209
+ * parser (`simdjson`, a custom XML library, etc.) or to forward the bytes verbatim.
210
+ *
211
+ * There is no symmetric `setRecord` method, because {@link KeyValueStore.setValue} already
212
+ * passes a `Buffer` (or `string` / `Stream`) through unchanged when an explicit `contentType`
213
+ * is provided. To write pre-serialized bytes, call
214
+ * `setValue(key, buffer, { contentType: 'application/json; charset=utf-8' })`.
215
+ *
216
+ * Returns `null` if the record does not exist.
217
+ *
218
+ * **Example usage:**
219
+ * ```javascript
220
+ * const store = await KeyValueStore.open();
221
+ * const record = await store.getRecord('huge.json');
222
+ * if (record) {
223
+ * const data = simdjson.parse(record.value);
224
+ * }
225
+ * ```
226
+ *
227
+ * @param key
228
+ * Unique key of the record. It can be at most 256 characters long and only consist
229
+ * of the following characters: `a`-`z`, `A`-`Z`, `0`-`9` and `!-_.'()`
230
+ */
231
+ async getRecord(key) {
232
+ tryCancel();
233
+ parseArgument(key, keySchema);
234
+ return this.readRecord(key);
152
235
  }
153
236
  /**
154
237
  * Tests whether a record with the given key exists in the key-value store without retrieving its value.
@@ -157,45 +240,96 @@ export class KeyValueStore {
157
240
  * @returns `true` if the record exists, `false` if it does not.
158
241
  */
159
242
  async recordExists(key) {
160
- checkStorageAccess();
161
- ow(key, ow.string.nonEmpty);
162
- return this.client.recordExists(key);
243
+ tryCancel();
244
+ parseArgument(key, keySchema);
245
+ const entry = this.bufferedJournalEntries()?.get(key);
246
+ if (entry) {
247
+ return entry.value !== null;
248
+ }
249
+ return this.backend.recordExists(key);
163
250
  }
164
251
  async getAutoSavedValue(key, defaultValue = {}) {
165
- checkStorageAccess();
166
- if (this.cache.has(key)) {
167
- return this.cache.get(key);
252
+ tryCancel();
253
+ if (this.#cache.has(key)) {
254
+ return this.#cache.get(key);
168
255
  }
169
- const value = await this.getValue(key, defaultValue);
256
+ // Auto-saved state is deliberately *not* transactional. The direct read bypasses any active
257
+ // transaction - a buffered value seeded into this shared cache would survive a rollback forever.
258
+ const value = await withDirectStorageAccess(async () => this.getValue(key, defaultValue));
170
259
  // The await above could have run in parallel with another call to this function. If the other call finished more quickly,
171
260
  // the value will in cache at this point, and returning the new fetched value would introduce two different instances of
172
261
  // the auto-saved object, and only the latter one would be persisted.
173
262
  // Therefore we re-check the cache here, and if such race condition happened, we drop the fetched value and return the cached one.
174
- if (this.cache.has(key)) {
175
- return this.cache.get(key);
263
+ if (this.#cache.has(key)) {
264
+ return this.#cache.get(key);
176
265
  }
177
- this.cache.set(key, value);
266
+ this.#cache.set(key, value);
178
267
  this.ensurePersistStateEvent();
179
268
  return value;
180
269
  }
181
270
  ensurePersistStateEvent() {
182
- if (this.persistStateEventStarted) {
271
+ if (this.#persistStateEventStarted) {
183
272
  return;
184
273
  }
185
- // use half the interval of `persistState` to avoid race conditions
186
- const persistStateIntervalMillis = this.config.get('persistStateIntervalMillis');
187
- const timeoutSecs = persistStateIntervalMillis / 2_000;
188
- this.config.getEventManager().on('persistState', async () => {
274
+ serviceLocator.getEventManager().on('persistState', async () => {
189
275
  const promises = [];
190
- for (const [key, value] of this.cache) {
191
- promises.push(this.setValue(key, value, {
192
- timeoutSecs,
193
- doNotRetryTimeouts: true,
194
- }).catch((error) => log.warning(`Failed to persist the state value to ${key}`, { error })));
276
+ for (const [key, value] of this.#cache) {
277
+ promises.push(this.setValue(key, value).catch((error) => serviceLocator.getLogger().warning(`Failed to persist the state value to ${key}`, { error })));
195
278
  }
196
279
  await Promise.all(promises);
197
280
  });
198
- this.persistStateEventStarted = true;
281
+ this.#persistStateEventStarted = true;
282
+ }
283
+ async *fetchKeyValuePages(options, mapRecord) {
284
+ // Reduce the journal once for the whole iteration, not once per key inside `readRecord`.
285
+ const buffered = this.bufferedJournalEntries();
286
+ for await (const page of this.fetchKeyPages(options, buffered)) {
287
+ const results = [];
288
+ for (const item of page) {
289
+ // The shared transaction-aware read, so a key that exists only in the transaction resolves
290
+ // here instead of being dropped (`values()` would disagree with `keys()` on length).
291
+ const record = await this.readRecord(item.key, buffered);
292
+ if (record) {
293
+ const parsed = parseValue(record.value, record.contentType ?? null);
294
+ results.push(mapRecord(item.key, parsed));
295
+ }
296
+ }
297
+ yield results;
298
+ }
299
+ }
300
+ async *fetchKeyPages(options, buffered = this.bufferedJournalEntries(), limit = KVS_KEYS_DEFAULT_LIMIT) {
301
+ // Buffered keys are emitted first, then the real pages with any buffered (or tombstoned) key
302
+ // skipped - a merge-join is not an option, since `listKeys` promises no sort order.
303
+ const shadowedKeys = new Set();
304
+ if (buffered) {
305
+ const bufferedItems = [];
306
+ for (const [key, entry] of buffered) {
307
+ shadowedKeys.add(key);
308
+ if (entry.value === null)
309
+ continue;
310
+ if (options.prefix !== undefined && !key.startsWith(options.prefix))
311
+ continue;
312
+ bufferedItems.push(bufferedKeyItemData(key, entry));
313
+ }
314
+ if (bufferedItems.length > 0) {
315
+ bufferedItems.sort((a, b) => (a.key < b.key ? -1 : 1));
316
+ yield bufferedItems;
317
+ }
318
+ }
319
+ let exclusiveStartKey;
320
+ while (true) {
321
+ this.#statsTracker.add('listCount');
322
+ const { items, isTruncated, nextExclusiveStartKey } = await this.backend.listKeys({
323
+ ...options,
324
+ exclusiveStartKey,
325
+ limit,
326
+ });
327
+ yield shadowedKeys.size > 0 ? items.filter((item) => !shadowedKeys.has(item.key)) : items;
328
+ if (!isTruncated)
329
+ break;
330
+ // Paginate from the raw backend cursor - it may reject a key it did not hand out.
331
+ exclusiveStartKey = nextExclusiveStartKey;
332
+ }
199
333
  }
200
334
  /**
201
335
  * Saves or deletes a record in the key-value store.
@@ -241,73 +375,110 @@ export class KeyValueStore {
241
375
  * @param [options] Record options.
242
376
  */
243
377
  async setValue(key, value, options = {}) {
244
- checkStorageAccess();
245
- ow(key, 'key', ow.string.nonEmpty);
246
- ow(key, ow.string.validate((k) => ({
247
- validator: ow.isValid(k, ow.string.matches(KEY_VALUE_STORE_KEY_REGEX)),
248
- message: `The "key" argument "${key}" must be at most 256 characters long and only contain the following characters: a-zA-Z0-9!-_.'()`,
249
- })));
250
- if (options.contentType &&
251
- !(ow.isValid(value, ow.any(ow.string, ow.uint8Array)) ||
252
- (ow.isValid(value, ow.object) && typeof value.pipe === 'function'))) {
253
- throw new ArgumentError('The "value" parameter must be a String, Buffer or Stream when "options.contentType" is specified.', this.setValue);
378
+ const transaction = activeStorageTransaction();
379
+ parseArgument(key, setValueKeySchema);
380
+ if (options.contentType && !(typeof value === 'string' || isBuffer(value) || isStream(value))) {
381
+ throw new Error('The "value" parameter must be a String, Buffer, ArrayBuffer, TypedArray, or Stream when "options.contentType" is specified.');
382
+ }
383
+ // The parse result is a fresh copy, so we never update what user passed.
384
+ const optionsCopy = parseArgument(options, recordOptionsSchema);
385
+ // The whole transaction branch sits *above* the auto-saved cache update below, so a buffered
386
+ // write touches nothing outside the journal. That cache is shared, process-lifetime frontend
387
+ // state, so mutating it here would survive a rollback and later be persisted by `persistState`.
388
+ // The commit replay re-enters this method with no active transaction and updates it then.
389
+ if (transaction) {
390
+ if (isStream(value)) {
391
+ // A stream cannot serve both a read-your-own-writes read and the commit replay. The
392
+ // transaction is known-active here, so throw directly rather than via the conditional guard.
393
+ throw operationRejectedInTransaction(`KeyValueStore.setValue() with a stream value (key "${key}")`, 'a stream can only be consumed once, so it cannot be buffered until commit.');
394
+ }
395
+ // Validation only, result discarded: the journal snapshot (`structuredClone`) accepts values
396
+ // JSON cannot, which would otherwise only throw at a later read or at commit.
397
+ if (value !== null) {
398
+ serializeValue(value, optionsCopy.contentType);
399
+ }
400
+ // One snapshot serves both the reads and the commit replay; `null` is a tombstone.
401
+ transaction.recordJournalEntry({
402
+ type: 'keyValueStore',
403
+ participant: this,
404
+ storageId: this.id,
405
+ key,
406
+ value: value === null ? null : snapshotValue(value),
407
+ options: optionsCopy,
408
+ });
409
+ return;
254
410
  }
255
- ow(options, ow.object.exactShape({
256
- contentType: ow.optional.string.nonEmpty,
257
- timeoutSecs: ow.optional.number,
258
- doNotRetryTimeouts: ow.optional.boolean,
259
- }));
260
- // Make copy of options, don't update what user passed.
261
- const optionsCopy = { ...options };
262
411
  // If we try to set the value of a cached state to a different reference, we need to update the cache accordingly.
263
- const cachedValue = this.cache.get(key);
412
+ const cachedValue = this.#cache.get(key);
264
413
  if (cachedValue && cachedValue !== value) {
265
414
  if (value === null) {
266
415
  // Cached state can be only object, so a propagation of `null` means removing all its properties.
267
- Object.keys(cachedValue).forEach((k) => this.cache.delete(k));
416
+ Object.keys(cachedValue).forEach((k) => this.#cache.delete(k));
268
417
  }
269
418
  else if (typeof value === 'object') {
270
419
  // We need to remove the keys that are no longer present in the new value.
271
420
  Object.keys(cachedValue)
272
421
  .filter((k) => !(k in value))
273
- .forEach((k) => this.cache.delete(k));
422
+ .forEach((k) => this.#cache.delete(k));
274
423
  // And update the existing ones + add new ones.
275
424
  Object.assign(cachedValue, value);
276
425
  }
277
426
  }
278
427
  // In this case delete the record.
279
- if (value === null)
280
- return this.client.deleteRecord(key);
281
- value = maybeStringify(value, optionsCopy);
282
- return this.client.setRecord({
428
+ if (value === null) {
429
+ this.#statsTracker.add('deleteCount');
430
+ return this.backend.deleteValue(key);
431
+ }
432
+ const serialized = serializeValue(value, optionsCopy.contentType);
433
+ this.#statsTracker.add('writeCount');
434
+ return this.backend.setValue({
283
435
  key,
284
- value,
285
- contentType: optionsCopy.contentType,
286
- }, {
287
- timeoutSecs: optionsCopy.timeoutSecs,
288
- doNotRetryTimeouts: optionsCopy.doNotRetryTimeouts,
436
+ value: serialized.value,
437
+ contentType: serialized.contentType,
289
438
  });
290
439
  }
440
+ /** @internal */
441
+ async commitJournalEntries(entries) {
442
+ // One `setValue` per key, last write wins - idempotent under retry.
443
+ const lastWritePerKey = new Map();
444
+ for (const entry of entries) {
445
+ if (entry.type === 'keyValueStore') {
446
+ lastWritePerKey.set(entry.key, { value: entry.value, options: entry.options });
447
+ }
448
+ }
449
+ for (const [key, { value, options }] of lastWritePerKey) {
450
+ await this.setValue(key, value, options);
451
+ }
452
+ }
291
453
  /**
292
454
  * Removes the key-value store either from the Apify cloud storage or from the local directory,
293
455
  * depending on the mode of operation.
294
456
  */
295
457
  async drop() {
296
- checkStorageAccess();
297
- await this.client.delete();
298
- const manager = StorageManager.getManager(KeyValueStore, this.config);
299
- manager.closeStorage(this);
458
+ rejectOperationInTransaction('KeyValueStore.drop()');
459
+ await this.backend.drop();
460
+ serviceLocator.getStorageInstanceManager().removeFromCache(this);
461
+ }
462
+ /**
463
+ * Removes all records from the store but keeps the store itself, along with its
464
+ * {@link KeyValueStore.id|`id`} and {@link KeyValueStore.name|`name`}.
465
+ */
466
+ async purge() {
467
+ rejectOperationInTransaction('KeyValueStore.purge()');
468
+ await this.backend.purge();
469
+ // The auto-saved values this cache holds are no longer in the store.
470
+ this.#cache.clear();
300
471
  }
301
472
  /** @internal */
302
473
  clearCache() {
303
- checkStorageAccess();
304
- this.cache.clear();
474
+ rejectOperationInTransaction('KeyValueStore.clearCache()');
475
+ this.#cache.clear();
305
476
  }
306
477
  /**
307
478
  * Iterates over key-value store keys, yielding each in turn to an `iteratee` function.
308
479
  * Each invocation of `iteratee` is called with three arguments: `(key, index, info)`, where `key`
309
480
  * is the record key, `index` is a zero-based index of the key in the current iteration
310
- * (regardless of `options.exclusiveStartKey`) and `info` is an object that contains a single property `size`
481
+ * and `info` is an object that contains a single property `size`
311
482
  * indicating size of the record in bytes.
312
483
  *
313
484
  * If the `iteratee` function returns a Promise then it is awaited before the next call.
@@ -325,32 +496,132 @@ export class KeyValueStore {
325
496
  * @param [options] All `forEachKey()` parameters.
326
497
  */
327
498
  async forEachKey(iteratee, options = {}) {
328
- checkStorageAccess();
329
- return this._forEachKey(iteratee, options);
330
- }
331
- async _forEachKey(iteratee, options = {}, index = 0) {
332
- const { exclusiveStartKey, prefix, collection } = options;
333
- ow(iteratee, ow.function);
334
- ow(options, ow.object.exactShape({
335
- exclusiveStartKey: ow.optional.string,
336
- prefix: ow.optional.string,
337
- collection: ow.optional.string,
338
- }));
339
- const response = await this.client.listKeys({ exclusiveStartKey, prefix, collection });
340
- const { nextExclusiveStartKey, isTruncated, items } = response;
341
- for (const item of items) {
342
- await iteratee(item.key, index++, { size: item.size });
499
+ tryCancel();
500
+ parseArgument(iteratee, schemas.anyFunction);
501
+ const parsedOptions = parseArgument(options, iteratorOptionsSchema);
502
+ let index = 0;
503
+ for await (const page of this.fetchKeyPages(parsedOptions)) {
504
+ for (const item of page) {
505
+ await iteratee(item.key, index++, { size: item.size });
506
+ }
343
507
  }
344
- return isTruncated
345
- ? this._forEachKey(iteratee, { exclusiveStartKey: nextExclusiveStartKey, prefix, collection }, index)
346
- : undefined; // [].forEach() returns undefined.
508
+ }
509
+ /**
510
+ * Returns key-value store keys.
511
+ *
512
+ * When awaited (`await store.keys()`), returns all keys as a flat `string[]` array.
513
+ * When used as an async iterable (`for await...of`), iterates over all keys across pages
514
+ * without loading everything into memory at once.
515
+ *
516
+ * **Example usage:**
517
+ * ```javascript
518
+ * const keyValueStore = await KeyValueStore.open();
519
+ *
520
+ * // Iterate over all keys (memory-efficient for large stores)
521
+ * for await (const key of keyValueStore.keys()) {
522
+ * console.log(key);
523
+ * }
524
+ *
525
+ * // Or fetch all keys at once
526
+ * const allKeys = await keyValueStore.keys();
527
+ * console.log(allKeys);
528
+ * ```
529
+ *
530
+ * @param options Options for the iteration.
531
+ */
532
+ keys(options = {}) {
533
+ tryCancel();
534
+ return createDualIterable({
535
+ createPages: () => this.fetchKeyPages(options),
536
+ extractItems: (page) => page.map((item) => item.key),
537
+ });
538
+ }
539
+ /**
540
+ * Returns key-value store values.
541
+ *
542
+ * When awaited (`await store.values()`), returns all values as a flat `T[]` array.
543
+ * When used as an async iterable (`for await...of`), iterates over all values across pages
544
+ * without loading everything into memory at once.
545
+ *
546
+ * **Example usage:**
547
+ * ```javascript
548
+ * const keyValueStore = await KeyValueStore.open();
549
+ *
550
+ * // Iterate over all values (memory-efficient for large stores)
551
+ * for await (const value of keyValueStore.values()) {
552
+ * console.log(value);
553
+ * }
554
+ *
555
+ * // Or fetch all values at once
556
+ * const allValues = await keyValueStore.values();
557
+ * console.log(allValues);
558
+ * ```
559
+ *
560
+ * @param options Options for the iteration.
561
+ */
562
+ values(options = {}) {
563
+ tryCancel();
564
+ return createDualIterable({
565
+ createPages: () => this.fetchKeyValuePages(options, (_key, value) => value),
566
+ extractItems: (page) => page,
567
+ });
568
+ }
569
+ /**
570
+ * Returns key-value store entries (key-value pairs).
571
+ *
572
+ * When awaited (`await store.entries()`), returns all entries as a flat `[key, value][]` array.
573
+ * When used as an async iterable (`for await...of`), iterates over all entries across pages
574
+ * without loading everything into memory at once.
575
+ *
576
+ * **Example usage:**
577
+ * ```javascript
578
+ * const keyValueStore = await KeyValueStore.open();
579
+ *
580
+ * // Iterate over all entries (memory-efficient for large stores)
581
+ * for await (const [key, value] of keyValueStore.entries()) {
582
+ * console.log(`${key}: ${value}`);
583
+ * }
584
+ *
585
+ * // Or fetch all entries at once
586
+ * const allEntries = await keyValueStore.entries();
587
+ * console.log(allEntries);
588
+ * ```
589
+ *
590
+ * @param options Options for the iteration.
591
+ */
592
+ entries(options = {}) {
593
+ tryCancel();
594
+ return createDualIterable({
595
+ createPages: () => this.fetchKeyValuePages(options, (key, value) => [key, value]),
596
+ extractItems: (page) => page,
597
+ });
598
+ }
599
+ /**
600
+ * Default async iterator for the key-value store, iterating over entries (key-value pairs).
601
+ * Allows using the store directly in a `for await...of` loop.
602
+ *
603
+ * **Example usage:**
604
+ * ```javascript
605
+ * const keyValueStore = await KeyValueStore.open();
606
+ * for await (const [key, value] of keyValueStore) {
607
+ * console.log(`${key}: ${value}`);
608
+ * }
609
+ * ```
610
+ */
611
+ async *[Symbol.asyncIterator]() {
612
+ yield* this.entries();
347
613
  }
348
614
  /**
349
615
  * Returns a file URL for the given key.
616
+ *
617
+ * The URL is derived from the key, so it is also returned for a record that does not exist (yet) —
618
+ * including one written earlier in an uncommitted storage transaction. Returns `undefined` only when
619
+ * the storage has no file URLs at all (e.g. the in-memory storage).
620
+ *
621
+ * @param key The key of the record to generate the public URL for.
350
622
  */
351
- getPublicUrl(key) {
352
- const name = this.name ?? this.config.get('defaultKeyValueStoreId');
353
- return `file://${process.cwd()}/storage/key_value_stores/${name}/${key}`;
623
+ async getPublicUrl(key) {
624
+ return this.backend.getPublicUrl(key);
354
625
  }
355
626
  /**
356
627
  * Opens a key-value store and returns a promise resolving to an instance of the {@link KeyValueStore} class.
@@ -361,23 +632,24 @@ export class KeyValueStore {
361
632
  *
362
633
  * For more details and code examples, see the {@link KeyValueStore} class.
363
634
  *
364
- * @param [storeIdOrName]
365
- * ID or name of the key-value store to be opened. If `null` or `undefined`,
366
- * the function returns the default key-value store associated with the crawler run.
635
+ * @param [identifier]
636
+ * ID or name of the key-value store to be opened. If a string is provided, it will first be
637
+ * looked up as an ID; if no such storage exists, it will be treated as a name.
638
+ * If `null` or `undefined`, the function returns the default key-value store associated with the crawler run.
367
639
  * @param [options] Storage manager options.
368
640
  */
369
- static async open(storeIdOrName, options = {}) {
370
- checkStorageAccess();
371
- ow(storeIdOrName, ow.optional.any(ow.string, ow.null));
372
- ow(options, ow.object.exactShape({
373
- config: ow.optional.object.instanceOf(Configuration),
374
- storageClient: ow.optional.object,
375
- }));
376
- options.config ??= Configuration.getGlobalConfig();
377
- options.storageClient ??= options.config.getStorageClient();
378
- await purgeDefaultStorages({ onlyPurgeOnce: true, client: options.storageClient, config: options.config });
379
- const manager = StorageManager.getManager(this, options.config);
380
- return manager.openStorage(storeIdOrName, options.storageClient);
641
+ static async open(identifier, options = {}) {
642
+ tryCancel();
643
+ const parsedOptions = parseArgument(options, openOptionsSchema);
644
+ const configuration = parsedOptions.configuration ?? Configuration.getGlobalConfiguration();
645
+ const storageBackend = parsedOptions.storageBackend ?? serviceLocator.getStorageBackend();
646
+ await purgeDefaultStorages({ onlyPurgeOnce: true, storageBackend, configuration });
647
+ const resolved = await resolveStorageIdentifier(identifier, storageBackend, 'KeyValueStore');
648
+ return serviceLocator.getStorageInstanceManager().openStorage(this, {
649
+ ...resolved,
650
+ backendOpener: () => storageBackend.createKeyValueStoreBackend(resolved),
651
+ backendCacheKey: storageBackend.getStorageBackendCacheKey?.() ?? storageBackend.constructor.name,
652
+ });
381
653
  }
382
654
  /**
383
655
  * Gets a value from the default {@link KeyValueStore} associated with the current crawler run.
@@ -412,6 +684,22 @@ export class KeyValueStore {
412
684
  const store = await this.open();
413
685
  return store.getValue(key, defaultValue);
414
686
  }
687
+ /**
688
+ * Reads a record from the default {@link KeyValueStore} associated with the current crawler run
689
+ * without parsing the value.
690
+ *
691
+ * This is just a convenient shortcut for {@link KeyValueStore.getRecord}. Returns `null` if the
692
+ * record does not exist.
693
+ *
694
+ * @param key
695
+ * Unique key of the record. It can be at most 256 characters long and only consist
696
+ * of the following characters: `a`-`z`, `A`-`Z`, `0`-`9` and `!-_.'()`
697
+ * @ignore
698
+ */
699
+ static async getRecord(key) {
700
+ const store = await this.open();
701
+ return store.getRecord(key);
702
+ }
415
703
  /**
416
704
  * Tests whether a record with the given key exists in the default {@link KeyValueStore} associated with the current crawler run.
417
705
  * @param key The queried record key.
@@ -462,8 +750,9 @@ export class KeyValueStore {
462
750
  }
463
751
  /**
464
752
  * Gets the crawler input value from the default {@link KeyValueStore} associated with the current crawler run.
465
- * By default, it will try to find root input files (either extension-less, `.json` or `.txt`),
466
- * or alternatively read the input from the default {@link KeyValueStore}.
753
+ *
754
+ * The input is read from the default {@link KeyValueStore} under the configured input key
755
+ * (`CRAWLEE_INPUT_KEY`, default `INPUT`).
467
756
  *
468
757
  * Note that the `getInput()` function does not cache the value read from the key-value store.
469
758
  * If you need to use the input multiple times in your crawler,
@@ -481,29 +770,25 @@ export class KeyValueStore {
481
770
  */
482
771
  static async getInput() {
483
772
  const store = await this.open();
484
- const inputKey = store.config.get('inputKey');
485
- const cwd = process.cwd();
486
- const possibleExtensions = ['', '.json', '.txt'];
487
- // Attempt to read input from root file instead of key-value store
488
- for (const extension of possibleExtensions) {
489
- const inputFile = join(cwd, `${inputKey}${extension}`);
490
- let input;
491
- // Try getting the file from the file system
492
- try {
493
- input = await readFile(inputFile);
494
- }
495
- catch {
496
- continue;
497
- }
498
- // Attempt to parse as JSON, or return the input as is otherwise
499
- try {
500
- return JSON5.parse(input.toString());
501
- }
502
- catch {
503
- return input;
504
- }
505
- }
506
- return store.getValue(inputKey);
773
+ return store.getValue(store.configuration.inputKey);
774
+ }
775
+ }
776
+ /** Normalizes a codec-serialized value into the `Buffer | ArrayBuffer` shape raw record reads promise. */
777
+ function normalizeSerializedValue(value) {
778
+ if (typeof value === 'string') {
779
+ return Buffer.from(value);
780
+ }
781
+ if (ArrayBuffer.isView(value)) {
782
+ return Buffer.isBuffer(value) ? value : Buffer.from(value.buffer, value.byteOffset, value.byteLength);
507
783
  }
784
+ return value;
785
+ }
786
+ /** Computes the key listing item (serialized byte size and content type) of a buffered entry. */
787
+ function bufferedKeyItemData(key, entry) {
788
+ const serialized = serializeValue(entry.value, entry.options?.contentType);
789
+ return {
790
+ key,
791
+ size: normalizeSerializedValue(serialized.value).byteLength,
792
+ contentType: serialized.contentType,
793
+ };
508
794
  }
509
- //# sourceMappingURL=key_value_store.js.map