Skip to content

Add more object functions. - #3

Merged
Brooooooklyn merged 1 commit into
napi-rs:masterfrom
Frando:object_helpers
Jan 27, 2019
Merged

Brooooooklyn merged 1 commit into
napi-rs:masterfrom
Frando:object_helpers

Conversation

@Frando

@Frando Frando commented Jan 26, 2019

Copy link
Copy Markdown
Contributor

Hi, started using napi-rs instead of neon. Works very well so far.

I needed a few more functions to work with js objects and arrays and added them here. Originally based on the fork from @cztomsik but rebased onto this master here.

@cztomsik

Copy link
Copy Markdown

wow, I had no idea anyone else could be beneficient from my additions, hope it helped you and thanks for pinging :-)

@Brooooooklyn

Copy link
Copy Markdown
Member

thanks!

@Brooooooklyn
Brooooooklyn merged commit b508ff4 into napi-rs:master Jan 27, 2019
hardfist pushed a commit to hardfist/napi-rs that referenced this pull request Sep 22, 2024
feat: support to use tuple with either
Brooooooklyn added a commit that referenced this pull request Jul 20, 2026
napi-rs registers class methods via `napi_define_class`, whose instance
methods carry a V8 FunctionTemplate signature bound to the constructing
template. A spoofed receiver (`ClassA.prototype.method.call(new ClassB())`)
is therefore rejected by V8 with "Illegal invocation" before the native
callback runs, making the `validate_type_tag` check on `self.this`
redundant on the hottest per-method path — net one fewer FFI per method
call. The V8-unguarded surfaces (field accessors, `&T`/`&mut T` params,
`ClassInstance`/`Reference` conversions) keep their own tag checks.

The `T: TypeName + MaybeTypeTag` bound on `unwrap_raw` is left intact so
signatures stay byte-stable across builds. Updates type-tag.spec test #3
comment: V8's signature is now the sole receiver guard; the test asserts
only that a catchable Error is thrown (not its message).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz
Brooooooklyn added a commit that referenced this pull request Jul 20, 2026
…3405)

* feat(sys): add napi_type_tag_object / napi_check_object_type_tag externs (node-api v8)

* feat(napi): unforgeable class identity via Node object type tags

Add a `TypeTag` trait (defined unconditionally) carrying a per-class
128-bit `napi_type_tag`. Stamp every `#[napi]` class instance right after
`napi_wrap` at all three wrap sites (`_construct`, `_factory`,
`new_instance`) and verify the tag before every blind pointer cast:
method receiver (`unwrap_raw`), `ClassInstance<T>`, field accessor, and
`Reference<T>`. This rejects wrong-class / prototype-spoofed objects with
a catchable `InvalidArg` error instead of a type-confused cast (UB).

The `tag_object` / `validate_type_tag` helpers are defined unconditionally
with `napi8`-gated bodies (a no-op on builds without `napi8`), because
they are also invoked from derive-generated code that expands in the
consumer crate where a `#[cfg(feature = "napi8")]` would resolve against
the consumer's features rather than napi's. Default (napi4) builds are
unchanged.

* feat(backend): stamp and check per-class type tag in derive codegen

Emit an unconditional `impl TypeTag` for every `#[napi]` class, with the
tag computed at macro-expansion time as an FNV-1a-128 hash of the class
`js_name` (the globally-unique registry key) split into two `u64`
literals. Inject a `validate_type_tag` check into the generated
`from_napi_ref` / `from_napi_mut_ref` so `&T` / `&mut T` params reject a
wrong-class / prototype-spoofed argument before the blind cast.

The check is emitted unconditionally (not `#[cfg(feature = "napi8")]`)
because it expands in the consumer crate; gating lives inside napi's
`validate_type_tag` (a no-op without `napi8`). The existing `strict` /
`instanceof` validation is left unchanged.

* test(napi): cover unforgeable class type-tag scenarios

Add two `#[napi]` classes (constructed via `new`, `#[napi(factory)]` and
by-value return) and a spec covering: normal usage round-trips; a
wrong-class `&T` argument throws; a receiver spoof throws a catchable
error; a prototype-spoofed argument that would pass `instanceof` is still
rejected by the tag; and subclass instances still pass. Regenerates the
example addon bindings and the type-def snapshot for the new surface.

* fix(backend): scope class type tag to crate+version+module (unforgeable across addons)

The per-class type tag was FNV-1a-128 of the bare `js_name`, so two classes
sharing a js_name (same name in different namespaces, or in two separately
compiled addons loaded in one process) got IDENTICAL tags. A wrapped instance
of one then passed the other's tag check and was blind-cast to the wrong Rust
type -- type confusion / UB that deterministically defeats the feature.

Build the hash input from a stable identity that includes the crate identity
and module: `{CARGO_PKG_NAME}@{CARGO_PKG_VERSION}::{js_mod}::{js_name}`. The
package name/version are read with `std::env::var` (NOT `env!`) so that, at
proc-macro expansion time, they resolve to the *consumer* crate's values rather
than this backend crate's. The tag only needs per-process uniqueness (stamp and
check share the same generated const in the same binary), so this identity is
fully sufficient and closes both the cross-namespace and cross-addon collisions.

Test: two `#[napi]` classes with the same js_name ("CollisionClient") in
different namespaces now get distinct tags; passing one where the other's
`&`-ref is expected throws `not an instance of class`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo

* fix(napi): keep napi4 class API stable via MaybeTypeTag marker bound

The `T: TypeTag` bounds added to the runtime generics (`ClassInstance<T>`
JsValue/JsObjectValue/FromNapiValue impls + assign_to_this_with_attributes;
`Reference<T>: FromNapiValue`; `new_instance`; the `CallbackInfo` construct/
factory/unwrap helpers; `ClassAccessorCallbackInfo::unwrap_raw` +
class_accessor_unwrap_this) were unconditional, so they narrowed the public API
even under the default napi4 build (where tagging is a no-op) -- a breaking
change for generic-over-class-`T` downstream code.

Introduce a marker bound `MaybeTypeTag` whose meaning is cfg-split once: under
napi8 it is a supertrait alias for `TypeTag` (so the napi8-only tag calls in the
generic bodies can still name `T::TYPE_TAG`); without napi8 it is a vacuous
blanket impl for every `T`, so the bounds disappear and the public signatures
are byte-identical to pre-change. Every runtime `T: TypeTag` bound becomes
`T: MaybeTypeTag`, and each in-body `tag_object`/`validate_type_tag` call is
gated `#[cfg(feature = "napi8")]` (the private `_construct`/`_factory` helpers
switch too, so a napi4 `MaybeTypeTag`-bound caller can reach them). The
derive-generated `from_napi_ref`/`from_napi_mut_ref` are untouched: they name
`<#name as TypeTag>::TYPE_TAG` on a concrete class (always satisfied) and must
stay unconditional. The `TypeTag` trait + generated impl remain unconditional.

Proof: a generic `fn f<T: 'static>(..) -> Reference<T>` (and the ClassInstance
equivalent) compiles under default napi4 with no TypeTag/MaybeTypeTag bound --
impossible under the old bound.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo

* fix(napi): tag object after reference registration to avoid leak on failure

In `_construct`/`_factory` (callback_info.rs) and `new_instance`
(js_values/class.rs) the `tag_object(..)?` call ran BEFORE
`Reference::add_ref(..)` transferred the finalize-`Arc` and the `napi_ref` into
`REFERENCE_MAP`. A tag failure early-returned before `add_ref`, leaking both the
`Arc` (an `Arc::into_raw` never adopted) and the `napi_ref` (never stored, never
deleted).

Move each `tag_object(..)?` to AFTER its `Reference::add_ref(..)` (add_ref does
not depend on the tag). On a tag failure the object is now fully registered, so
GC reclaims value_ref + object_ref + Arc -- no leak.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo

* fix(backend): make class type-tag identity injective and fork-unique

The per-class type tag was derived from
`format!("{pkg}@{ver}::{module}::{js_name}")` hashed with a plain FNV-1a-128
over the joined bytes. That serialization was non-injective: `(module="a::b",
js_name="c")` and `(module="a", js_name="b::c")` produce identical bytes, and
`None` vs `Some("")` for the module both collapse to `""`. Two distinct classes
could therefore share a tag — exactly the blind cast the tag exists to prevent.
It also could not distinguish two addons built from forks with identical
name+version manifest metadata.

Fixes:
- Replace `fnv1a_128(&str)` with `fnv1a_128_fields(&[&str])`, which hashes each
  component as a little-endian u64 length prefix followed by its bytes, so
  component boundaries are unambiguous and `["a::b","c"] != ["a","b::c"]`.
- Add `CARGO_MANIFEST_DIR` (read via `std::env::var`, like the other vars) as
  the leading identity component so different source trees / forks get distinct
  tags; the same source built twice resolves to the same dir.
- Encode `js_mod` via `encode_js_mod` (`None` -> "n", `Some(m)` -> "s{m}") so
  the no-module case never collides with an empty-string module.
- Do NOT fail closed on empty env: the injective encoding + manifest_dir already
  keep distinct within-process types distinct; an empty pkg only reduces
  cross-addon entropy. Rationale documented inline.

Add a `#[cfg(test)]` unit test proving injectivity of component boundaries,
None-vs-Some("") (and None-vs-Some("n")) module distinctness, and determinism.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo

* refactor(backend): derive class type tag from TypeId for guaranteed per-type uniqueness

The per-class type tag was derived from string fields (manifest_dir/pkg/
version/js_mod/js_name), which omit the actual Rust type identity: two
distinct Rust classes sharing all five strings (duplicate js_name+namespace
in one addon, or same-path forks) received the same tag -> blind cast -> UB.

Derive the tag from std::any::TypeId instead -- rustc's canonical,
guaranteed-unique-per-type identity (unique across modules, addons, forks,
and feature variants via the crate SVH). napi already bounds every class
type to 'static, so TypeId::of::<T>() is always valid.

- TypeTag: const TYPE_TAG -> fn type_tag() -> napi_type_tag.
- Add unconditional type_tag_from_type_id(TypeId) helper: two fixed-seed
  DefaultHasher passes with distinct salt bytes -> deterministic 128-bit tag.
- Derive emits impl TypeTag { fn type_tag() { OnceLock cache ->
  type_tag_from_type_id(TypeId::of::<Name[<'static>]>()) } }; delete the
  fnv1a_128 / encode_js_mod string machinery and its unit tests.
- Replace every T::TYPE_TAG / <Name as TypeTag>::TYPE_TAG with the method
  call at the runtime stamp/check sites and in the generated ref accessors.
- Tests: two #[napi] classes sharing the SAME js_name AND namespace now get
  distinct tags; plus TypeId distinctness + determinism.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo

* fix(backend): derive class type tag from a process-unique static address

The TypeId-based tag had two real defects: `impl Hash for TypeId` hashes
only the lower 64 bits, capping entropy at 64 bits and letting distinct
classes with a colliding TypeId-half share a tag deterministically; and
TypeId is nominal, so two separately-compiled same-metadata addon builds
can share a TypeId, colliding across addons.

Derive the tag instead from the address of a per-class `AtomicU8` static.
The address is process-unique by construction (distinct classes have
distinct anchor statics; separately-loaded addons map statics at distinct
addresses) and is fed in injectively as the tag's lower half, so distinct
classes can never collide (no hashing, no birthday bound). AtomicU8 gives
the static interior mutability so it lands in writable data and the linker
never merges two classes' anchors. The body no longer names the class type,
so lifetime classes need no `'static` form for the tag.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo

* fix(napi): restrict class type-tagging to native targets (no-op on wasm)

The per-class tag is derived from a static's address. That is a
process-global identity only on native targets; on wasm it is an
instance-local linear-memory offset, so two instances of the same wasm
addon map their anchor statics at identical offsets and receive identical
tags, defeating cross-instance uniqueness. Node-API type-tag support on
wasm/emnapi is also host-dependent (the extern may be unresolved).

Gate the real bodies of `tag_object` / `validate_type_tag` to
`all(feature = "napi8", not(target_family = "wasm"))` and widen the no-op
fallbacks to `not(all(feature = "napi8", not(target_family = "wasm")))`.
On wasm the binding reverts to its pre-tag behavior (blind cast, or
`instanceof` under `strict`) — no worse than before, and no
unresolved-symbol risk. Native tagging is unchanged and still active.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo

* fix(napi): gate class type-tag marker + generic stamp/check to native targets (Codex P2)

The `MaybeTypeTag` marker and the seven generic `T::type_tag()` stamp/check
call sites were gated on bare `feature = "napi8"`, so on wasm+napi8 the
marker forced `T: TypeTag` and the call sites compiled `T::type_tag()` while
invoking the (already no-op-on-wasm) helpers. That gratuitously narrowed the
public generic API (`Reference<T>`, `ClassInstance<T>`, `new_instance<T>`, the
`CallbackInfo`/class-accessor helpers) for wasm manual-class-wrapper users,
even though tagging does nothing on wasm.

Move the marker AND all seven call sites to the same native-only predicate
that already gates the real helper bodies:
`all(feature = "napi8", not(target_family = "wasm"))` (and the negation for
the vacuous marker variant). The marker and the six/seventh call sites must
move together: a vacuous marker with call sites still under bare `napi8`
would leave `T::type_tag()` unresolved on wasm+napi8. Net effect: on
wasm+napi8 the stamp/check sites compile out (helpers were no-ops there
anyway) and `MaybeTypeTag` is vacuous, so the generic public API is
byte-identical to the pre-tag / napi4 surface. Native napi8 is unchanged.

The derive-injected `<#name as TypeTag>::type_tag()` check in
crates/napi-derive-backend stays unconditional: it names the concrete type
(whose `impl TypeTag` is unconditional) and calls the no-op helper on wasm.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo

* test(napi): skip native-only type-tag rejection tests on wasm

Object type tags are a native-only guarantee: on wasm `tag_object` /
`validate_type_tag` are no-ops (the per-class anchor address is an
instance-local linear-memory offset, not a process-global identity, and
Node-API type-tag support on wasm/emnapi is host-dependent). So wrong-class,
receiver-spoof, prototype-spoof and same-js_name-collision arguments are not
rejected on wasm, and the four rejection assertions fail there.

Gate only those four negative tests to native via the repo's
`process.env.WASI_TEST` idiom (`const napi8NativeOnlyTest = process.env
.WASI_TEST ? test.skip : test`); the two positive round-trip tests keep
running everywhere. Native assertions are unchanged, and no wasm branch
asserts a blind-cast return value.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo

* test(napi): drop redundant cross-namespace type-tag fixtures (covered by same-namespace assert_ne)

The two cross-namespace fixtures `AlphaCollision` / `BetaCollision` (both
`js_name = "CollisionClient"`, in namespaces `tag_collision_alpha` /
`tag_collision_beta`) exposed a PRE-EXISTING napi typegen bug: constructor
metadata is keyed by the bare `js_name` rather than `js_mod` + `js_name`, so the
generated `index.d.cts` was wrong (alpha non-constructible, beta with a
duplicated constructor). That typegen bug is unrelated to this type-tag PR and
is tracked separately.

The cross-namespace runtime check they backed is redundant: napi-cargo-test's
`SameNameOne` / `SameNameTwo` share the SAME `js_name` AND the SAME namespace
(`dup_tag`) and already `assert_ne!` on their `type_tag()`s -- strictly stronger,
since the address-based tag design makes js_name / namespace irrelevant by
construction. No real coverage is lost.

Removes the fixtures, the F1 spec test, and regenerates the example addon
bindings and the type-def snapshot for the trimmed surface.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo

* feat(napi): derive class type tag from content identity string (B1)

Replace the per-class-static-address anchor with a content-derived
128-bit FNV-1a of `crate@version::module_path::ClassName`. This keeps
the tag stable across process reload and dual-load (Node's documented
type-tag contract) while staying per-class unique because Rust forbids
duplicate `module_path::ident`.

`type_tag_from_ident` is a `const fn` so the derive-generated
`type_tag()` folds at compile time in every build, including default
napi4. Adds a golden known-vector unit test locking the wire value.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz

* refactor(napi): unify MaybeTypeTag marker cfg across native and wasm (B2)

Change the `MaybeTypeTag` marker cfg from
`all(feature="napi8", not(target_family="wasm"))` to `feature="napi8"`,
so napi8 native and napi8 wasm present the identical `: TypeTag` bound.
The tag *bodies* (`tag_object`/`validate_type_tag`) stay
napi8-native-only and remain no-ops on wasm, so naming `T::type_tag()`
on wasm is harmless. Under napi4/no-napi8 the marker stays vacuous, so
the default public API is byte-identical to the pre-tag baseline.

Deviation from plan Task 2b: the three `MaybeTypeTag` bounds on
`ClassInstance` (JsValue/JsObjectValue impls and
`assign_to_this_with_attributes`) are NOT collateral — they are
transitively required under napi8 because `JsValue: FromNapiValue` and
`FromNapiValue for ClassInstance<T>` (the load-bearing site the plan
keeps) needs `T: MaybeTypeTag`. Removing any of them breaks the napi8
build, so they are retained with clarifying comments. Under napi4 they
are vacuous, so no un-narrowing was lost.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz

* perf(napi): drop redundant method-receiver tag check in unwrap_raw

napi-rs registers class methods via `napi_define_class`, whose instance
methods carry a V8 FunctionTemplate signature bound to the constructing
template. A spoofed receiver (`ClassA.prototype.method.call(new ClassB())`)
is therefore rejected by V8 with "Illegal invocation" before the native
callback runs, making the `validate_type_tag` check on `self.this`
redundant on the hottest per-method path — net one fewer FFI per method
call. The V8-unguarded surfaces (field accessors, `&T`/`&mut T` params,
`ClassInstance`/`Reference` conversions) keep their own tag checks.

The `T: TypeName + MaybeTypeTag` bound on `unwrap_raw` is left intact so
signatures stay byte-stable across builds. Updates type-tag.spec test #3
comment: V8's signature is now the sole receiver guard; the test asserts
only that a catchable Error is thrown (not its message).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz

* feat(napi): add wrap_and_tag helper + stamp the manual-wrap escape hatch (#4)

Add a documented, cfg-uniform public `wrap_and_tag<T: TypeTag>` helper:
it does `napi_wrap` + `tag_object` in one step so hand-rolled wrappers'
own V8-unguarded field accessors and `&T` params pass the tag check
instead of throwing "Value is not an instance of class". The tag stamp
is the same no-op as `tag_object` on non-napi8 builds and on all wasm
targets, so the helper is a bare `napi_wrap` there; its `T: TypeTag`
bound compiles on every target (the derive's impl is unconditional).

Route the `create_reentrant_borrow_order_test_target` fixture through
the helper (preserving its None-finalizer + drop-on-failure contract),
and add a native-only regression test asserting a manually-wrapped
instance round-trips its own `values` accessor. Verified TDD: the test
fails pre-stamp ("Value is not an instance of class
`ReentrantBorrowOrderTest`") and passes post-stamp.

Also refresh the now-stale wasm rationale in the `tag_object` /
`validate_type_tag` docs (they referenced the removed anchor-address
mechanism) to the content-derivation + host-dependent-extern reasoning,
and point manual wrappers at `wrap_and_tag`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz

* fix(napi): release map entry + napi_ref even when finalize returns Err (#1)

Reorder `raw_finalize_unchecked`: take the payload box, remove the
`REFERENCE_MAP` entry, run the user `finalize()`, run the reference
bookkeeping (Arc release + `napi_delete_reference`), then throw the
finalize error LAST. Previously an errored `finalize()` early-returned
before removing the map entry, which could leave a stale entry keyed on
the just-freed pointer. The success path behaviour is unchanged; only
the `Err` path now also releases the map entry + napi_ref instead of
early-returning. Pure hardening (path is unreachable via the normal
public API today).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz

* fix(napi): make wrap_and_tag atomic (roll back wrap on tag failure)

The manual-wrap helper wrapped `native` into `js_obj` and then stamped the
type tag as two independent steps. If `napi_wrap` succeeded but
`napi_type_tag_object` failed (napi8-native, e.g. an already-tagged object),
`wrap_and_tag` returned `Err` with `js_obj` still wrapping `native`. Callers
free `native` on that error (the `None` finalizer means the JS engine never
owns it), so `js_obj` was left holding dangling memory and the next
`napi_unwrap` would be a use-after-free.

Roll back the wrap with `napi_remove_wrap` when tagging fails, so the wrap+tag
is atomic and the caller's error-path free is always sound. On non-napi8 / wasm
`tag_object` is an infallible no-op, so the rollback branch is dead there and
the call remains a bare `napi_wrap`.

Found by the adversarial review of the type-tag fix delta.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz

* fix(napi): keep MaybeTypeTag vacuous on wasm (restore native-only gate)

Addresses the Codex P2 review comment. Commit e6aadc1 originally gated the
MaybeTypeTag marker to napi8-native (`all(feature="napi8", not(wasm))`) so wasm
addons — where no tag is ever stamped or checked (the tag_object /
validate_type_tag bodies are no-ops on wasm) — do not narrow ClassInstance<T> /
Reference<T> / new_instance<T> for zero benefit. A later refactor unified the
gate to `feature="napi8"` alone, which re-introduced that gratuitous wasm
narrowing. Restore the native-only gate.

Verified: on wasm+napi8 a generic `fn f<T>(&ClassInstance<T>)` compiles with no
`T: MaybeTypeTag` bound; on napi8-native it still (correctly) requires the bound
because the tag check names `T::type_tag()`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz

* feat(napi): add optional #[napi(type_tag = "...")] class tag salt override

Let a `#[napi]` class opt into a crate-unique salt for its content-derived
type tag via `#[napi(type_tag = "SALT")]`. The salt REPLACES the default
`crate@version` identity component (module_path + ClassName still apply), so a
class's tag cannot collide with an unrelated addon that happens to share the
same crate name@version + module path + class name. Absent → unchanged default
`crate@version::module_path::ClassName`. Both forms are compile-time constants,
so the tag stays stable across process reload / dual-load, and module_path +
ClassName still prevent any intra-crate self-collision. Runtime-only; never
emitted into TypeScript.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz

* fix(napi): restore method-receiver type-tag check in unwrap_raw (Codex P1)

The V8 FunctionTemplate signature that `napi_define_class` installs on
instance methods rejects a wrong receiver with "Illegal invocation" only
on runtimes that honor it. Bun does not: on Bun 1.3.14
`TypeTagA.prototype.getValue.call(new TypeTagB(2))` runs the native
callback with a foreign receiver, so `napi_unwrap` hands back TypeTagB's
pointer and the blind `*mut c_void -> *mut T` cast is type-confused (UB) —
it returned `2` instead of throwing.

Restore the `validate_type_tag` check in `unwrap_raw` (napi8 native only)
so the receiver tag is the portable guard, not V8's signature. Verified:
wrong-receiver now throws on Node ("Illegal invocation", V8) AND Bun
("Value is not an instance of class `TypeTagA`", tag check). The
type-tag spec's receiver-spoof case asserts only that a catchable Error
is thrown, since the message differs by runtime.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants