1use std::fmt::Write as _;
9
10use crate::bridge::Manifest;
11use crate::codegen::{PortApi, PortFn, Wire, wire};
12use crate::ts::exports::{ExportedFn, LocalType};
13use crate::ts::shape::{self, Shape};
14use crate::wire::{Ty, rust_read_args, rust_write, schema_expr};
15
16fn shape_ty(s: &Shape, types: &[LocalType], depth: usize) -> Ty {
18 if depth > 6 {
19 return Ty::Dyn;
20 }
21 let str_like = |s: &Shape| matches!(s, Shape::Str | Shape::LitStr(_));
22 let num_like = |s: &Shape| matches!(s, Shape::Num | Shape::Int | Shape::LitNum(_));
23 let bool_like = |s: &Shape| matches!(s, Shape::Bool | Shape::LitBool(_));
24 match s {
25 Shape::Str | Shape::LitStr(_) => Ty::Str16,
26 Shape::Num | Shape::Int | Shape::LitNum(_) => Ty::Num,
27 Shape::Bool | Shape::LitBool(_) => Ty::Bool,
28 Shape::Null | Shape::Undefined | Shape::Any | Shape::Bytes | Shape::Tuple(_) => Ty::Dyn,
29 Shape::Array(item) => Ty::List {
30 item: Box::new(shape_ty(item, types, depth + 1)),
31 native: "ts".into(),
32 array: false,
33 },
34 Shape::Object(props, None) if props.len() <= usize::from(u8::MAX) => Ty::Obj(
35 props
36 .iter()
37 .map(|(name, optional, s)| {
38 let t = shape_ty(s, types, depth + 1);
39 let t = match t {
40 Ty::OptJs {
41 inner, nullable, ..
42 } if *optional => Ty::OptJs {
43 inner,
44 nullable,
45 undefinable: true,
46 },
47 t if *optional && t != Ty::Dyn => Ty::OptJs {
48 inner: Box::new(t),
49 nullable: false,
50 undefinable: true,
51 },
52 t => t,
53 };
54 (name.clone(), t)
55 })
56 .collect(),
57 ),
58 Shape::Object(props, Some(value)) if props.is_empty() => {
59 Ty::Map16(Box::new(shape_ty(value, types, depth + 1)))
60 }
61 Shape::Object(..) => Ty::Dyn,
62 Shape::Union(members) => {
63 let nullable = members.iter().any(|m| matches!(m, Shape::Null));
64 let undefinable = members.iter().any(|m| matches!(m, Shape::Undefined));
65 let rest: Vec<&Shape> = members
66 .iter()
67 .filter(|m| !matches!(m, Shape::Null | Shape::Undefined))
68 .collect();
69 let base = if rest.is_empty() {
70 Ty::Dyn
71 } else if rest.iter().all(|m| str_like(m)) {
72 Ty::Str16
73 } else if rest.iter().all(|m| num_like(m)) {
74 Ty::Num
75 } else if rest.iter().all(|m| bool_like(m)) {
76 Ty::Bool
77 } else if rest.len() == 1 {
78 shape_ty(rest[0], types, depth + 1)
79 } else {
80 Ty::Dyn
81 };
82 if (nullable || undefinable) && base != Ty::Dyn {
83 Ty::OptJs {
84 inner: Box::new(base),
85 nullable,
86 undefinable,
87 }
88 } else {
89 base
90 }
91 }
92 Shape::Ref(name, args) => {
93 let resolved = shape::resolve(name, args, types);
94 if matches!(resolved, Shape::Ref(..)) {
95 Ty::Dyn
96 } else {
97 shape_ty(&resolved, types, depth + 1)
98 }
99 }
100 }
101}
102
103fn js_key(k: &str) -> String {
104 serde_json::to_string(k).unwrap_or_else(|_| "\"\"".into())
105}
106
107fn js_enc(x: &str, t: &Ty, d: usize) -> String {
109 match t {
110 Ty::Num => format!("if (typeof {x} !== 'number') return false\nwF64({x})\n"),
111 Ty::Bool => format!("if (typeof {x} !== 'boolean') return false\nwU8({x} ? 1 : 0)\n"),
112 Ty::Str16 => format!("if (typeof {x} !== 'string') return false\nwStr({x})\n"),
113 Ty::Dyn => format!("if (!wDyn({x})) return false\n"),
114 Ty::OptJs {
115 inner,
116 nullable,
117 undefinable,
118 } => format!(
119 "if ({x} === undefined) {{\n{}wU8(0)\n}} else if ({x} === null) {{\n{}wU8(2)\n}} else {{\nwU8(1)\n{}}}\n",
120 if *undefinable { "" } else { "return false\n" },
121 if *nullable { "" } else { "return false\n" },
122 js_enc(x, inner, d)
123 ),
124 Ty::List { item, .. } => format!(
125 "if (!Array.isArray({x})) return false\nwU8(1)\nwU32({x}.length)\nfor (let i{d} = 0; i{d} < {x}.length; i{d}++) {{\nconst v{d} = {x}[i{d}]\n{}}}\n",
126 js_enc(&format!("v{d}"), item, d + 1)
127 ),
128 Ty::Map16(value) => format!(
129 "if ({x} === null || typeof {x} !== 'object' || Array.isArray({x})) return false\n{{\nconst k{d} = Object.keys({x})\nwU8(1)\nwU32(k{d}.length)\nfor (const key{d} of k{d}) {{\nwStr(key{d})\nconst v{d} = {x}[key{d}]\n{}}}\n}}\n",
130 js_enc(&format!("v{d}"), value, d + 1)
131 ),
132 Ty::Obj(fields) => {
133 let required = fields
136 .iter()
137 .filter(|(_, ft)| {
138 !(matches!(
139 ft,
140 Ty::OptJs {
141 undefinable: true,
142 ..
143 }
144 ) || *ft == Ty::Dyn)
145 })
146 .count();
147 let mut cases = String::new();
148 for (i, (key, ft)) in fields.iter().enumerate() {
149 let optional = matches!(
150 ft,
151 Ty::OptJs {
152 undefinable: true,
153 ..
154 }
155 ) || *ft == Ty::Dyn;
156 let _ = write!(
157 cases,
158 "case {}: {{\nwU8({i})\n{}const f{d} = {x}[k{d}]\n{}break\n}}\n",
159 js_key(key),
160 if optional {
161 String::new()
162 } else {
163 format!("r{d}++\n")
164 },
165 js_enc(&format!("f{d}"), ft, d + 1)
166 );
167 }
168 format!(
169 "if ({x} === null || typeof {x} !== 'object' || Array.isArray({x})) return false\n{{\n\
170 const at{d} = at\nwU8(0)\nlet n{d} = 0, r{d} = 0\nfor (const k{d} in {x}) {{\nswitch (k{d}) {{\n{cases}default: return false\n}}\n\
171 if (++n{d} > 255) return false\n}}\nif (r{d} !== {required}) return false\niv.setUint8(at{d}, n{d})\n}}\n"
172 )
173 }
174 _ => "return false\n".into(),
175 }
176}
177
178fn js_dec(target: &str, t: &Ty, d: usize) -> String {
180 match t {
181 Ty::Num => format!("{target} = rF64()\n"),
182 Ty::Bool => format!("{target} = rU8() === 1\n"),
183 Ty::Str16 => format!("{target} = rStr()\n"),
184 Ty::Dyn => format!("{target} = rDyn()\n"),
185 Ty::OptJs { inner, .. } => format!(
186 "{{\nconst g{d} = rU8()\nif (g{d} === 0) {target} = undefined\nelse if (g{d} === 2) {target} = null\nelse {{\n{}}}\n}}\n",
187 js_dec(target, inner, d + 1)
188 ),
189 Ty::List { item, .. } => format!(
190 "if (rU8() === 0) {target} = null\nelse {{\nconst n{d} = rU32()\nconst a{d} = new Array(n{d})\nfor (let i{d} = 0; i{d} < n{d}; i{d}++) {{\nlet v{d}\n{}a{d}[i{d}] = v{d}\n}}\n{target} = a{d}\n}}\n",
191 js_dec(&format!("v{d}"), item, d + 1)
192 ),
193 Ty::Map16(value) => format!(
194 "if (rU8() === 0) {target} = null\nelse {{\nconst n{d} = rU32()\nconst o{d} = {{}}\nfor (let i{d} = 0; i{d} < n{d}; i{d}++) {{\nconst k{d} = rStr()\nlet v{d}\n{}o{d}[k{d}] = v{d}\n}}\n{target} = o{d}\n}}\n",
195 js_dec(&format!("v{d}"), value, d + 1)
196 ),
197 Ty::Obj(fields) => {
198 let mut cases = String::new();
199 for (i, (key, ft)) in fields.iter().enumerate() {
200 let _ = write!(
201 cases,
202 "case {i}: {{\nlet v{d}\n{}o{d}[{}] = v{d}\nbreak\n}}\n",
203 js_dec(&format!("v{d}"), ft, d + 1),
204 js_key(key)
205 );
206 }
207 format!(
208 "{{\nconst o{d} = {{}}\nconst n{d} = rU8()\nfor (let j{d} = 0; j{d} < n{d}; j{d}++) {{\nswitch (rU8()) {{\n{cases}default: {{\nconst k{d} = rStr()\no{d}[k{d}] = rDyn()\n}}\n}}\n}}\n{target} = o{d}\n}}\n"
209 )
210 }
211 _ => format!("{target} = undefined\n"),
212 }
213}
214
215const WIRE_NAPI_CJS: &str = r#"
217// The binary wire (see rust-anything's `wire.rs`): arguments are written into `wIn`, results read
218// from `wOut`; both are registered with the native module once.
219let wIn = new Uint8Array(1 << 16), wOut = new Uint8Array(1 << 16)
220// Its own ArrayBuffer: Bun (JavaScriptCore) may relocate a small typed array whose `.buffer`
221// nobody read, and Rust then reads a length of 0 and reports `wire data ended early`.
222const wLen = new Uint32Array(new ArrayBuffer(4))
223let iv = new DataView(wIn.buffer), ov = new DataView(wOut.buffer), at = 0, p = 0
224native.rustAnythingWireInit(wIn, wOut, wLen)
225const regrow = () => native.rustAnythingWireInit(wIn, wOut, wLen)
226// Runs a wire function; a result larger than `wOut` is fetched once `wOut` has grown.
227const wireCall = fn => {
228 wLen[0] = at
229 const n = fn()
230 if (Number.isNaN(n)) return false
231 if (n === Infinity) {
232 p = 0
233 throw new Error(rStr())
234 }
235 if (n < 0) {
236 wOut = new Uint8Array(Math.max(wOut.length * 2, -n))
237 ov = new DataView(wOut.buffer)
238 native.rustAnythingWireInit(wIn, wOut, wLen)
239 native.rustAnythingWireFlush()
240 }
241 p = 0
242 return true
243}
244"#;
245
246const WIRE_WASM_CJS: &str = r#"
247// The binary wire (see rust-anything's `wire.rs`): arguments are written into `wIn` and copied into
248// wasm memory in one step; results are read where the Rust side left them.
249let wIn = new Uint8Array(1 << 16), iv = new DataView(wIn.buffer), at = 0, p = 0
250const mem = native.rustAnythingWireMemory()
251let wOut = new Uint8Array(mem.buffer), ov = new DataView(mem.buffer)
252const regrow = () => {}
253// Growing wasm memory replaces its buffer: views are made again when that happened.
254const views = () => {
255 if (wOut.buffer !== mem.buffer) {
256 wOut = new Uint8Array(mem.buffer)
257 ov = new DataView(mem.buffer)
258 }
259}
260const wireCall = fn => {
261 const ptr = native.rustAnythingWireIn(at)
262 views()
263 wOut.set(wIn.subarray(0, at), ptr)
264 if (fn(at) === 0xFFFFFFFF) return false
265 views()
266 p = native.rustAnythingWireOut()
267 return true
268}
269"#;
270
271const WIRE_CJS: &str = r#"
272const need = n => {
273 if (at + n <= wIn.length) return
274 const grown = new Uint8Array(Math.max(wIn.length * 2, at + n))
275 grown.set(wIn)
276 wIn = grown
277 iv = new DataView(wIn.buffer)
278 regrow()
279}
280const wU8 = v => { need(1); iv.setUint8(at++, v) }
281const wU32 = v => { need(4); iv.setUint32(at, v, true); at += 4 }
282const wF64 = v => { need(8); iv.setFloat64(at, v, true); at += 8 }
283const wUnits = s => {
284 need(4 + 2 * s.length)
285 iv.setUint32(at, s.length, true)
286 at += 4
287 for (let i = 0; i < s.length; i++) { iv.setUint16(at, s.charCodeAt(i), true); at += 2 }
288}
289const wStr = s => { wU8(4); wUnits(s) }
290const wDyn = v => {
291 switch (typeof v) {
292 case 'undefined': wU8(0); return true
293 case 'boolean': wU8(v ? 3 : 2); return true
294 case 'number': wU8(4); wF64(v); return true
295 case 'string': wU8(5); wUnits(v); return true
296 case 'object':
297 if (v === null) { wU8(1); return true }
298 if (Array.isArray(v)) {
299 wU8(6); wU32(v.length)
300 for (let i = 0; i < v.length; i++) if (!wDyn(v[i])) return false
301 return true
302 }
303 if (Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null) return false
304 {
305 const keys = Object.keys(v)
306 wU8(7); wU32(keys.length)
307 for (const k of keys) { wUnits(k); if (!wDyn(v[k])) return false }
308 return true
309 }
310 }
311 return false
312}
313const rU8 = () => ov.getUint8(p++)
314const rU32 = () => { const v = ov.getUint32(p, true); p += 4; return v }
315const rF64 = () => { const v = ov.getFloat64(p, true); p += 8; return v }
316// ignoreBOM: a leading U+FEFF is part of the string, not a byte-order mark.
317const utf16 = new TextDecoder('utf-16le', { ignoreBOM: true })
318const rUnits = (wellFormed) => {
319 const n = rU32()
320 let s
321 if (n > 24 && wellFormed) s = utf16.decode(wOut.subarray(p, p + 2 * n))
322 else {
323 s = ''
324 for (let i = 0; i < n; i++) s += String.fromCharCode(ov.getUint16(p + 2 * i, true))
325 }
326 p += 2 * n
327 return s
328}
329// Tag 1: a string from Rust (well-formed); 4: raw code units, lone surrogates included.
330const rStr = () => rUnits(rU8() === 1)
331const rDyn = () => {
332 switch (rU8()) {
333 case 0: return undefined
334 case 1: return null
335 case 2: return false
336 case 3: return true
337 case 4: return rF64()
338 case 5: return rUnits(false)
339 case 6: { const n = rU32(); const a = new Array(n); for (let i = 0; i < n; i++) a[i] = rDyn(); return a }
340 case 7: { const n = rU32(); const o = {}; for (let i = 0; i < n; i++) { const k = rUnits(false); o[k] = rDyn() } return o }
341 }
342}
343"#;
344
345const WIRE_NAPI_RS: &str = r#"
347// ---- the binary wire ------------------------------------------------------------------------
348
349type WireBuffers = (
350 napi::bindgen_prelude::Uint8Array,
351 napi::bindgen_prelude::Uint8Array,
352 napi::bindgen_prelude::Uint32Array,
353);
354
355thread_local! {
356 static WIRE: std::cell::RefCell<Option<WireBuffers>> = const { std::cell::RefCell::new(None) };
357 static PENDING: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
358 static SCRATCH: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
359}
360
361/// Registers the argument, result and argument-length buffers `index.cjs` uses.
362#[napi(js_name = "rustAnythingWireInit")]
363pub fn rust_anything_wire_init(
364 input: napi::bindgen_prelude::Uint8Array,
365 output: napi::bindgen_prelude::Uint8Array,
366 len: napi::bindgen_prelude::Uint32Array,
367) {
368 WIRE.with(|w| *w.borrow_mut() = Some((input, output, len)));
369}
370
371/// Copies a result that did not fit into the (now larger) result buffer.
372#[napi(js_name = "rustAnythingWireFlush")]
373pub fn rust_anything_wire_flush() -> f64 {
374 let bytes = PENDING.with(|p| std::mem::take(&mut *p.borrow_mut()));
375 WIRE.with(|w| {
376 let mut w = w.borrow_mut();
377 let Some((_, output, _)) = w.as_mut() else {
378 return -1.0;
379 };
380 // SAFETY: the call is synchronous; JS does not touch `output` until it returns.
381 let out = unsafe { output.as_mut() };
382 let n = bytes.len().min(out.len());
383 out[..n].copy_from_slice(&bytes[..n]);
384 n as f64
385 })
386}
387
388/// Reads the argument bytes (`wLen[0]` of them), runs `f`, and writes its result; a negative
389/// return is the size of a result that did not fit, kept for `rustAnythingWireFlush`.
390fn wire_io(f: impl FnOnce(&mut wire::Reader, &mut wire::Writer) -> Result<(), String>) -> napi::Result<f64> {
391 WIRE.with(|cell| {
392 let mut guard = cell.borrow_mut();
393 let Some((input, output, len)) = guard.as_mut() else {
394 return Err(napi::Error::from_reason("rust-anything: the wire buffers are not registered"));
395 };
396 let len = (len.first().copied().unwrap_or(0) as usize).min(input.len());
397 let mut w = wire::Writer(SCRATCH.with(|s| std::mem::take(&mut *s.borrow_mut())));
398 w.0.clear();
399 let result = run(|| f(&mut wire::Reader::new(&input[..len]), &mut w));
400 let keep = |w: wire::Writer| SCRATCH.with(|s| *s.borrow_mut() = w.0);
401 match result {
402 // A result of another shape than the TS type: JS runs the call through JSON.
403 Err(e) if e.reason.starts_with(wire::MISMATCH) => {
404 keep(w);
405 return Ok(f64::NAN);
406 }
407 Err(e) => {
408 keep(w);
409 let mut m = wire::Writer::default();
410 m.string16(&e.reason);
411 // SAFETY: the call is synchronous; JS does not touch `output` until it returns.
412 let out = unsafe { output.as_mut() };
413 if m.0.len() > out.len() {
414 return Err(e);
415 }
416 out[..m.0.len()].copy_from_slice(&m.0);
417 return Ok(f64::INFINITY);
418 }
419 Ok(()) => {}
420 }
421 // SAFETY: the call is synchronous; JS does not touch `output` until it returns.
422 let out = unsafe { output.as_mut() };
423 let n = w.0.len();
424 if n > out.len() {
425 PENDING.with(|p| *p.borrow_mut() = w.0);
426 return Ok(-(n as f64));
427 }
428 out[..n].copy_from_slice(&w.0);
429 keep(w);
430 Ok(n as f64)
431 })
432}
433"#;
434
435const WIRE_WASM_RS: &str = r#"
437// ---- the binary wire ------------------------------------------------------------------------
438
439thread_local! {
440 static WIRE_IN: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
441 static WIRE_OUT: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
442}
443
444/// This module's memory, where `index.cjs` reads and writes the wire buffers.
445#[wasm_bindgen(js_name = "rustAnythingWireMemory")]
446pub fn rust_anything_wire_memory() -> JsValue {
447 wasm_bindgen::memory()
448}
449
450/// The address of an argument buffer of `len` bytes.
451#[wasm_bindgen(js_name = "rustAnythingWireIn")]
452pub fn rust_anything_wire_in(len: u32) -> u32 {
453 WIRE_IN.with(|b| {
454 let mut b = b.borrow_mut();
455 b.resize(len as usize, 0);
456 b.as_mut_ptr() as usize as u32
457 })
458}
459
460/// The address of the last result.
461#[wasm_bindgen(js_name = "rustAnythingWireOut")]
462pub fn rust_anything_wire_out() -> u32 {
463 WIRE_OUT.with(|b| b.borrow().as_ptr() as usize as u32)
464}
465
466/// Reads `len` argument bytes, runs `f`, and keeps its result for `rustAnythingWireOut`.
467fn wire_io(len: u32, f: impl FnOnce(&mut wire::Reader, &mut wire::Writer) -> Result<(), String>) -> Result<u32, JsError> {
468 let input = WIRE_IN.with(|b| std::mem::take(&mut *b.borrow_mut()));
469 let mut w = wire::Writer::default();
470 let result = f(&mut wire::Reader::new(&input[..(len as usize).min(input.len())]), &mut w);
471 WIRE_IN.with(|b| *b.borrow_mut() = input);
472 match result {
473 // A result of another shape than the TS type: JS runs the call through JSON.
474 Err(e) if e.starts_with(wire::MISMATCH) => return Ok(u32::MAX),
475 other => other.map_err(|e| JsError::new(&e))?,
476 }
477 let n = w.0.len();
478 WIRE_OUT.with(|b| *b.borrow_mut() = w.0);
479 Ok(u32::try_from(n).unwrap_or(u32::MAX))
480}
481"#;
482
483struct WireFn<'m> {
485 export: &'m ExportedFn,
486 port: &'m PortFn,
487 params: Vec<Ty>,
488 result: Option<Ty>,
489 rust: String,
490}
491
492pub(crate) fn types_for(m: &Manifest, file: &str) -> Vec<LocalType> {
494 let text = std::fs::read_to_string(m.root.join(file)).unwrap_or_default();
495 crate::bridge::types_in_scope(&m.root, file, &text)
496}
497
498fn wire_fns<'m>(m: &'m Manifest, api: &'m PortApi) -> Vec<WireFn<'m>> {
501 let mut out = Vec::new();
502 let mut scopes: std::collections::HashMap<&str, Vec<LocalType>> =
503 std::collections::HashMap::new();
504 for f in &api.functions {
505 if f.is_async {
506 continue;
507 }
508 let structured =
509 f.params.iter().any(|(_, t)| wire(t) == Wire::Json) || wire(&f.ret) == Wire::Json;
510 let napi = m.kind == crate::bridge::Kind::Napi;
511 if !structured && !napi {
512 continue;
513 }
514 let Some(e) = m.exports.iter().find(|e| e.name == f.js_name) else {
515 continue;
516 };
517 if e.params.len() != f.params.len() || e.params.iter().any(|p| p.rest) {
518 continue;
519 }
520 let types = scopes
521 .entry(e.file.as_str())
522 .or_insert_with(|| types_for(m, &e.file));
523 let params: Vec<Ty> = e
524 .params
525 .iter()
526 .map(|p| {
527 let t = shape_ty(&shape::parse(&p.ts_type), types, 0);
528 if p.optional || p.default.is_some() {
529 match t {
530 Ty::OptJs {
531 inner, nullable, ..
532 } => Ty::OptJs {
533 inner,
534 nullable,
535 undefinable: true,
536 },
537 Ty::Dyn => Ty::Dyn,
538 t => Ty::OptJs {
539 inner: Box::new(t),
540 nullable: false,
541 undefinable: true,
542 },
543 }
544 } else {
545 t
546 }
547 })
548 .collect();
549 let params: Vec<Ty> = params
550 .into_iter()
551 .zip(&f.params)
552 .map(|(t, (_, rust))| {
553 let rust: String = rust.chars().filter(|c| !c.is_whitespace()).collect();
554 let value = rust
555 .strip_prefix("Option<")
556 .and_then(|r| r.strip_suffix('>'))
557 .unwrap_or(&rust);
558 if matches!(value, "Value" | "serde_json::Value") {
559 Ty::Dyn
560 } else {
561 t
562 }
563 })
564 .collect();
565 let result = (f.ret != "()").then(|| shape_ty(&shape::parse(&e.returns), types, 0));
566 let named: Vec<(String, Ty)> = f
567 .params
568 .iter()
569 .map(|(n, _)| n.clone())
570 .zip(params.iter().cloned())
571 .collect();
572 let mut statics = String::new();
573 let prefix = format!("S_{}", crate::bridge::snake_case(&f.js_name).to_uppercase());
574 let Some(reads) = rust_read_args(&named, &f.params, &prefix, &mut statics) else {
575 continue;
576 };
577 let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
578 let call = format!("port::{}({})", f.rust_name, args.join(", "));
579 let call = if f.fallible { format!("{call}?") } else { call };
580 let write = match &result {
581 None => format!(" let () = {call};\n"),
582 Some(t) => {
583 let schema = format!("{prefix}_OUT");
584 let Some(w) = rust_write(t, &f.ret, "out", &schema, 0) else {
585 continue;
586 };
587 if w.contains(&schema) {
588 let _ = writeln!(
589 statics,
590 "static {schema}: wire::Schema = {};",
591 schema_expr(t)
592 );
593 }
594 format!(" let out = &{call};\n {w}\n")
595 }
596 };
597 let (attr, ret, len, len_arg) = if napi {
598 ("napi", "napi::Result<f64>", "", "")
599 } else {
600 ("wasm_bindgen", "Result<u32, JsError>", "len: u32", "len, ")
601 };
602 let r = if reads.contains("r.") || reads.contains("(r") {
603 "r"
604 } else {
605 "_r"
606 };
607 let w = if write.contains("w.") || write.contains("(w") {
608 "w"
609 } else {
610 "_w"
611 };
612 let rust = format!(
613 "\n{statics}\n/// `{js}` over the binary wire.\n#[{attr}(js_name = \"{js}Wire\")]\npub fn {name}_wire({len}) -> {ret} {{\n \
614 wire_io({len_arg}|{r}, {w}| {{\n{reads}{write} Ok(())\n }})\n}}\n",
615 js = f.js_name,
616 name = f.rust_name.trim_start_matches("r#"),
617 );
618 out.push(WireFn {
619 export: e,
620 port: f,
621 params,
622 result,
623 rust,
624 });
625 }
626 out
627}
628
629pub fn napi_rs(m: &Manifest, api: &PortApi) -> String {
632 let fns = wire_fns(m, api);
633 if fns.is_empty() {
634 return String::new();
635 }
636 let mut out = String::from(if m.kind == crate::bridge::Kind::Wasm {
637 WIRE_WASM_RS
638 } else {
639 WIRE_NAPI_RS
640 });
641 for f in fns {
642 out.push_str(&f.rust);
643 }
644 out
645}
646
647pub fn wired(m: &Manifest, api: &PortApi) -> Vec<String> {
650 if !matches!(
651 m.kind,
652 crate::bridge::Kind::Napi | crate::bridge::Kind::Wasm
653 ) {
654 return Vec::new();
655 }
656 wire_fns(m, api)
657 .iter()
658 .map(|f| f.port.js_name.clone())
659 .collect()
660}
661
662pub fn uses_wire(m: &Manifest, api: &PortApi) -> bool {
664 matches!(
665 m.kind,
666 crate::bridge::Kind::Napi | crate::bridge::Kind::Wasm
667 ) && !wire_fns(m, api).is_empty()
668}
669
670pub fn index_cjs(m: &Manifest, api: &PortApi) -> String {
673 let fns = wire_fns(m, api);
674 if fns.is_empty() {
675 return String::new();
676 }
677 let mut out = String::from(if m.kind == crate::bridge::Kind::Wasm {
678 WIRE_WASM_CJS
679 } else {
680 WIRE_NAPI_CJS
681 });
682 out.push_str(WIRE_CJS);
683 for f in &fns {
684 let n = f.params.len();
685 let names: Vec<String> = (0..n).map(|i| format!("a{i}")).collect();
686 let mut enc = String::new();
687 for (i, t) in f.params.iter().enumerate() {
688 enc.push_str(&js_enc(&format!("a{i}"), t, 0));
689 }
690 let dec = f
691 .result
692 .as_ref()
693 .map_or_else(String::new, |t| js_dec("t", t, 0));
694 let js = &f.port.js_name;
695 let checks: String = crate::codegen::string_params(f.port)
696 .iter()
697 .map(|i| {
698 format!(
699 " if (illFormed(a{i})) throw new TypeError('argument {} of {js} has a lone surrogate, which a Rust String cannot hold')\n",
700 i + 1
701 )
702 })
703 .collect();
704 let _ = write!(
705 out,
706 "\n// `{js}`: binary wire; the JSON version handles inputs of other shapes.\n{{\n\
707 const json = module.exports.{js}\nconst call = native.{js}Wire\n\
708 const encode = ({args}) => {{\nat = 0\n{enc}return true\n}}\n\
709 const decode = () => {{\nlet t\n{dec}return t\n}}\n\
710 module.exports.{js} = function {js} ({args}) {{\n{checks} try {{\n \
711 if (arguments.length <= {n} && encode({args}) && wireCall(call)) return decode()\n \
712 return json(...arguments)\n }} catch (e) {{\n throw jsError(e)\n }}\n}}\n}}\n",
713 args = names.join(", "),
714 );
715 let _ = f.export;
716 }
717 out
718}
719
720#[cfg(test)]
721mod tests {
722 use super::*;
723
724 #[test]
725 fn the_argument_length_has_an_array_buffer_of_its_own() {
726 assert!(
730 WIRE_NAPI_CJS.contains("const wLen = new Uint32Array(new ArrayBuffer(4))"),
731 "the loader must give `wLen` its own ArrayBuffer"
732 );
733 assert!(
734 !WIRE_NAPI_CJS.contains("new Uint32Array(1)"),
735 "a bare `new Uint32Array(1)` is the shape Bun relocates"
736 );
737 }
738
739 #[test]
740 fn wide_objects_use_dynamic_keys_instead_of_truncating_field_indexes() {
741 let shape = |n| {
742 Shape::Object(
743 (0..n)
744 .map(|i| (format!("p{i}"), true, Shape::Num))
745 .collect(),
746 None,
747 )
748 };
749 assert!(matches!(shape_ty(&shape(255), &[], 0), Ty::Obj(fields) if fields.len() == 255));
750 assert_eq!(shape_ty(&shape(256), &[], 0), Ty::Dyn);
751 assert_eq!(shape_ty(&shape(257), &[], 0), Ty::Dyn);
752 }
753
754 #[test]
755 fn maps_ts_shapes() {
756 let none: Vec<LocalType> = Vec::new();
757 let t = shape_ty(
758 &shape::parse("{ start: number; end: number; label?: string | null }"),
759 &none,
760 0,
761 );
762 let Ty::Obj(fields) = &t else { panic!("{t:?}") };
763 assert_eq!(fields[0], ("start".into(), Ty::Num));
764 assert_eq!(
765 fields[2].1,
766 Ty::OptJs {
767 inner: Box::new(Ty::Str16),
768 nullable: true,
769 undefinable: true
770 }
771 );
772 assert_eq!(shape_ty(&shape::parse("'a' | 'b'"), &none, 0), Ty::Str16);
773 assert_eq!(shape_ty(&shape::parse("unknown"), &none, 0), Ty::Dyn);
774 assert!(matches!(
775 shape_ty(&shape::parse("Record<string, number>"), &none, 0),
776 Ty::Map16(_)
777 ));
778 }
779}