1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! Function registry for collecting and managing JS functions and exports.
//!
//! This module provides the registry system that collects JS function specifications,
//! inline JS modules, and exported Rust types via the `inventory` crate.
use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt::Write;
use core::ops::Deref;
use once_cell::sync::{Lazy, OnceCell};
use crate::function::JSFunction;
use crate::ipc::{DecodedData, EncodedData};
/// Function specification for the registry
#[derive(Clone, Copy)]
pub struct JsFunctionSpec {
/// Function that generates the JS code
js_code: fn() -> String,
}
impl JsFunctionSpec {
pub const fn new(js_code: fn() -> String) -> Self {
Self { js_code }
}
/// Get the JS code generator function
pub const fn js_code(&self) -> fn() -> String {
self.js_code
}
pub const fn resolve_as<F>(&self) -> LazyJsFunction<F> {
LazyJsFunction {
spec: *self,
inner: OnceCell::new(),
}
}
}
inventory::collect!(JsFunctionSpec);
/// A type that dynamically resolves to a JSFunction from the registry on first use.
pub struct LazyJsFunction<F> {
spec: JsFunctionSpec,
inner: OnceCell<JSFunction<F>>,
}
impl<F> Deref for LazyJsFunction<F> {
type Target = JSFunction<F>;
fn deref(&self) -> &Self::Target {
self.inner.get_or_init(|| {
FUNCTION_REGISTRY
.get_function(self.spec)
.unwrap_or_else(|| {
panic!("Function not found for code: {}", (self.spec.js_code())())
})
})
}
}
/// Inline JS module info
#[derive(Clone, Copy)]
pub struct InlineJsModule {
/// The JS module content
content: &'static str,
}
impl InlineJsModule {
pub const fn new(content: &'static str) -> Self {
Self { content }
}
/// Get the JS module content
pub const fn content(&self) -> &'static str {
self.content
}
/// Calculate the hash of the module content for use as a filename
/// This uses a simple FNV-1a hash that can also be computed at compile time
pub fn hash(&self) -> String {
format!("{:x}", self.const_hash())
}
/// Const-compatible hash function (FNV-1a)
pub const fn const_hash(&self) -> u64 {
const FNV_OFFSET_BASIS: u64 = 0xcbf29ce484222325;
const FNV_PRIME: u64 = 0x100000001b3;
let mut hash = FNV_OFFSET_BASIS;
let mut i = 0;
let bytes = self.content.as_bytes();
while i < bytes.len() {
hash ^= bytes[i] as u64;
hash = hash.wrapping_mul(FNV_PRIME);
i += 1;
}
hash
}
}
inventory::collect!(InlineJsModule);
/// Type of class member for exported Rust structs
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum JsClassMemberKind {
/// Constructor function (e.g., `Counter.new`)
Constructor,
/// Instance method on prototype (e.g., `Counter.prototype.increment`)
Method,
/// Static method on class (e.g., `Counter.staticMethod`)
StaticMethod,
/// Property getter (e.g., `get count()`)
Getter,
/// Property setter (e.g., `set count(v)`)
Setter,
}
/// Specification for a member of an exported Rust class
///
/// All class members (methods, constructors, getters, setters) are collected
/// and used to generate complete class code in FunctionRegistry.
#[derive(Clone, Copy)]
pub struct JsClassMemberSpec {
/// The class name this member belongs to (e.g., "Counter")
class_name: &'static str,
/// The JavaScript member name (e.g., "increment", "count")
member_name: &'static str,
/// The export name for IPC calls (e.g., "Counter::increment")
export_name: &'static str,
/// Number of arguments (excluding self/handle)
arg_count: usize,
/// Function that returns type definitions for explicit arguments.
arg_types: fn() -> Vec<Vec<u8>>,
/// Function that returns the optional return type definition.
return_type: fn() -> Option<Vec<u8>>,
/// Type of member
kind: JsClassMemberKind,
}
impl JsClassMemberSpec {
pub const fn new(
class_name: &'static str,
member_name: &'static str,
export_name: &'static str,
arg_count: usize,
arg_types: fn() -> Vec<Vec<u8>>,
return_type: fn() -> Option<Vec<u8>>,
kind: JsClassMemberKind,
) -> Self {
Self {
class_name,
member_name,
export_name,
arg_count,
arg_types,
return_type,
kind,
}
}
/// Get the class name this member belongs to
pub const fn class_name(&self) -> &'static str {
self.class_name
}
/// Get the JavaScript member name
pub const fn member_name(&self) -> &'static str {
self.member_name
}
/// Get the export name for IPC calls
pub const fn export_name(&self) -> &'static str {
self.export_name
}
/// Get the number of arguments (excluding self/handle)
pub const fn arg_count(&self) -> usize {
self.arg_count
}
/// Get type definitions for explicit arguments.
pub fn arg_types(&self) -> Vec<Vec<u8>> {
(self.arg_types)()
}
/// Get the optional return type definition.
pub fn return_type(&self) -> Option<Vec<u8>> {
(self.return_type)()
}
/// Get the type of member
pub const fn kind(&self) -> JsClassMemberKind {
self.kind
}
}
inventory::collect!(JsClassMemberSpec);
/// Specification for an exported Rust function/method callable from JavaScript.
///
/// This is used by the `#[wasm_bindgen]` macro when exporting structs and impl blocks.
/// Each export is registered via inventory and collected at runtime.
#[derive(Clone, Copy)]
pub struct JsExportSpec {
/// The export name (e.g., "MyStruct::new", "MyStruct::method")
pub name: &'static str,
/// Handler function that decodes arguments, calls the Rust function, and encodes the result
pub handler: fn(&mut DecodedData) -> Result<EncodedData, alloc::string::String>,
}
impl JsExportSpec {
pub const fn new(
name: &'static str,
handler: fn(&mut DecodedData) -> Result<EncodedData, alloc::string::String>,
) -> Self {
Self { name, handler }
}
}
inventory::collect!(JsExportSpec);
/// Registry of JS functions collected via inventory
pub(crate) struct FunctionRegistry {
functions: String,
function_specs: Vec<JsFunctionSpec>,
/// Map of module path -> module content for inline_js modules
modules: BTreeMap<String, &'static str>,
}
/// The registry of javascript functions registered via inventory. This
/// is shared between all webviews.
pub(crate) static FUNCTION_REGISTRY: Lazy<FunctionRegistry> =
Lazy::new(FunctionRegistry::collect_from_inventory);
/// Generate argument names for JS function (a0, a1, a2, ...)
fn generate_args(count: usize) -> String {
(0..count)
.map(|i| format!("a{i}"))
.collect::<Vec<_>>()
.join(", ")
}
fn object_handle_type_def() -> Vec<u8> {
vec![crate::encode::TypeTag::U32 as u8]
}
fn js_u8_array_literal(bytes: &[u8]) -> String {
let mut out = String::from("[");
for (i, byte) in bytes.iter().enumerate() {
if i > 0 {
out.push_str(", ");
}
write!(&mut out, "{byte}").unwrap();
}
out.push(']');
out
}
fn js_type_defs_literal(types: &[Vec<u8>]) -> String {
let mut out = String::from("[");
for (i, ty) in types.iter().enumerate() {
if i > 0 {
out.push_str(", ");
}
out.push_str(&js_u8_array_literal(ty));
}
out.push(']');
out
}
fn js_optional_type_def_literal(ty: Option<Vec<u8>>) -> String {
ty.map(|ty| js_u8_array_literal(&ty))
.unwrap_or_else(|| "null".to_string())
}
fn call_export_expression(
export_name: &str,
arg_types: &[Vec<u8>],
return_type: Option<Vec<u8>>,
args_call: &str,
) -> String {
format!(
r#"window.__wryCallExport("{}", {}, {}, [{}])"#,
export_name,
js_type_defs_literal(arg_types),
js_optional_type_def_literal(return_type),
args_call,
)
}
impl FunctionRegistry {
fn collect_from_inventory() -> Self {
let mut modules = BTreeMap::new();
// Collect all inline JS modules and deduplicate by content hash
for inline_js in inventory::iter::<InlineJsModule>() {
let hash = inline_js.hash();
let module_path = format!("{hash}.js");
// Only insert if we haven't seen this content before
modules.entry(module_path).or_insert(inline_js.content());
}
// Collect all function specs
let specs: Vec<_> = inventory::iter::<JsFunctionSpec>().copied().collect();
// Build the script - load modules from wry:// handler before setting up function registry
let mut script = String::new();
// Wrap everything in an async IIFE to use await
script.push_str("(async () => {\n");
// Track which modules we've already imported (by hash)
let mut imported_modules = alloc::collections::BTreeSet::new();
// Load all inline_js modules from the wry handler (deduplicated by content hash)
for inline_js in inventory::iter::<InlineJsModule>() {
let hash = inline_js.hash();
// Only import each unique module once
if imported_modules.insert(hash.clone()) {
// Dynamically import the module from /__wbg__/snippets/{hash}.js
writeln!(
&mut script,
" const module_{hash} = await import('/__wbg__/snippets/{hash}.js');"
)
.unwrap();
}
}
// Now set up the function registry after all modules are loaded
// Store raw JS functions - type info will be passed at call time
script.push_str(" window.setFunctionRegistry([");
for (i, spec) in specs.iter().enumerate() {
if i > 0 {
script.push_str(",\n");
}
let js_code = (spec.js_code())();
write!(&mut script, "{js_code}").unwrap();
}
script.push_str("]);\n");
// Collect all class members and group by class name
let mut class_members: BTreeMap<&str, Vec<&JsClassMemberSpec>> = BTreeMap::new();
for member in inventory::iter::<JsClassMemberSpec>() {
class_members
.entry(member.class_name())
.or_default()
.push(member);
}
// Generate complete class definitions for each exported struct
for (class_name, members) in &class_members {
let drop_export_name = format!("{class_name}::__drop");
let drop_arg_types = [object_handle_type_def()];
let drop_call =
call_export_expression(&drop_export_name, &drop_arg_types, None, "handle");
// Generate class shell
writeln!(
&mut script,
r#" class {class_name} {{
constructor(handle) {{
this.__handle = handle;
this.__className = "{class_name}";
window.__wryExportRegistry.register(this, {{ handle, className: "{class_name}" }});
}}
static __wrap(handle) {{
const obj = Object.create({class_name}.prototype);
obj.__handle = handle;
obj.__className = "{class_name}";
window.__wryExportRegistry.register(obj, {{ handle, className: "{class_name}" }});
return obj;
}}
free() {{
const handle = this.__handle;
this.__handle = 0;
if (handle !== 0) {drop_call};
}}"#
)
.unwrap();
// Track getters/setters to combine them into single property descriptors
let mut getters: BTreeMap<&str, &JsClassMemberSpec> = BTreeMap::new();
let mut setters: BTreeMap<&str, &JsClassMemberSpec> = BTreeMap::new();
// Generate methods inside the class body
for member in members {
match member.kind() {
JsClassMemberKind::Method => {
// Instance method
let args = generate_args(member.arg_count());
let args_with_handle = if member.arg_count() > 0 {
format!("this.__handle, {args}")
} else {
"this.__handle".to_string()
};
let mut arg_types = vec![object_handle_type_def()];
arg_types.extend(member.arg_types());
let call = call_export_expression(
member.export_name(),
&arg_types,
member.return_type(),
&args_with_handle,
);
writeln!(
&mut script,
r#" {}({}) {{ return {}; }}"#,
member.member_name(),
args,
call
)
.unwrap();
}
JsClassMemberKind::Getter => {
getters.insert(member.member_name(), member);
}
JsClassMemberKind::Setter => {
setters.insert(member.member_name(), member);
}
_ => {} // Constructor and static handled separately
}
}
// Generate getters/setters as property accessors inside the class
let mut property_names: alloc::collections::BTreeSet<&str> =
alloc::collections::BTreeSet::new();
property_names.extend(getters.keys());
property_names.extend(setters.keys());
// Build a property-accessor call for a getter (`this.__handle`) or
// setter (`this.__handle, v`) member.
let accessor_call = |member: &JsClassMemberSpec, args_call: &str| {
let mut arg_types = vec![object_handle_type_def()];
arg_types.extend(member.arg_types());
call_export_expression(
member.export_name(),
&arg_types,
member.return_type(),
args_call,
)
};
for prop_name in property_names {
let getter = getters.get(prop_name);
let setter = setters.get(prop_name);
if let Some(g) = getter {
let call = accessor_call(g, "this.__handle");
writeln!(&mut script, r#" get {prop_name}() {{ return {call}; }}"#).unwrap();
}
if let Some(s) = setter {
let call = accessor_call(s, "this.__handle, v");
writeln!(&mut script, r#" set {prop_name}(v) {{ {call}; }}"#).unwrap();
}
}
// Close the class body
script.push_str(" }\n");
// Add static methods and constructors outside the class
for member in members {
let is_constructor = match member.kind() {
JsClassMemberKind::Constructor => true,
JsClassMemberKind::StaticMethod => false,
_ => continue, // Methods, getters, setters already handled
};
let args = generate_args(member.arg_count());
let args_call = if member.arg_count() > 0 { &args } else { "" };
let call = call_export_expression(
member.export_name(),
&member.arg_types(),
member.return_type(),
args_call,
);
let method_name = member.member_name();
// Constructors wrap the returned handle in a class instance;
// static methods return the call result directly.
let body = if is_constructor {
format!("const handle = {call}; return {class_name}.__wrap(handle);")
} else {
format!("return {call};")
};
writeln!(
&mut script,
r#" {class_name}.{method_name} = function({args}) {{ {body} }};"#
)
.unwrap();
}
// Register class on window
writeln!(&mut script, " window.{class_name} = {class_name};").unwrap();
}
// Send a request to wry to notify that the function registry is initialized
script.push_str(" fetch(`/__wbg__/initialized`, { method: 'POST', body: [] });\n");
// Close the async IIFE
script.push_str("})();\n");
Self {
functions: script,
function_specs: specs,
modules,
}
}
/// Get a function by name from the registry
pub fn get_function<F>(&self, spec: JsFunctionSpec) -> Option<JSFunction<F>> {
let index = self
.function_specs
.iter()
.position(|s| s.js_code() as usize == spec.js_code() as usize)?;
Some(JSFunction::new(index as _))
}
/// Get the initialization script
pub fn script(&self) -> &str {
&self.functions
}
/// Get the content of an inline_js module by path
pub fn get_module(&self, path: &str) -> Option<&'static str> {
self.modules.get(path).copied()
}
}