-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
56 lines (49 loc) · 1.62 KB
/
index.js
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
let { CompressionStream, DecompressionStream } = globalThis;
if (!CompressionStream) {
// original idea: MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource>
// @see https://github.com/oven-sh/bun/issues/1723#issuecomment-1774174194
const {
createGzip, createGunzip,
createDeflate, createInflate,
createDeflateRaw, createInflateRaw,
} = await import('node:zlib');
class Stream {
constructor(compress, format) {
let handler;
if (format === 'gzip')
handler = compress ? createGzip() : createGunzip();
else if (format === 'deflate')
handler = compress ? createDeflate() : createInflate();
else if (format === 'deflate-raw')
handler = compress ? createDeflateRaw() : createInflateRaw();
else {
throw new TypeError([
`Failed to construct '${this.constructor.name}'`,
`Unsupported compression format: '${format}'`
].join(': '));
}
this.readable = new ReadableStream({
type: 'bytes',
start: controller => {
handler.on('data', chunk => controller.enqueue(chunk));
handler.once('end', () => controller.close());
},
});
this.writable = new WritableStream({
write: chunk => handler.write(chunk),
close: () => handler.end(),
});
}
}
CompressionStream = class CompressionStream extends Stream {
constructor(format) {
super(true, format);
}
}
DecompressionStream = class DecompressionStream extends Stream {
constructor(format) {
super(false, format);
}
}
}
export { CompressionStream, DecompressionStream };