-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathlz4.ts
More file actions
58 lines (47 loc) · 1.81 KB
/
Copy pathlz4.ts
File metadata and controls
58 lines (47 loc) · 1.81 KB
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
57
58
import type LZ4Namespace from 'lz4';
type LZ4Module = typeof LZ4Namespace;
// Loader function — extracted so tests can inject a stub without
// having to patch CJS-only Module._load. Default is the real require.
// eslint-disable-next-line global-require
let loader: () => LZ4Module = () => require('lz4');
/** Test-only: replace the loader. Restores the real one when called with no arg. */
export function setLz4LoaderForTest(fn?: () => LZ4Module): void {
// eslint-disable-next-line global-require
loader = fn ?? (() => require('lz4'));
}
function tryLoadLZ4Module(): LZ4Module | undefined {
try {
return loader();
} catch (err) {
if (!(err instanceof Error) || !('code' in err)) {
// eslint-disable-next-line no-console
console.warn('Unexpected error loading LZ4 module: Invalid error object', err);
return undefined;
}
if (err.code === 'MODULE_NOT_FOUND') {
return undefined;
}
if (err.code === 'ERR_DLOPEN_FAILED') {
// eslint-disable-next-line no-console
console.warn('LZ4 native module failed to load: Architecture or version mismatch', err);
return undefined;
}
// If it's not a known error, return undefined
// eslint-disable-next-line no-console
console.warn('Unknown error loading LZ4 module: Unhandled error code', err);
return undefined;
}
}
// The null is already tried resolving that failed
let resolvedModule: LZ4Module | null | undefined;
function getResolvedModule() {
if (resolvedModule === undefined) {
resolvedModule = tryLoadLZ4Module() ?? null;
}
return resolvedModule === null ? undefined : resolvedModule;
}
/** Test-only: reset the memoized resolution so the next call re-invokes the loader. */
export function resetLz4CacheForTest(): void {
resolvedModule = undefined;
}
export default getResolvedModule;