@crawlee/core 3.0.0-alpha.2 → 3.0.0-alpha.22

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 (159) hide show
  1. package/autoscaling/autoscaled_pool.d.ts +296 -0
  2. package/autoscaling/autoscaled_pool.d.ts.map +1 -0
  3. package/autoscaling/autoscaled_pool.js +673 -0
  4. package/autoscaling/autoscaled_pool.js.map +1 -0
  5. package/autoscaling/index.d.ts +4 -0
  6. package/autoscaling/index.d.ts.map +1 -0
  7. package/autoscaling/index.js +7 -0
  8. package/autoscaling/index.js.map +1 -0
  9. package/autoscaling/snapshotter.d.ts +193 -0
  10. package/autoscaling/snapshotter.d.ts.map +1 -0
  11. package/autoscaling/snapshotter.js +377 -0
  12. package/autoscaling/snapshotter.js.map +1 -0
  13. package/autoscaling/system_status.d.ts +181 -0
  14. package/autoscaling/system_status.d.ts.map +1 -0
  15. package/autoscaling/system_status.js +194 -0
  16. package/autoscaling/system_status.js.map +1 -0
  17. package/cache_container.d.ts +18 -0
  18. package/cache_container.d.ts.map +1 -0
  19. package/cache_container.js +42 -0
  20. package/cache_container.js.map +1 -0
  21. package/configuration.d.ts +150 -0
  22. package/configuration.d.ts.map +1 -0
  23. package/configuration.js +284 -0
  24. package/configuration.js.map +1 -0
  25. package/constants.d.ts +3 -0
  26. package/constants.d.ts.map +1 -0
  27. package/constants.js +6 -0
  28. package/constants.js.map +1 -0
  29. package/crawlers/crawler_commons.d.ts +25 -0
  30. package/crawlers/crawler_commons.d.ts.map +1 -0
  31. package/crawlers/crawler_commons.js +3 -0
  32. package/crawlers/crawler_commons.js.map +1 -0
  33. package/crawlers/crawler_extension.d.ts +11 -0
  34. package/crawlers/crawler_extension.d.ts.map +1 -0
  35. package/crawlers/crawler_extension.js +30 -0
  36. package/crawlers/crawler_extension.js.map +1 -0
  37. package/crawlers/crawler_utils.d.ts +20 -0
  38. package/crawlers/crawler_utils.d.ts.map +1 -0
  39. package/crawlers/crawler_utils.js +61 -0
  40. package/crawlers/crawler_utils.js.map +1 -0
  41. package/crawlers/index.d.ts +5 -0
  42. package/crawlers/index.d.ts.map +1 -0
  43. package/crawlers/index.js +8 -0
  44. package/crawlers/index.js.map +1 -0
  45. package/crawlers/statistics.d.ts +147 -0
  46. package/crawlers/statistics.d.ts.map +1 -0
  47. package/crawlers/statistics.js +360 -0
  48. package/crawlers/statistics.js.map +1 -0
  49. package/enqueue_links/enqueue_links.d.ts +151 -0
  50. package/enqueue_links/enqueue_links.d.ts.map +1 -0
  51. package/enqueue_links/enqueue_links.js +152 -0
  52. package/enqueue_links/enqueue_links.js.map +1 -0
  53. package/enqueue_links/index.d.ts +3 -0
  54. package/enqueue_links/index.d.ts.map +1 -0
  55. package/enqueue_links/index.js +6 -0
  56. package/enqueue_links/index.js.map +1 -0
  57. package/enqueue_links/shared.d.ts +60 -0
  58. package/enqueue_links/shared.d.ts.map +1 -0
  59. package/enqueue_links/shared.js +148 -0
  60. package/enqueue_links/shared.js.map +1 -0
  61. package/errors.d.ts +8 -0
  62. package/errors.d.ts.map +1 -0
  63. package/errors.js +12 -0
  64. package/errors.js.map +1 -0
  65. package/events/event_manager.d.ts +41 -0
  66. package/events/event_manager.d.ts.map +1 -0
  67. package/events/event_manager.js +103 -0
  68. package/events/event_manager.js.map +1 -0
  69. package/events/index.d.ts +3 -0
  70. package/events/index.d.ts.map +1 -0
  71. package/events/index.js +6 -0
  72. package/events/index.js.map +1 -0
  73. package/events/local_event_manager.d.ts +32 -0
  74. package/events/local_event_manager.d.ts.map +1 -0
  75. package/events/local_event_manager.js +114 -0
  76. package/events/local_event_manager.js.map +1 -0
  77. package/index.d.ts +14 -0
  78. package/index.d.ts.map +1 -0
  79. package/index.js +17 -0
  80. package/index.js.map +1 -0
  81. package/index.mjs +61 -0
  82. package/log.d.ts +3 -0
  83. package/log.d.ts.map +1 -0
  84. package/log.js +12 -0
  85. package/log.js.map +1 -0
  86. package/package.json +4 -8
  87. package/proxy_configuration.d.ts +181 -0
  88. package/proxy_configuration.d.ts.map +1 -0
  89. package/proxy_configuration.js +209 -0
  90. package/proxy_configuration.js.map +1 -0
  91. package/request.d.ts +185 -0
  92. package/request.d.ts.map +1 -0
  93. package/request.js +330 -0
  94. package/request.js.map +1 -0
  95. package/serialization.d.ts +33 -0
  96. package/serialization.d.ts.map +1 -0
  97. package/serialization.js +146 -0
  98. package/serialization.js.map +1 -0
  99. package/session_pool/errors.d.ts +8 -0
  100. package/session_pool/errors.d.ts.map +1 -0
  101. package/session_pool/errors.js +20 -0
  102. package/session_pool/errors.js.map +1 -0
  103. package/session_pool/events.d.ts +3 -0
  104. package/session_pool/events.d.ts.map +1 -0
  105. package/session_pool/events.js +6 -0
  106. package/session_pool/events.js.map +1 -0
  107. package/session_pool/index.d.ts +6 -0
  108. package/session_pool/index.d.ts.map +1 -0
  109. package/session_pool/index.js +9 -0
  110. package/session_pool/index.js.map +1 -0
  111. package/session_pool/session.d.ts +212 -0
  112. package/session_pool/session.d.ts.map +1 -0
  113. package/session_pool/session.js +360 -0
  114. package/session_pool/session.js.map +1 -0
  115. package/session_pool/session_pool.d.ts +222 -0
  116. package/session_pool/session_pool.d.ts.map +1 -0
  117. package/session_pool/session_pool.js +389 -0
  118. package/session_pool/session_pool.js.map +1 -0
  119. package/session_pool/session_utils.d.ts +9 -0
  120. package/session_pool/session_utils.d.ts.map +1 -0
  121. package/session_pool/session_utils.js +19 -0
  122. package/session_pool/session_utils.js.map +1 -0
  123. package/storages/dataset.d.ts +317 -0
  124. package/storages/dataset.d.ts.map +1 -0
  125. package/storages/dataset.js +367 -0
  126. package/storages/dataset.js.map +1 -0
  127. package/storages/index.d.ts +7 -0
  128. package/storages/index.d.ts.map +1 -0
  129. package/storages/index.js +11 -0
  130. package/storages/index.js.map +1 -0
  131. package/storages/key_value_store.d.ts +242 -0
  132. package/storages/key_value_store.d.ts.map +1 -0
  133. package/storages/key_value_store.js +320 -0
  134. package/storages/key_value_store.js.map +1 -0
  135. package/storages/request_list.d.ts +469 -0
  136. package/storages/request_list.d.ts.map +1 -0
  137. package/storages/request_list.js +724 -0
  138. package/storages/request_list.js.map +1 -0
  139. package/storages/request_queue.d.ts +315 -0
  140. package/storages/request_queue.d.ts.map +1 -0
  141. package/storages/request_queue.js +730 -0
  142. package/storages/request_queue.js.map +1 -0
  143. package/storages/storage.d.ts +260 -0
  144. package/storages/storage.d.ts.map +1 -0
  145. package/storages/storage.js +3 -0
  146. package/storages/storage.js.map +1 -0
  147. package/storages/storage_manager.d.ts +40 -0
  148. package/storages/storage_manager.d.ts.map +1 -0
  149. package/storages/storage_manager.js +119 -0
  150. package/storages/storage_manager.js.map +1 -0
  151. package/tsconfig.build.tsbuildinfo +1 -0
  152. package/typedefs.d.ts +12 -0
  153. package/typedefs.d.ts.map +1 -0
  154. package/typedefs.js +15 -0
  155. package/typedefs.js.map +1 -0
  156. package/validators.d.ts +21 -0
  157. package/validators.d.ts.map +1 -0
  158. package/validators.js +26 -0
  159. package/validators.js.map +1 -0
@@ -0,0 +1,317 @@
1
+ import { Awaitable, Dictionary } from '../typedefs';
2
+ import { StorageManagerOptions } from './storage_manager';
3
+ import { DatasetClient, DatasetInfo, PaginatedList, StorageClient } from './storage';
4
+ /** @internal */
5
+ export declare const DATASET_ITERATORS_DEFAULT_LIMIT = 10000;
6
+ /**
7
+ * Accepts a JSON serializable object as an input, validates its serializability,
8
+ * and validates its serialized size against limitBytes. Optionally accepts its index
9
+ * in an array to provide better error messages. Returns serialized object.
10
+ * @ignore
11
+ */
12
+ export declare function checkAndSerialize<T>(item: T, limitBytes: number, index?: number): string;
13
+ /**
14
+ * Takes an array of JSONs (payloads) as input and produces an array of JSON strings
15
+ * where each string is a JSON array of payloads with a maximum size of limitBytes per one
16
+ * JSON array. Fits as many payloads as possible into a single JSON array and then moves
17
+ * on to the next, preserving item order.
18
+ *
19
+ * The function assumes that none of the items is larger than limitBytes and does not validate.
20
+ * @ignore
21
+ */
22
+ export declare function chunkBySize(items: string[], limitBytes: number): string[];
23
+ export interface DatasetDataOptions {
24
+ /**
25
+ * Number of array elements that should be skipped at the start.
26
+ * @default 0
27
+ */
28
+ offset?: number;
29
+ /**
30
+ * Maximum number of array elements to return.
31
+ * @default 250000
32
+ */
33
+ limit?: number;
34
+ /**
35
+ * If `true` then the objects are sorted by `createdAt` in descending order.
36
+ * Otherwise they are sorted in ascending order.
37
+ * @default false
38
+ */
39
+ desc?: boolean;
40
+ /**
41
+ * An array of field names that will be included in the result. If omitted, all fields are included in the results.
42
+ */
43
+ fields?: string[];
44
+ /**
45
+ * Specifies a name of the field in the result objects that will be used to unwind the resulting objects.
46
+ * By default, the results are returned as they are.
47
+ */
48
+ unwind?: string;
49
+ /**
50
+ * If `true` then the function returns only non-empty items and skips hidden fields (i.e. fields starting with `#` character).
51
+ * Note that the `clean` parameter is a shortcut for `skipHidden: true` and `skipEmpty: true` options.
52
+ * @default false
53
+ */
54
+ clean?: boolean;
55
+ /**
56
+ * If `true` then the function doesn't return hidden fields (fields starting with "#" character).
57
+ * @default false
58
+ */
59
+ skipHidden?: boolean;
60
+ /**
61
+ * If `true` then the function doesn't return empty items.
62
+ * Note that in this case the returned number of items might be lower than limit parameter and pagination must be done using the `limit` value.
63
+ * @default false
64
+ */
65
+ skipEmpty?: boolean;
66
+ }
67
+ export interface DatasetIteratorOptions extends Omit<DatasetDataOptions, 'offset' | 'limit' | 'clean' | 'skipHidden' | 'skipEmpty'> {
68
+ /** @internal */
69
+ offset?: number;
70
+ /**
71
+ * @default 10000
72
+ * @internal
73
+ */
74
+ limit?: number;
75
+ /** @internal */
76
+ clean?: boolean;
77
+ /** @internal */
78
+ skipHidden?: boolean;
79
+ /** @internal */
80
+ skipEmpty?: boolean;
81
+ /** @internal */
82
+ format?: string;
83
+ }
84
+ /**
85
+ * The `Dataset` class represents a store for structured data where each object stored has the same attributes,
86
+ * such as online store products or real estate offers. You can imagine it as a table,
87
+ * where each object is a row and its attributes are columns.
88
+ * Dataset is an append-only storage - you can only add new records to it but you cannot modify or remove existing records.
89
+ * Typically it is used to store crawling results.
90
+ *
91
+ * Do not instantiate this class directly, use the
92
+ * {@link Dataset.open} function instead.
93
+ *
94
+ * `Dataset` stores its data either on local disk or in the Apify cloud,
95
+ * depending on whether the `APIFY_LOCAL_STORAGE_DIR` or `APIFY_TOKEN` environment variables are set.
96
+ *
97
+ * If the `APIFY_LOCAL_STORAGE_DIR` environment variable is set, the data is stored in
98
+ * the local directory in the following files:
99
+ * ```
100
+ * {APIFY_LOCAL_STORAGE_DIR}/datasets/{DATASET_ID}/{INDEX}.json
101
+ * ```
102
+ * Note that `{DATASET_ID}` is the name or ID of the dataset. The default dataset has ID: `default`,
103
+ * unless you override it by setting the `APIFY_DEFAULT_DATASET_ID` environment variable.
104
+ * Each dataset item is stored as a separate JSON file, where `{INDEX}` is a zero-based index of the item in the dataset.
105
+ *
106
+ * If the `APIFY_TOKEN` environment variable is set but `APIFY_LOCAL_STORAGE_DIR` not, the data is stored in the
107
+ * [Apify Dataset](https://docs.apify.com/storage/dataset)
108
+ * cloud storage. Note that you can force usage of the cloud storage also by passing the `forceCloud`
109
+ * option to {@link Dataset.open} function,
110
+ * even if the `APIFY_LOCAL_STORAGE_DIR` variable is set.
111
+ *
112
+ * **Example usage:**
113
+ *
114
+ * ```javascript
115
+ * // Write a single row to the default dataset
116
+ * await Actor.pushData({ col1: 123, col2: 'val2' });
117
+ *
118
+ * // Open a named dataset
119
+ * const dataset = await Dataset.open('some-name');
120
+ *
121
+ * // Write a single row
122
+ * await dataset.pushData({ foo: 'bar' });
123
+ *
124
+ * // Write multiple rows
125
+ * await dataset.pushData([
126
+ * { foo: 'bar2', col2: 'val2' },
127
+ * { col3: 123 },
128
+ * ]);
129
+ * ```
130
+ * @category Result Stores
131
+ */
132
+ export declare class Dataset<Data extends Dictionary = Dictionary> {
133
+ id: string;
134
+ name?: string;
135
+ client: DatasetClient<Data>;
136
+ log: import("@apify/log/log").Log;
137
+ /**
138
+ * @internal
139
+ */
140
+ constructor(options: DatasetOptions);
141
+ /**
142
+ * Stores an object or an array of objects to the dataset.
143
+ * The function returns a promise that resolves when the operation finishes.
144
+ * It has no result, but throws on invalid args or other errors.
145
+ *
146
+ * **IMPORTANT**: Make sure to use the `await` keyword when calling `pushData()`,
147
+ * otherwise the actor process might finish before the data is stored!
148
+ *
149
+ * The size of the data is limited by the receiving API and therefore `pushData()` will only
150
+ * allow objects whose JSON representation is smaller than 9MB. When an array is passed,
151
+ * none of the included objects
152
+ * may be larger than 9MB, but the array itself may be of any size.
153
+ *
154
+ * The function internally
155
+ * chunks the array into separate items and pushes them sequentially.
156
+ * The chunking process is stable (keeps order of data), but it does not provide a transaction
157
+ * safety mechanism. Therefore, in the event of an uploading error (after several automatic retries),
158
+ * the function's Promise will reject and the dataset will be left in a state where some of
159
+ * the items have already been saved to the dataset while other items from the source array were not.
160
+ * To overcome this limitation, the developer may, for example, read the last item saved in the dataset
161
+ * and re-attempt the save of the data from this item onwards to prevent duplicates.
162
+ * @param data Object or array of objects containing data to be stored in the default dataset.
163
+ * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
164
+ */
165
+ pushData(data: Data | Data[]): Promise<void>;
166
+ /**
167
+ * Returns {@link DatasetContent} object holding the items in the dataset based on the provided parameters.
168
+ *
169
+ * If you need to get data in an unparsed format, use the {@link Actor.newClient} function to get a new
170
+ * `apify-client` instance and call
171
+ * [`datasetClient.downloadItems()`](https://github.com/apify/apify-client-js#DatasetClient+downloadItems)
172
+ */
173
+ getData(options?: DatasetDataOptions): Promise<PaginatedList<Data>>;
174
+ /**
175
+ * Returns an object containing general information about the dataset.
176
+ *
177
+ * The function returns the same object as the Apify API Client's
178
+ * [getDataset](https://docs.apify.com/api/apify-client-js/latest#ApifyClient-datasets-getDataset)
179
+ * function, which in turn calls the
180
+ * [Get dataset](https://apify.com/docs/api/v2#/reference/datasets/dataset/get-dataset)
181
+ * API endpoint.
182
+ *
183
+ * **Example:**
184
+ * ```
185
+ * {
186
+ * id: "WkzbQMuFYuamGv3YF",
187
+ * name: "my-dataset",
188
+ * userId: "wRsJZtadYvn4mBZmm",
189
+ * createdAt: new Date("2015-12-12T07:34:14.202Z"),
190
+ * modifiedAt: new Date("2015-12-13T08:36:13.202Z"),
191
+ * accessedAt: new Date("2015-12-14T08:36:13.202Z"),
192
+ * itemCount: 14,
193
+ * cleanItemCount: 10
194
+ * }
195
+ * ```
196
+ */
197
+ getInfo(): Promise<DatasetInfo | undefined>;
198
+ /**
199
+ * Iterates over dataset items, yielding each in turn to an `iteratee` function.
200
+ * Each invocation of `iteratee` is called with two arguments: `(item, index)`.
201
+ *
202
+ * If the `iteratee` function returns a Promise then it is awaited before the next call.
203
+ * If it throws an error, the iteration is aborted and the `forEach` function throws the error.
204
+ *
205
+ * **Example usage**
206
+ * ```javascript
207
+ * const dataset = await Dataset.open('my-results');
208
+ * await dataset.forEach(async (item, index) => {
209
+ * console.log(`Item at ${index}: ${JSON.stringify(item)}`);
210
+ * });
211
+ * ```
212
+ *
213
+ * @param iteratee A function that is called for every item in the dataset.
214
+ * @param [options] All `forEach()` parameters.
215
+ * @param [index] Specifies the initial index number passed to the `iteratee` function.
216
+ * @default 0
217
+ */
218
+ forEach(iteratee: DatasetConsumer<Data>, options?: DatasetIteratorOptions, index?: number): Promise<void>;
219
+ /**
220
+ * Produces a new array of values by mapping each value in list through a transformation function `iteratee()`.
221
+ * Each invocation of `iteratee()` is called with two arguments: `(element, index)`.
222
+ *
223
+ * If `iteratee` returns a `Promise` then it's awaited before a next call.
224
+ *
225
+ * @param iteratee
226
+ * @param [options] All `map()` parameters.
227
+ */
228
+ map<R>(iteratee: DatasetMapper<Data, R>, options?: DatasetIteratorOptions): Promise<R[]>;
229
+ /**
230
+ * Reduces a list of values down to a single value.
231
+ *
232
+ * Memo is the initial state of the reduction, and each successive step of it should be returned by `iteratee()`.
233
+ * The `iteratee()` is passed three arguments: the `memo`, then the `value` and `index` of the iteration.
234
+ *
235
+ * If no `memo` is passed to the initial invocation of reduce, the `iteratee()` is not invoked on the first element of the list.
236
+ * The first element is instead passed as the memo in the invocation of the `iteratee()` on the next element in the list.
237
+ *
238
+ * If `iteratee()` returns a `Promise` then it's awaited before a next call.
239
+ *
240
+ * @param iteratee
241
+ * @param memo Initial state of the reduction.
242
+ * @param [options] All `reduce()` parameters.
243
+ */
244
+ reduce<T>(iteratee: DatasetReducer<T, Data>, memo: T, options?: DatasetIteratorOptions): Promise<T>;
245
+ /**
246
+ * Removes the dataset either from the Apify cloud storage or from the local directory,
247
+ * depending on the mode of operation.
248
+ */
249
+ drop(): Promise<void>;
250
+ /**
251
+ * Opens a dataset and returns a promise resolving to an instance of the {@link Dataset} class.
252
+ *
253
+ * Datasets are used to store structured data where each object stored has the same attributes,
254
+ * such as online store products or real estate offers.
255
+ * The actual data is stored either on the local filesystem or in the cloud.
256
+ *
257
+ * For more details and code examples, see the {@link Dataset} class.
258
+ *
259
+ * @param [datasetIdOrName]
260
+ * ID or name of the dataset to be opened. If `null` or `undefined`,
261
+ * the function returns the default dataset associated with the actor run.
262
+ * @param [options] Storage manager options.
263
+ */
264
+ static open<Data extends Dictionary = Dictionary>(datasetIdOrName?: string | null, options?: StorageManagerOptions): Promise<Dataset<Data>>;
265
+ }
266
+ /**
267
+ * User-function used in the `Dataset.forEach()` API.
268
+ */
269
+ export interface DatasetConsumer<Data> {
270
+ /**
271
+ * @param item Current {@link Dataset} entry being processed.
272
+ * @param index Position of current {Dataset} entry.
273
+ */
274
+ (item: Data, index: number): Awaitable<void>;
275
+ }
276
+ /**
277
+ * User-function used in the `Dataset.map()` API.
278
+ */
279
+ export interface DatasetMapper<Data, R> {
280
+ /**
281
+ * User-function used in the `Dataset.map()` API.
282
+ * @param item Current {@link Dataset} entry being processed.
283
+ * @param index Position of current {Dataset} entry.
284
+ */
285
+ (item: Data, index: number): Awaitable<R>;
286
+ }
287
+ /**
288
+ * User-function used in the `Dataset.reduce()` API.
289
+ */
290
+ export interface DatasetReducer<T, Data> {
291
+ /**
292
+ * @param memo Previous state of the reduction.
293
+ * @param item Current {@link Dataset} entry being processed.
294
+ * @param index Position of current {Dataset} entry.
295
+ */
296
+ (memo: T, item: Data, index: number): Awaitable<T>;
297
+ }
298
+ export interface DatasetOptions {
299
+ id: string;
300
+ name?: string;
301
+ client: StorageClient;
302
+ }
303
+ export interface DatasetContent<Data> {
304
+ /** Total count of entries in the dataset. */
305
+ total: number;
306
+ /** Count of dataset entries returned in this set. */
307
+ count: number;
308
+ /** Position of the first returned entry in the dataset. */
309
+ offset: number;
310
+ /** Maximum number of dataset entries requested. */
311
+ limit: number;
312
+ /** Should the results be in descending order. */
313
+ desc: boolean;
314
+ /** Dataset entries based on chosen format parameter. */
315
+ items: Data[];
316
+ }
317
+ //# sourceMappingURL=dataset.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dataset.d.ts","sourceRoot":"","sources":["../../src/storages/dataset.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAkB,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAErF,gBAAgB;AAChB,eAAO,MAAM,+BAA+B,QAAQ,CAAC;AAIrD;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,UAAU,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAsBxF;AAED;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,EAAE,CA8BzE;AAED,MAAM,WAAW,kBAAkB;IAC/B;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAA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7C;AAED;;GAEG;AACH,MAAM,WAAW,cAAc,CAAC,CAAC,EAAE,IAAI;IAEnC;;;;OAIG;IACH,CAAC,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;CAEtD;AAED,MAAM,WAAW,cAAc;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,aAAa,CAAC;CACzB;AAGD,MAAM,WAAW,cAAc,CAAC,IAAI;IAChC,6CAA6C;IAC7C,KAAK,EAAE,MAAM,CAAC;IACd,qDAAqD;IACrD,KAAK,EAAE,MAAM,CAAC;IACd,2DAA2D;IAC3D,MAAM,EAAE,MAAM,CAAC;IACf,mDAAmD;IACnD,KAAK,EAAE,MAAM,CAAC;IACd,iDAAiD;IACjD,IAAI,EAAE,OAAO,CAAC;IACd,wDAAwD;IACxD,KAAK,EAAE,IAAI,EAAE,CAAC;CACjB"}
@@ -0,0 +1,367 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Dataset = exports.chunkBySize = exports.checkAndSerialize = exports.DATASET_ITERATORS_DEFAULT_LIMIT = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const consts_1 = require("@apify/consts");
6
+ const ow_1 = tslib_1.__importDefault(require("ow"));
7
+ const configuration_1 = require("../configuration");
8
+ const log_1 = require("../log");
9
+ const storage_manager_1 = require("./storage_manager");
10
+ /** @internal */
11
+ exports.DATASET_ITERATORS_DEFAULT_LIMIT = 10000;
12
+ const SAFETY_BUFFER_PERCENT = 0.01 / 100; // 0.01%
13
+ /**
14
+ * Accepts a JSON serializable object as an input, validates its serializability,
15
+ * and validates its serialized size against limitBytes. Optionally accepts its index
16
+ * in an array to provide better error messages. Returns serialized object.
17
+ * @ignore
18
+ */
19
+ function checkAndSerialize(item, limitBytes, index) {
20
+ const s = typeof index === 'number' ? ` at index ${index} ` : ' ';
21
+ const isItemObject = item && typeof item === 'object' && !Array.isArray(item);
22
+ if (!isItemObject) {
23
+ throw new Error(`Data item${s}is not an object. You can push only objects into a dataset.`);
24
+ }
25
+ let payload;
26
+ try {
27
+ payload = JSON.stringify(item);
28
+ }
29
+ catch (e) {
30
+ const err = e;
31
+ throw new Error(`Data item${s}is not serializable to JSON.\nCause: ${err.message}`);
32
+ }
33
+ const bytes = Buffer.byteLength(payload);
34
+ if (bytes > limitBytes) {
35
+ throw new Error(`Data item${s}is too large (size: ${bytes} bytes, limit: ${limitBytes} bytes)`);
36
+ }
37
+ return payload;
38
+ }
39
+ exports.checkAndSerialize = checkAndSerialize;
40
+ /**
41
+ * Takes an array of JSONs (payloads) as input and produces an array of JSON strings
42
+ * where each string is a JSON array of payloads with a maximum size of limitBytes per one
43
+ * JSON array. Fits as many payloads as possible into a single JSON array and then moves
44
+ * on to the next, preserving item order.
45
+ *
46
+ * The function assumes that none of the items is larger than limitBytes and does not validate.
47
+ * @ignore
48
+ */
49
+ function chunkBySize(items, limitBytes) {
50
+ if (!items.length)
51
+ return [];
52
+ if (items.length === 1)
53
+ return items;
54
+ // Split payloads into buckets of valid size.
55
+ let lastChunkBytes = 2; // Add 2 bytes for [] wrapper.
56
+ const chunks = [];
57
+ for (const payload of items) {
58
+ const bytes = Buffer.byteLength(payload);
59
+ if (bytes <= limitBytes && (bytes + 2) > limitBytes) {
60
+ // Handle cases where wrapping with [] would fail, but solo object is fine.
61
+ chunks.push(payload);
62
+ lastChunkBytes = bytes;
63
+ }
64
+ else if (lastChunkBytes + bytes <= limitBytes) {
65
+ // ensure array
66
+ if (!Array.isArray(chunks[chunks.length - 1])) {
67
+ chunks.push([]);
68
+ }
69
+ chunks[chunks.length - 1].push(payload);
70
+ lastChunkBytes += bytes + 1; // Add 1 byte for ',' separator.
71
+ }
72
+ else {
73
+ chunks.push([payload]);
74
+ lastChunkBytes = bytes + 2; // Add 2 bytes for [] wrapper.
75
+ }
76
+ }
77
+ // Stringify array chunks.
78
+ return chunks.map((chunk) => (typeof chunk === 'string' ? chunk : `[${chunk.join(',')}]`));
79
+ }
80
+ exports.chunkBySize = chunkBySize;
81
+ /**
82
+ * The `Dataset` class represents a store for structured data where each object stored has the same attributes,
83
+ * such as online store products or real estate offers. You can imagine it as a table,
84
+ * where each object is a row and its attributes are columns.
85
+ * Dataset is an append-only storage - you can only add new records to it but you cannot modify or remove existing records.
86
+ * Typically it is used to store crawling results.
87
+ *
88
+ * Do not instantiate this class directly, use the
89
+ * {@link Dataset.open} function instead.
90
+ *
91
+ * `Dataset` stores its data either on local disk or in the Apify cloud,
92
+ * depending on whether the `APIFY_LOCAL_STORAGE_DIR` or `APIFY_TOKEN` environment variables are set.
93
+ *
94
+ * If the `APIFY_LOCAL_STORAGE_DIR` environment variable is set, the data is stored in
95
+ * the local directory in the following files:
96
+ * ```
97
+ * {APIFY_LOCAL_STORAGE_DIR}/datasets/{DATASET_ID}/{INDEX}.json
98
+ * ```
99
+ * Note that `{DATASET_ID}` is the name or ID of the dataset. The default dataset has ID: `default`,
100
+ * unless you override it by setting the `APIFY_DEFAULT_DATASET_ID` environment variable.
101
+ * Each dataset item is stored as a separate JSON file, where `{INDEX}` is a zero-based index of the item in the dataset.
102
+ *
103
+ * If the `APIFY_TOKEN` environment variable is set but `APIFY_LOCAL_STORAGE_DIR` not, the data is stored in the
104
+ * [Apify Dataset](https://docs.apify.com/storage/dataset)
105
+ * cloud storage. Note that you can force usage of the cloud storage also by passing the `forceCloud`
106
+ * option to {@link Dataset.open} function,
107
+ * even if the `APIFY_LOCAL_STORAGE_DIR` variable is set.
108
+ *
109
+ * **Example usage:**
110
+ *
111
+ * ```javascript
112
+ * // Write a single row to the default dataset
113
+ * await Actor.pushData({ col1: 123, col2: 'val2' });
114
+ *
115
+ * // Open a named dataset
116
+ * const dataset = await Dataset.open('some-name');
117
+ *
118
+ * // Write a single row
119
+ * await dataset.pushData({ foo: 'bar' });
120
+ *
121
+ * // Write multiple rows
122
+ * await dataset.pushData([
123
+ * { foo: 'bar2', col2: 'val2' },
124
+ * { col3: 123 },
125
+ * ]);
126
+ * ```
127
+ * @category Result Stores
128
+ */
129
+ class Dataset {
130
+ /**
131
+ * @internal
132
+ */
133
+ constructor(options) {
134
+ Object.defineProperty(this, "id", {
135
+ enumerable: true,
136
+ configurable: true,
137
+ writable: true,
138
+ value: void 0
139
+ });
140
+ Object.defineProperty(this, "name", {
141
+ enumerable: true,
142
+ configurable: true,
143
+ writable: true,
144
+ value: void 0
145
+ });
146
+ Object.defineProperty(this, "client", {
147
+ enumerable: true,
148
+ configurable: true,
149
+ writable: true,
150
+ value: void 0
151
+ });
152
+ Object.defineProperty(this, "log", {
153
+ enumerable: true,
154
+ configurable: true,
155
+ writable: true,
156
+ value: log_1.log.child({ prefix: 'Dataset' })
157
+ });
158
+ this.id = options.id;
159
+ this.name = options.name;
160
+ this.client = options.client.dataset(this.id);
161
+ }
162
+ /**
163
+ * Stores an object or an array of objects to the dataset.
164
+ * The function returns a promise that resolves when the operation finishes.
165
+ * It has no result, but throws on invalid args or other errors.
166
+ *
167
+ * **IMPORTANT**: Make sure to use the `await` keyword when calling `pushData()`,
168
+ * otherwise the actor process might finish before the data is stored!
169
+ *
170
+ * The size of the data is limited by the receiving API and therefore `pushData()` will only
171
+ * allow objects whose JSON representation is smaller than 9MB. When an array is passed,
172
+ * none of the included objects
173
+ * may be larger than 9MB, but the array itself may be of any size.
174
+ *
175
+ * The function internally
176
+ * chunks the array into separate items and pushes them sequentially.
177
+ * The chunking process is stable (keeps order of data), but it does not provide a transaction
178
+ * safety mechanism. Therefore, in the event of an uploading error (after several automatic retries),
179
+ * the function's Promise will reject and the dataset will be left in a state where some of
180
+ * the items have already been saved to the dataset while other items from the source array were not.
181
+ * To overcome this limitation, the developer may, for example, read the last item saved in the dataset
182
+ * and re-attempt the save of the data from this item onwards to prevent duplicates.
183
+ * @param data Object or array of objects containing data to be stored in the default dataset.
184
+ * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
185
+ */
186
+ async pushData(data) {
187
+ (0, ow_1.default)(data, 'data', ow_1.default.object);
188
+ const dispatch = (payload) => this.client.pushItems(payload);
189
+ const limit = consts_1.MAX_PAYLOAD_SIZE_BYTES - Math.ceil(consts_1.MAX_PAYLOAD_SIZE_BYTES * SAFETY_BUFFER_PERCENT);
190
+ // Handle singular Objects
191
+ if (!Array.isArray(data)) {
192
+ const payload = checkAndSerialize(data, limit);
193
+ return dispatch(payload);
194
+ }
195
+ // Handle Arrays
196
+ const payloads = data.map((item, index) => checkAndSerialize(item, limit, index));
197
+ const chunks = chunkBySize(payloads, limit);
198
+ // Invoke client in series to preserve order of data
199
+ for (const chunk of chunks) {
200
+ await dispatch(chunk);
201
+ }
202
+ }
203
+ /**
204
+ * Returns {@link DatasetContent} object holding the items in the dataset based on the provided parameters.
205
+ *
206
+ * If you need to get data in an unparsed format, use the {@link Actor.newClient} function to get a new
207
+ * `apify-client` instance and call
208
+ * [`datasetClient.downloadItems()`](https://github.com/apify/apify-client-js#DatasetClient+downloadItems)
209
+ */
210
+ async getData(options = {}) {
211
+ try {
212
+ return await this.client.listItems(options);
213
+ }
214
+ catch (e) {
215
+ const error = e;
216
+ if (error.message.includes('Cannot create a string longer than')) {
217
+ throw new Error('dataset.getData(): The response is too large for parsing. You can fix this by lowering the "limit" option.');
218
+ }
219
+ throw e;
220
+ }
221
+ }
222
+ /**
223
+ * Returns an object containing general information about the dataset.
224
+ *
225
+ * The function returns the same object as the Apify API Client's
226
+ * [getDataset](https://docs.apify.com/api/apify-client-js/latest#ApifyClient-datasets-getDataset)
227
+ * function, which in turn calls the
228
+ * [Get dataset](https://apify.com/docs/api/v2#/reference/datasets/dataset/get-dataset)
229
+ * API endpoint.
230
+ *
231
+ * **Example:**
232
+ * ```
233
+ * {
234
+ * id: "WkzbQMuFYuamGv3YF",
235
+ * name: "my-dataset",
236
+ * userId: "wRsJZtadYvn4mBZmm",
237
+ * createdAt: new Date("2015-12-12T07:34:14.202Z"),
238
+ * modifiedAt: new Date("2015-12-13T08:36:13.202Z"),
239
+ * accessedAt: new Date("2015-12-14T08:36:13.202Z"),
240
+ * itemCount: 14,
241
+ * cleanItemCount: 10
242
+ * }
243
+ * ```
244
+ */
245
+ async getInfo() {
246
+ return this.client.get();
247
+ }
248
+ /**
249
+ * Iterates over dataset items, yielding each in turn to an `iteratee` function.
250
+ * Each invocation of `iteratee` is called with two arguments: `(item, index)`.
251
+ *
252
+ * If the `iteratee` function returns a Promise then it is awaited before the next call.
253
+ * If it throws an error, the iteration is aborted and the `forEach` function throws the error.
254
+ *
255
+ * **Example usage**
256
+ * ```javascript
257
+ * const dataset = await Dataset.open('my-results');
258
+ * await dataset.forEach(async (item, index) => {
259
+ * console.log(`Item at ${index}: ${JSON.stringify(item)}`);
260
+ * });
261
+ * ```
262
+ *
263
+ * @param iteratee A function that is called for every item in the dataset.
264
+ * @param [options] All `forEach()` parameters.
265
+ * @param [index] Specifies the initial index number passed to the `iteratee` function.
266
+ * @default 0
267
+ */
268
+ async forEach(iteratee, options = {}, index = 0) {
269
+ if (!options.offset)
270
+ options.offset = 0;
271
+ if (options.format && options.format !== 'json')
272
+ throw new Error('Dataset.forEach/map/reduce() support only a "json" format.');
273
+ if (!options.limit)
274
+ options.limit = exports.DATASET_ITERATORS_DEFAULT_LIMIT;
275
+ const { items, total, limit, offset } = await this.getData(options);
276
+ for (const item of items) {
277
+ await iteratee(item, index++);
278
+ }
279
+ const newOffset = offset + limit;
280
+ if (newOffset >= total)
281
+ return;
282
+ const newOpts = { ...options, offset: newOffset };
283
+ return this.forEach(iteratee, newOpts, index);
284
+ }
285
+ /**
286
+ * Produces a new array of values by mapping each value in list through a transformation function `iteratee()`.
287
+ * Each invocation of `iteratee()` is called with two arguments: `(element, index)`.
288
+ *
289
+ * If `iteratee` returns a `Promise` then it's awaited before a next call.
290
+ *
291
+ * @param iteratee
292
+ * @param [options] All `map()` parameters.
293
+ */
294
+ async map(iteratee, options = {}) {
295
+ const result = [];
296
+ await this.forEach(async (item, index) => {
297
+ const res = await iteratee(item, index);
298
+ result.push(res);
299
+ }, options);
300
+ return result;
301
+ }
302
+ /**
303
+ * Reduces a list of values down to a single value.
304
+ *
305
+ * Memo is the initial state of the reduction, and each successive step of it should be returned by `iteratee()`.
306
+ * The `iteratee()` is passed three arguments: the `memo`, then the `value` and `index` of the iteration.
307
+ *
308
+ * If no `memo` is passed to the initial invocation of reduce, the `iteratee()` is not invoked on the first element of the list.
309
+ * The first element is instead passed as the memo in the invocation of the `iteratee()` on the next element in the list.
310
+ *
311
+ * If `iteratee()` returns a `Promise` then it's awaited before a next call.
312
+ *
313
+ * @param iteratee
314
+ * @param memo Initial state of the reduction.
315
+ * @param [options] All `reduce()` parameters.
316
+ */
317
+ async reduce(iteratee, memo, options = {}) {
318
+ let currentMemo = memo;
319
+ const wrappedFunc = (item, index) => {
320
+ return Promise
321
+ .resolve()
322
+ .then(() => {
323
+ return !index && currentMemo === undefined
324
+ ? item
325
+ : iteratee(currentMemo, item, index);
326
+ })
327
+ .then((newMemo) => {
328
+ currentMemo = newMemo;
329
+ });
330
+ };
331
+ await this.forEach(wrappedFunc, options);
332
+ return currentMemo;
333
+ }
334
+ /**
335
+ * Removes the dataset either from the Apify cloud storage or from the local directory,
336
+ * depending on the mode of operation.
337
+ */
338
+ async drop() {
339
+ await this.client.delete();
340
+ const manager = new storage_manager_1.StorageManager(Dataset);
341
+ manager.closeStorage(this);
342
+ }
343
+ /**
344
+ * Opens a dataset and returns a promise resolving to an instance of the {@link Dataset} class.
345
+ *
346
+ * Datasets are used to store structured data where each object stored has the same attributes,
347
+ * such as online store products or real estate offers.
348
+ * The actual data is stored either on the local filesystem or in the cloud.
349
+ *
350
+ * For more details and code examples, see the {@link Dataset} class.
351
+ *
352
+ * @param [datasetIdOrName]
353
+ * ID or name of the dataset to be opened. If `null` or `undefined`,
354
+ * the function returns the default dataset associated with the actor run.
355
+ * @param [options] Storage manager options.
356
+ */
357
+ static async open(datasetIdOrName, options = {}) {
358
+ (0, ow_1.default)(datasetIdOrName, ow_1.default.optional.string);
359
+ (0, ow_1.default)(options, ow_1.default.object.exactShape({
360
+ config: ow_1.default.optional.object.instanceOf(configuration_1.Configuration),
361
+ }));
362
+ const manager = new storage_manager_1.StorageManager(Dataset, options.config);
363
+ return manager.openStorage(datasetIdOrName);
364
+ }
365
+ }
366
+ exports.Dataset = Dataset;
367
+ //# sourceMappingURL=dataset.js.map