Skip to content

Commit f1caf93

Browse files
committed
fix: simplify ESM native module loading and remove redundant fallback logic
1 parent 4c44084 commit f1caf93

1 file changed

Lines changed: 15 additions & 23 deletions

File tree

src/syslog.ts

Lines changed: 15 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,32 @@
11
import type { SyslogOptions, SyslogFacilityType, SyslogLevelType, SyslogOptionType } from './types/index.js';
22
import { SyslogFacility, SyslogLevel, SyslogOption } from './types/index.js';
3+
import { createRequire } from 'module';
4+
import { fileURLToPath } from 'url';
5+
import { dirname } from 'path';
36

47
/**
58
* Native module loader with fallback
69
* @internal
710
*/
8-
declare const require: (id: string) => any;
9-
declare const __dirname: string;
11+
const require = createRequire(import.meta.url);
12+
const __dirname = dirname(fileURLToPath(import.meta.url));
1013

1114
function loadNativeModule() {
12-
// Check if we're in a test environment and mock is available
15+
// Return mock in test environment
1316
if (typeof process !== 'undefined' && (process.env.NODE_ENV === 'test' || process.env.VITEST === 'true')) {
14-
try {
15-
// Try to load the mock from the global test setup
16-
if ((globalThis as any).__MOCK_SYSLOG__) {
17-
return (globalThis as any).__MOCK_SYSLOG__;
18-
}
19-
} catch {
20-
// Continue with normal loading if mock not available
17+
if ((globalThis as any).__MOCK_SYSLOG__) {
18+
return (globalThis as any).__MOCK_SYSLOG__;
2119
}
2220
}
2321

22+
// Use node-gyp-build (handles path resolution automatically)
2423
try {
25-
// Try to load the precompiled binary first
26-
return require('../lib/binding/syslog_native.node');
24+
return require('node-gyp-build')(__dirname);
2725
} catch (error) {
28-
try {
29-
// Fallback to the source module
30-
return require('node-gyp-build')(__dirname);
31-
} catch (fallbackError) {
32-
throw new Error(
33-
`Failed to load native syslog module. This package only supports Linux x64/ARM64.\n` +
34-
`Original error: ${error instanceof Error ? error.message : String(error)}\n` +
35-
`Fallback error: ${fallbackError instanceof Error ? fallbackError.message : String(fallbackError)}`
36-
);
37-
}
26+
throw new Error(
27+
`Failed to load native syslog module. This package only supports Linux x64/ARM64.\n` +
28+
`Error: ${error instanceof Error ? error.message : String(error)}`
29+
);
3830
}
3931
}
4032

@@ -85,7 +77,7 @@ export class Syslog {
8577
*/
8678
constructor(options: SyslogOptions = {}) {
8779
this.native = loadNativeModule();
88-
this.ident = options.ident || (typeof require !== 'undefined' && (require as any).main?.filename) || 'node';
80+
this.ident = options.ident || (typeof process !== 'undefined' && process.argv[1]) || 'node';
8981
this.facility = options.facility ?? SyslogFacility.LOG_USER;
9082
this.options = options.options ?? SyslogOption.LOG_PID;
9183

0 commit comments

Comments
 (0)