Repository navigation
Expand file tree
/
Copy pathNodeModuleModule.rs
More file actions
235 lines (210 loc) · 7.72 KB
/
Copy pathNodeModuleModule.rs
File metadata and controls
235 lines (210 loc) · 7.72 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
use crate::{
self as jsc, JSArray, JSGlobalObject, JSValue, JsResult, StringJsc, Strong,
VirtualMachineRef as VirtualMachine,
};
use bun_ast::Loader;
use bun_bundler::options::DEFAULT_LOADERS;
use bun_core::{String as BunString, strings};
use bun_options_types::LoaderExt as _;
use bun_options_types::schema::api;
// `bun.schema.api.Loader` — bindgen-emitted schema enum.
// Mirrored as a transparent `u8` because the schema enum is *open*
// and the FFI caller may hand us discriminants outside
// the closed Rust `api::Loader` set; transmuting an unknown tag would be UB.
#[repr(transparent)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub(crate) struct ApiLoader(pub u8);
impl ApiLoader {
/// `_none = 254`.
const NONE: Self = Self(api::Loader::_none as u8);
/// Reconstruct the closed schema enum. Only valid when `self != NONE` is
/// already established and the C++ caller honoured the `BunLoaderType`
/// contract (headers-handwritten.h keeps the discriminants in sync).
fn to_schema(self) -> api::Loader {
debug_assert_ne!(self, Self::NONE);
// C++ caller passes a valid `BunLoaderType` discriminant per
// headers-handwritten.h; `from_raw` maps unknowns to `_none`.
api::Loader::from_raw(self.0)
}
}
// The C++ caller (NodeModuleModule.cpp
// `jsFunctionFindPath`) does the CallFrame → (BunString, JSArray*) extraction itself and
// invokes this with the coerced args directly — there is no CallFrame here.
#[unsafe(no_mangle)]
extern "C" fn NodeModuleModule__findPath(
global: &JSGlobalObject,
request_bun_str: &BunString,
paths_maybe: *mut JSArray,
) -> JSValue {
// `JSArray` is an `opaque_ffi!` ZST handle; `opaque_ref` is the centralised
// non-null-ZST deref proof. Nullable per the C++ caller contract.
let paths_maybe: Option<&JSArray> =
(!paths_maybe.is_null()).then(|| JSArray::opaque_ref(paths_maybe));
jsc::host_fn::to_js_host_call(global, || find_path(global, request_bun_str, paths_maybe))
}
// https://github.com/nodejs/node/blob/40ef9d541ed79470977f90eb445c291b95ab75a0/lib/internal/modules/cjs/loader.js#L666
fn find_path(
global: &JSGlobalObject,
request_bun_str: &BunString,
paths_maybe: Option<&JSArray>,
) -> JsResult<JSValue> {
let request_slice = request_bun_str.to_utf8();
let request = request_slice.slice();
let absolute_request = bun_paths::is_absolute(request);
if !absolute_request && paths_maybe.is_none() {
return Ok(JSValue::FALSE);
}
// for each path
let found = if let Some(paths) = paths_maybe {
'found: {
let mut iter = paths.iterator(global)?;
while let Some(path) = iter.next()? {
let cur_path = BunString::from_js(path, global)?;
if let Some(found) = find_path_inner(request_bun_str, &cur_path, global)? {
break 'found Some(found);
}
}
break 'found None;
}
} else {
find_path_inner(request_bun_str, &BunString::EMPTY, global)?
};
if let Some(str) = found {
return str.into_js(global);
}
Ok(JSValue::FALSE)
}
fn find_path_inner(
request: &BunString,
cur_path: &BunString,
global: &JSGlobalObject,
) -> JsResult<Option<BunString>> {
Ok(VirtualMachine::resolve_maybe_needs_trailing_slash::<true>(
global,
request,
cur_path,
None,
crate::virtual_machine::ResolveMode::RequireResolve,
)?
.ok())
}
pub(crate) fn stat(path: &[u8]) -> i32 {
// Node passes the path to `uv_fs_stat` as a C string, which ends at the first NUL.
let path = bun_core::slice_to_nul(path);
// PERF: `exists_at_type`
// takes a `&ZStr`, so we copy into a NUL-terminated heap buffer here.
let zpath = bun_core::ZBox::from_bytes(path);
match bun_sys::exists_at_type(bun_sys::Fd::cwd(), &zpath) {
Ok(bun_sys::ExistsAtType::File) => 0, // Returns 0 for files.
Ok(bun_sys::ExistsAtType::Directory) => 1, // Returns 1 for directories.
Err(_) => -1, // Returns a negative integer for any other kind of strings.
}
}
pub enum CustomLoader {
Loader(Loader),
Custom(Strong),
}
impl Default for CustomLoader {
/// Placeholder for `StringArrayHashMap::get_or_put` — overwritten
/// immediately when `!found_existing`.
fn default() -> Self {
CustomLoader::Loader(Loader::default())
}
}
fn on_require_extension_modify(
global: &JSGlobalObject,
str: &[u8],
loader: ApiLoader,
value: JSValue,
) -> Result<(), bun_alloc::AllocError> {
let vm = global.bun_vm();
let is_built_in = DEFAULT_LOADERS.get(str).is_some();
vm.commonjs_custom_extensions.with_mut(|extensions| {
let gop = extensions.get_or_put(str)?;
if !gop.found_existing {
// The map boxed the key on insert.
if is_built_in {
vm.has_mutated_built_in_extensions.update(|n| n + 1);
}
*gop.value_ptr = if loader != ApiLoader::NONE {
CustomLoader::Loader(Loader::from_api(loader.to_schema()))
} else {
CustomLoader::Custom(Strong::create(value, global))
};
} else if loader != ApiLoader::NONE {
// Replacing with a built-in loader: drop any held Strong via assignment.
*gop.value_ptr = CustomLoader::Loader(Loader::from_api(loader.to_schema()));
} else {
match gop.value_ptr {
CustomLoader::Loader(_) => {
*gop.value_ptr = CustomLoader::Custom(Strong::create(value, global));
}
CustomLoader::Custom(strong) => strong.set(global, value),
}
}
Ok::<_, bun_alloc::AllocError>(())
})?;
tell_resolver_the_extensions(vm);
Ok(())
}
fn on_require_extension_modify_non_function(
global: &JSGlobalObject,
str: &[u8],
) -> Result<(), bun_alloc::AllocError> {
let vm = global.bun_vm();
let is_built_in = DEFAULT_LOADERS.get(str).is_some();
if let Some(prev) = (vm.commonjs_custom_extensions).with_mut(|it| it.fetch_swap_remove(str)) {
// `prev.key: Box<[u8]>` — freed on drop.
if is_built_in {
vm.has_mutated_built_in_extensions.update(|n| n - 1);
}
// `prev.value` drops here, releasing any held `Strong`.
drop(prev);
}
tell_resolver_the_extensions(vm);
Ok(())
}
fn tell_resolver_the_extensions(vm: &VirtualMachine) {
let extensions = vm.commonjs_custom_extensions.get().keys().into();
(vm.transpiler).with_mut(|t| t.resolver.opts.extra_cjs_extensions = extensions);
}
pub fn find_longest_registered_extension<'a>(
vm: &'a VirtualMachine,
filename: &[u8],
) -> Option<&'a CustomLoader> {
let basename = bun_paths::basename(filename);
let mut next: usize = 0;
while let Some(i) = strings::index_of_char_pos(basename, b'.', next) {
next = i + 1;
if i == 0 {
continue;
}
let ext = &basename[i..];
if let Some(value) = vm.commonjs_custom_extensions.get().get(ext) {
return Some(value);
}
}
None
}
#[unsafe(no_mangle)]
extern "C" fn NodeModuleModule__onRequireExtensionModify(
global: &JSGlobalObject,
str: &BunString,
loader: ApiLoader,
value: JSValue,
) {
let str_slice = str.to_utf8();
if on_require_extension_modify(global, str_slice.slice(), loader, value).is_err() {
bun_core::out_of_memory();
}
}
#[unsafe(no_mangle)]
extern "C" fn NodeModuleModule__onRequireExtensionModifyNonFunction(
global: &JSGlobalObject,
str: &BunString,
) {
let str_slice = str.to_utf8();
if on_require_extension_modify_non_function(global, str_slice.slice()).is_err() {
bun_core::out_of_memory();
}
}