Repository navigation
Conversation
|
Updated 2:23 AM PT - Aug 3rd, 2026
❌ @robobun, your commit 2cd35e8 has 1 failures in
🧪 To try this PR locally: bunx bun-pr 36801That installs a local version of the PR into your bun-36801 --bun |
|
Found 4 issues this PR may fix:
🤖 Generated with Claude Code |
WalkthroughThe N-API bindings now propagate VM exceptions and apply updated coercion, string, symbol, buffer, and module filename behavior. Reference and thread-safe-function handling now covers collected values, null callbacks, and bounded dispatch. Tests cover Node.js semantic parity and these runtime cases. ChangesN-API behavior alignment
Suggested reviewers: 🚥 Pre-merge checks | ✅ 3 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (3 passed)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/runtime/napi/napi_body.rs`:
- Around line 2541-2550: Update the documentation for schedule_dispatch to
clarify that holding self_.lock is required only when called by addon-thread
callers, while JS-thread callers such as this iteration-yield path and
env_teardown may call it without the lock. Keep the existing scheduling behavior
unchanged.
- Around line 2045-2049: Update the validation guard in napi_get_buffer_info to
reject bare SharedArrayBuffer values as well as bare ArrayBuffer values by
checking array_buf.shared alongside array_buf.typed_array_type. Preserve
acceptance of ArrayBufferView values, including shared typed arrays and
DataView.
In `@test/napi/napi-app/module.js`:
- Around line 1397-1401: Update both drivers in test/napi/napi-app/module.js: in
lines 1397-1401, replace the unconditional gcUntil predicate with a non-printing
native accessor that reports whether the weak referent was collected; in lines
1405-1411, replace the fixed ten-turn setImmediate loop with a bounded poll of
the recorded tsfn_nullcb_was_null state, stopping once call_js has run. Add or
reuse accessors without printf so checkSameOutput remains unchanged.
In `@test/napi/napi.test.ts`:
- Line 1564: Update the assertion in the relevant N-API test to match each of
the three result_written diagnostics separately, associating the expected value
with new_instance(throws), get_named_property(throws), and
has_named_property(throws). Keep checkSameOutput as the authoritative
full-output assertion.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 45f754fc-f919-48a2-8bf9-f4ace8809522
📒 Files selected for processing (6)
src/jsc/bindings/NapiRef.cppsrc/jsc/bindings/napi.cppsrc/runtime/napi/napi_body.rstest/napi/napi-app/module.jstest/napi/napi-app/standalone_tests.cpptest/napi/napi.test.ts
|
This PR may be a duplicate of:
🤖 Generated with Claude Code |
There was a problem hiding this comment.
All prior findings (TSFN yield-path UAF, external-string zero-length ownership, gcUntil predicate, dead test locals, kMaxIterationCount coverage) look addressed and nothing new turned up on this pass. Still deferring to a human: this is ~13 independent N-API behavioral changes across the C++ bindings and the Rust TSFN dispatch/refcount paths, and it needed two memory-safety fixes during review — worth a maintainer's eyes on the final shape.
What was reviewed:
- TSFN
on_dispatchyield: re-checked theclosing == Closedguard againstmaybe_queue_finalizer/schedule_dispatch— the finalizer-already-queued path now returns before re-enqueue. node_api_create_external_string_{latin1,utf16}: zero-length branch now returnsnapi_okunconditionally afterdoFinalizer;length <= INT_MAXgate precedes theunsignedcast.- ToObject coercion sites (
define_properties/freeze/seal/set_prototype/type_tag): each is under a throw scope thatRETURN_IF_EXCEPTIONreads. NapiRef::ref()collected-referent check is scoped torefCount == 0 && !weakValueRef.isClear(), so strong/eternal refs are unaffected.
Extended reasoning...
Overview
Thirteen distinct N-API semantic-parity fixes spread across src/jsc/bindings/napi.cpp (symbol description, external-string arg validation, ToObject coercion for define/freeze/seal/set_prototype/type_tag, result-write ordering on exception, empty named key, module filename), src/jsc/bindings/NapiRef.cpp (napi_reference_ref after collection), and src/runtime/napi/napi_body.rs (TSFN js_callback NULL, kMaxIterationCount yield, napi_get_buffer_info ArrayBuffer gate). Test coverage lands in test/napi/napi-app/standalone_tests.cpp, module.js, and four new checkSameOutput cases in napi.test.ts.
Security risks
No auth/crypto/permission surface. The risk axis is memory safety in native code: TSFN task double-schedule after finalizer enqueue, and external-string ownership on the zero-length + pending-exception path. Both were flagged in earlier passes and have targeted fixes plus a 1200-item TSFN drain test that runs under ASAN.
Level of scrutiny
High. Per REVIEW.md this is the most-blocked category (native memory safety, refcounts, cross-thread TSFN lifecycle). The PR already required two correctness corrections mid-review (a UAF and an ownership/double-free), which is exactly why a maintainer should sign off on the final state rather than a bot.
Other factors
- All earlier inline threads are resolved; the current bug-hunt pass found nothing new.
- The
test_tsfn_many_itemsfixture (1200 items, release, bounded poll) covers both the yield re-schedule and theClosedearly-return under ASAN, closing the coverage gap I flagged. checkSameOutputpins every changed status/pending/result-written line against Node v26, so behavioral regressions surface as byte diffs.- Breadth (13 functions in one PR) and the removal of a previously load-bearing pending-exception guard in the external-string path are the kind of design-shaped choices a human should confirm.
|
@robobun rebase |
A grab-bag of N-API functions whose observable behaviour (not just
return status) differed from Node.js v26, each verified by running the
same native addon under both runtimes:
- napi_set_named_property: accept the empty string as a property key
(Node's CHECK_NEW_FROM_UTF8 only rejects nullptr).
- napi_create_symbol: only a nullptr description yields a symbol with
no description; JS undefined/null return napi_string_expected, and an
empty-string description produces Symbol('').description === ''.
- node_api_create_external_string_latin1/_utf16: accept (nullptr, 0)
like Node's CHECK_NEW_STRING_ARGS, and reject length > INT_MAX with
napi_invalid_arg instead of truncating into a wild pointer (crash).
- napi_get_buffer_info: reject a bare ArrayBuffer (Node gates on
node::Buffer::HasInstance which is IsArrayBufferView).
- napi_define_properties / napi_object_freeze / napi_object_seal /
napi_type_tag_object / napi_check_object_type_tag /
node_api_set_prototype: ToObject-coerce primitives and leave the
TypeError pending for null/undefined, instead of an unconditional
napi_object_expected without an exception.
- napi_new_instance / napi_get_named_property / napi_has_named_property:
check for an exception before writing *result so a failed call leaves
the caller's out-param untouched.
- node_api_get_module_file_name: return "" instead of a null pointer
when the env was created on a path that did not set a filename.
- NapiRef::ref(): when the weak referent has already been collected,
leave the refcount at 0 (Node's Reference::Ref returns 0 once the
persistent is empty).
- ThreadSafeFunction: when created without a JS func, pass a null
napi_value to call_js_cb (addons test js_callback != NULL); cap the
per-tick dispatch loop at 1000 iterations and re-schedule the
remainder so a fast producer cannot starve the event loop.
Intentionally not changed: napi_set_property/_element put-return
(V8's Object::Set always returns Just(true), so Node's
napi_generic_failure branch is unreachable and Bun already matches),
and napi_get_prototype (Bun already avoids the Proxy trap).
Only return 0 when we held a weak handle that GC has since cleared; a reference whose weak handle was never set (can_be_weak=false primitives) keeps its previous ref() behaviour.
…rify schedule_dispatch lock contract - Test drivers now poll test_weak_ref_is_collected / test_tsfn_null_js_callback_ran instead of assuming a fixed amount of event-loop progress. - Spot-check each result_written line separately. - schedule_dispatch doc: lock is only needed by addon-thread callers.
If the 1000th dispatch_one() in a tick drains the final item with thread_count == 0 it enqueues the finalizer task and transitions closing -> Closed before returning true. Re-scheduling from the yield path then would enqueue a second on_dispatch on the same pointer, which runs on freed memory after the finalizer task destroy()s it. Check the closing state before re-scheduling. Also tighten a few review-flagged comments and drop unused locals from the new parity test.
… TSFN yield path
node_api_create_external_string_{latin1,utf16}: after adopting a
zero-length buffer and running its finalizer, return napi_ok directly.
The previous NAPI_RETURN_SUCCESS_UNLESS_EXCEPTION tail could observe an
exception that doFinalizer promoted from a pre-existing napi_throw and
report napi_pending_exception after the buffer had already been freed,
inviting a caller double-free. Node has no pending-exception gate here
and returns napi_ok.
Also add a test that enqueues 1200 TSFN items so the kMaxIterationCount
yield and re-schedule runs under ASAN and cannot silently stall or
double-dispatch.
f67c47f to
5b847ee
Compare
… ASAN With 1200 items the 1000th dispatch still has 200 queued, so the closing == Closed early-return is never taken. 2000 (a multiple of the cap) makes the second tick's 1000th dispatch the final item: the finalizer is queued inside dispatch_one() and the yield path then hits the guard.
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/runtime/napi/napi_body.rs (1)
3179-3183: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winSynchronize the debug ownership checks with
env_teardown.
env_teardownwritesself.event_loop = Nonewhile holdingfunc.lock. These addon-thread debug checks read the same non-atomic field without that lock. This can cause a data race during teardown.
src/runtime/napi/napi_body.rs#L3179-L3183: Holdfunc.lockwhile readingfunc.event_loop.src/runtime/napi/napi_body.rs#L3200-L3204: Holdfunc.lockwhile readingfunc.event_loop.Proposed fix
#[cfg(debug_assertions)] - if let (Some(loop_), Some(env)) = (func.event_loop.as_ref(), unsafe { env_.as_ref() }) { - debug_assert!(core::ptr::eq(loop_.global.unwrap().as_ptr(), env.to_js())); + if let Some(env) = unsafe { env_.as_ref() } { + let _g = func.lock.lock_guard(); + if let Some(loop_) = func.event_loop.as_ref() { + debug_assert!(core::ptr::eq(loop_.global.unwrap().as_ptr(), env.to_js())); + } }As per coding guidelines, “synchronize shared state.”
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/runtime/napi/napi_body.rs` around lines 3179 - 3183, Synchronize both debug ownership checks in src/runtime/napi/napi_body.rs at lines 3179-3183 and 3200-3204 with env_teardown by acquiring func.lock before reading func.event_loop. Keep the existing assertions and null/environment handling unchanged; both sites require the lock while accessing the shared field.Source: Coding guidelines
src/jsc/bindings/napi.cpp (1)
3012-3018: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winReturn unconditionally after throwing the out-of-memory error.
The guard depends on
RETURN_IF_EXCEPTIONto leave the function. IfthrowOutOfMemoryErrordoes not leave an exception pending, control reachesJSBigInt::createFromWordswith the oversizedword_count, which is the read the guard exists to prevent. Make the early return explicit.♻️ Proposed change
if (word_count > jscBigIntMaxWords) { JSC::throwOutOfMemoryError(globalObject, scope); - RETURN_IF_EXCEPTION(scope, napi_set_last_error(env, napi_pending_exception)); + return napi_set_last_error(env, napi_pending_exception); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/jsc/bindings/napi.cpp` around lines 3012 - 3018, Update the oversized-word guard before JSBigInt::createFromWords to return unconditionally after throwOutOfMemoryError, rather than relying on RETURN_IF_EXCEPTION; preserve the existing pending-exception handling while ensuring oversized word_count never reaches JSC::tryCreateFromWords.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/jsc/bindings/napi.cpp`:
- Around line 1457-1462: Update node_api_create_external_string_latin1 in
src/jsc/bindings/napi.cpp:1457-1462 to resolve NAPI_AUTO_LENGTH with strlen(str)
first, then validate length <= INT_MAX without exempting NAPI_AUTO_LENGTH before
the unsigned cast. Apply the same ordering and validation change in
node_api_create_external_string_utf16 at src/jsc/bindings/napi.cpp:1503-1508,
using std::char_traits<char16_t>::length(str); both sites require direct
changes.
In `@test/napi/napi-app/module.js`:
- Around line 1405-1421: Make both bounded polling drivers fail when their
expected completion condition is not met: in test_tsfn_null_js_callback_driver,
throw if test_tsfn_null_js_callback_ran() remains false after 1,000 iterations;
in test_tsfn_many_items_driver, throw unless test_tsfn_many_items_count() equals
exactly 2,000. Only invoke each corresponding result function after the
validation succeeds.
In `@test/napi/napi.test.ts`:
- Around line 1645-1649: Strengthen the first output assertion in the test
“napi_reference_ref returns 0 after the referent is collected” by matching the
complete first-line prefix, including “get_reference_value is undefined=” before
“reference_ref count=0”. Keep the second assertion targeting the separate
“second reference_ref count=0” line.
---
Outside diff comments:
In `@src/jsc/bindings/napi.cpp`:
- Around line 3012-3018: Update the oversized-word guard before
JSBigInt::createFromWords to return unconditionally after throwOutOfMemoryError,
rather than relying on RETURN_IF_EXCEPTION; preserve the existing
pending-exception handling while ensuring oversized word_count never reaches
JSC::tryCreateFromWords.
In `@src/runtime/napi/napi_body.rs`:
- Around line 3179-3183: Synchronize both debug ownership checks in
src/runtime/napi/napi_body.rs at lines 3179-3183 and 3200-3204 with env_teardown
by acquiring func.lock before reading func.event_loop. Keep the existing
assertions and null/environment handling unchanged; both sites require the lock
while accessing the shared field.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 2ccda1e5-315a-47da-8bf7-a29ffb3e157c
📒 Files selected for processing (6)
src/jsc/bindings/NapiRef.cppsrc/jsc/bindings/napi.cppsrc/runtime/napi/napi_body.rstest/napi/napi-app/module.jstest/napi/napi-app/standalone_tests.cpptest/napi/napi.test.ts
|
CI on 2cd35e8 (build 88054): the N-API tests pass on all lanes. The failures are unrelated to this diff:
Ready for review. |
There was a problem hiding this comment.
No new issues found — the earlier concerns (TSFN yield-path UAF, external-string zero-length ownership, and coverage for the closing == Closed guard) are all addressed in the current revision. Deferring to a human because this touches ~15 distinct N-API entry points across the C++ bindings and the Rust TSFN dispatch loop, several of which are memory-ownership boundaries.
What was reviewed:
- TSFN
on_dispatchiteration cap: verified the 2000-item test now hits theClosedearly-return, andschedule_dispatchwithout the lock is JS-thread-only so it can't raceenv_teardownforevent_loop. node_api_create_external_string_*zero-length branch: confirmed both variants now unconditionally returnnapi_okafterdoFinalizer, matching the non-zero path's ownership contract.NAPI_CHECK_TO_OBJECTadoption in freeze/seal/define_properties/set_prototype/type_tag matches the existing macro pattern used by the element/property functions.NapiRef::ref()collected-referent guard:!weakValueRef.isClear() && !weakValueRef.get()correctly distinguishes "was set, now collected" from "never set".
Extended reasoning...
Overview
This PR aligns ~15 N-API functions with Node.js v26 semantics: napi_set_named_property (empty key), napi_create_symbol (undefined/null/empty description), node_api_create_external_string_{latin1,utf16} (null str with len=0, INT_MAX overflow guard, zero-length ownership), napi_get_buffer_info (reject bare ArrayBuffer), ToObject coercion for napi_define_properties/napi_object_freeze/napi_object_seal/node_api_set_prototype/napi_type_tag_object/napi_check_object_type_tag, result-write ordering for napi_new_instance/napi_{get,has}_named_property, node_api_get_module_file_name non-null, napi_reference_ref after collection, TSFN js_callback NULL when created without a func, and the TSFN kMaxIterationCount yield. Files: src/jsc/bindings/NapiRef.cpp, src/jsc/bindings/napi.cpp, src/runtime/napi/napi_body.rs, plus checkSameOutput tests in test/napi/.
Security risks
No auth/crypto surface. The relevant risk class is memory safety at the FFI boundary: the external-string ownership contract (double-free on non-ok return), the TSFN dispatch re-schedule (UAF on a finalized pointer), and the static_cast<unsigned> span-length overflow. All three were examined during review — the first two were flagged and fixed in-PR, the third is the crash the PR itself fixes with the INT_MAX guard.
Level of scrutiny
High. N-API is the native-addon ABI; every function here is called from third-party C/C++ with caller-owned memory. The TSFN change edits a concurrent dispatch loop with atomic state and a finalizer that heap-frees self. Two memory-safety issues were found and fixed during the review cycle, which is a signal that the change class is non-trivial. The schedule_dispatch doc-comment change relaxes a lock precondition — I verified the new JS-thread-only caller can't race the only writer of event_loop (env_teardown, also JS-thread), but a maintainer sign-off on that reasoning would be valuable.
Other factors
Every behavioral change ships with a checkSameOutput test that byte-compares Bun against Node, which is strong coverage. All prior review threads (mine, CodeRabbit, comment-cop) are resolved; the only human interaction was a rebase request. The PR went through five fix commits responding to review, and the final state looks correct to me — but the breadth (15 entry points, two languages, refcounting + concurrency) puts it outside the bar for bot-only approval.
Split from #36801 (1/5). ## What When the threadsafe function was created with `func == NULL`, pass `js_callback = NULL` to `call_js_cb` instead of an encoded `undefined`. ## Why (fixes #13771, closes #30543) Node's `DispatchOne` ([src/node_api.cc#L452-L462](https://github.com/nodejs/node/blob/v26.x/src/node_api.cc#L452-L462)): ```cpp napi_value js_callback = nullptr; if (!ref.IsEmpty()) { v8::Local<v8::Function> js_cb = v8::Local<v8::Function>::New(env->isolate, ref); js_callback = v8impl::JsValueFromV8LocalValue(js_cb); } env->CallbackIntoModule<false>( [&](napi_env env) { call_js_cb(env, js_callback, context, data); }); ``` When `ref` is empty (the caller passed `func = NULL` to `napi_create_threadsafe_function`), `js_callback` stays `nullptr`. Bun was passing `napi_value::create(env, cb_js.get().unwrap_or(JSValue::UNDEFINED))`, which is the encoded `undefined` value (a non-zero pointer). Addons such as napi-rs and lightningcss test `if (js_callback != NULL)` and, seeing a non-null value, try to `napi_call_function` it: ``` thread '<unnamed>' panicked at napi/src/threadsafe_function.rs:235:57: called `Result::unwrap()` on an `Err` value: Error { status: InvalidArg, reason: "expect Function, got: Undefined" } ``` ## Verification New `checkSameOutput` test fails under the released Bun: ``` $ USE_SYSTEM_BUN=1 bun test test/napi/napi.test.ts -t "passes NULL js_callback" - "js_callback == NULL: 1 + "js_callback == NULL: 0 ``` The `kMaxIterationCount` cap that was in the first revision of this PR has been dropped: no issue has been filed about the unbounded dispatch loop, and the cap as written did not yield to setImmediate/timers anyway (`enqueue_task_concurrent` is drained inside the same `tick()`). <!-- robobun:evidence:begin --> --- **no test proof** · iteration 3 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/napi/napi.test.ts <!-- robobun:evidence:end -->
…#36845) Split from oven-sh#36801 (1/5). ## What When the threadsafe function was created with `func == NULL`, pass `js_callback = NULL` to `call_js_cb` instead of an encoded `undefined`. ## Why (fixes oven-sh#13771, closes oven-sh#30543) Node's `DispatchOne` ([src/node_api.cc#L452-L462](https://github.com/nodejs/node/blob/v26.x/src/node_api.cc#L452-L462)): ```cpp napi_value js_callback = nullptr; if (!ref.IsEmpty()) { v8::Local<v8::Function> js_cb = v8::Local<v8::Function>::New(env->isolate, ref); js_callback = v8impl::JsValueFromV8LocalValue(js_cb); } env->CallbackIntoModule<false>( [&](napi_env env) { call_js_cb(env, js_callback, context, data); }); ``` When `ref` is empty (the caller passed `func = NULL` to `napi_create_threadsafe_function`), `js_callback` stays `nullptr`. Bun was passing `napi_value::create(env, cb_js.get().unwrap_or(JSValue::UNDEFINED))`, which is the encoded `undefined` value (a non-zero pointer). Addons such as napi-rs and lightningcss test `if (js_callback != NULL)` and, seeing a non-null value, try to `napi_call_function` it: ``` thread '<unnamed>' panicked at napi/src/threadsafe_function.rs:235:57: called `Result::unwrap()` on an `Err` value: Error { status: InvalidArg, reason: "expect Function, got: Undefined" } ``` ## Verification New `checkSameOutput` test fails under the released Bun: ``` $ USE_SYSTEM_BUN=1 bun test test/napi/napi.test.ts -t "passes NULL js_callback" - "js_callback == NULL: 1 + "js_callback == NULL: 0 ``` The `kMaxIterationCount` cap that was in the first revision of this PR has been dropped: no issue has been filed about the unbounded dispatch loop, and the cap as written did not yield to setImmediate/timers anyway (`enqueue_task_concurrent` is drained inside the same `tick()`). <!-- robobun:evidence:begin --> --- **no test proof** · iteration 3 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/napi/napi.test.ts <!-- robobun:evidence:end -->
…e_tag/set_prototype (#36846) Split from #36801 (2/5). ## What `napi_define_properties`, `napi_object_freeze`, `napi_object_seal`, `napi_type_tag_object`, `napi_check_object_type_tag`, and `node_api_set_prototype` now ToObject-coerce a primitive `object` argument (succeeding) and leave a `TypeError` pending for `null`/`undefined`, instead of returning `napi_object_expected` with no exception for any non-object. | Input | Before (Bun) | Node.js / after | |---|---|---| | number/string/bool | `napi_object_expected`, no exception | `napi_ok` (ToObject-coerced) | | `null`/`undefined` (define_properties/freeze/seal/set_prototype) | `napi_object_expected`, no exception | `napi_object_expected`, pending `TypeError` | | `null`/`undefined` (type_tag_object/check_object_type_tag) | `napi_object_expected`, no exception | `napi_pending_exception` | ## Node.js source All six use `CHECK_TO_OBJECT` or `CHECK_TO_OBJECT_WITH_PREAMBLE`, which is `ToObject()` coercion ([src/js_native_api_v8.h#L245-L274](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.h#L245-L274)): - `napi_define_properties`: [src/js_native_api_v8.cc#L1426](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1426) - `napi_object_freeze` / `napi_object_seal`: [src/js_native_api_v8.cc#L1502](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1502), [#L1519](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1519) - `napi_type_tag_object` / `napi_check_object_type_tag`: [src/js_native_api_v8.cc#L2728](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L2728), [#L2767](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L2767) (`_WITH_PREAMBLE` → `napi_pending_exception`) - `node_api_set_prototype`: [src/js_native_api_v8.cc#L1584](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1584) `CHECK_TO_TYPE` returns the supplied status (`napi_object_expected`) on failure; `CHECK_TO_TYPE_WITH_PREAMBLE` returns `napi_pending_exception` when an exception was caught, which is why the two `type_tag` functions report a different status on `null`. ## Verification New `checkSameOutput` test compares Bun against Node byte-for-byte. Fails under the released Bun (e.g. `define_properties(number): status=2 pending=0` vs Node's `status=0 pending=0`). <!-- robobun:evidence:begin --> --- **no test proof** · iteration 5 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/napi/napi.test.ts <!-- robobun:evidence:end -->
…ng, module_file_name (#36849) Split from #36801 (4/5). ## What | Function | Before (Bun) | Node.js / after | |---|---|---| | `napi_set_named_property(env, obj, "", v)` | `napi_invalid_arg` | `napi_ok` (sets `obj[""]`) | | `napi_create_symbol(env, <js undefined/null>, &r)` | `napi_ok`, `Symbol()` | `napi_string_expected` | | `napi_create_symbol(env, <js "">, &r)` | `.description === undefined` | `.description === ""` | | `napi_new_instance` / `napi_get_named_property` / `napi_has_named_property` when underlying JS throws | writes `*result`, then `napi_pending_exception` | `napi_pending_exception`, `*result` untouched | | `node_api_get_module_file_name` on the `napi_module_register` path | writes `NULL` | writes `""` | ## Node.js source - `napi_set_named_property` uses `CHECK_NEW_FROM_UTF8`, which only rejects `nullptr`: [src/js_native_api_v8.cc#L25-L41, #L1262-L1283](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L25-L41) - `napi_create_symbol` special-cases only `description == nullptr`; any non-null non-string is `napi_string_expected`: [src/js_native_api_v8.cc#L1925-L1944](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1925-L1944) - `napi_new_instance` / `napi_get_named_property` / `napi_has_named_property` check the `Maybe` before writing `*result`: [src/js_native_api_v8.cc#L3026-L3029](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L3026-L3029), [#L1327-L1331](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1327-L1331), [#L1303-L1306](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1303-L1306) - `node_api_get_module_file_name` returns `filename.c_str()` from a `std::string`, which is never `NULL`: [src/node_api.cc#L1456-L1464](https://github.com/nodejs/node/blob/v26.x/src/node_api.cc#L1456-L1464), [src/node_api_internals.h#L39-L41](https://github.com/nodejs/node/blob/v26.x/src/node_api_internals.h#L39-L41) ## Verification New `checkSameOutput` test compares Bun against Node byte-for-byte; fails under the released Bun. <!-- robobun:evidence:begin --> --- **no test proof** · iteration 5 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/napi/napi.test.ts <!-- robobun:evidence:end -->
…e_tag/set_prototype (oven-sh#36846) Split from oven-sh#36801 (2/5). ## What `napi_define_properties`, `napi_object_freeze`, `napi_object_seal`, `napi_type_tag_object`, `napi_check_object_type_tag`, and `node_api_set_prototype` now ToObject-coerce a primitive `object` argument (succeeding) and leave a `TypeError` pending for `null`/`undefined`, instead of returning `napi_object_expected` with no exception for any non-object. | Input | Before (Bun) | Node.js / after | |---|---|---| | number/string/bool | `napi_object_expected`, no exception | `napi_ok` (ToObject-coerced) | | `null`/`undefined` (define_properties/freeze/seal/set_prototype) | `napi_object_expected`, no exception | `napi_object_expected`, pending `TypeError` | | `null`/`undefined` (type_tag_object/check_object_type_tag) | `napi_object_expected`, no exception | `napi_pending_exception` | ## Node.js source All six use `CHECK_TO_OBJECT` or `CHECK_TO_OBJECT_WITH_PREAMBLE`, which is `ToObject()` coercion ([src/js_native_api_v8.h#L245-L274](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.h#L245-L274)): - `napi_define_properties`: [src/js_native_api_v8.cc#L1426](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1426) - `napi_object_freeze` / `napi_object_seal`: [src/js_native_api_v8.cc#L1502](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1502), [#L1519](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1519) - `napi_type_tag_object` / `napi_check_object_type_tag`: [src/js_native_api_v8.cc#L2728](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L2728), [#L2767](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L2767) (`_WITH_PREAMBLE` → `napi_pending_exception`) - `node_api_set_prototype`: [src/js_native_api_v8.cc#L1584](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1584) `CHECK_TO_TYPE` returns the supplied status (`napi_object_expected`) on failure; `CHECK_TO_TYPE_WITH_PREAMBLE` returns `napi_pending_exception` when an exception was caught, which is why the two `type_tag` functions report a different status on `null`. ## Verification New `checkSameOutput` test compares Bun against Node byte-for-byte. Fails under the released Bun (e.g. `define_properties(number): status=2 pending=0` vs Node's `status=0 pending=0`). <!-- robobun:evidence:begin --> --- **no test proof** · iteration 5 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/napi/napi.test.ts <!-- robobun:evidence:end -->
…ng, module_file_name (oven-sh#36849) Split from oven-sh#36801 (4/5). ## What | Function | Before (Bun) | Node.js / after | |---|---|---| | `napi_set_named_property(env, obj, "", v)` | `napi_invalid_arg` | `napi_ok` (sets `obj[""]`) | | `napi_create_symbol(env, <js undefined/null>, &r)` | `napi_ok`, `Symbol()` | `napi_string_expected` | | `napi_create_symbol(env, <js "">, &r)` | `.description === undefined` | `.description === ""` | | `napi_new_instance` / `napi_get_named_property` / `napi_has_named_property` when underlying JS throws | writes `*result`, then `napi_pending_exception` | `napi_pending_exception`, `*result` untouched | | `node_api_get_module_file_name` on the `napi_module_register` path | writes `NULL` | writes `""` | ## Node.js source - `napi_set_named_property` uses `CHECK_NEW_FROM_UTF8`, which only rejects `nullptr`: [src/js_native_api_v8.cc#L25-L41, #L1262-L1283](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L25-L41) - `napi_create_symbol` special-cases only `description == nullptr`; any non-null non-string is `napi_string_expected`: [src/js_native_api_v8.cc#L1925-L1944](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1925-L1944) - `napi_new_instance` / `napi_get_named_property` / `napi_has_named_property` check the `Maybe` before writing `*result`: [src/js_native_api_v8.cc#L3026-L3029](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L3026-L3029), [#L1327-L1331](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1327-L1331), [#L1303-L1306](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1303-L1306) - `node_api_get_module_file_name` returns `filename.c_str()` from a `std::string`, which is never `NULL`: [src/node_api.cc#L1456-L1464](https://github.com/nodejs/node/blob/v26.x/src/node_api.cc#L1456-L1464), [src/node_api_internals.h#L39-L41](https://github.com/nodejs/node/blob/v26.x/src/node_api_internals.h#L39-L41) ## Verification New `checkSameOutput` test compares Bun against Node byte-for-byte; fails under the released Bun. <!-- robobun:evidence:begin --> --- **no test proof** · iteration 5 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/napi/napi.test.ts <!-- robobun:evidence:end -->
…_NEW_STRING_ARGS (#36847) Split from #36801 (3/5). ## What `node_api_create_external_string_latin1` / `_utf16`: - Accept `(str = NULL, length = 0)` and return the empty string - Reject `length > INT_MAX` with `napi_invalid_arg` (previously the `static_cast<unsigned int>(length)` truncated into a wild span over the caller's buffer and **crashed**) - Zero-length branch returns `napi_ok` directly after running the finalizer, so a pre-existing `napi_throw_*` that `doFinalizer` promotes to the VM cannot cause a non-ok status after the buffer has already been freed | Input | Before (Bun) | Node.js / after | |---|---|---| | `(NULL, 0)` | `napi_invalid_arg` | `napi_ok` (empty string) | | `(ptr, INT_MAX+1)` | **crash** | `napi_invalid_arg` | ## Node.js source `CHECK_NEW_STRING_ARGS` ([src/js_native_api_v8.cc#L43-L52](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L43-L52)): ```cpp #define CHECK_NEW_STRING_ARGS(env, str, length, result) \ do { \ CHECK_ENV_NOT_IN_GC((env)); \ if ((length) > 0) CHECK_ARG((env), (str)); \ CHECK_ARG((env), (result)); \ RETURN_STATUS_IF_FALSE( \ (env), \ ((length) == NAPI_AUTO_LENGTH) || (length) <= INT_MAX, \ napi_invalid_arg); \ } while (0) ``` Used by `NewExternalString` at [src/js_native_api_v8.cc#L107-L137](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L107-L137). No pending-exception gate. ## Verification New `checkSameOutput` test in `test/napi/napi.test.ts`. The released Bun returns `status=1` for `(NULL,0)` and crashes on `(ptr, INT_MAX+1)`. <!-- robobun:evidence:begin --> --- **no test proof** · iteration 5 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/napi/napi.test.ts <!-- robobun:evidence:end -->
…_NEW_STRING_ARGS (oven-sh#36847) Split from oven-sh#36801 (3/5). ## What `node_api_create_external_string_latin1` / `_utf16`: - Accept `(str = NULL, length = 0)` and return the empty string - Reject `length > INT_MAX` with `napi_invalid_arg` (previously the `static_cast<unsigned int>(length)` truncated into a wild span over the caller's buffer and **crashed**) - Zero-length branch returns `napi_ok` directly after running the finalizer, so a pre-existing `napi_throw_*` that `doFinalizer` promotes to the VM cannot cause a non-ok status after the buffer has already been freed | Input | Before (Bun) | Node.js / after | |---|---|---| | `(NULL, 0)` | `napi_invalid_arg` | `napi_ok` (empty string) | | `(ptr, INT_MAX+1)` | **crash** | `napi_invalid_arg` | ## Node.js source `CHECK_NEW_STRING_ARGS` ([src/js_native_api_v8.cc#L43-L52](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L43-L52)): ```cpp #define CHECK_NEW_STRING_ARGS(env, str, length, result) \ do { \ CHECK_ENV_NOT_IN_GC((env)); \ if ((length) > 0) CHECK_ARG((env), (str)); \ CHECK_ARG((env), (result)); \ RETURN_STATUS_IF_FALSE( \ (env), \ ((length) == NAPI_AUTO_LENGTH) || (length) <= INT_MAX, \ napi_invalid_arg); \ } while (0) ``` Used by `NewExternalString` at [src/js_native_api_v8.cc#L107-L137](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L107-L137). No pending-exception gate. ## Verification New `checkSameOutput` test in `test/napi/napi.test.ts`. The released Bun returns `status=1` for `(NULL,0)` and crashes on `(ptr, INT_MAX+1)`. <!-- robobun:evidence:begin --> --- **no test proof** · iteration 5 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/napi/napi.test.ts <!-- robobun:evidence:end -->
…api_get_buffer_info rejects bare ArrayBuffer (#36850) Split from #36801 (5/5). ## What | Function | Before (Bun) | Node.js / after | |---|---|---| | `napi_reference_ref` after the weak referent is collected | increments (returns 1, 2, ...) | returns 0, does not increment | | `napi_get_buffer_info(env, <ArrayBuffer>, ...)` | `napi_ok` | `napi_invalid_arg` | ## Node.js source - `Reference::Ref()` returns 0 without incrementing once the persistent is empty: [src/js_native_api_v8.cc#L690-L700](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L690-L700) ```cpp uint32_t Reference::Ref() { if (persistent_.IsEmpty()) { return 0; } if (++refcount_ == 1 && can_be_weak_) { persistent_.ClearWeak(); } return refcount_; } ``` The check in `NapiRef::ref()` is `refCount == 0 && !weakValueRef.isClear() && !weakValueRef.get()` so it only fires when a weak handle was set and has since been cleared by GC; strongly-held or never-weak references keep their existing behaviour. - `napi_get_buffer_info` gates on `node::Buffer::HasInstance`: [src/node_api.cc#L1150-L1169](https://github.com/nodejs/node/blob/v26.x/src/node_api.cc#L1150-L1169), which is `IsArrayBufferView()` ([src/node_buffer.cc](https://github.com/nodejs/node/blob/v26.x/src/node_buffer.cc)). Typed arrays and DataView pass; a bare `ArrayBuffer` / `SharedArrayBuffer` does not. ## Verification Two new `checkSameOutput` tests. The `reference_ref` driver polls `napi_get_reference_value` via `gcUntil` so it waits for collection instead of assuming a single GC pass. <!-- robobun:evidence:begin --> --- **no test proof** · iteration 8 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/napi/napi.test.ts <!-- robobun:evidence:end -->
…api_get_buffer_info rejects bare ArrayBuffer (oven-sh#36850) Split from oven-sh#36801 (5/5). ## What | Function | Before (Bun) | Node.js / after | |---|---|---| | `napi_reference_ref` after the weak referent is collected | increments (returns 1, 2, ...) | returns 0, does not increment | | `napi_get_buffer_info(env, <ArrayBuffer>, ...)` | `napi_ok` | `napi_invalid_arg` | ## Node.js source - `Reference::Ref()` returns 0 without incrementing once the persistent is empty: [src/js_native_api_v8.cc#L690-L700](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L690-L700) ```cpp uint32_t Reference::Ref() { if (persistent_.IsEmpty()) { return 0; } if (++refcount_ == 1 && can_be_weak_) { persistent_.ClearWeak(); } return refcount_; } ``` The check in `NapiRef::ref()` is `refCount == 0 && !weakValueRef.isClear() && !weakValueRef.get()` so it only fires when a weak handle was set and has since been cleared by GC; strongly-held or never-weak references keep their existing behaviour. - `napi_get_buffer_info` gates on `node::Buffer::HasInstance`: [src/node_api.cc#L1150-L1169](https://github.com/nodejs/node/blob/v26.x/src/node_api.cc#L1150-L1169), which is `IsArrayBufferView()` ([src/node_buffer.cc](https://github.com/nodejs/node/blob/v26.x/src/node_buffer.cc)). Typed arrays and DataView pass; a bare `ArrayBuffer` / `SharedArrayBuffer` does not. ## Verification Two new `checkSameOutput` tests. The `reference_ref` driver polls `napi_get_reference_value` via `gcUntil` so it waits for collection instead of assuming a single GC pass. <!-- robobun:evidence:begin --> --- **no test proof** · iteration 8 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/napi/napi.test.ts <!-- robobun:evidence:end -->
… like Node (#39418) ### Problem - `napi_get_prototype` on a Proxy runs the Proxy's `getPrototypeOf` trap. Node does not: V8's `Object::GetPrototype`, which Node's `napi_get_prototype` wraps, cannot run JS and returns `null` for any Proxy (verified with Node 26.3, output in the details below). - Running the trap also makes the failure mode wrong: when the trap throws (or returns a non-object, or the proxy is revoked) the call returns `napi_ok`, writes a NULL `napi_value` into `*result`, and leaves the exception pending without telling the addon. Current canary on the new fixture: `trap throws: status=0 pending=true result=null handle exception=the trap's error`. - This is an unreleased regression from #33731 (86caf6e): `napi_get_prototype` used to call the JSC C API's `JSObjectGetPrototype`, which is `getPrototypeDirect()`, and JSC creates Proxy structures with a null prototype, so 1.3.14 already returned `null` for a Proxy without running anything. #33731 replaced it with `JSValue::get_prototype`, JSC's full `[[GetPrototypeOf]]` (traps included), which returned a bare `JSValue` that is empty (encoded 0, i.e. a NULL handle) when it threw, so the call site in `src/runtime/napi/napi_body.rs` could not tell success from failure. Affects 1.4.0 canary only; the `napi_get_prototype` line in the #36801 audit ("already avoids the trap") describes the pre-#33731 state. - The other `getPrototype` exception-handling sites found by the same reading (the inspect property walk, `napi_get_all_property_names`, `util.isError`) are separate fixes in #29642, #32263 and #37202; this PR merges cleanly in either order with them. ### Fix - `napi_get_prototype` returns `null` for a `ProxyObject` without touching its handler, the same result Node produces and the same result 1.3.14 produced. Every other object type's `[[GetPrototypeOf]]` in JSC is a plain read (`JSGlobalProxy` forwards to the global object, `ImportMetaObject` returns null, primitives get their wrapper prototype), so the function no longer runs JS for any input, like Node's. - `JSValue::get_prototype` (`src/jsc/JSValue.rs`) now returns `JsResult<JSValue>` through `host_fn::from_js_host_call`, the wrapper `JSValue::call` and `unwrap_boxed_primitive` already use for JSC calls that return empty exactly when they threw. This is what let the empty value reach `*result`, and the remaining callers (`ConsoleObject.rs`, `pretty_format.rs`, `ScopeFunctions.rs`, all already returning `JsResult`) now propagate with `?` instead of holding a possibly-empty value. They only ever see ordinary objects (the formatters print a Proxy's target), so their output is unchanged. In `napi_get_prototype` the `Err` arm maps to `napi_pending_exception` as the generic Node-API protocol; with the Proxy case handled above it is not reachable with today's object types. - Test: `test/napi/napi.test.ts` (`napi_get_prototype`) runs fixture `test_napi_get_prototype_proxy` (`napi-app/module.js`) through `checkSameOutput`, so the output is compared byte for byte with Node, and then pins the lines. The helper `perform_get_prototype` (`napi-app/js_test_helpers.cpp`) pre-fills `*result` with a sentinel so the output distinguishes a real `null` from "not written" and from a NULL handle. Cases: proxy without traps, callable proxy, a trap that counts its calls (must stay 0), a trap that throws, a trap returning a number, a revoked proxy, plus plain / null-prototype objects and an object whose prototype is a proxy (returned as-is, only the object itself is special-cased). - Fails under `USE_SYSTEM_BUN=1` (1.4.0-canary.1: 7 of 11 lines differ from Node, see details), passes with `bun bd test test/napi/napi.test.ts`. - Also run on the debug build: the rest of `test/napi/napi.test.ts`, Node's own `test_general` suite (`test/napi/node-napi-tests/.../test_general/do.test.ts`, which asserts `napi_get_prototype` matches `Object.getPrototypeOf` for ordinary objects), `test/js/bun/util/inspect.test.js`, `test/js/bun/test/printing/diffexample.test.ts`, `jest-each.test.ts`, `describe.test.ts`, `pretty-format-overflow.test.ts`, `console-table.test.ts`; plus a script formatting classes, functions, null-prototype objects and proxies, and a `bun test` file exercising `describe.each` / `test.each` / `skipIf` and class-instance `toEqual` diffs, both clean under `BUN_JSC_validateExceptionChecks=1`. - Noted while reviewing the other Proxy-receiver paths, not changed here (different function and file): `napi_remove_wrap` on a Proxy or on `globalThis` reports success but leaves the wrap attached, because `src/jsc/bindings/napi.cpp` removes it with the virtual `deleteProperty` (which `ProxyObject` refuses for private names and `JSGlobalProxy` forwards to its target) while `napi_wrap` / `napi_unwrap` use `putDirect` / `getDirect`; Node removes it. Probe output is in the second details block. ### Background - `[[GetPrototypeOf]]` is the spec operation behind `Object.getPrototypeOf`. For ordinary objects it reads a field and cannot fail; a Proxy implements it by calling its handler's `getPrototypeOf` trap, so it can run arbitrary JS and throw. V8's `Object::GetPrototype` returns a plain `Local<Value>` rather than a `MaybeLocal`, so it cannot run a trap, and it reports `null` for a Proxy; that is the behavior Node-API addons are written against. - `getPrototypeDirect()` is JSC's raw read of the prototype stored in an object's Structure, bypassing any override; `getPrototype()` is the full operation that dispatches to `ProxyObject`'s trap. The JSC C API's `JSObjectGetPrototype` is the former. - JSC signals a throw from a value-returning operation by returning the empty `JSValue` (encoding 0) and leaving the exception on the VM. `host_fn::from_js_host_call` maps that to `Err(JsError::Thrown)` and, in debug builds, asserts the value is empty if and only if an exception is pending. - A `napi_value` is an encoded `JSValue`, so storing the empty value hands the addon a NULL handle. - `napi_pending_exception` is the status a Node-API call returns when JS it ran threw; the exception stays pending for `napi_get_and_clear_last_exception` and out-params are left unwritten. <details> <summary>Fixture output: Node 26.3 (and this branch, identical) vs current canary</summary> Node v26.3.0, and this branch: ``` plain object: status=0 pending=false result=Object.prototype exception=none null prototype: status=0 pending=false result=null exception=none proxy without traps: status=0 pending=false result=null exception=none callable proxy: status=0 pending=false result=null exception=none trap returns Array.prototype: status=0 pending=false result=null exception=none getPrototypeOf trap calls: 0 trap throws: status=0 pending=false result=null exception=none trap returns a number: status=0 pending=false result=null exception=none revoked proxy: status=0 pending=false result=null exception=none object whose prototype is a proxy: status=0 pending=false result=the proxy exception=none plain object again: status=0 pending=false result=Object.prototype exception=none ``` Bun 1.4.0-canary.1 (`USE_SYSTEM_BUN=1`): ``` plain object: status=0 pending=false result=Object.prototype exception=none null prototype: status=0 pending=false result=null exception=none proxy without traps: status=0 pending=false result=Array.prototype exception=none callable proxy: status=0 pending=false result=Function.prototype exception=none trap returns Array.prototype: status=0 pending=false result=Array.prototype exception=none getPrototypeOf trap calls: 1 trap throws: status=0 pending=true result=null handle exception=the trap's error trap returns a number: status=0 pending=true result=null handle exception=TypeError revoked proxy: status=0 pending=true result=null handle exception=TypeError object whose prototype is a proxy: status=0 pending=false result=the proxy exception=none plain object again: status=0 pending=false result=Object.prototype exception=none ``` </details> <details> <summary>napi_remove_wrap follow-up: probe output (existing try_wrap / try_remove_wrap / try_unwrap helpers from napi-app, wrapping the number 6, then trying to re-wrap with 7)</summary> Node v26.3.0: ``` plain: wrap=true remove=6 unwrap_after=undefined rewrap=true proxy: wrap=true remove=6 unwrap_after=undefined rewrap=true callable proxy: wrap=true remove=6 unwrap_after=undefined rewrap=true globalThis: wrap=true remove=6 unwrap_after=undefined rewrap=true ``` Bun (this branch, unchanged in this respect): ``` plain: wrap=true remove=6 unwrap_after=undefined rewrap=true proxy: wrap=true remove=6 unwrap_after=6 rewrap=false callable proxy: wrap=true remove=6 unwrap_after=6 rewrap=false globalThis: wrap=true remove=6 unwrap_after=6 rewrap=false ``` </details> <details> <summary>Earlier version of this PR</summary> The first revision kept running the trap and changed only the failure report: `napi_pending_exception` with `*result` untouched when the trap threw, tested on Bun alone since Node never reaches that path. Review asked to match Node instead and not run JS, which is the current shape; the `JsResult` change to `JSValue::get_prototype` is unchanged from that revision. </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 0 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/napi/napi.test.ts <!-- robobun:evidence:end -->
|
Closing this PR because it has been inactive for more than 90 days. |
What
A set of N-API functions whose observable behaviour (not just return status) differed from Node.js. Each was verified by running the same native addon under both
nodev26 andbun; the new tests usecheckSameOutputso Bun's stdout is compared byte-for-byte with Node's.napi_set_named_property(env, obj, "", v)napi_invalid_argnapi_ok(setsobj[""])napi_create_symbol(env, <js undefined/null>, &r)napi_ok,Symbol()napi_string_expectednapi_create_symbol(env, <js "">, &r).description === undefined.description === ""node_api_create_external_string_latin1(env, NULL, 0, ...)napi_invalid_argnapi_ok(empty string)node_api_create_external_string_{latin1,utf16}(env, p, INT_MAX+1, ...)static_cast<unsigned>span)napi_invalid_argnapi_get_buffer_info(env, <ArrayBuffer>, ...)napi_oknapi_invalid_arg(HasInstance=IsArrayBufferView)napi_define_properties/napi_object_freeze/napi_object_seal/node_api_set_prototypeon a numbernapi_object_expected, no exceptionnapi_ok(ToObject-coerced)null/undefinednapi_object_expected, no exceptionnapi_object_expected, pendingTypeErrornapi_type_tag_object/napi_check_object_type_tagon a numbernapi_object_expected, no exceptionnapi_oknullnapi_object_expected, no exceptionnapi_pending_exceptionnapi_new_instance/napi_get_named_property/napi_has_named_propertywhen the underlying JS throws*result, thennapi_pending_exceptionnapi_pending_exception,*resultuntouchednode_api_get_module_file_nameon thenapi_module_registerpathNULL""napi_reference_refafter the weak referent is collectedcall_js_cbwhen created withfunc == NULLjs_callbackis encodedundefined(non-null)js_callback == NULLkMaxIterationCount)Why
These are the cases where a correct N-API addon observes a different answer under Bun than under Node.js, for the same sequence of calls. The external-string length overflow is a crash in practice (the truncated
unsignedis used as a span length over the caller's buffer). Thejs_callback != NULLcheck is how napi-rs and similar decide whether to invoke the JS function insidecall_js_cb; the encodedundefinedvalue is a non-zero pointer, so addons were callingnapi_call_functionon it and panicking with "expect Function, got: Undefined".Fixes #13771
Closes #30543 (subsumed; same TSFN
js_callbackfix)Two items from the originating audit were dropped after empirical verification:
napi_set_property/_elementdo not need a put-return check (V8'sObject::Setnever returnsJust(false), so Node'snapi_generic_failurebranch is unreachable and Bun already matches), andnapi_get_prototypealready avoids the ProxygetPrototypeOftrap in Bun.The
napi_get_typedarray_info/napi_get_dataview_infotype gate and thenapi_add_finalizerteardown guarantee are already covered by #34132 and #32912 respectively.Verification
New
checkSameOutputtests intest/napi/napi.test.ts(-t "semantic parity with Node") compare Bun against Node.js and fail under the released Bun:The vendored Node.js
js-native-api/test_symbol,test_object,test_properties,test_reference, andnode-api/test_threadsafe_functionsuites continue to pass.no test proof · iteration 0 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/napi/napi.test.ts