@crawlee/core 4.0.0-beta.21 → 4.0.0-beta.211

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 (270) hide show
  1. package/README.md +14 -14
  2. package/byte_utils.d.ts +17 -0
  3. package/byte_utils.js +42 -0
  4. package/configuration.d.ts +88 -227
  5. package/configuration.js +162 -226
  6. package/debug.d.ts +36 -0
  7. package/debug.js +70 -0
  8. package/errors.d.ts +45 -18
  9. package/errors.js +58 -27
  10. package/events/event_manager.d.ts +35 -9
  11. package/events/event_manager.js +12 -13
  12. package/events/index.d.ts +1 -1
  13. package/events/index.js +0 -1
  14. package/events/local_event_manager.d.ts +15 -3
  15. package/events/local_event_manager.js +39 -13
  16. package/events/system_info.d.ts +38 -0
  17. package/events/system_info.js +1 -0
  18. package/index.d.ts +7 -11
  19. package/index.js +8 -10
  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 +40 -0
  35. package/memory-storage/resource-clients/dataset.js +106 -0
  36. package/memory-storage/resource-clients/key-value-store.d.ts +56 -0
  37. package/memory-storage/resource-clients/key-value-store.js +180 -0
  38. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  39. package/memory-storage/resource-clients/request-queue.js +414 -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 +19 -20
  45. package/proxy_configuration.d.ts +28 -77
  46. package/proxy_configuration.js +37 -146
  47. package/recoverable_state.d.ts +106 -52
  48. package/recoverable_state.js +200 -72
  49. package/request.d.ts +48 -93
  50. package/request.js +112 -230
  51. package/serialization.d.ts +0 -1
  52. package/serialization.js +18 -18
  53. package/service_locator.d.ts +168 -0
  54. package/service_locator.js +255 -0
  55. package/storages/batched_adds.d.ts +37 -0
  56. package/storages/batched_adds.js +73 -0
  57. package/storages/dataset.d.ts +115 -58
  58. package/storages/dataset.js +291 -149
  59. package/storages/index.d.ts +8 -9
  60. package/storages/index.js +4 -9
  61. package/storages/key_value_store.d.ts +186 -71
  62. package/storages/key_value_store.js +449 -194
  63. package/storages/key_value_store_codec.d.ts +32 -0
  64. package/storages/key_value_store_codec.js +113 -0
  65. package/storages/request_dedup_cache.d.ts +22 -0
  66. package/storages/request_dedup_cache.js +48 -0
  67. package/storages/request_list.d.ts +50 -133
  68. package/storages/request_list.js +269 -248
  69. package/storages/request_loader.d.ts +127 -0
  70. package/storages/request_loader.js +36 -0
  71. package/storages/request_manager.d.ts +119 -0
  72. package/storages/request_manager.js +1 -0
  73. package/storages/request_manager_tandem.d.ts +50 -24
  74. package/storages/request_manager_tandem.js +134 -58
  75. package/storages/request_queue.d.ts +293 -48
  76. package/storages/request_queue.js +766 -216
  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 +271 -0
  82. package/storages/transaction.js +296 -0
  83. package/storages/utils.d.ts +59 -11
  84. package/storages/utils.js +75 -15
  85. package/system-info/cpu-info.d.ts +67 -0
  86. package/system-info/cpu-info.js +216 -0
  87. package/system-info/memory-info.d.ts +31 -0
  88. package/system-info/memory-info.js +115 -0
  89. package/system-info/ps-tree.d.ts +17 -0
  90. package/system-info/ps-tree.js +144 -0
  91. package/system-info/runtime.d.ts +14 -0
  92. package/system-info/runtime.js +80 -0
  93. package/typedefs.d.ts +0 -6
  94. package/typedefs.js +0 -1
  95. package/url.d.ts +9 -0
  96. package/url.js +11 -0
  97. package/validators.d.ts +23 -18
  98. package/validators.js +14 -18
  99. package/autoscaling/autoscaled_pool.d.ts +0 -300
  100. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  101. package/autoscaling/autoscaled_pool.js +0 -533
  102. package/autoscaling/autoscaled_pool.js.map +0 -1
  103. package/autoscaling/index.d.ts +0 -4
  104. package/autoscaling/index.d.ts.map +0 -1
  105. package/autoscaling/index.js +0 -4
  106. package/autoscaling/index.js.map +0 -1
  107. package/autoscaling/snapshotter.d.ts +0 -189
  108. package/autoscaling/snapshotter.d.ts.map +0 -1
  109. package/autoscaling/snapshotter.js +0 -285
  110. package/autoscaling/snapshotter.js.map +0 -1
  111. package/autoscaling/system_status.d.ts +0 -181
  112. package/autoscaling/system_status.d.ts.map +0 -1
  113. package/autoscaling/system_status.js +0 -169
  114. package/autoscaling/system_status.js.map +0 -1
  115. package/configuration.d.ts.map +0 -1
  116. package/configuration.js.map +0 -1
  117. package/cookie_utils.d.ts +0 -43
  118. package/cookie_utils.d.ts.map +0 -1
  119. package/cookie_utils.js +0 -111
  120. package/cookie_utils.js.map +0 -1
  121. package/crawlers/context_pipeline.d.ts +0 -61
  122. package/crawlers/context_pipeline.d.ts.map +0 -1
  123. package/crawlers/context_pipeline.js +0 -99
  124. package/crawlers/context_pipeline.js.map +0 -1
  125. package/crawlers/crawler_commons.d.ts +0 -194
  126. package/crawlers/crawler_commons.d.ts.map +0 -1
  127. package/crawlers/crawler_commons.js +0 -108
  128. package/crawlers/crawler_commons.js.map +0 -1
  129. package/crawlers/crawler_utils.d.ts +0 -10
  130. package/crawlers/crawler_utils.d.ts.map +0 -1
  131. package/crawlers/crawler_utils.js +0 -12
  132. package/crawlers/crawler_utils.js.map +0 -1
  133. package/crawlers/error_snapshotter.d.ts +0 -60
  134. package/crawlers/error_snapshotter.d.ts.map +0 -1
  135. package/crawlers/error_snapshotter.js +0 -118
  136. package/crawlers/error_snapshotter.js.map +0 -1
  137. package/crawlers/error_tracker.d.ts +0 -55
  138. package/crawlers/error_tracker.d.ts.map +0 -1
  139. package/crawlers/error_tracker.js +0 -309
  140. package/crawlers/error_tracker.js.map +0 -1
  141. package/crawlers/index.d.ts +0 -7
  142. package/crawlers/index.d.ts.map +0 -1
  143. package/crawlers/index.js +0 -7
  144. package/crawlers/index.js.map +0 -1
  145. package/crawlers/internals/types.d.ts +0 -8
  146. package/crawlers/internals/types.d.ts.map +0 -1
  147. package/crawlers/internals/types.js +0 -2
  148. package/crawlers/internals/types.js.map +0 -1
  149. package/crawlers/statistics.d.ts +0 -213
  150. package/crawlers/statistics.d.ts.map +0 -1
  151. package/crawlers/statistics.js +0 -349
  152. package/crawlers/statistics.js.map +0 -1
  153. package/enqueue_links/enqueue_links.d.ts +0 -249
  154. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  155. package/enqueue_links/enqueue_links.js +0 -269
  156. package/enqueue_links/enqueue_links.js.map +0 -1
  157. package/enqueue_links/index.d.ts +0 -3
  158. package/enqueue_links/index.d.ts.map +0 -1
  159. package/enqueue_links/index.js +0 -3
  160. package/enqueue_links/index.js.map +0 -1
  161. package/enqueue_links/shared.d.ts +0 -73
  162. package/enqueue_links/shared.d.ts.map +0 -1
  163. package/enqueue_links/shared.js +0 -212
  164. package/enqueue_links/shared.js.map +0 -1
  165. package/errors.d.ts.map +0 -1
  166. package/errors.js.map +0 -1
  167. package/events/event_manager.d.ts.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.map +0 -1
  173. package/http_clients/base-http-client.d.ts +0 -12
  174. package/http_clients/base-http-client.d.ts.map +0 -1
  175. package/http_clients/base-http-client.js +0 -44
  176. package/http_clients/base-http-client.js.map +0 -1
  177. package/http_clients/form-data-like.d.ts +0 -67
  178. package/http_clients/form-data-like.d.ts.map +0 -1
  179. package/http_clients/form-data-like.js +0 -5
  180. package/http_clients/form-data-like.js.map +0 -1
  181. package/http_clients/got-scraping-http-client.d.ts +0 -22
  182. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  183. package/http_clients/got-scraping-http-client.js +0 -116
  184. package/http_clients/got-scraping-http-client.js.map +0 -1
  185. package/http_clients/index.d.ts +0 -3
  186. package/http_clients/index.d.ts.map +0 -1
  187. package/http_clients/index.js +0 -3
  188. package/http_clients/index.js.map +0 -1
  189. package/index.d.ts.map +0 -1
  190. package/index.js.map +0 -1
  191. package/log.d.ts.map +0 -1
  192. package/log.js.map +0 -1
  193. package/proxy_configuration.d.ts.map +0 -1
  194. package/proxy_configuration.js.map +0 -1
  195. package/recoverable_state.d.ts.map +0 -1
  196. package/recoverable_state.js.map +0 -1
  197. package/request.d.ts.map +0 -1
  198. package/request.js.map +0 -1
  199. package/router.d.ts +0 -134
  200. package/router.d.ts.map +0 -1
  201. package/router.js +0 -164
  202. package/router.js.map +0 -1
  203. package/serialization.d.ts.map +0 -1
  204. package/serialization.js.map +0 -1
  205. package/session_pool/consts.d.ts +0 -4
  206. package/session_pool/consts.d.ts.map +0 -1
  207. package/session_pool/consts.js +0 -4
  208. package/session_pool/consts.js.map +0 -1
  209. package/session_pool/errors.d.ts +0 -8
  210. package/session_pool/errors.d.ts.map +0 -1
  211. package/session_pool/errors.js +0 -12
  212. package/session_pool/errors.js.map +0 -1
  213. package/session_pool/events.d.ts +0 -3
  214. package/session_pool/events.d.ts.map +0 -1
  215. package/session_pool/events.js +0 -3
  216. package/session_pool/events.js.map +0 -1
  217. package/session_pool/index.d.ts +0 -6
  218. package/session_pool/index.d.ts.map +0 -1
  219. package/session_pool/index.js +0 -6
  220. package/session_pool/index.js.map +0 -1
  221. package/session_pool/session.d.ts +0 -186
  222. package/session_pool/session.d.ts.map +0 -1
  223. package/session_pool/session.js +0 -278
  224. package/session_pool/session.js.map +0 -1
  225. package/session_pool/session_pool.d.ts +0 -258
  226. package/session_pool/session_pool.d.ts.map +0 -1
  227. package/session_pool/session_pool.js +0 -387
  228. package/session_pool/session_pool.js.map +0 -1
  229. package/storages/access_checking.d.ts +0 -13
  230. package/storages/access_checking.d.ts.map +0 -1
  231. package/storages/access_checking.js +0 -14
  232. package/storages/access_checking.js.map +0 -1
  233. package/storages/dataset.d.ts.map +0 -1
  234. package/storages/dataset.js.map +0 -1
  235. package/storages/index.d.ts.map +0 -1
  236. package/storages/index.js.map +0 -1
  237. package/storages/key_value_store.d.ts.map +0 -1
  238. package/storages/key_value_store.js.map +0 -1
  239. package/storages/request_list.d.ts.map +0 -1
  240. package/storages/request_list.js.map +0 -1
  241. package/storages/request_list_adapter.d.ts +0 -58
  242. package/storages/request_list_adapter.d.ts.map +0 -1
  243. package/storages/request_list_adapter.js +0 -81
  244. package/storages/request_list_adapter.js.map +0 -1
  245. package/storages/request_manager_tandem.d.ts.map +0 -1
  246. package/storages/request_manager_tandem.js.map +0 -1
  247. package/storages/request_provider.d.ts +0 -372
  248. package/storages/request_provider.d.ts.map +0 -1
  249. package/storages/request_provider.js +0 -591
  250. package/storages/request_provider.js.map +0 -1
  251. package/storages/request_queue.d.ts.map +0 -1
  252. package/storages/request_queue.js.map +0 -1
  253. package/storages/request_queue_v2.d.ts +0 -87
  254. package/storages/request_queue_v2.d.ts.map +0 -1
  255. package/storages/request_queue_v2.js +0 -438
  256. package/storages/request_queue_v2.js.map +0 -1
  257. package/storages/sitemap_request_list.d.ts +0 -250
  258. package/storages/sitemap_request_list.d.ts.map +0 -1
  259. package/storages/sitemap_request_list.js +0 -431
  260. package/storages/sitemap_request_list.js.map +0 -1
  261. package/storages/storage_manager.d.ts +0 -62
  262. package/storages/storage_manager.d.ts.map +0 -1
  263. package/storages/storage_manager.js +0 -105
  264. package/storages/storage_manager.js.map +0 -1
  265. package/storages/utils.d.ts.map +0 -1
  266. package/storages/utils.js.map +0 -1
  267. package/typedefs.d.ts.map +0 -1
  268. package/typedefs.js.map +0 -1
  269. package/validators.d.ts.map +0 -1
  270. package/validators.js.map +0 -1
@@ -0,0 +1,271 @@
1
+ import type { Awaitable, Dictionary, RequestSchema } from '@crawlee/types';
2
+ import type { RecordOptions } from './key_value_store.js';
3
+ /**
4
+ * Governs whether writes of a given storage type performed inside a {@link StorageTransaction} are
5
+ * applied immediately (`writeThrough`) or recorded and replayed on commit (`deferred`).
6
+ */
7
+ export type StorageWriteMode = 'deferred' | 'writeThrough';
8
+ /**
9
+ * Per-storage-type write policy of a {@link StorageTransaction}. Datasets and key-value stores are
10
+ * always `deferred` and not configurable — deferring is the only safe mode for non-idempotent writes,
11
+ * and {@link withDirectStorageAccess} covers one-off immediate writes.
12
+ */
13
+ export interface StorageWritePolicy {
14
+ /**
15
+ * Write mode for request queue additions. Note that this is a *write policy* for the queue, not the
16
+ * queue instance itself (which is the top-level `requestQueue` crawler option).
17
+ *
18
+ * - `writeThrough` (default): requests are added immediately and are **not** rolled back with the
19
+ * transaction. This is safe (additions are deduplicated by `uniqueKey`, so a retry is idempotent)
20
+ * and keeps new requests visible to the crawler while the handler still runs.
21
+ * - `deferred`: requests are only added when the transaction commits — strict all-or-nothing
22
+ * semantics, at the cost of the crawler not seeing them until the handler finishes.
23
+ */
24
+ requestQueue: StorageWriteMode;
25
+ }
26
+ export type StorageTransactionState = 'open' | 'committing' | 'committed' | 'failed' | 'rolledBack';
27
+ /**
28
+ * A storage frontend that can record operations in a transaction journal.
29
+ * @internal
30
+ */
31
+ export interface TransactionParticipant {
32
+ /**
33
+ * Replay the given buffered journal entries (all recorded by this participant) into the real storage
34
+ * backend. Called during commit, with the transaction already in the `committing` state, so the
35
+ * replayed operations pass through.
36
+ */
37
+ commitJournalEntries(entries: JournalEntry[]): Promise<void>;
38
+ }
39
+ /**
40
+ * A single dataset write (`pushData`) recorded in a transaction journal.
41
+ * @internal
42
+ */
43
+ export interface DatasetJournalEntry {
44
+ type: 'dataset';
45
+ /** @internal **/
46
+ participant: TransactionParticipant;
47
+ storageId: string;
48
+ /** The pushed items, captured by `structuredClone` at write time. */
49
+ items: Dictionary[];
50
+ recordedAt: Date;
51
+ }
52
+ /**
53
+ * A single key-value store write (`setValue`) recorded in a transaction journal.
54
+ * @internal
55
+ */
56
+ export interface KeyValueStoreJournalEntry {
57
+ type: 'keyValueStore';
58
+ /** @internal **/
59
+ participant: TransactionParticipant;
60
+ storageId: string;
61
+ key: string;
62
+ /** The original, pre-serialization value captured by `structuredClone`; `null` denotes a deletion. */
63
+ value: unknown;
64
+ options?: RecordOptions;
65
+ }
66
+ /**
67
+ * A request recorded in a transaction journal.
68
+ * @internal
69
+ */
70
+ export interface JournaledRequest {
71
+ url: string;
72
+ uniqueKey: string;
73
+ label?: string;
74
+ /**
75
+ * A full JSON snapshot of the request for the commit replay. Only present for buffered additions —
76
+ * deduplicated and write-through ones are journaled for introspection only.
77
+ */
78
+ snapshot?: RequestSchema;
79
+ }
80
+ /**
81
+ * A batch of request queue additions recorded in a transaction journal.
82
+ * @internal
83
+ */
84
+ export interface RequestQueueJournalEntry {
85
+ type: 'requestQueue';
86
+ /** @internal **/
87
+ participant: TransactionParticipant;
88
+ requests: JournaledRequest[];
89
+ forefront: boolean;
90
+ /** Write-through entries were applied immediately; they are never replayed. */
91
+ writeThrough: boolean;
92
+ }
93
+ /** @internal */
94
+ export type JournalEntry = DatasetJournalEntry | KeyValueStoreJournalEntry | RequestQueueJournalEntry;
95
+ /**
96
+ * A read-only view of a {@link StorageTransaction}: only the journal-backed introspection accessors,
97
+ * without the lifecycle methods. The accessors are synchronous and expose the original pre-serialization
98
+ * values. They cover every write recorded while the transaction was open, under either write policy —
99
+ * with the one exception noted on {@link StorageTransactionView.enqueuedUrls|`enqueuedUrls`}. A view
100
+ * is valid until the transaction is disposed.
101
+ */
102
+ export interface StorageTransactionView {
103
+ readonly state: StorageTransactionState;
104
+ /** Items pushed to datasets during the transaction, in push order. */
105
+ readonly datasetItems: {
106
+ item: Dictionary;
107
+ datasetId: string;
108
+ }[];
109
+ /**
110
+ * URLs enqueued to request queues during the transaction, under either write policy. Recorded as
111
+ * requested, so duplicate, already-present and backend-rejected URLs are included.
112
+ *
113
+ * One gap: unless a caller of `addRequestsBatched()` waits for every chunk
114
+ * (`waitForAllRequestsToBeAdded` or `maxNewRequests`, both of which {@link enqueueLinks} sets when
115
+ * a crawl limit applies), the chunks after the first are added by a background writer that outlives
116
+ * the transaction and is not recorded here.
117
+ */
118
+ readonly enqueuedUrls: {
119
+ url: string;
120
+ label?: string;
121
+ }[];
122
+ /** Key-value store changes made during the transaction, keyed by store id, last write per key. */
123
+ readonly keyValueStoreChanges: Record<string, Record<string, {
124
+ changedValue: unknown;
125
+ options?: RecordOptions;
126
+ }>>;
127
+ }
128
+ export interface StorageTransactionOptions {
129
+ /** Overrides of the per-storage-type write policy. See {@link StorageWritePolicy}. */
130
+ policy?: Partial<StorageWritePolicy>;
131
+ /**
132
+ * How long a commit may take before it fails, in milliseconds. There is no automatic retry — the
133
+ * replay of dataset items is not idempotent.
134
+ * @default 300000
135
+ */
136
+ commitTimeoutMillis?: number;
137
+ }
138
+ /**
139
+ * A storage transaction scoped to a request's lifecycle. Writes made through the storage frontends
140
+ * ({@link Dataset}, {@link KeyValueStore}, {@link RequestQueue}) while the transaction is active
141
+ * are recorded rather than applied; on {@link StorageTransaction.commit|`commit()`} they are replayed
142
+ * into real storage, on {@link StorageTransaction.rollback|`rollback()`} they are dropped. Reads consult
143
+ * the recorded writes first, so a handler sees its own writes.
144
+ *
145
+ * Create one with {@link createStorageTransaction} (explicit commit/rollback) or
146
+ * {@link withStorageTransaction} (scoped sugar). Crawlers open one automatically around every request
147
+ * handler unless `transactionalStorage: false` is set.
148
+ */
149
+ export declare class StorageTransaction implements StorageTransactionView {
150
+ #private;
151
+ /**
152
+ * The ordered, append-only journal — the source of truth for commit, introspection and reads.
153
+ * @internal
154
+ */
155
+ readonly journal: JournalEntry[];
156
+ /** @internal */
157
+ constructor(options?: StorageTransactionOptions);
158
+ /**
159
+ * Per-storage-type write policy.
160
+ * @internal
161
+ */
162
+ get policy(): StorageWritePolicy;
163
+ get state(): StorageTransactionState;
164
+ /**
165
+ * `true` only while `state === 'open'`. This is the single predicate every storage operation
166
+ * consults — operations performed after the transaction is closed pass through to the real backend.
167
+ */
168
+ get isActive(): boolean;
169
+ /** Runs `callback` with this transaction installed in the async context. */
170
+ run<T>(callback: () => Awaitable<T>): Promise<T>;
171
+ /**
172
+ * Records a write operation in the journal.
173
+ * @internal
174
+ */
175
+ recordJournalEntry(entry: JournalEntry): void;
176
+ /**
177
+ * Registers a callback to run once a commit has been attempted, whether it succeeded (`error` is
178
+ * `undefined`) or failed - the only point at which a deferred write can be reacted to where it was
179
+ * made. Callbacks run in registration order; the first to throw propagates, the rest do not run, and
180
+ * on a failed commit its error replaces the commit error. Not run on rollback: nothing was written.
181
+ */
182
+ afterCommit(callback: (error?: Error) => Awaitable<void>): void;
183
+ /**
184
+ * Replays the journaled writes into real storage. A no-op unless the transaction is `open`.
185
+ *
186
+ * The transaction transitions to `committing` *before* anything is flushed, so a commit that throws
187
+ * partway lands in `failed` (never back in `open`) and subsequent storage operations pass through
188
+ * rather than recording into a dead transaction. Delivery is at-least-once — a commit that fails
189
+ * partway may have applied some of the writes already.
190
+ */
191
+ commit(): Promise<void>;
192
+ private flush;
193
+ /**
194
+ * Discards the journaled writes. A no-op unless the transaction is `open` — in particular, calling it
195
+ * after a successful `commit()` (which the crawler's error handling can legitimately do) does nothing
196
+ * and never throws.
197
+ */
198
+ rollback(): void;
199
+ /**
200
+ * Releases the journal, the write-time snapshots it holds and any registered commit callbacks. Must
201
+ * be called for *every* terminal state, `failed` included. Idempotent, never throws, and does not
202
+ * change `state`. Any {@link StorageTransactionView} of this transaction is only valid until this
203
+ * is called.
204
+ */
205
+ dispose(): void;
206
+ get datasetItems(): {
207
+ item: Dictionary;
208
+ datasetId: string;
209
+ }[];
210
+ get enqueuedUrls(): {
211
+ url: string;
212
+ label?: string;
213
+ }[];
214
+ get keyValueStoreChanges(): Record<string, Record<string, {
215
+ changedValue: unknown;
216
+ options?: RecordOptions;
217
+ }>>;
218
+ }
219
+ /**
220
+ * Opens a {@link StorageTransaction} without running anything yet. The caller owns the outcome:
221
+ * `run()`, then `commit()` or `rollback()`, and always `dispose()` when done. For the common
222
+ * open-run-commit flow, prefer {@link withStorageTransaction}.
223
+ */
224
+ export declare function createStorageTransaction(options?: StorageTransactionOptions): StorageTransaction;
225
+ /**
226
+ * Runs `callback` inside a new {@link StorageTransaction}: storage writes made in the callback are
227
+ * committed when it returns and rolled back when it throws. If a transaction is already active in the
228
+ * current async context, it is reused and its outcome is left to its owner (and `options` are ignored)
229
+ * — there are no nested transaction semantics.
230
+ */
231
+ export declare function withStorageTransaction<T>(callback: (transaction: StorageTransaction) => Awaitable<T>, options?: StorageTransactionOptions): Promise<T>;
232
+ /**
233
+ * Runs `callback` outside of any storage transaction — the per-call-site escape hatch. Storage operations
234
+ * made inside it hit the real backend directly, are not rolled back, and operations that a transaction
235
+ * rejects (`drop`, stream-valued `setValue`, request queue internals, ...) are permitted.
236
+ */
237
+ export declare function withDirectStorageAccess<T>(callback: () => Awaitable<T>): Promise<T>;
238
+ /**
239
+ * The per-operation hook consulted by every storage frontend method: performs the cancellation check
240
+ * that aborts storage operations when the request handler times out, and returns the active storage
241
+ * transaction. Returns `undefined` when there is no transaction in the async context *or* when it is no
242
+ * longer open — operations on a closed transaction deliberately pass through to the real backend.
243
+ * @internal
244
+ */
245
+ export declare function activeStorageTransaction(): StorageTransaction | undefined;
246
+ /**
247
+ * Returns the transaction installed in the current async context, regardless of its state. Used by the
248
+ * crawler to drive the outcome of the transaction it opened.
249
+ * @internal
250
+ */
251
+ export declare function currentStorageTransaction(): StorageTransaction | undefined;
252
+ /**
253
+ * Captures a value at write time, so that later mutations of the caller's object affect neither the
254
+ * read-your-own-writes reads nor the commit replay. `structuredClone` for fidelity (`Date`, `Map`, `Set`,
255
+ * typed arrays, `undefined`); values it cannot handle fall back to the JSON round-trip the storage
256
+ * backends perform anyway.
257
+ * @internal
258
+ */
259
+ export declare function snapshotValue<T>(value: T): T;
260
+ /**
261
+ * The guard for operations that cannot be performed inside a storage transaction: throws when one is
262
+ * active, and performs the per-operation cancellation check either way.
263
+ * @internal
264
+ */
265
+ export declare function rejectOperationInTransaction(operation: string, reason?: string): void;
266
+ /**
267
+ * Builds the "operation not allowed in a transaction" error, for a call site that has already
268
+ * established a transaction is active and so wants to `throw` unconditionally.
269
+ * @internal
270
+ */
271
+ export declare function operationRejectedInTransaction(operation: string, reason?: string): Error;
@@ -0,0 +1,296 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { addTimeoutToPromise, storage as timeoutStorage, tryCancel } from '@apify/timeout';
3
+ import { serviceLocator } from '../service_locator.js';
4
+ import { AfterCommitError, NonRetryableError } from '../errors.js';
5
+ const DEFAULT_STORAGE_WRITE_POLICY = { requestQueue: 'writeThrough' };
6
+ const DEFAULT_COMMIT_TIMEOUT_MILLIS = 300_000;
7
+ const transactionStorage = new AsyncLocalStorage();
8
+ const COMMIT_ORDER = ['keyValueStore', 'requestQueue', 'dataset'];
9
+ /**
10
+ * A storage transaction scoped to a request's lifecycle. Writes made through the storage frontends
11
+ * ({@link Dataset}, {@link KeyValueStore}, {@link RequestQueue}) while the transaction is active
12
+ * are recorded rather than applied; on {@link StorageTransaction.commit|`commit()`} they are replayed
13
+ * into real storage, on {@link StorageTransaction.rollback|`rollback()`} they are dropped. Reads consult
14
+ * the recorded writes first, so a handler sees its own writes.
15
+ *
16
+ * Create one with {@link createStorageTransaction} (explicit commit/rollback) or
17
+ * {@link withStorageTransaction} (scoped sugar). Crawlers open one automatically around every request
18
+ * handler unless `transactionalStorage: false` is set.
19
+ */
20
+ export class StorageTransaction {
21
+ /**
22
+ * The ordered, append-only journal — the source of truth for commit, introspection and reads.
23
+ * @internal
24
+ */
25
+ journal = [];
26
+ #policy;
27
+ #commitTimeoutMillis;
28
+ #state = 'open';
29
+ #disposed = false;
30
+ /** Callbacks registered via `afterCommit()`, run in registration order once a commit has been attempted. */
31
+ #afterCommitCallbacks = [];
32
+ /** @internal */
33
+ constructor(options = {}) {
34
+ this.#policy = { ...DEFAULT_STORAGE_WRITE_POLICY, ...options.policy };
35
+ this.#commitTimeoutMillis = options.commitTimeoutMillis ?? DEFAULT_COMMIT_TIMEOUT_MILLIS;
36
+ }
37
+ /**
38
+ * Per-storage-type write policy.
39
+ * @internal
40
+ */
41
+ get policy() {
42
+ return this.#policy;
43
+ }
44
+ get state() {
45
+ return this.#state;
46
+ }
47
+ /**
48
+ * `true` only while `state === 'open'`. This is the single predicate every storage operation
49
+ * consults — operations performed after the transaction is closed pass through to the real backend.
50
+ */
51
+ get isActive() {
52
+ return this.#state === 'open';
53
+ }
54
+ /** Runs `callback` with this transaction installed in the async context. */
55
+ async run(callback) {
56
+ return transactionStorage.run(this, async () => callback());
57
+ }
58
+ /**
59
+ * Records a write operation in the journal.
60
+ * @internal
61
+ */
62
+ recordJournalEntry(entry) {
63
+ if (!this.isActive) {
64
+ throw new Error(`Cannot record a journal entry on a transaction in the '${this.#state}' state`);
65
+ }
66
+ this.journal.push(entry);
67
+ }
68
+ /**
69
+ * Registers a callback to run once a commit has been attempted, whether it succeeded (`error` is
70
+ * `undefined`) or failed - the only point at which a deferred write can be reacted to where it was
71
+ * made. Callbacks run in registration order; the first to throw propagates, the rest do not run, and
72
+ * on a failed commit its error replaces the commit error. Not run on rollback: nothing was written.
73
+ */
74
+ afterCommit(callback) {
75
+ if (!this.isActive) {
76
+ throw new Error(`Cannot register a commit callback on a transaction in the '${this.#state}' state`);
77
+ }
78
+ this.#afterCommitCallbacks.push(callback);
79
+ }
80
+ /**
81
+ * Replays the journaled writes into real storage. A no-op unless the transaction is `open`.
82
+ *
83
+ * The transaction transitions to `committing` *before* anything is flushed, so a commit that throws
84
+ * partway lands in `failed` (never back in `open`) and subsequent storage operations pass through
85
+ * rather than recording into a dead transaction. Delivery is at-least-once — a commit that fails
86
+ * partway may have applied some of the writes already.
87
+ */
88
+ async commit() {
89
+ if (this.#state !== 'open') {
90
+ return;
91
+ }
92
+ this.#state = 'committing';
93
+ try {
94
+ // The replay re-drives the frontend write path, which checks for cancellation (`tryCancel`)
95
+ // on every operation - and `@apify/timeout` shares one `AbortController` across nested
96
+ // frames, so a request-handler timeout that already fired would abort the commit of a
97
+ // handler that succeeded. Hence a fresh timeout context, which also provides the time bound.
98
+ await timeoutStorage.exit(async () => addTimeoutToPromise(async () => this.flush(), this.#commitTimeoutMillis, `Committing the storage transaction timed out after ${this.#commitTimeoutMillis / 1000} seconds.`));
99
+ }
100
+ catch (error) {
101
+ this.#state = 'failed';
102
+ // Callbacks are handed an `Error`, so a backend that rejects with anything else gets wrapped.
103
+ const commitError = error instanceof Error ? error : new Error(String(error), { cause: error });
104
+ // A callback that throws here propagates instead: it was handed the failure and decided what
105
+ // the request should fail with.
106
+ await this.#runAfterCommitCallbacks(commitError);
107
+ throw commitError;
108
+ }
109
+ this.#state = 'committed';
110
+ try {
111
+ await this.#runAfterCommitCallbacks();
112
+ }
113
+ catch (error) {
114
+ throw error instanceof NonRetryableError ? error : new AfterCommitError(error);
115
+ }
116
+ }
117
+ /** Fresh timeout context for the same reason as the flush. */
118
+ async #runAfterCommitCallbacks(error) {
119
+ await timeoutStorage.exit(async () => {
120
+ for (const callback of this.#afterCommitCallbacks) {
121
+ await callback(error);
122
+ }
123
+ });
124
+ }
125
+ async flush() {
126
+ // Each participating frontend replays all of its buffered entries in one call. Frontends are
127
+ // ordered by storage type: key-value stores and request queues first (idempotent under retry),
128
+ // datasets last (not idempotent), minimizing the blast radius of a partial commit failure.
129
+ const groups = new Map();
130
+ for (const entry of this.journal) {
131
+ if (entry.type === 'requestQueue' && entry.writeThrough)
132
+ continue;
133
+ const group = groups.get(entry.participant);
134
+ if (group)
135
+ group.push(entry);
136
+ else
137
+ groups.set(entry.participant, [entry]);
138
+ }
139
+ // A participant only records entries of its own storage type, so the first entry determines
140
+ // the group's place in the commit order.
141
+ const orderedGroups = [...groups.values()].sort((a, b) => COMMIT_ORDER.indexOf(a[0].type) - COMMIT_ORDER.indexOf(b[0].type));
142
+ for (const entries of orderedGroups) {
143
+ await entries[0].participant.commitJournalEntries(entries);
144
+ }
145
+ }
146
+ /**
147
+ * Discards the journaled writes. A no-op unless the transaction is `open` — in particular, calling it
148
+ * after a successful `commit()` (which the crawler's error handling can legitimately do) does nothing
149
+ * and never throws.
150
+ */
151
+ rollback() {
152
+ if (this.#state !== 'open') {
153
+ return;
154
+ }
155
+ this.#state = 'rolledBack';
156
+ }
157
+ /**
158
+ * Releases the journal, the write-time snapshots it holds and any registered commit callbacks. Must
159
+ * be called for *every* terminal state, `failed` included. Idempotent, never throws, and does not
160
+ * change `state`. Any {@link StorageTransactionView} of this transaction is only valid until this
161
+ * is called.
162
+ */
163
+ dispose() {
164
+ if (this.#disposed) {
165
+ return;
166
+ }
167
+ if (this.#state === 'open') {
168
+ // Disposing an open transaction is an internal invariant violation - roll back first.
169
+ try {
170
+ serviceLocator
171
+ .getLogger()
172
+ .warning('Internal error: a storage transaction was disposed while still open; rolling it back.');
173
+ }
174
+ catch {
175
+ // Never throw from dispose.
176
+ }
177
+ this.rollback();
178
+ }
179
+ this.#disposed = true;
180
+ this.journal.length = 0;
181
+ this.#afterCommitCallbacks.length = 0;
182
+ }
183
+ get datasetItems() {
184
+ return this.journal.flatMap((entry) => entry.type === 'dataset' ? entry.items.map((item) => ({ item, datasetId: entry.storageId })) : []);
185
+ }
186
+ get enqueuedUrls() {
187
+ return this.journal.flatMap((entry) => entry.type === 'requestQueue' ? entry.requests.map(({ url, label }) => ({ url, label })) : []);
188
+ }
189
+ get keyValueStoreChanges() {
190
+ const result = {};
191
+ for (const entry of this.journal) {
192
+ if (entry.type !== 'keyValueStore')
193
+ continue;
194
+ result[entry.storageId] ??= {};
195
+ result[entry.storageId][entry.key] = { changedValue: entry.value, options: entry.options };
196
+ }
197
+ return result;
198
+ }
199
+ }
200
+ /**
201
+ * Opens a {@link StorageTransaction} without running anything yet. The caller owns the outcome:
202
+ * `run()`, then `commit()` or `rollback()`, and always `dispose()` when done. For the common
203
+ * open-run-commit flow, prefer {@link withStorageTransaction}.
204
+ */
205
+ export function createStorageTransaction(options = {}) {
206
+ return new StorageTransaction(options);
207
+ }
208
+ /**
209
+ * Runs `callback` inside a new {@link StorageTransaction}: storage writes made in the callback are
210
+ * committed when it returns and rolled back when it throws. If a transaction is already active in the
211
+ * current async context, it is reused and its outcome is left to its owner (and `options` are ignored)
212
+ * — there are no nested transaction semantics.
213
+ */
214
+ export async function withStorageTransaction(callback, options = {}) {
215
+ const existing = transactionStorage.getStore();
216
+ if (existing?.isActive) {
217
+ return callback(existing);
218
+ }
219
+ const transaction = createStorageTransaction(options);
220
+ try {
221
+ const result = await transaction.run(async () => callback(transaction));
222
+ await transaction.commit();
223
+ return result;
224
+ }
225
+ catch (error) {
226
+ transaction.rollback();
227
+ throw error;
228
+ }
229
+ finally {
230
+ transaction.dispose();
231
+ }
232
+ }
233
+ /**
234
+ * Runs `callback` outside of any storage transaction — the per-call-site escape hatch. Storage operations
235
+ * made inside it hit the real backend directly, are not rolled back, and operations that a transaction
236
+ * rejects (`drop`, stream-valued `setValue`, request queue internals, ...) are permitted.
237
+ */
238
+ export async function withDirectStorageAccess(callback) {
239
+ return transactionStorage.exit(async () => callback());
240
+ }
241
+ /**
242
+ * The per-operation hook consulted by every storage frontend method: performs the cancellation check
243
+ * that aborts storage operations when the request handler times out, and returns the active storage
244
+ * transaction. Returns `undefined` when there is no transaction in the async context *or* when it is no
245
+ * longer open — operations on a closed transaction deliberately pass through to the real backend.
246
+ * @internal
247
+ */
248
+ export function activeStorageTransaction() {
249
+ tryCancel();
250
+ const transaction = transactionStorage.getStore();
251
+ return transaction?.isActive ? transaction : undefined;
252
+ }
253
+ /**
254
+ * Returns the transaction installed in the current async context, regardless of its state. Used by the
255
+ * crawler to drive the outcome of the transaction it opened.
256
+ * @internal
257
+ */
258
+ export function currentStorageTransaction() {
259
+ return transactionStorage.getStore();
260
+ }
261
+ /**
262
+ * Captures a value at write time, so that later mutations of the caller's object affect neither the
263
+ * read-your-own-writes reads nor the commit replay. `structuredClone` for fidelity (`Date`, `Map`, `Set`,
264
+ * typed arrays, `undefined`); values it cannot handle fall back to the JSON round-trip the storage
265
+ * backends perform anyway.
266
+ * @internal
267
+ */
268
+ export function snapshotValue(value) {
269
+ try {
270
+ return structuredClone(value);
271
+ }
272
+ catch {
273
+ return JSON.parse(JSON.stringify(value));
274
+ }
275
+ }
276
+ /**
277
+ * The guard for operations that cannot be performed inside a storage transaction: throws when one is
278
+ * active, and performs the per-operation cancellation check either way.
279
+ * @internal
280
+ */
281
+ export function rejectOperationInTransaction(operation, reason = 'it cannot be rolled back.') {
282
+ if (activeStorageTransaction() === undefined) {
283
+ return;
284
+ }
285
+ throw operationRejectedInTransaction(operation, reason);
286
+ }
287
+ /**
288
+ * Builds the "operation not allowed in a transaction" error, for a call site that has already
289
+ * established a transaction is active and so wants to `throw` unconditionally.
290
+ * @internal
291
+ */
292
+ export function operationRejectedInTransaction(operation, reason = 'it cannot be rolled back.') {
293
+ return new Error(`${operation} cannot be used inside a storage transaction: ${reason} ` +
294
+ 'If you really need it, wrap the call in withDirectStorageAccess(() => ...) - operations ' +
295
+ 'performed there are applied immediately and are not rolled back.');
296
+ }
@@ -1,5 +1,7 @@
1
- import type { Dictionary, StorageClient } from '@crawlee/types';
1
+ import type { BaseHttpClient } from '@crawlee/http-client';
2
+ import type { Dictionary, StorageBackend } from '@crawlee/types';
2
3
  import { Configuration } from '../configuration.js';
4
+ import type { IProxyConfiguration } from '../proxy_configuration.js';
3
5
  /**
4
6
  * Options for purging default storage.
5
7
  */
@@ -8,18 +10,19 @@ interface PurgeDefaultStorageOptions {
8
10
  * If set to `true`, calling multiple times will only have effect at the first time.
9
11
  */
10
12
  onlyPurgeOnce?: boolean;
11
- config?: Configuration;
12
- client?: StorageClient;
13
+ configuration?: Configuration;
14
+ storageBackend?: StorageBackend;
13
15
  }
14
16
  /**
15
17
  * Cleans up the local storage folder (defaults to `./storage`) created when running code locally.
16
- * Purging will remove all the files in all storages except for INPUT.json in the default KV store.
18
+ * Purging empties the storages that belong to a single run — the default one and every alias-keyed one —
19
+ * Named storages persist across runs and are not touched.
17
20
  *
18
21
  * Purging of storages is happening automatically when we run our crawler (or when we open some storage
19
22
  * explicitly, e.g. via `RequestList.open()`). We can disable that via `purgeOnStart` {@link Configuration}
20
23
  * option or by setting `CRAWLEE_PURGE_ON_START` environment variable to `0` or `false`.
21
24
  *
22
- * This is a shortcut for running (optional) `purge` method on the StorageClient interface, in other words
25
+ * This is a shortcut for running (optional) `purge` method on the StorageBackend interface, in other words
23
26
  * it will call the `purge` method of the underlying storage implementation we are currently using. You can
24
27
  * make sure the storage is purged only once for a given execution context if you set `onlyPurgeOnce` to `true` in
25
28
  * the `options` object
@@ -27,18 +30,19 @@ interface PurgeDefaultStorageOptions {
27
30
  export declare function purgeDefaultStorages(options?: PurgeDefaultStorageOptions): Promise<void>;
28
31
  /**
29
32
  * Cleans up the local storage folder (defaults to `./storage`) created when running code locally.
30
- * Purging will remove all the files in all storages except for INPUT.json in the default KV store.
33
+ * Purging empties the storages that belong to a single run — the default one and every alias-keyed one —
34
+ * Named storages persist across runs and are not touched.
31
35
  *
32
36
  * Purging of storages is happening automatically when we run our crawler (or when we open some storage
33
37
  * explicitly, e.g. via `RequestList.open()`). We can disable that via `purgeOnStart` {@link Configuration}
34
38
  * option or by setting `CRAWLEE_PURGE_ON_START` environment variable to `0` or `false`.
35
39
  *
36
- * This is a shortcut for running (optional) `purge` method on the StorageClient interface, in other words
40
+ * This is a shortcut for running (optional) `purge` method on the StorageBackend interface, in other words
37
41
  * it will call the `purge` method of the underlying storage implementation we are currently using.
38
42
  */
39
- export declare function purgeDefaultStorages(config?: Configuration, client?: StorageClient): Promise<void>;
43
+ export declare function purgeDefaultStorages(configuration?: Configuration, storageBackend?: StorageBackend): Promise<void>;
40
44
  export interface UseStateOptions {
41
- config?: Configuration;
45
+ configuration?: Configuration;
42
46
  /**
43
47
  * The name of the key-value store you'd like the state to be stored in.
44
48
  * If not provided, the default store will be used.
@@ -52,7 +56,7 @@ export interface UseStateOptions {
52
56
  *
53
57
  * @param name The name of the store to use.
54
58
  * @param defaultValue If the store does not yet have a value in it, the value will be initialized with the `defaultValue` you provide.
55
- * @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
59
+ * @param options An optional object parameter where a custom `keyValueStoreName` and `configuration` can be passed in.
56
60
  */
57
61
  export declare function useState<State extends Dictionary = Dictionary>(name?: string, defaultValue?: State, options?: UseStateOptions): Promise<State>;
58
62
  /**
@@ -89,5 +93,49 @@ export declare const API_PROCESSED_REQUESTS_DELAY_MILLIS = 10000;
89
93
  * @internal
90
94
  */
91
95
  export declare const MAX_QUERIES_FOR_CONSISTENCY = 6;
96
+ /** @internal */
97
+ export interface DualIterableOptions<TItem, TRawPage> {
98
+ /** Factory that returns an async generator yielding pages. */
99
+ createPages: () => AsyncGenerator<TRawPage>;
100
+ /** Extracts individual items from a page (for iteration). */
101
+ extractItems: (page: TRawPage) => TItem[];
102
+ }
103
+ /**
104
+ * Creates an object that is both an `AsyncIterable<TItem>` (for `for await...of`)
105
+ * and a `Promise<TItem[]>` (for `await`) from a single async page generator.
106
+ *
107
+ * - `await result` drains all pages from a fresh generator and returns every
108
+ * item as a flat array.
109
+ * - `for await (const item of result)` streams all items across all pages,
110
+ * yielding them one by one without buffering everything in memory.
111
+ *
112
+ * Each usage path creates its own generator instance, so `await` and
113
+ * `for await...of` never interfere with each other.
114
+ *
115
+ * @internal
116
+ */
117
+ export declare function createDualIterable<TItem, TRawPage>(options: DualIterableOptions<TItem, TRawPage>): AsyncIterable<TItem> & Promise<TItem[]>;
118
+ /**
119
+ * Options for the static `open()` method on storage classes ({@link Dataset}, {@link KeyValueStore}, {@link RequestQueue}).
120
+ */
121
+ export interface StorageOpenOptions {
122
+ /**
123
+ * SDK configuration instance, defaults to the static register.
124
+ */
125
+ configuration?: Configuration;
126
+ /**
127
+ * Optional storage backend that should be used to open storages.
128
+ */
129
+ storageBackend?: StorageBackend;
130
+ /**
131
+ * Used to pass the proxy configuration for the `requestsFromUrl` objects.
132
+ * Takes advantage of the internal address rotation and authentication process.
133
+ * If undefined, the `requestsFromUrl` requests will be made without proxy.
134
+ */
135
+ proxyConfiguration?: IProxyConfiguration;
136
+ /**
137
+ * HTTP client to be used to download the list of URLs in `RequestQueue`.
138
+ */
139
+ httpClient?: BaseHttpClient;
140
+ }
92
141
  export {};
93
- //# sourceMappingURL=utils.d.ts.map