import { loadAsync } from "jszip" import { arrayToMap } from "../../../array" import { blobToArrayBuffer, isBlob } from "../../../bit" /** 解压一个 zip 文件 */ export async function unzip( data: Blob | ArrayBuffer | Uint8Array, options?: { // 只解压指定文件名的的文件 files: string[] // 提供手动解码文件名的方法 decodeFileName?: (bytes: string[] | Uint8Array | Buffer) => string } ): Promise<{ [filePath: string]: Uint8Array } | void> { let u8array!: Uint8Array if (isBlob(data)) u8array = new Uint8Array(await blobToArrayBuffer(data)) if (data instanceof ArrayBuffer) u8array = new Uint8Array(data) if (data instanceof Uint8Array) u8array = data if (u8array === undefined) throw new Error("unzip: data is not a Blob, ArrayBuffer or Uint8Array") let opt: any = { decodeFileName: options?.decodeFileName, } let fileNameMap: any if (options?.files) fileNameMap = arrayToMap(options.files) let zip = await loadAsync(data, opt) let files: any = {} let ps: any = [] zip.forEach((relativePath, file) => { if (fileNameMap) { if (!fileNameMap[relativePath]) return } ps.push(file.async("arraybuffer").then((re) => (files[relativePath] = re))) }) await Promise.all(ps) return files }