@@ -6,7 +6,11 @@ import {
66 constants as zlibConstants
77} from "node:zlib"
88import { gzip , gunzip , deflate , inflate } from "node:zlib"
9+ import * as nodeZlib from "node:zlib"
10+ import { createRequire } from "node:module"
911import { promisify } from "node:util"
12+
13+ const nodeRequire = createRequire ( __filename )
1014import type { CompressionOptions } from "./types"
1115import { PayloadTooLargeError } from "./errors"
1216
@@ -42,22 +46,7 @@ let zstdAsync: { compress: (b: Uint8Array, opts?: object) => Promise<Buffer>; de
4246function tryLoadZstd ( ) : boolean {
4347 if ( zstdSync && zstdAsync ) return true
4448 try {
45- const napi : any = require ( "@napi-rs/zstd" )
46- if ( napi && typeof napi . compressSync === "function" ) {
47- zstdSync = {
48- compress : ( b ) => Buffer . from ( napi . compressSync ( Buffer . from ( b ) ) ) ,
49- decompress : ( b ) => Buffer . from ( napi . decompressSync ( Buffer . from ( b ) ) )
50- }
51- zstdAsync = {
52- compress : async ( b ) => Buffer . from ( await napi . compress ( Buffer . from ( b ) ) ) ,
53- decompress : async ( b ) => Buffer . from ( await napi . decompress ( Buffer . from ( b ) ) )
54- }
55- return true
56- }
57- } catch { }
58- try {
59- const zlib = require ( "node:zlib" ) as typeof import ( "node:zlib" )
60- const z : any = zlib
49+ const z : any = nodeZlib
6150 if ( typeof z . zstdCompressSync === "function" ) {
6251 zstdSync = {
6352 compress : ( b , opts ) => z . zstdCompressSync ( b , opts ) ,
@@ -91,7 +80,7 @@ export async function maybeCompressAsync(buf: Uint8Array, opts: ResolvedCompress
9180 return { data : buf , encoding : "identity" }
9281 }
9382 try {
94- const { isCompressionWorkerEnabled, compressionWorkerThreshold, workerCompress } = require ( "./compression-worker" ) as typeof import ( "./compression-worker" )
83+ const { isCompressionWorkerEnabled, compressionWorkerThreshold, workerCompress } = nodeRequire ( "./compression-worker" ) as typeof import ( "./compression-worker" )
9584 if ( isCompressionWorkerEnabled ( ) && buf . byteLength >= compressionWorkerThreshold ( ) ) {
9685 const algo : "gzip" | "deflate" | "zstd" = opts . algorithm === "zstd" && tryLoadZstd ( ) ? "zstd" : opts . algorithm === "deflate" ? "deflate" : "gzip"
9786 const data = await workerCompress ( buf , algo , opts . level )
@@ -219,7 +208,7 @@ export async function maybeDecompressAsync(buf: Uint8Array, encoding?: string, m
219208async function tryWorkerDecompress ( buf : Uint8Array , encoding : "gzip" | "deflate" , maxOutputBytes ?: number ) : Promise < Uint8Array | null > {
220209 let mod : typeof import ( "./compression-worker" )
221210 try {
222- mod = require ( "./compression-worker" ) as typeof import ( "./compression-worker" )
211+ mod = nodeRequire ( "./compression-worker" ) as typeof import ( "./compression-worker" )
223212 } catch {
224213 return null
225214 }
0 commit comments