|
1 | 1 | import { execSync } from 'node:child_process'; |
| 2 | +import { resolve } from 'node:path'; |
2 | 3 | import type { |
3 | 4 | NativeRequestOptions, |
4 | 5 | NativeResponse, |
@@ -33,6 +34,14 @@ type NativeTarget = { |
33 | 34 |
|
34 | 35 | let nativeBinding: NativeBinding | undefined; |
35 | 36 |
|
| 37 | +function tryRequire<T>(id: string): T | undefined { |
| 38 | + try { |
| 39 | + return require(id) as T; |
| 40 | + } catch { |
| 41 | + return undefined; |
| 42 | + } |
| 43 | +} |
| 44 | + |
36 | 45 | function isMuslRuntime(): boolean { |
37 | 46 | if (process.platform !== 'linux') { |
38 | 47 | return false; |
@@ -111,28 +120,37 @@ function loadNativeBinding(): NativeBinding { |
111 | 120 | } |
112 | 121 |
|
113 | 122 | const attempted: string[] = [target.packageName]; |
| 123 | + const packageBinding = tryRequire<NativeBinding>(target.packageName); |
114 | 124 |
|
115 | | - try { |
116 | | - return require(target.packageName) as NativeBinding; |
117 | | - } catch { |
118 | | - attempted.push(`../rust/${target.binaryName}`); |
| 125 | + if (packageBinding) { |
| 126 | + return packageBinding; |
119 | 127 | } |
120 | 128 |
|
121 | | - try { |
122 | | - return require(`../rust/${target.binaryName}`) as NativeBinding; |
123 | | - } catch { |
124 | | - attempted.push('../rust/node-wreq.node'); |
| 129 | + const localBinaryPath = resolve(__dirname, '../../rust', target.binaryName); |
| 130 | + |
| 131 | + attempted.push(localBinaryPath); |
| 132 | + |
| 133 | + const localPlatformBinding = tryRequire<NativeBinding>(localBinaryPath); |
| 134 | + |
| 135 | + if (localPlatformBinding) { |
| 136 | + return localPlatformBinding; |
125 | 137 | } |
126 | 138 |
|
127 | | - try { |
128 | | - return require('../rust/node-wreq.node') as NativeBinding; |
129 | | - } catch { |
130 | | - throw new Error( |
131 | | - `Failed to load native module for ${platform}-${arch}. ` + |
132 | | - `Tried: ${attempted.join(', ')}. ` + |
133 | | - `Make sure the matching @node-wreq platform package is installed or build the local native module.` |
134 | | - ); |
| 139 | + const localGenericBinaryPath = resolve(__dirname, '../../rust/node-wreq.node'); |
| 140 | + |
| 141 | + attempted.push(localGenericBinaryPath); |
| 142 | + |
| 143 | + const localGenericBinding = tryRequire<NativeBinding>(localGenericBinaryPath); |
| 144 | + |
| 145 | + if (localGenericBinding) { |
| 146 | + return localGenericBinding; |
135 | 147 | } |
| 148 | + |
| 149 | + throw new Error( |
| 150 | + `Failed to load native module for ${platform}-${arch}. ` + |
| 151 | + `Tried: ${attempted.join(', ')}. ` + |
| 152 | + `Make sure the matching @node-wreq platform package is installed or build the local native module.` |
| 153 | + ); |
136 | 154 | } |
137 | 155 |
|
138 | 156 | export function getBinding(): NativeBinding { |
|
0 commit comments