Description
Describe the Bug
When exporting a struct from Rust to JavaScript, calling console.log
or JSON.stringify
on an object of the class shows only a ptr
property and none of the exported struct's properties
Steps to Reproduce
I've created an example project at codehearts/whoops to reproduce the issue
Consider the following exported Rust struct:
#[wasm_bindgen]
pub struct Series {
name: String
}
#[wasm_bindgen]
impl Series {
#[wasm_bindgen(js_name=okKo)]
pub fn ok_ko() -> Self {
Self {
name: "OK K.O.! Let's Be Heroes".to_string(),
}
}
#[wasm_bindgen(getter)]
pub fn name(&self) -> String {
self.name.clone()
}
}
In the output from wasm-pack build
, the Series
object has the following properties:
const series = Series.okKo();
console.log(series.name); // OK K.O.! Let's Be Heroes
However, when logging the object we see neither of these properties:
console.log(series); // Series { ptr: 1114136 }
console.log(JSON.parse(JSON.stringify(series))); // { ptr: 1114136 }
Expected Behavior
I would expect to see the name
property exported from Rust, like how a native JavaScript class would look
Actual Behavior
The object shows only a ptr
property, which is not useful for debugging or logging state
Additional Context
I found a solution that works for Node.js at least. The output of console.log
can be customized by defining a [util.inspect.custom]
method within the class, and the JSON.stringify
result is based on an existing toJSON
method if one is defined
wasm-bindgen would have to define the [util.inspect.custom]
method because util
is not imported by default and the brackets create an invalid symbol during compilation, but toJSON
can be exported from the Rust
I'm wondering if wasm-bindgen should provide a default [util.inspect.custom]
, toJSON
, and toString
which provides the exported properties. Would these be appropriate methods for wasm-bindgen to include when targeting Node.js (and possible just JS for the JSON and string representations?)