scrapfly-sdk 0.12.0 → 0.12.2

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 (85) hide show
  1. package/README.md +38 -9
  2. package/esm/browserconfig.d.ts +20 -4
  3. package/esm/browserconfig.d.ts.map +1 -1
  4. package/esm/browserconfig.js +12 -2
  5. package/esm/browserdownloads.d.ts +70 -0
  6. package/esm/browserdownloads.d.ts.map +1 -0
  7. package/esm/browserdownloads.js +215 -0
  8. package/esm/client.d.ts +107 -4
  9. package/esm/client.d.ts.map +1 -1
  10. package/esm/client.js +307 -24
  11. package/esm/crawl.d.ts +26 -1
  12. package/esm/crawl.d.ts.map +1 -1
  13. package/esm/crawl.js +18 -0
  14. package/esm/crawlerconfig.d.ts +8 -3
  15. package/esm/crawlerconfig.d.ts.map +1 -1
  16. package/esm/crawlerconfig.js +1 -1
  17. package/esm/crawlerresult.d.ts +39 -0
  18. package/esm/crawlerresult.d.ts.map +1 -1
  19. package/esm/main.d.ts +10 -5
  20. package/esm/main.d.ts.map +1 -1
  21. package/esm/main.js +8 -3
  22. package/esm/monitoringconfig.d.ts +2 -2
  23. package/esm/result.d.ts +11 -1
  24. package/esm/result.d.ts.map +1 -1
  25. package/esm/result.js +14 -5
  26. package/esm/scrapeconfig.d.ts +19 -7
  27. package/esm/scrapeconfig.d.ts.map +1 -1
  28. package/esm/scrapeconfig.js +33 -1
  29. package/esm/screenshotconfig.d.ts +8 -1
  30. package/esm/screenshotconfig.d.ts.map +1 -1
  31. package/esm/screenshotconfig.js +12 -1
  32. package/esm/types.d.ts +128 -0
  33. package/esm/types.d.ts.map +1 -1
  34. package/esm/types.js +22 -1
  35. package/esm/utils.d.ts.map +1 -1
  36. package/esm/utils.js +16 -2
  37. package/package.json +1 -1
  38. package/script/browserconfig.d.ts +20 -4
  39. package/script/browserconfig.d.ts.map +1 -1
  40. package/script/browserconfig.js +12 -2
  41. package/script/browserdownloads.d.ts +70 -0
  42. package/script/browserdownloads.d.ts.map +1 -0
  43. package/script/browserdownloads.js +221 -0
  44. package/script/client.d.ts +107 -4
  45. package/script/client.d.ts.map +1 -1
  46. package/script/client.js +307 -24
  47. package/script/crawl.d.ts +26 -1
  48. package/script/crawl.d.ts.map +1 -1
  49. package/script/crawl.js +18 -0
  50. package/script/crawlerconfig.d.ts +8 -3
  51. package/script/crawlerconfig.d.ts.map +1 -1
  52. package/script/crawlerconfig.js +1 -1
  53. package/script/crawlerresult.d.ts +39 -0
  54. package/script/crawlerresult.d.ts.map +1 -1
  55. package/script/main.d.ts +10 -5
  56. package/script/main.d.ts.map +1 -1
  57. package/script/main.js +13 -4
  58. package/script/monitoringconfig.d.ts +2 -2
  59. package/script/result.d.ts +11 -1
  60. package/script/result.d.ts.map +1 -1
  61. package/script/result.js +14 -5
  62. package/script/scrapeconfig.d.ts +19 -7
  63. package/script/scrapeconfig.d.ts.map +1 -1
  64. package/script/scrapeconfig.js +33 -1
  65. package/script/screenshotconfig.d.ts +8 -1
  66. package/script/screenshotconfig.d.ts.map +1 -1
  67. package/script/screenshotconfig.js +12 -1
  68. package/script/types.d.ts +128 -0
  69. package/script/types.d.ts.map +1 -1
  70. package/script/types.js +23 -0
  71. package/script/utils.d.ts.map +1 -1
  72. package/script/utils.js +16 -2
  73. package/src/browserconfig.ts +22 -4
  74. package/src/browserdownloads.ts +266 -0
  75. package/src/client.ts +390 -27
  76. package/src/crawl.ts +32 -0
  77. package/src/crawlerconfig.ts +8 -3
  78. package/src/crawlerresult.ts +41 -0
  79. package/src/main.ts +31 -4
  80. package/src/monitoringconfig.ts +2 -2
  81. package/src/result.ts +13 -5
  82. package/src/scrapeconfig.ts +24 -7
  83. package/src/screenshotconfig.ts +13 -1
  84. package/src/types.ts +159 -0
  85. package/src/utils.ts +16 -2
package/script/types.js CHANGED
@@ -1,2 +1,25 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VaultLinkedService = void 0;
4
+ // ---------------------------------------------------------------------------
5
+ // Linked secret managers (1Password).
6
+ //
7
+ // A linked vault mirrors an upstream secret manager: the provider's
8
+ // service-account token is sealed under the vault key as a reserved item, and
9
+ // the syncer owns every row it imports. The token travels in the request body
10
+ // of link / update / test and is NEVER stored by the caller, logged, or echoed
11
+ // back by the server.
12
+ // ---------------------------------------------------------------------------
13
+ /**
14
+ * Linked-service discriminator, and the only closed value set a caller has to
15
+ * name when linking. 1Password is the sole entry in the server's linked-service
16
+ * registry; anything else is a 400, not a typed provider error.
17
+ */
18
+ var VaultLinkedService;
19
+ (function (VaultLinkedService) {
20
+ /**
21
+ * 1Password service account. Also the `source` written on every row its
22
+ * syncer mirrors.
23
+ */
24
+ VaultLinkedService["ONE_PASSWORD"] = "1password";
25
+ })(VaultLinkedService || (exports.VaultLinkedService = VaultLinkedService = {}));
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAEtC,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAQtD;AAED,MAAM,MAAM,cAAc,GAAG;IAC3B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,GAAG,CAAC;IAMd,IAAI,CAAC,EAAE,MAAM,GAAG,UAAU,GAAG,GAAG,CAAC;CAClC,CAAC;AAEF,wBAAsB,UAAU,CAC9B,MAAM,EAAE,cAAc,EACtB,OAAO,GAAE,MAAU,EACnB,UAAU,GAAE,MAAa,GACxB,OAAO,CAAC,QAAQ,CAAC,CA6CnB;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,OAAO,GAAG,GAAG,CAAC,MAAM,CAAC,CAc5E"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAEtC,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAQtD;AAED,MAAM,MAAM,cAAc,GAAG;IAC3B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,GAAG,CAAC;IAMd,IAAI,CAAC,EAAE,MAAM,GAAG,UAAU,GAAG,GAAG,CAAC;CAClC,CAAC;AAcF,wBAAsB,UAAU,CAC9B,MAAM,EAAE,cAAc,EACtB,OAAO,GAAE,MAAU,EACnB,UAAU,GAAE,MAAa,GACxB,OAAO,CAAC,QAAQ,CAAC,CA+CnB;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,OAAO,GAAG,GAAG,CAAC,MAAM,CAAC,CAc5E"}
package/script/utils.js CHANGED
@@ -13,6 +13,18 @@ function urlsafe_b64encode(data) {
13
13
  .replace(/=+$/, '');
14
14
  return base64;
15
15
  }
16
+ const KEY_IN_URL = /(?<=[?&]key=)[^&\s)'"]+/g;
17
+ /**
18
+ * Mask the API key in a fetch error, in place: Deno prints the request URL,
19
+ * query and key included, in the message and in the stack it captured.
20
+ */
21
+ function maskKey(error) {
22
+ if (!(error instanceof Error))
23
+ return;
24
+ error.message = error.message.replace(KEY_IN_URL, 'REDACTED');
25
+ if (error.stack !== undefined)
26
+ error.stack = error.stack.replace(KEY_IN_URL, 'REDACTED');
27
+ }
16
28
  async function fetchRetry(config, retries = 3, retryDelay = 1000) {
17
29
  let lastError = null;
18
30
  for (let attempt = 1; attempt <= retries; attempt++) {
@@ -31,8 +43,9 @@ async function fetchRetry(config, retries = 3, retryDelay = 1000) {
31
43
  body: reqInit.body,
32
44
  };
33
45
  const response = await fetch(new Request(url, init));
34
- // retry 5xx status codes
35
- if (response.status >= 500 && response.status < 600) {
46
+ // Retry 5xx status codes. A single-attempt caller reads the 5xx body
47
+ // itself: it carries the typed error.
48
+ if (response.status >= 500 && response.status < 600 && retries > 1) {
36
49
  const _text = await response.text(); // consume response to prevent leak
37
50
  lastError = new Error(`Fetch failed with status: ${response.status}`);
38
51
  if (attempt < retries) {
@@ -45,6 +58,7 @@ async function fetchRetry(config, retries = 3, retryDelay = 1000) {
45
58
  }
46
59
  }
47
60
  catch (error) {
61
+ maskKey(error);
48
62
  lastError = error;
49
63
  // AbortError should never be retried: it means the caller explicitly
50
64
  // gave up (cancel token, timeout, etc.) and we shouldn't paper over it.
@@ -74,9 +74,17 @@ export type BrowserConfigOptions = {
74
74
  cache?: boolean;
75
75
  /** Apply Scrapfly's abuse blacklist. */
76
76
  blacklist?: boolean;
77
- /** Enable anti-scraping-protection bypass. */
77
+ /**
78
+ * @deprecated The Cloud Browser WebSocket endpoint does not read this
79
+ * parameter; it is sent but has no effect. Use
80
+ * {@link ScrapflyClient.cloudBrowserUnblock} (the `/unblock` endpoint).
81
+ */
78
82
  unblock?: boolean;
79
- /** Timeout in seconds for the unblock step. */
83
+ /**
84
+ * @deprecated The Cloud Browser WebSocket endpoint does not read this
85
+ * parameter; it is sent but has no effect. Use
86
+ * {@link ScrapflyClient.cloudBrowserUnblock}, which takes its own timeouts.
87
+ */
80
88
  unblock_timeout?: number;
81
89
  /** Browser brand to emulate (e.g. "chrome", "firefox"). */
82
90
  browser_brand?: string;
@@ -119,6 +127,12 @@ export type BrowserConfigOptions = {
119
127
  * comma-separated string or an array of bare IPs / CIDRs.
120
128
  */
121
129
  hitl_allowed_networks?: string | string[];
130
+ /**
131
+ * Return large downloaded files from `ScrapiumBrowser.getDownloads` as IO stream handles instead of
132
+ * inline base64: read them with `CloudBrowserDownloads`.
133
+ * See https://scrapfly.io/docs/cloud-browser-api/file-downloads#large-downloads
134
+ */
135
+ downloads_stream?: boolean;
122
136
  };
123
137
 
124
138
  /**
@@ -165,9 +179,9 @@ export class BrowserConfig {
165
179
  cache?: boolean;
166
180
  /** See {@link BrowserConfigOptions.blacklist}. */
167
181
  blacklist?: boolean;
168
- /** See {@link BrowserConfigOptions.unblock}. */
182
+ /** @deprecated Not read by the API, see {@link BrowserConfigOptions.unblock}. */
169
183
  unblock?: boolean;
170
- /** See {@link BrowserConfigOptions.unblock_timeout}. */
184
+ /** @deprecated Not read by the API, see {@link BrowserConfigOptions.unblock_timeout}. */
171
185
  unblock_timeout?: number;
172
186
  /** See {@link BrowserConfigOptions.browser_brand}. */
173
187
  browser_brand?: string;
@@ -191,6 +205,8 @@ export class BrowserConfig {
191
205
  rtc_password?: string;
192
206
  /** See {@link BrowserConfigOptions.hitl_allowed_networks}. */
193
207
  hitl_allowed_networks?: string;
208
+ /** See {@link BrowserConfigOptions.downloads_stream}. */
209
+ downloads_stream?: boolean;
194
210
 
195
211
  /**
196
212
  * @param options Session options. See {@link BrowserConfigOptions}.
@@ -244,6 +260,7 @@ export class BrowserConfig {
244
260
  } else {
245
261
  this.hitl_allowed_networks = options.hitl_allowed_networks || undefined;
246
262
  }
263
+ this.downloads_stream = options.downloads_stream;
247
264
  }
248
265
 
249
266
  /**
@@ -327,6 +344,7 @@ export class BrowserConfig {
327
344
  if (this.rtc_username !== undefined) params.set('rtc_username', this.rtc_username);
328
345
  if (this.rtc_password !== undefined) params.set('rtc_password', this.rtc_password);
329
346
  if (this.hitl_allowed_networks !== undefined) params.set('hitl_allowed_networks', this.hitl_allowed_networks);
347
+ if (this.downloads_stream !== undefined) params.set('downloads_stream', String(this.downloads_stream));
330
348
 
331
349
  const baseHost = host || 'wss://browser.scrapfly.io';
332
350
  return `${baseHost}?${params.toString()}`;
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Retrieve the files a Cloud Browser session downloaded.
3
+ *
4
+ * Connect with `new BrowserConfig({ downloads_stream: true })`: `ScrapiumBrowser.getDownloads` then returns
5
+ * each small file inline and each large one as an IO stream handle, which these helpers read in chunks with
6
+ * `IO.read`, so no CDP message is larger than one chunk. Without the option every file comes back inline,
7
+ * and the helpers read that shape too.
8
+ *
9
+ * A session is anything with a `send(method, params)` method answering the CDP result: Puppeteer's and
10
+ * Playwright's `CDPSession`, a chrome-remote-interface client, or such a function.
11
+ *
12
+ * ```ts
13
+ * const downloads = new CloudBrowserDownloads(await page.createCDPSession());
14
+ * await downloads.waitFor('report.pdf');
15
+ * const paths = await downloads.saveAll('downloads');
16
+ * ```
17
+ */
18
+ import { mkdir, open, stat } from 'node:fs/promises';
19
+ import { basename, join } from 'node:path';
20
+
21
+ /** Base64 characters per `IO.read`: an 8 MiB message carrying 6 MiB of the file. */
22
+ export const DEFAULT_CHUNK_SIZE = 8 * 1024 * 1024;
23
+ /** The largest chunk the Cloud Browser serves per `IO.read`. */
24
+ export const MAX_CHUNK_SIZE = 32 * 1024 * 1024;
25
+
26
+ const DEFAULT_WAIT_TIMEOUT_MS = 60_000;
27
+ const DEFAULT_WAIT_INTERVAL_MS = 500;
28
+
29
+ /** A CDP session: Puppeteer's or Playwright's `CDPSession`, or a chrome-remote-interface client. */
30
+ export interface CdpSession {
31
+ // deno-lint-ignore no-explicit-any
32
+ send(method: any, params?: any): Promise<any>;
33
+ }
34
+
35
+ /** A function sending one CDP command and resolving to its result. */
36
+ // deno-lint-ignore no-explicit-any
37
+ export type CdpSend = (method: string, params?: Record<string, unknown>) => Promise<any>;
38
+
39
+ /**
40
+ * One file of the session's download directory. A small file carries its base64 content in `data`. A large
41
+ * one, with `downloads_stream`, carries the IO handle to read in `stream` instead, and its size in bytes.
42
+ */
43
+ export interface BrowserDownload {
44
+ name: string;
45
+ guid?: string;
46
+ size?: number;
47
+ data?: string;
48
+ stream?: string;
49
+ }
50
+
51
+ /** A download could not be read whole. */
52
+ export class BrowserDownloadError extends Error {
53
+ constructor(message: string) {
54
+ super(message);
55
+ this.name = 'BrowserDownloadError';
56
+ }
57
+ }
58
+
59
+ interface StreamEntry {
60
+ stream: string;
61
+ size?: number;
62
+ name?: string;
63
+ }
64
+
65
+ interface GetDownloadsResult {
66
+ files?: Record<string, string>;
67
+ files_by_guid?: Record<string, string>;
68
+ guid_names?: Record<string, string>;
69
+ streams?: Record<string, StreamEntry>;
70
+ }
71
+
72
+ /** The downloads of a `ScrapiumBrowser.getDownloads` result, in either of its shapes. */
73
+ export function parseDownloads(result: GetDownloadsResult): BrowserDownload[] {
74
+ const downloads: BrowserDownload[] = [];
75
+ if (result.guid_names !== undefined || result.streams !== undefined) {
76
+ const guidNames = result.guid_names ?? {};
77
+ for (const [guid, data] of Object.entries(result.files_by_guid ?? {})) {
78
+ downloads.push({ name: guidNames[guid] || guid, guid, size: decodedSize(data), data });
79
+ }
80
+ for (const [guid, entry] of Object.entries(result.streams ?? {})) {
81
+ downloads.push({ name: entry.name || guidNames[guid] || guid, guid, size: entry.size, stream: entry.stream });
82
+ }
83
+ // A file on disk with no download GUID, such as one finished before this session attached.
84
+ for (const [name, data] of Object.entries(result.files ?? {})) {
85
+ downloads.push({ name, size: decodedSize(data), data });
86
+ }
87
+ return downloads;
88
+ }
89
+
90
+ // Without downloads_stream every file is inline under `files`, and again under `files_by_guid` with no
91
+ // name: `files` alone holds each file once.
92
+ for (const [name, data] of Object.entries(result.files ?? {})) {
93
+ downloads.push({ name, size: decodedSize(data), data });
94
+ }
95
+ return downloads;
96
+ }
97
+
98
+ function decodedSize(data: string): number {
99
+ let padding = 0;
100
+ if (data.endsWith('==')) {
101
+ padding = 2;
102
+ } else if (data.endsWith('=')) {
103
+ padding = 1;
104
+ }
105
+ return Math.floor(data.length / 4) * 3 - padding;
106
+ }
107
+
108
+ function decodeBase64(data: string): Uint8Array {
109
+ const binary = atob(data);
110
+ const bytes = new Uint8Array(binary.length);
111
+ for (let i = 0; i < binary.length; i++) {
112
+ bytes[i] = binary.charCodeAt(i);
113
+ }
114
+ return bytes;
115
+ }
116
+
117
+ function checkChunkSize(chunkSize: number): number {
118
+ if (!Number.isInteger(chunkSize) || chunkSize < 4 || chunkSize > MAX_CHUNK_SIZE) {
119
+ throw new RangeError(`chunkSize must be an integer between 4 and ${MAX_CHUNK_SIZE} base64 characters`);
120
+ }
121
+ return chunkSize - (chunkSize % 4);
122
+ }
123
+
124
+ async function isDirectory(path: string): Promise<boolean> {
125
+ try {
126
+ return (await stat(path)).isDirectory();
127
+ } catch {
128
+ return false;
129
+ }
130
+ }
131
+
132
+ async function targetPath(download: BrowserDownload, path?: string): Promise<string> {
133
+ // The name comes from the remote browser: keep its last component only.
134
+ const name = basename(download.name.replaceAll('\\', '/')) || download.guid || 'download';
135
+ if (path === undefined) {
136
+ return name;
137
+ }
138
+ if (await isDirectory(path)) {
139
+ return join(path, name);
140
+ }
141
+ return path;
142
+ }
143
+
144
+ export interface CloudBrowserDownloadsOptions {
145
+ /** Base64 characters per `IO.read`, rounded down to a multiple of 4. Defaults to 8 MiB, 32 MiB at most. */
146
+ chunkSize?: number;
147
+ }
148
+
149
+ export interface WaitForOptions {
150
+ /** Milliseconds before giving up. Defaults to 60000. */
151
+ timeout?: number;
152
+ /** Milliseconds between two checks. Defaults to 500. */
153
+ interval?: number;
154
+ }
155
+
156
+ /** Download helpers over a CDP session of a Cloud Browser. */
157
+ export class CloudBrowserDownloads {
158
+ readonly chunkSize: number;
159
+ private readonly sendCommand: CdpSend;
160
+
161
+ constructor(session: CdpSession | CdpSend, options: CloudBrowserDownloadsOptions = {}) {
162
+ if (typeof session === 'function') {
163
+ this.sendCommand = session;
164
+ } else {
165
+ this.sendCommand = (method, params) => session.send(method, params);
166
+ }
167
+ this.chunkSize = checkChunkSize(options.chunkSize ?? DEFAULT_CHUNK_SIZE);
168
+ }
169
+
170
+ /** The size in bytes of every completed download, by filename. */
171
+ async metadata(): Promise<Record<string, number>> {
172
+ const reply = await this.sendCommand('ScrapiumBrowser.getDownloadsMetadatas', {});
173
+ return reply?.metadata ?? {};
174
+ }
175
+
176
+ /** Wait until `filename` is listed with the same size twice in a row, and resolve to that size. */
177
+ async waitFor(filename: string, options: WaitForOptions = {}): Promise<number> {
178
+ const timeout = options.timeout ?? DEFAULT_WAIT_TIMEOUT_MS;
179
+ const interval = options.interval ?? DEFAULT_WAIT_INTERVAL_MS;
180
+ const deadline = Date.now() + timeout;
181
+ let last = -1;
182
+ while (Date.now() < deadline) {
183
+ const size = (await this.metadata())[filename] ?? -1;
184
+ if (size >= 0 && size === last) {
185
+ return size;
186
+ }
187
+ last = size;
188
+ await new Promise((resolve) => setTimeout(resolve, interval));
189
+ }
190
+ throw new Error(`${filename} did not finish downloading in ${timeout}ms`);
191
+ }
192
+
193
+ /** Every download of the session: small ones with their content, large ones as handles. */
194
+ async list(): Promise<BrowserDownload[]> {
195
+ return parseDownloads(await this.sendCommand('ScrapiumBrowser.getDownloads', {}));
196
+ }
197
+
198
+ /** The bytes of a download, one decoded chunk at a time. A stream handle is read once. */
199
+ async *chunks(download: BrowserDownload): AsyncGenerator<Uint8Array> {
200
+ if (download.stream === undefined) {
201
+ yield decodeBase64(download.data ?? '');
202
+ return;
203
+ }
204
+ let written = 0;
205
+ try {
206
+ while (true) {
207
+ const reply = await this.sendCommand('IO.read', { handle: download.stream, size: this.chunkSize });
208
+ const data: string = reply?.data ?? '';
209
+ if (data.length > 0) {
210
+ const chunk = reply.base64Encoded === false ? new TextEncoder().encode(data) : decodeBase64(data);
211
+ written += chunk.length;
212
+ yield chunk;
213
+ }
214
+ if (reply?.eof) {
215
+ break;
216
+ }
217
+ }
218
+ } finally {
219
+ await this.sendCommand('IO.close', { handle: download.stream });
220
+ }
221
+ if (download.size !== undefined && written !== download.size) {
222
+ throw new BrowserDownloadError(`${download.name}: read ${written} bytes, expected ${download.size}`);
223
+ }
224
+ }
225
+
226
+ /** The whole content of a download, in memory. */
227
+ async read(download: BrowserDownload): Promise<Uint8Array> {
228
+ const parts: Uint8Array[] = [];
229
+ let total = 0;
230
+ for await (const chunk of this.chunks(download)) {
231
+ parts.push(chunk);
232
+ total += chunk.length;
233
+ }
234
+ const bytes = new Uint8Array(total);
235
+ let offset = 0;
236
+ for (const part of parts) {
237
+ bytes.set(part, offset);
238
+ offset += part.length;
239
+ }
240
+ return bytes;
241
+ }
242
+
243
+ /** Write a download to `path` (a file or a directory, the current one by default) chunk by chunk. */
244
+ async save(download: BrowserDownload, path?: string): Promise<string> {
245
+ const target = await targetPath(download, path);
246
+ const file = await open(target, 'w');
247
+ try {
248
+ for await (const chunk of this.chunks(download)) {
249
+ await file.write(chunk);
250
+ }
251
+ } finally {
252
+ await file.close();
253
+ }
254
+ return target;
255
+ }
256
+
257
+ /** Write every download of the session into `directory` and resolve to their paths. */
258
+ async saveAll(directory = '.'): Promise<string[]> {
259
+ await mkdir(directory, { recursive: true });
260
+ const paths: string[] = [];
261
+ for (const download of await this.list()) {
262
+ paths.push(await this.save(download, directory));
263
+ }
264
+ return paths;
265
+ }
266
+ }