Skip to main content

rust_anything/
codegen_tswire.rs

1//! The binary wire for TypeScript/JavaScript: generated JS encoders write arguments into a
2//! buffer registered once with the Rust module, the Rust side reads them in place, and the
3//! result comes back the same way. No JSON text, no per-property napi calls.
4//!
5//! When an argument does not have the declared shape at run time, that call falls back to the
6//! JSON bridge, so behavior on unexpected inputs stays exactly as before.
7
8use 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
16/// The wire type of a TS shape. Shapes the wire does not model travel as tagged values.
17fn 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
107/// JS statements writing `x` as `t`; `return false` when `x` does not have the shape.
108fn 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            // Keys in the object's own order (a port may pass the object through); a key the
134            // type does not list sends the call through JSON.
135            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
178/// JS statements decoding a value of `t` into the variable `target`.
179fn 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
215/// The JS runtime: registered buffers, writers, readers, tagged values.
216const 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
345/// The napi side: buffer registration and the call helper.
346const 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
435/// The wasm side: buffers in wasm memory, and the call helper.
436const 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
483/// One wire function: its export, parameter and result types, and the generated code.
484struct WireFn<'m> {
485    export: &'m ExportedFn,
486    port: &'m PortFn,
487    params: Vec<Ty>,
488    result: Option<Ty>,
489    rust: String,
490}
491
492fn types_for(m: &Manifest, file: &str) -> Vec<LocalType> {
493    let text = std::fs::read_to_string(m.root.join(file)).unwrap_or_default();
494    crate::bridge::types_in_scope(&m.root, file, &text)
495}
496
497/// The functions that cross the wire: synchronous, with a structured parameter or result, and
498/// port types that fit the wire types.
499fn wire_fns<'m>(m: &'m Manifest, api: &'m PortApi) -> Vec<WireFn<'m>> {
500    let mut out = Vec::new();
501    let mut scopes: std::collections::HashMap<&str, Vec<LocalType>> =
502        std::collections::HashMap::new();
503    for f in &api.functions {
504        if f.is_async {
505            continue;
506        }
507        let structured =
508            f.params.iter().any(|(_, t)| wire(t) == Wire::Json) || wire(&f.ret) == Wire::Json;
509        let napi = m.kind == crate::bridge::Kind::Napi;
510        if !structured && !napi {
511            continue;
512        }
513        let Some(e) = m.exports.iter().find(|e| e.name == f.js_name) else {
514            continue;
515        };
516        if e.params.len() != f.params.len() || e.params.iter().any(|p| p.rest) {
517            continue;
518        }
519        let types = scopes
520            .entry(e.file.as_str())
521            .or_insert_with(|| types_for(m, &e.file));
522        let params: Vec<Ty> = e
523            .params
524            .iter()
525            .map(|p| {
526                let t = shape_ty(&shape::parse(&p.ts_type), types, 0);
527                if p.optional || p.default.is_some() {
528                    match t {
529                        Ty::OptJs {
530                            inner, nullable, ..
531                        } => Ty::OptJs {
532                            inner,
533                            nullable,
534                            undefinable: true,
535                        },
536                        Ty::Dyn => Ty::Dyn,
537                        t => Ty::OptJs {
538                            inner: Box::new(t),
539                            nullable: false,
540                            undefinable: true,
541                        },
542                    }
543                } else {
544                    t
545                }
546            })
547            .collect();
548        let params: Vec<Ty> = params
549            .into_iter()
550            .zip(&f.params)
551            .map(|(t, (_, rust))| {
552                let rust: String = rust.chars().filter(|c| !c.is_whitespace()).collect();
553                let value = rust
554                    .strip_prefix("Option<")
555                    .and_then(|r| r.strip_suffix('>'))
556                    .unwrap_or(&rust);
557                if matches!(value, "Value" | "serde_json::Value") {
558                    Ty::Dyn
559                } else {
560                    t
561                }
562            })
563            .collect();
564        let result = (f.ret != "()").then(|| shape_ty(&shape::parse(&e.returns), types, 0));
565        let named: Vec<(String, Ty)> = f
566            .params
567            .iter()
568            .map(|(n, _)| n.clone())
569            .zip(params.iter().cloned())
570            .collect();
571        let mut statics = String::new();
572        let prefix = format!("S_{}", crate::bridge::snake_case(&f.js_name).to_uppercase());
573        let Some(reads) = rust_read_args(&named, &f.params, &prefix, &mut statics) else {
574            continue;
575        };
576        let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
577        let call = format!("port::{}({})", f.rust_name, args.join(", "));
578        let call = if f.fallible { format!("{call}?") } else { call };
579        let write = match &result {
580            None => format!("        let () = {call};\n"),
581            Some(t) => {
582                let schema = format!("{prefix}_OUT");
583                let Some(w) = rust_write(t, &f.ret, "out", &schema, 0) else {
584                    continue;
585                };
586                if w.contains(&schema) {
587                    let _ = writeln!(
588                        statics,
589                        "static {schema}: wire::Schema = {};",
590                        schema_expr(t)
591                    );
592                }
593                format!("        let out = &{call};\n        {w}\n")
594            }
595        };
596        let (attr, ret, len, len_arg) = if napi {
597            ("napi", "napi::Result<f64>", "", "")
598        } else {
599            ("wasm_bindgen", "Result<u32, JsError>", "len: u32", "len, ")
600        };
601        let r = if reads.contains("r.") || reads.contains("(r") {
602            "r"
603        } else {
604            "_r"
605        };
606        let w = if write.contains("w.") || write.contains("(w") {
607            "w"
608        } else {
609            "_w"
610        };
611        let rust = format!(
612            "\n{statics}\n/// `{js}` over the binary wire.\n#[{attr}(js_name = \"{js}Wire\")]\npub fn {name}_wire({len}) -> {ret} {{\n    \
613             wire_io({len_arg}|{r}, {w}| {{\n{reads}{write}        Ok(())\n    }})\n}}\n",
614            js = f.js_name,
615            name = f.rust_name.trim_start_matches("r#"),
616        );
617        out.push(WireFn {
618            export: e,
619            port: f,
620            params,
621            result,
622            rust,
623        });
624    }
625    out
626}
627
628/// Rust code for `lib.rs` (napi): the wire runtime and one function per wire export; empty
629/// when no function uses the wire.
630pub fn napi_rs(m: &Manifest, api: &PortApi) -> String {
631    let fns = wire_fns(m, api);
632    if fns.is_empty() {
633        return String::new();
634    }
635    let mut out = String::from(if m.kind == crate::bridge::Kind::Wasm {
636        WIRE_WASM_RS
637    } else {
638        WIRE_NAPI_RS
639    });
640    for f in fns {
641        out.push_str(&f.rust);
642    }
643    out
644}
645
646/// The functions `index.cjs` sends over the wire: their wrapper also refuses lone surrogates and
647/// keeps JS error classes, in place of the guard layer.
648pub fn wired(m: &Manifest, api: &PortApi) -> Vec<String> {
649    if !matches!(
650        m.kind,
651        crate::bridge::Kind::Napi | crate::bridge::Kind::Wasm
652    ) {
653        return Vec::new();
654    }
655    wire_fns(m, api)
656        .iter()
657        .map(|f| f.port.js_name.clone())
658        .collect()
659}
660
661/// Whether the crate has wire functions (and needs `src/wire.rs`).
662pub fn uses_wire(m: &Manifest, api: &PortApi) -> bool {
663    matches!(
664        m.kind,
665        crate::bridge::Kind::Napi | crate::bridge::Kind::Wasm
666    ) && !wire_fns(m, api).is_empty()
667}
668
669/// JS for `index.cjs`, after the exports are set: the runtime, and each wire function in front
670/// of its JSON version.
671pub fn index_cjs(m: &Manifest, api: &PortApi) -> String {
672    let fns = wire_fns(m, api);
673    if fns.is_empty() {
674        return String::new();
675    }
676    let mut out = String::from(if m.kind == crate::bridge::Kind::Wasm {
677        WIRE_WASM_CJS
678    } else {
679        WIRE_NAPI_CJS
680    });
681    out.push_str(WIRE_CJS);
682    for f in &fns {
683        let n = f.params.len();
684        let names: Vec<String> = (0..n).map(|i| format!("a{i}")).collect();
685        let mut enc = String::new();
686        for (i, t) in f.params.iter().enumerate() {
687            enc.push_str(&js_enc(&format!("a{i}"), t, 0));
688        }
689        let dec = f
690            .result
691            .as_ref()
692            .map_or_else(String::new, |t| js_dec("t", t, 0));
693        let js = &f.port.js_name;
694        let checks: String = crate::codegen::string_params(f.port)
695            .iter()
696            .map(|i| {
697                format!(
698                    "  if (illFormed(a{i})) throw new TypeError('argument {} of {js} has a lone surrogate, which a Rust String cannot hold')\n",
699                    i + 1
700                )
701            })
702            .collect();
703        let _ = write!(
704            out,
705            "\n// `{js}`: binary wire; the JSON version handles inputs of other shapes.\n{{\n\
706             const json = module.exports.{js}\nconst call = native.{js}Wire\n\
707             const encode = ({args}) => {{\nat = 0\n{enc}return true\n}}\n\
708             const decode = () => {{\nlet t\n{dec}return t\n}}\n\
709             module.exports.{js} = function {js} ({args}) {{\n{checks}  try {{\n    \
710             if (arguments.length <= {n} && encode({args}) && wireCall(call)) return decode()\n    \
711             return json(...arguments)\n  }} catch (e) {{\n    throw jsError(e)\n  }}\n}}\n}}\n",
712            args = names.join(", "),
713        );
714        let _ = f.export;
715    }
716    out
717}
718
719#[cfg(test)]
720mod tests {
721    use super::*;
722
723    #[test]
724    fn the_argument_length_has_an_array_buffer_of_its_own() {
725        // `wIn` and `wOut` are registered after their `.buffer` is read for the DataViews above;
726        // `wLen` never was, and Bun (JavaScriptCore) may then move the small typed array, so Rust
727        // read a length of 0 and every call failed with `wire data ended early`.
728        assert!(
729            WIRE_NAPI_CJS.contains("const wLen = new Uint32Array(new ArrayBuffer(4))"),
730            "the loader must give `wLen` its own ArrayBuffer"
731        );
732        assert!(
733            !WIRE_NAPI_CJS.contains("new Uint32Array(1)"),
734            "a bare `new Uint32Array(1)` is the shape Bun relocates"
735        );
736    }
737
738    #[test]
739    fn wide_objects_use_dynamic_keys_instead_of_truncating_field_indexes() {
740        let shape = |n| {
741            Shape::Object(
742                (0..n)
743                    .map(|i| (format!("p{i}"), true, Shape::Num))
744                    .collect(),
745                None,
746            )
747        };
748        assert!(matches!(shape_ty(&shape(255), &[], 0), Ty::Obj(fields) if fields.len() == 255));
749        assert_eq!(shape_ty(&shape(256), &[], 0), Ty::Dyn);
750        assert_eq!(shape_ty(&shape(257), &[], 0), Ty::Dyn);
751    }
752
753    #[test]
754    fn maps_ts_shapes() {
755        let none: Vec<LocalType> = Vec::new();
756        let t = shape_ty(
757            &shape::parse("{ start: number; end: number; label?: string | null }"),
758            &none,
759            0,
760        );
761        let Ty::Obj(fields) = &t else { panic!("{t:?}") };
762        assert_eq!(fields[0], ("start".into(), Ty::Num));
763        assert_eq!(
764            fields[2].1,
765            Ty::OptJs {
766                inner: Box::new(Ty::Str16),
767                nullable: true,
768                undefinable: true
769            }
770        );
771        assert_eq!(shape_ty(&shape::parse("'a' | 'b'"), &none, 0), Ty::Str16);
772        assert_eq!(shape_ty(&shape::parse("unknown"), &none, 0), Ty::Dyn);
773        assert!(matches!(
774            shape_ty(&shape::parse("Record<string, number>"), &none, 0),
775            Ty::Map16(_)
776        ));
777    }
778}