|
1 | | -import { BlobWriter, HttpReader, ZipWriter } from '@zip.js/zip.js' |
| 1 | +import { BlobReader, BlobWriter, HttpReader, ZipWriter } from '@zip.js/zip.js' |
2 | 2 | import pLimit from 'p-limit' |
3 | 3 |
|
4 | | -export interface Resource { |
| 4 | +export interface UrlResource { |
5 | 5 | name: string |
6 | 6 | url: string | URL |
7 | 7 | } |
8 | 8 |
|
9 | | -export interface Options { |
10 | | - filename: string |
| 9 | +export interface BlobResource { |
| 10 | + name: string |
| 11 | + blob: Blob |
| 12 | +} |
| 13 | + |
| 14 | +function isBlobResource(resource: Resource): resource is BlobResource { |
| 15 | + return (resource as BlobResource).blob instanceof Blob |
| 16 | +} |
| 17 | + |
| 18 | +export type Resource = UrlResource | BlobResource |
| 19 | + |
| 20 | +interface OptionsBase { |
11 | 21 | resources: Resource[] |
12 | 22 | concurrency?: number |
13 | 23 | onProgress?: (index: number) => Promise<void> |
14 | 24 | } |
15 | 25 |
|
16 | | -export default async function downloader(options: Options): Promise<void> { |
| 26 | +export interface SaveOptions extends OptionsBase { |
| 27 | + filename: string |
| 28 | +} |
| 29 | + |
| 30 | +function isSaveOptions(options: Options): options is SaveOptions { |
| 31 | + return 'filename' in options |
| 32 | +} |
| 33 | + |
| 34 | +export interface ZipOptions extends OptionsBase { } |
| 35 | + |
| 36 | +export type Options = ZipOptions | SaveOptions |
| 37 | + |
| 38 | +export default async function downloader(options: SaveOptions): Promise<void> |
| 39 | +export default async function downloader(options: ZipOptions): Promise<Blob> |
| 40 | +export default async function downloader(options: Options): Promise<void | Blob> { |
17 | 41 | const writer = new ZipWriter(new BlobWriter('application/zip')) |
18 | 42 | const limit = pLimit(options.concurrency || 10) |
19 | 43 | await Promise.all(options.resources.map((resource, index) => limit(async () => { |
20 | 44 | await options.onProgress?.(index) |
21 | | - return writer.add(resource.name, new HttpReader(resource.url)) |
| 45 | + const reader = isBlobResource(resource) |
| 46 | + ? new BlobReader(resource.blob) |
| 47 | + : new HttpReader(resource.url) |
| 48 | + return writer.add(resource.name, reader) |
22 | 49 | }))) |
23 | 50 | const blob = await writer.close() |
24 | | - const url = URL.createObjectURL(blob) |
25 | | - GM_download(url, options.filename) |
| 51 | + if (!isSaveOptions(options)) { |
| 52 | + return blob |
| 53 | + } |
| 54 | + GM_download(URL.createObjectURL(blob), options.filename) |
26 | 55 | } |
0 commit comments