Skip to content

Commit 5651926

Browse files
committed
Bring back node fallbacks, originally added in #5556.
I r+ed their removal in #5584 because node supports CompressionStream, but I forgot to ask for the fallbacks to be put back when we switched back to using a worker.
1 parent 98bd7e6 commit 5651926

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/utils/gz.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,45 @@ export async function compress(
3434
// Encode the data if it's a string
3535
const arrayData =
3636
typeof data === 'string' ? new TextEncoder().encode(data) : data;
37+
38+
if (!(typeof window === 'object' && 'Worker' in window)) {
39+
// Try to fall back to Node's zlib library.
40+
const zlib = await import('zlib');
41+
return new Promise((resolve, reject) => {
42+
zlib.gzip(data, (errorOrNull, result) => {
43+
if (errorOrNull) {
44+
reject(errorOrNull);
45+
} else {
46+
resolve(new Uint8Array(result.buffer as ArrayBuffer));
47+
}
48+
});
49+
});
50+
}
51+
3752
return runGzWorker('compress', arrayData);
3853
}
3954

4055
export async function decompress(
4156
data: Uint8Array<ArrayBuffer>
4257
): Promise<Uint8Array<ArrayBuffer>> {
58+
if (!(typeof window === 'object' && 'Worker' in window)) {
59+
// Handle the case where we're not running in the browser, e.g. when
60+
// this code is used as part of a library in a Node project.
61+
// We don't get here when running Firefox profiler tests, because our
62+
// tests create a mock window with a mock Worker class.
63+
// Try to fall back to Node's zlib library.
64+
const zlib = await import('zlib');
65+
return new Promise((resolve, reject) => {
66+
zlib.gunzip(data, (errorOrNull, result) => {
67+
if (errorOrNull) {
68+
reject(errorOrNull);
69+
} else {
70+
resolve(new Uint8Array(result.buffer as ArrayBuffer));
71+
}
72+
});
73+
});
74+
}
75+
4376
return runGzWorker('decompress', data);
4477
}
4578

0 commit comments

Comments
 (0)