Repository navigation
napi: implement the five NAPI_EXPERIMENTAL node_api_* functions added in Node v26 - #34147
Conversation
WalkthroughAdds experimental Node-API bindings for prototype assignment, property-based object creation, and SharedArrayBuffer operations, wires their native symbols, and adds addon and standalone tests covering validation, backing-store access, and external finalization. ChangesExperimental Node-API extensions
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 8:05 PM PT - Jul 14th, 2026
❌ @robobun, your commit 5cdd867 has 2 failures in
🧪 To try this PR locally: bunx bun-pr 34147That installs a local version of the PR into your bun-34147 --bun |
There was a problem hiding this comment.
All three earlier findings are addressed (prototype validation in node_api_set_prototype, putDirectMayBeIndex for index-like keys, CRLF-tolerant test assertions), and I didn't find anything new. Deferring to a human because this adds five new exported N-API functions plus a new NapiNoEnvExternalBufferDestructor for cross-agent SAB lifetime — new native ABI surface and finalizer semantics that warrant a maintainer's eyes.
Checked: symbol exports are consistent across symbols.{txt,dyn,def} and keep_symbols!; the get_all_property_names de-dup keeps the {status, keys}-returning helper and module.js was updated to .keys at its one consuming call site; arm() ordering in the external-SAB path mirrors the existing napi_create_external_arraybuffer pattern.
Extended reasoning...
Overview
Implements and exports five NAPI_EXPERIMENTAL functions from Node v26 (node_api_set_prototype, node_api_create_object_with_properties, node_api_create_sharedarraybuffer, node_api_create_external_sharedarraybuffer, node_api_is_sharedarraybuffer) in src/jsc/bindings/napi.cpp (~160 new lines including a new NapiNoEnvExternalBufferDestructor : SharedTask<void(void*)>), adds header declarations under #ifdef NAPI_EXPERIMENTAL, wires the symbols through all three export lists and the Rust keep_symbols! list, adds C++ test drivers in standalone_tests.cpp, three checkSameOutput tests in napi.test.ts, and de-duplicates a colliding get_all_property_names helper in the test addon (adjusting one module.js caller to the surviving helper's {status, keys} shape).
Follow-up on prior review
My previous run flagged three issues; all are fixed in the current diff and the threads are resolved:
node_api_set_prototypenow rejects non-object/non-null prototypes withnapi_invalid_argbefore reaching JSC'ssetPrototypeassertion.node_api_create_object_with_propertiesnow usesputDirectMayBeIndexand the test exercises a"0"key vianapi_get_element.- The three new tests now compare via
output.split(/\r?\n/)so Windows CRT\r\ndoesn't break the assertion.
No new issues surfaced this pass. I also spot-checked that the surviving get_all_property_names helper's other callers (test_get_all_property_names_own_only, the discarded-result loops in test_property_names_cache_poisoning) already match its {status, keys} return shape.
Security risks
None identified. Inputs come from native addon callers (already inside the trust boundary); there's no parsing of untrusted network/file data. The external-SAB finalizer runs addon-provided code, which is the N-API contract.
Level of scrutiny
High. This is new public ABI surface exported from the binary, with JSC-integration and memory-lifetime concerns: ArrayBuffer::createFromBytes + makeShared() for external data, a new SharedTask-based no-env finalizer whose run() may fire on a thread/agent that outlives the creating napi_env, and setPrototype/constructEmptyObject interactions with JSC structures. The arm()-after-create pattern matches the existing NapiExternalBufferDestructor idiom in this file, but whether makeShared() on an externally-backed ArrayBuffer behaves identically to Node's BackingStore semantics (e.g. transferability, isShared() after posting to a worker) is the kind of thing a maintainer familiar with JSC's SAB machinery should confirm.
Other factors
Tests are checkSameOutput against the ABI-matching Node, which is the right shape for N-API compat work, and the PR description confirms fail-before under USE_SYSTEM_BUN=1. The change is well-scoped and follows file-local conventions (NAPI_PREAMBLE/NAPI_CHECK_ARG/NAPI_RETURN_EARLY_IF_FALSE). Still, per the approval bar, five new exported native functions with a bespoke finalizer class is not a mechanical change I should auto-approve.
There was a problem hiding this comment.
All four earlier findings are addressed in the current diff and this pass found nothing new. I'm deferring rather than approving because this adds five new public NAPI symbols plus a new SharedArrayBuffer external-backing-store finalizer path (NapiNoEnvExternalBufferDestructor, no-env finalize semantics) — that's the kind of ABI/memory-lifetime surface a maintainer should sign off on.
What was checked this pass:
node_api_set_prototypeandnode_api_create_object_with_propertiesnow both reject primitive prototypes withnapi_invalid_arg; the latter routes index-like keys throughputDirectMayBeIndex.- The three new tests use
output.split(/\r?\n/)so Windows CRT\r\nno longer breaks the assertions. node_api_create_external_sharedarraybuffer's arm-after-create pattern mirrors the existingnapi_create_external_arraybufferdestructor flow; thedestructorPtrraw pointer is safe becauseArrayBuffer::createFromBytesretains theSharedTaskref.
Extended reasoning...
Overview
Implements five NAPI_EXPERIMENTAL functions from Node v26 in src/jsc/bindings/napi.cpp (~170 lines of new C++), exports them via symbols.{txt,dyn,def} and the Rust keep_symbols! list, declares them under #ifdef NAPI_EXPERIMENTAL in js_native_api.h, and adds three checkSameOutput tests in standalone_tests.cpp / napi.test.ts. Also de-duplicates a get_all_property_names helper collision in the test addon.
Prior review state
I left four inline findings across two earlier passes (Windows CRLF in the new tests, putDirect on index-like property names, missing object-or-null validation on the prototype argument in both node_api_set_prototype and node_api_create_object_with_properties). All four are resolved in the current diff, and the follow-up commits added test coverage for the index-key case ("0" → napi_get_element). The bug-hunting system found nothing new on this revision.
Security risks
None in the traditional sense — these are native-addon-facing entry points, so the caller is already running arbitrary native code. The relevant risk class is memory safety: node_api_create_external_sharedarraybuffer hands JSC a caller-owned backing store with a finalizer that (per Node's spec) may fire on any thread after the creating napi_env is gone. The new NapiNoEnvExternalBufferDestructor correctly avoids capturing env and uses the same arm-after-create pattern as the existing NapiExternalBufferDestructor, and the Ref<> moved into ArrayBuffer::createFromBytes keeps the raw destructorPtr valid across the arm() call.
Level of scrutiny
High. This is new public ABI surface (five exported symbols across all three platforms), and SharedArrayBuffer + external backing store + cross-agent lifetime is exactly the corner of NAPI where subtle lifetime bugs live. The implementations closely follow existing siblings (napi_create_arraybuffer, napi_create_external_arraybuffer, napi_get_prototype) and are validated against Node via checkSameOutput, but a maintainer should confirm the makeShared()-after-tryCreate / createFromBytes sequence and the no-env finalizer contract match what they want long-term.
Other factors
Tests compare output byte-for-byte against the ABI-matching Node binary, which is strong evidence for the happy paths and the napi_name_expected / napi_invalid_arg error paths that are exercised. The js_test_helpers.cpp de-dup and the module.js .keys accessor change are collateral to fix a build break from two conflicting recent PRs and look correct against the surviving get_all_property_names helper's {status, keys} return shape.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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 1736-1759: Update node_api_create_external_sharedarraybuffer to
check for pending exceptions immediately after JSC::JSArrayBuffer::create(...)
and before arming the destructor, assigning result, or returning success,
matching node_api_create_sharedarraybuffer. Also add the sibling’s
NAPI_CHECK_ENV_NOT_IN_GC(env) validation in this function.
- Around line 1597-1619: Add NAPI_CHECK_ENV_NOT_IN_GC(env) immediately after
NAPI_PREAMBLE(env) in both node_api_set_prototype and
node_api_create_external_sharedarraybuffer. Update both affected sites in
src/jsc/bindings/napi.cpp:1597-1619 and src/jsc/bindings/napi.cpp:1736-1759.
🪄 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: 53bbedab-66e6-49b8-9277-a07f3c27d25f
📒 Files selected for processing (10)
src/jsc/bindings/napi.cppsrc/runtime/napi/js_native_api.hsrc/runtime/napi/napi_body.rssrc/symbols.defsrc/symbols.dynsrc/symbols.txttest/napi/napi-app/js_test_helpers.cpptest/napi/napi-app/module.jstest/napi/napi-app/standalone_tests.cpptest/napi/napi.test.ts
💤 Files with no reviewable changes (1)
- test/napi/napi-app/js_test_helpers.cpp
There was a problem hiding this comment.
No new issues found — all four prior rounds of feedback (primitive-prototype validation, putDirectMayBeIndex for index keys, Windows CRLF in tests, NAPI_CHECK_ENV_NOT_IN_GC, NULL property_names[i]) are addressed in the current diff. Deferring to a human for sign-off given this adds five new public N-API entry points plus a custom SharedTask-based finalizer class for external SharedArrayBuffer backing stores.
Checked this pass: the arm-after-create ordering in node_api_create_external_sharedarraybuffer mirrors napi_create_external_arraybuffer and correctly leaves ownership with the caller on the (currently unreachable) failure path; node_api_is_sharedarraybuffer uses dynamicDowncast + isShared() so it won't misreport typed arrays or plain ArrayBuffers; the get_all_property_names de-dup in js_test_helpers.cpp keeps the {status, keys}-returning variant that module.js and the own_only test both consume.
Extended reasoning...
Overview
Implements five NAPI_EXPERIMENTAL functions from Node v26 in src/jsc/bindings/napi.cpp (~170 lines): node_api_set_prototype, node_api_create_object_with_properties, node_api_create_sharedarraybuffer, node_api_create_external_sharedarraybuffer, node_api_is_sharedarraybuffer. Wires exports through symbols.{txt,dyn,def} and napi_body.rs keep_symbols!, declares them under #ifdef NAPI_EXPERIMENTAL in js_native_api.h, and adds checkSameOutput-based tests in standalone_tests.cpp / napi.test.ts. Also de-duplicates a colliding get_all_property_names helper in the test addon.
Security risks
None identified. Inputs come from native addon code (already fully trusted in-process); the new functions validate object/null prototypes, string/symbol property names, and null out-params before touching JSC internals. No parsing of untrusted external data, no auth/crypto surface.
Level of scrutiny
High. This is new public ABI surface in the N-API compatibility layer — memory-management-sensitive C++ that interacts with JSC's GC, ArrayBuffer backing stores, and introduces a new NapiNoEnvExternalBufferDestructor : SharedTask<void(void*)> for the env-less SharedArrayBuffer finalizer contract. SharedArrayBuffer backing stores can outlive the creating agent, so the finalizer-without-env design is a real semantic decision worth a maintainer's eyes. Per the approval guidelines this is well outside "simple, mechanical, or obvious."
Other factors
Four prior review rounds on this PR surfaced and resolved: primitive prototypes reaching setPrototype's engine assertion; putDirect on index-like keys; Windows CRLF in multi-line printf assertions; missing NAPI_CHECK_ENV_NOT_IN_GC on two entry points; and NULL entries in property_names[]. The current diff reflects all of those fixes. Tests use checkSameOutput against the ABI-matching Node, which gives good behavioral parity coverage, and the index-key case ("0") was added to the property test after review. The one open CodeRabbit suggestion (exception check after JSArrayBuffer::create in the external-SAB path) was reasonably declined by the author with reference to the existing napi_create_external_arraybuffer precedent and assertNoException() in NAPI_RETURN_SUCCESS.
|
The three new The remaining red in #73112 is unrelated to this diff:
Ready for review. |
… in Node v26 Implements and exports node_api_set_prototype, node_api_create_object_with_properties, node_api_create_sharedarraybuffer, node_api_create_external_sharedarraybuffer, and node_api_is_sharedarraybuffer. These are the only five node_api_*/napi_* symbols from Node v26 that Bun does not already export. Because addon binding is lazy, an addon that references any of them loads cleanly on Bun and then dies with an uncatchable ld.so "symbol lookup error" (exit 127) the first time the code path is hit, with no JS exception to catch. The new tests in standalone_tests.cpp take link-time references to all five symbols and compare their behaviour against the ABI-matching Node (currently v26.3.0) via checkSameOutput. Also de-duplicates get_all_property_names in js_test_helpers.cpp, where two recent PRs (#34126, #34130) each added a helper with that name and the addon stopped building.
…eys in node_api_create_object_with_properties node_api_set_prototype now rejects a primitive prototype with napi_invalid_arg instead of reaching JSC's ASSERT(prototype.isObject() || prototype.isNull()) in setPrototypeDirect. node_api_create_object_with_properties now routes property assignment through putDirectMayBeIndex so numeric-string keys like "0" go to indexed storage instead of tripping ASSERT(!parseIndex(propertyName)) in putDirect. The test now covers a "0" key.
…th_properties Matches the validation in node_api_set_prototype added earlier in this PR so both prototype-taking functions handle a non-object non-null prototype the same way.
…_api_create_external_sharedarraybuffer Matches the guard present in the sibling create helpers and Node's NAPI_PREAMBLE semantics.
6afec59 to
5cdd867
Compare
There was a problem hiding this comment.
All prior review findings have been addressed and CI is green across platforms, but this adds five new public N-API entry points in napi.cpp (including a new NapiNoEnvExternalBufferDestructor with cross-env SAB finalizer semantics), so it's worth a human look.
Checked this run: the putDirectMayBeIndex / primitive-prototype / NULL-name / NAPI_CHECK_ENV_NOT_IN_GC fixes are all in the current diff; the destructorPtr->arm() ordering matches the existing napi_create_external_arraybuffer pattern and NAPI_RETURN_SUCCESS covers the no-exception assert; the three symbol files and keep_symbols! are consistent; and the new tests use .split(/\r?\n/) so Windows CRLF is handled.
Extended reasoning...
Overview
Implements and exports five NAPI_EXPERIMENTAL functions added in Node v26: node_api_set_prototype, node_api_create_object_with_properties, node_api_create_sharedarraybuffer, node_api_create_external_sharedarraybuffer, node_api_is_sharedarraybuffer. Touches src/jsc/bindings/napi.cpp (~170 new lines including a new NapiNoEnvExternalBufferDestructor SharedTask subclass), the three symbol export lists, napi_body.rs FFI declarations + keep_symbols!, the js_native_api.h header, and adds C++ test fixtures + three checkSameOutput tests.
Security risks
None identified. Inputs come from native addons (already trusted at process level). Argument validation now covers null pointers, primitive prototypes, non-name property keys, and NULL array elements. No parsing of untrusted external data, no auth/crypto/permissions.
Level of scrutiny
High. This is new public N-API surface in C++ JSC bindings with memory-lifetime concerns: setPrototype on user objects, putDirectMayBeIndex with user-supplied keys, and especially node_api_create_external_sharedarraybuffer which introduces a node_api_noenv_finalize callback type and a destructor class whose run() may fire after the creating env is gone (SAB backing stores can be posted cross-agent). The arm-after-create pattern mirrors napi_create_external_arraybuffer, but the design choice of a no-env finalizer and its interaction with JSC's ArrayBuffer teardown deserves a maintainer's eye.
Other factors
Four rounds of review feedback (mine + CodeRabbit) have been applied and all threads are resolved. CI passed on Linux/macOS/Windows per robobun. Tests use checkSameOutput against ABI-matching Node, which is strong evidence of behavioral parity for the covered paths. The one candidate flagged this run (5-line comment vs 3-line max) was ruled out as not blocking. Deferring because new native public API + custom finalizer lifetime is beyond what I should approve unilaterally, not because of any known defect.
What does this PR do?
Implements and exports the five
NAPI_EXPERIMENTALfunctions introduced in Node v26 that Bun did not yet provide:node_api_set_prototypenode_api_create_object_with_propertiesnode_api_create_sharedarraybuffernode_api_create_external_sharedarraybuffernode_api_is_sharedarraybufferSymbol census on a Bun 1.4 / origin/main build vs Node v26.3.0 shows these are the only
napi_*/node_api_*exports Bun is missing (155/161 before, 161/161 after).Repro
Because addon binding is lazy, an addon that references any of these symbols loads cleanly on Bun (require succeeds, other exports run), then dies with an uncatchable dynamic-linker error the first time the code path runs:
Exit 127, no JS exception, no
uncaughtException, nothing points at the addon's JS caller.Cause
The functions were added to Node's
js_native_api.hunderNAPI_EXPERIMENTALfor v26 and had no corresponding implementation/export in Bun.Fix
src/jsc/bindings/napi.cpp: implements all five using the same patterns as the existingnapi_create_arraybuffer/napi_create_external_arraybuffer/napi_get_prototype.node_api_create_external_sharedarraybuffertakes anode_api_noenv_finalize(no env parameter, since SAB backing stores can outlive the creating env), so it uses a dedicatedNapiNoEnvExternalBufferDestructorrather thanNapiExternalBufferDestructor.src/symbols.{txt,dyn,def}andsrc/runtime/napi/napi_body.rs(keep_symbols!): export the symbols from the binary.src/runtime/napi/js_native_api.h: declare under#ifdef NAPI_EXPERIMENTAL.How did you verify your code works?
New tests in
test/napi/napi-app/standalone_tests.cpptake link-time references to all five functions and exercise them, thennapi.test.tscompares the output against the ABI-matching Node (currently v26.3.0) viacheckSameOutput:With
USE_SYSTEM_BUN=1the same three tests fail withsymbol lookup error: ... undefined symbol: node_api_set_prototypeetc, confirming the fail-before.no test proof · iteration 7 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/napi/napi.test.ts