-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcompression.ts
38 lines (33 loc) · 1.22 KB
/
compression.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const jsonStringToBlob = (text: string): Blob => {
return new Blob([text], { type: "application/json" });
};
const compressBlob = async (content: Blob): Promise<Blob> => {
const cs = new CompressionStream("gzip");
const compressedStream = content.stream().pipeThrough(cs);
return new Response(compressedStream).blob();
};
export const blobToBase64 = async (blob: Blob): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = function () {
const base64data = (reader.result as string).split(",")[1];
resolve(base64data);
};
reader.onerror = reject;
reader.readAsDataURL(blob);
});
};
async function blobToUint8Array(blob: Blob): Promise<Uint8Array> {
return new Uint8Array(await blob.arrayBuffer());
}
export const compressBundle = async (
bundleJson: BundleJson
): Promise<{ compressedBundle: Uint8Array; uncompressedSize: string }> => {
const uncompressedBlob = jsonStringToBlob(JSON.stringify(bundleJson));
const compressedBlob = await compressBlob(uncompressedBlob);
const compressedBundle = await blobToUint8Array(compressedBlob);
return {
compressedBundle,
uncompressedSize: String(uncompressedBlob.size),
};
};