Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

96.4 KB
Raw Blame
//! Code generation for a bridge crate: port stubs from TS signatures, and the binding layer
//! (`lib.rs`, `index.cjs`) from the port's Rust signatures.
//!
//! The binding layer follows `port.rs`, not the TS: change a port's types, run
//! `rust-anything refresh`, and the bindings and loader follow. Values cross three ways:
//!
//! - native: strings, numbers, booleans and lists or options of those, with no extra cost;
//! - JSON text: anything structured, as one string each way (`JSON.parse` is fast in V8), with
//!   markers for what JSON lacks (`undefined`, NaN, lone surrogates; see `js.rs`);
//! - UTF-16 units: a `Vec<u16>` return, for strings that may hold lone surrogates.

use crate::MIN_RUST;
use std::fmt::Write as _;

use crate::bridge::{Kind, Manifest, RType, param_type, snake_case};
use crate::ts::exports::{ExportedFn, LocalType};
use crate::ts::shape::Shape;

/// A port function, as declared in `port.rs`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PortFn {
    pub js_name: String,
    pub rust_name: String,
    pub params: Vec<(String, String)>,
    /// The success type, `()` for none.
    pub ret: String,
    /// Returns `Result<T, String>`; an `Err` becomes a thrown JS error.
    pub fallible: bool,
    pub is_async: bool,
}

/// A port class: a struct with `new` and methods taking `&self` or `&mut self`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PortClass {
    pub js_name: String,
    pub rust_name: String,
    pub constructor: PortFn,
    pub methods: Vec<(PortFn, bool)>,
}

/// What `port.rs` offers to JS. `methods` pairs each method with whether it takes `&mut self`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PortApi {
    pub functions: Vec<PortFn>,
    pub classes: Vec<PortClass>,
    /// Every `pub struct` of `port.rs` (a batch uses `<Name>Index` when the port defines one).
    pub structs: Vec<String>,
    /// The structs whose `impl` has a `pub fn rank` (an index that ranks by itself).
    pub ranked: Vec<String>,
    /// The functions, by Rust name, that a `/// Port of` line names.
    pub doc_named: Vec<String>,
    /// Whether `port.rs` mentions `serde_json` or `Value`.
    pub uses_json_value: bool,
}

impl PortFn {
    /// The port takes a parameter by `&mut` (an argument the original changes in place) or a
    /// `stdout: &mut String` (what the original prints): the bindings hand both back to the
    /// caller, and the call is not wired, batched or checked by its return value alone.
    pub fn has_effects(&self) -> bool {
        self.params
            .iter()
            .any(|(_, t)| t.trim_start().starts_with("&mut "))
    }

    /// The port writes what the original prints to `stdout: &mut String`.
    pub fn prints(&self) -> bool {
        self.params
            .iter()
            .any(|(n, t)| n == "stdout" && t.trim() == "&mut String")
    }

    /// The parameters the caller passes, as `(name, type without `&mut`, changed in place)`:
    /// the `stdout` sink is the port's, not the caller's.
    pub fn visible(&self) -> Vec<(&str, &str, bool)> {
        self.params
            .iter()
            .filter(|(n, t)| !(n == "stdout" && t.trim() == "&mut String"))
            .map(|(n, t)| match t.trim_start().strip_prefix("&mut ") {
                Some(inner) => (n.as_str(), inner.trim(), true),
                None => (n.as_str(), t.as_str(), false),
            })
            .collect()
    }
}

impl PortApi {
    /// Every function and method, for dependency and wire checks.
    pub fn all(&self) -> impl Iterator<Item = &PortFn> {
        self.functions.iter().chain(
            self.classes.iter().flat_map(|c| {
                std::iter::once(&c.constructor).chain(c.methods.iter().map(|(m, _)| m))
            }),
        )
    }

    pub fn needs_json(&self) -> bool {
        self.all().any(|f| {
            f.has_effects()
                || wire(&f.ret) == Wire::Json
                || f.params.iter().any(|(_, t)| wire(t) == Wire::Json)
        })
    }
}

/// How a Rust type crosses the bridge.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Wire {
    Native,
    Json,
    Units,
}

pub fn wire(ty: &str) -> Wire {
    let ty: String = ty.chars().filter(|c| !c.is_whitespace()).collect();
    let ty = ty.strip_prefix("&mut").unwrap_or(&ty);
    match ty {
        "String" | "f64" | "i64" | "bool" | "()" | "Vec<String>" | "Vec<f64>" | "Vec<i64>"
        | "Option<String>" | "Option<f64>" | "Option<i64>" | "Option<bool>" => Wire::Native,
        "Vec<u16>" => Wire::Units,
        _ => Wire::Json,
    }
}

// ---- port.rs stubs ---------------------------------------------------------------------------

/// `port.rs` with one stub per export, typed from the TS signature.
pub fn port_rs(m: &Manifest) -> String {
    let mut out = format!(
        "//! The Rust port of `{}`.\n//!\n\
         //! Replace each `unimplemented!` with the port of the source function. Return `Err` where\n\
         //! the source throws or raises: the caller gets an error there too. After changing a\n\
         //! signature, run `rust-anything refresh` to regenerate the bindings. `rust-anything diff` checks\n\
         //! behavior against what the source recorded.\n\n\
         #![forbid(unsafe_code)]\n",
        m.unit
    );
    for f in &m.exports {
        let params = f
            .params
            .iter()
            .map(|p| {
                let ty = go_unsigned(m, p.native_type.as_deref())
                    .or_else(|| swift_unsigned(m, p.native_type.as_deref()))
                    .unwrap_or_else(|| port_param_type(m, p).rust());
                // An argument the original changes in place is `&mut`: the caller sees the change.
                let by = if f.mutates.contains(&p.name) {
                    "&mut "
                } else {
                    ""
                };
                format!("{}: {by}{ty}", snake_case(&p.name))
            })
            .chain(f.prints.then(|| "stdout: &mut String".to_string()))
            .collect::<Vec<_>>()
            .join(", ");
        let ret = match (
            go_unsigned_result(m, f).or_else(|| swift_unsigned(m, f.native_return.as_deref())),
            RType::from_ts(&f.returns),
        ) {
            (Some(unsigned), _) => unsigned,
            (None, RType::Unit) => "()".to_string(),
            (None, t) => t.rust(),
        };
        let names: Vec<String> = f
            .params
            .iter()
            .map(|p| snake_case(&p.name))
            .chain(f.prints.then(|| "stdout".to_string()))
            .collect();
        let asyncness = if is_async(f) { "async " } else { "" };
        out.push('\n');
        let _ = writeln!(out, "/// Port of `{}` (`{}:{}`).", f.name, f.file, f.line);
        let mut effects = Vec::new();
        if !f.mutates.is_empty() {
            effects.push(format!(
                "changes `{}` in place: this port takes it by `&mut` and must leave it as the original does",
                f.mutates.join("`, `")
            ));
        }
        if f.prints {
            effects.push(
                "prints: write what it prints to `stdout`, which the caller then prints"
                    .to_string(),
            );
        }
        if !effects.is_empty() {
            let _ = writeln!(
                out,
                "///\n/// The original {}. `record` keeps the arguments after each call and the output; \
                 `diff` compares both.",
                effects.join(", and ")
            );
        }
        for p in f.params.iter().filter(|p| p.default.is_some()) {
            let _ = writeln!(
                out,
                "///\n/// `{}` defaults to `{}` in the source.",
                snake_case(&p.name),
                p.default.as_deref().unwrap_or_default()
            );
        }
        let _ = writeln!(
            out,
            "pub {asyncness}fn {}({params}) -> Result<{ret}, String> {{",
            snake_case(&f.name)
        );
        match names.len() {
            0 => {}
            1 => {
                let _ = writeln!(out, "    let _ = &{};", names[0]);
            }
            _ => {
                let refs: Vec<String> = names.iter().map(|n| format!("&{n}")).collect();
                let _ = writeln!(out, "    let _ = ({});", refs.join(", "));
            }
        }
        let _ = writeln!(
            out,
            "    unimplemented!(\"port `{}` from {}\")",
            f.name, f.file
        );
        out.push_str("}\n");
    }
    for c in &m.classes {
        let _ = writeln!(
            out,
            "\n/// Port of class `{}` (`{}:{}`): holds the instance state.",
            c.name, c.file, c.line
        );
        let _ = writeln!(out, "pub struct {} {{}}\n", c.name);
        let _ = writeln!(out, "impl {} {{", c.name);
        let ctor = stub_params(m, &c.constructor);
        let _ = writeln!(
            out,
            "    /// Port of `{}` constructor (`{}:{}`).",
            c.name, c.file, c.line
        );
        let _ = writeln!(out, "    pub fn new({}) -> Result<Self, String> {{", ctor.0);
        let _ = write!(out, "{}", ctor.1);
        let _ = writeln!(
            out,
            "        unimplemented!(\"port the `{}` constructor\")\n    }}",
            c.name
        );
        for f in &c.methods {
            let (params, unused) = stub_params(m, &f.params);
            let ret = match RType::from_ts(&f.returns) {
                RType::Unit => "()".to_string(),
                t => t.rust(),
            };
            let receiver = if params.is_empty() {
                "&mut self".to_string()
            } else {
                format!("&mut self, {params}")
            };
            let _ = writeln!(
                out,
                "\n    /// Port of `{}.{}` (`{}:{}`).",
                c.name, f.name, f.file, f.line
            );
            let _ = writeln!(
                out,
                "    pub fn {}({receiver}) -> Result<{ret}, String> {{",
                snake_case(&f.name)
            );
            let _ = write!(out, "{unused}");
            let _ = writeln!(
                out,
                "        unimplemented!(\"port `{}.{}`\")\n    }}",
                c.name, f.name
            );
        }
        out.push_str("}\n");
    }
    out
}

/// The port type of a Go `uint64`, `uint` or `uintptr`: the dialect calls every Go integer `int`,
/// which is `i64` in the port and cannot hold the upper half of their range.
fn go_unsigned(m: &Manifest, go_type: Option<&str>) -> Option<String> {
    matches!(m.language, crate::lang::Lang::Go)
        .then(|| go_type.and_then(crate::codegen_go::unsigned_port_type))
        .flatten()
}

/// The port type of a Swift `UInt` or `UInt64`: the dialect calls every Swift integer `int`, which is
/// `i64` in the port and cannot hold the upper half of their range (issue #1045).
fn swift_unsigned(m: &Manifest, swift_type: Option<&str>) -> Option<String> {
    matches!(m.language, crate::lang::Lang::Swift)
        .then(|| swift_type.and_then(crate::codegen_swift::unsigned_port_type))
        .flatten()
}

/// [`go_unsigned`] for a function with one result; several results cross as one JSON value.
fn go_unsigned_result(m: &Manifest, f: &crate::ts::exports::ExportedFn) -> Option<String> {
    match crate::codegen_go::results(f).0.as_slice() {
        [result] => go_unsigned(m, Some(result)),
        _ => None,
    }
}

/// A parameter's type in the port. Python parameters with a literal default (`sep="-"`) are
/// plain values: PyO3 fills in the default, and an explicit `None` stays an error, as in Python.
fn port_param_type(m: &Manifest, p: &crate::ts::exports::Param) -> RType {
    if matches!(
        m.language,
        crate::lang::Lang::Python
            | crate::lang::Lang::Ruby
            | crate::lang::Lang::Php
            | crate::lang::Lang::Csharp
            | crate::lang::Lang::Powershell
    ) && crate::codegen_py::has_literal_default(p)
    {
        RType::from_ts(&p.ts_type)
    } else {
        param_type(p)
    }
}

/// Parameters of a method stub, and a line marking them used.
fn stub_params(m: &Manifest, params: &[crate::ts::exports::Param]) -> (String, String) {
    let list = params
        .iter()
        .map(|p| format!("{}: {}", snake_case(&p.name), port_param_type(m, p).rust()))
        .collect::<Vec<_>>()
        .join(", ");
    let names: Vec<String> = params
        .iter()
        .map(|p| format!("&{}", snake_case(&p.name)))
        .collect();
    let unused = match names.len() {
        0 => String::new(),
        1 => format!("        let _ = {};\n", names[0]),
        _ => format!("        let _ = ({});\n", names.join(", ")),
    };
    (list, unused)
}

pub fn is_async(f: &ExportedFn) -> bool {
    f.is_async || f.returns.trim().starts_with("Promise<")
}

// ---- reading port.rs -------------------------------------------------------------------------

/// The functions and classes `port.rs` offers. A function's JS name comes from its
/// `/// Port of `name`` doc line (else its Rust name in camelCase); a class is a `pub struct`
/// documented `/// Port of class `Name``, with an `impl` holding `new` and its methods.
pub fn parse_port(source: &str) -> PortApi {
    let lines: Vec<&str> = source.lines().collect();
    let functions = functions_in(&lines, "");
    let mut api = PortApi {
        doc_named: functions
            .iter()
            .filter(|(_, named)| *named)
            .map(|(f, _)| f.rust_name.clone())
            .collect(),
        functions: functions.into_iter().map(|(f, _)| f).collect(),
        classes: Vec::new(),
        structs: lines
            .iter()
            .filter_map(|l| l.trim_start().strip_prefix("pub struct "))
            .map(|r| {
                r.chars()
                    .take_while(|c| c.is_alphanumeric() || *c == '_')
                    .collect()
            })
            .collect(),
        ranked: Vec::new(),
        uses_json_value: mentions_json_value(source),
    };
    // `impl Name {` ... `}` at column 0: does it define `pub fn rank`?
    for (i, line) in lines.iter().enumerate() {
        let Some(rest) = line.strip_prefix("impl ") else {
            continue;
        };
        let name: String = rest
            .chars()
            .take_while(|c| c.is_alphanumeric() || *c == '_')
            .collect();
        let body = lines[i + 1..].iter().take_while(|l| !l.starts_with('}'));
        if body
            .into_iter()
            .any(|l| l.trim_start().starts_with("pub fn rank("))
        {
            api.ranked.push(name);
        }
    }
    for (i, line) in lines.iter().enumerate() {
        let Some(rest) = line.strip_prefix("pub struct ") else {
            continue;
        };
        let rust_name: String = rest
            .chars()
            .take_while(|c| c.is_alphanumeric() || *c == '_')
            .collect();
        let Some(js_name) = doc_name(&lines[..i], "Port of class `") else {
            continue;
        };
        // The `impl Name {` block, up to its closing `}` at column 0.
        let Some(start) = lines
            .iter()
            .position(|l| l.trim_end() == format!("impl {rust_name} {{"))
        else {
            continue;
        };
        let end = lines[start..]
            .iter()
            .position(|l| *l == "}")
            .map_or(lines.len(), |e| start + e);
        let block = &lines[start + 1..end];
        let mut constructor = None;
        let mut methods = Vec::new();
        for (f, _) in functions_in(block, "    ") {
            if f.rust_name == "new" {
                constructor = Some(f);
            } else {
                let signature_line = block
                    .iter()
                    .find(|l| l.contains(&format!("fn {}(", f.rust_name)))
                    .copied()
                    .unwrap_or("");
                let block_text = block.join("\n");
                let mutable = signature_line.contains("&mut self") || {
                    let at = block_text
                        .find(&format!("fn {}(", f.rust_name))
                        .unwrap_or(0);
                    block_text[at..]
                        .split('{')
                        .next()
                        .unwrap_or("")
                        .contains("&mut self")
                };
                methods.push((f, mutable));
            }
        }
        if let Some(constructor) = constructor {
            api.classes.push(PortClass {
                js_name,
                rust_name,
                constructor,
                methods,
            });
        }
    }
    // The type names the port declares itself: structs, enums and aliases.
    let own: Vec<String> = lines
        .iter()
        .filter_map(|line| {
            ["pub struct ", "pub enum ", "pub type "]
                .iter()
                .find_map(|keyword| line.trim_start().strip_prefix(keyword))
        })
        .map(|rest| {
            rest.chars()
                .take_while(|c| c.is_alphanumeric() || *c == '_')
                .collect()
        })
        .collect();
    let functions = api.functions.iter_mut();
    let in_classes = api.classes.iter_mut().flat_map(|class| {
        let methods = class.methods.iter_mut().map(|(method, _)| method);
        std::iter::once(&mut class.constructor).chain(methods)
    });
    for function in functions.chain(in_classes) {
        function.ret = with_paths(&function.ret, &own);
        for (_, ty) in &mut function.params {
            *ty = with_paths(ty, &own);
        }
    }
    api
}

/// Type names a port may import instead of spelling out. The bindings repeat a port's types
/// in files that have none of its `use` lines, so they need the path.
const IMPORTABLE: [(&str, &str); 3] = [
    ("Value", "serde_json::Value"),
    ("HashMap", "std::collections::HashMap"),
    ("PathBuf", "std::path::PathBuf"),
];

/// `ty` with each bare [`IMPORTABLE`] name given its path. A name already behind a path
/// (`serde_json::Value`) and a name the port defines itself (`own`) stay as written.
fn with_paths(ty: &str, own: &[String]) -> String {
    let mut out = String::new();
    let mut word = String::new();
    let flush = |out: &mut String, word: &mut String| {
        let path = IMPORTABLE
            .iter()
            .find(|(name, _)| name == word)
            .filter(|_| !out.trim_end().ends_with("::") && !own.contains(word));
        out.push_str(path.map_or(word.as_str(), |(_, path)| path));
        word.clear();
    };
    for c in ty.chars() {
        if c.is_alphanumeric() || c == '_' {
            word.push(c);
        } else {
            flush(&mut out, &mut word);
            out.push(c);
        }
    }
    flush(&mut out, &mut word);
    out
}

fn doc_name(before: &[&str], prefix: &str) -> Option<String> {
    before
        .iter()
        .rev()
        .take_while(|l| l.trim_start().starts_with("///") || l.trim_start().starts_with("#["))
        .find_map(|l| {
            let doc = l.trim_start().strip_prefix("///")?.trim();
            let rest = doc.strip_prefix(prefix)?;
            Some(rest.split('`').next()?.to_string())
        })
}

/// `pub fn` items at one indentation level. In an `impl`, `Port of `Class.method`` names the
/// method `method`. Each comes with whether such a line names it.
fn functions_in(lines: &[&str], indent: &str) -> Vec<(PortFn, bool)> {
    let mut out = Vec::new();
    let mut i = 0;
    while i < lines.len() {
        let line = lines[i].strip_prefix(indent).unwrap_or("");
        let (is_async, rest) = if let Some(rest) = line.strip_prefix("pub async fn ") {
            (true, rest)
        } else if let Some(rest) = line.strip_prefix("pub fn ") {
            (false, rest)
        } else {
            i += 1;
            continue;
        };
        // The signature runs to the `{` that opens the body, possibly over several lines.
        let mut signature = rest.to_string();
        let mut j = i;
        while !balanced_open_brace(&signature) && j + 1 < lines.len() {
            j += 1;
            signature.push(' ');
            signature.push_str(lines[j].trim());
        }
        let js_name = doc_name(&lines[..i], "Port of `")
            .map(|n| n.rsplit('.').next().unwrap_or(&n).to_string());
        let named = js_name.is_some();
        if let Some(f) = parse_signature(&signature, is_async, js_name) {
            out.push((f, named));
        }
        i = j + 1;
    }
    out
}

/// Whether the text reaches the body's `{` outside parentheses and angle brackets.
fn balanced_open_brace(text: &str) -> bool {
    let mut depth = 0i32;
    let mut previous = ' ';
    for c in text.chars() {
        let arrow = c == '>' && previous == '-';
        previous = c;
        match c {
            '(' | '<' | '[' => depth += 1,
            // `->` is not a closing bracket.
            '>' if arrow => {}
            ')' | '>' | ']' => depth -= 1,
            '{' if depth == 0 => return true,
            _ => {}
        }
    }
    false
}

fn parse_signature(signature: &str, is_async: bool, js_name: Option<String>) -> Option<PortFn> {
    let open = signature.find('(')?;
    let rust_name = signature[..open].trim().to_string();
    let mut depth = 0i32;
    let mut close = None;
    for (i, c) in signature.char_indices().skip(open) {
        match c {
            '(' | '<' | '[' => depth += 1,
            ')' | '>' | ']' => {
                depth -= 1;
                if depth == 0 && c == ')' {
                    close = Some(i);
                    break;
                }
            }
            _ => {}
        }
    }
    let close = close?;
    let params = split_top(&signature[open + 1..close])
        .into_iter()
        .filter(|p| !p.trim().is_empty())
        .filter_map(|p| {
            let (name, ty) = p.split_once(':')?;
            Some((
                name.trim().trim_start_matches("mut ").to_string(),
                ty.trim().to_string(),
            ))
        })
        .collect();
    let after = &signature[close + 1..];
    let body = after.find('{').unwrap_or(after.len());
    let ret_text = after[..body].trim();
    let ret_text = ret_text.strip_prefix("->").map_or("()", str::trim);
    let (ret, fallible) = match ret_text
        .strip_prefix("Result<")
        .and_then(|r| r.strip_suffix('>'))
    {
        Some(inner) => (
            split_top(inner)
                .first()
                .map_or("()", |t| t.trim())
                .to_string(),
            true,
        ),
        None => (ret_text.to_string(), false),
    };
    Some(PortFn {
        js_name: js_name.unwrap_or_else(|| camel_case(&rust_name)),
        rust_name,
        params,
        ret,
        fallible,
        is_async,
    })
}

fn split_top(text: &str) -> Vec<&str> {
    let mut out = Vec::new();
    let mut depth = 0i32;
    let mut start = 0;
    for (i, c) in text.char_indices() {
        match c {
            '(' | '<' | '[' => depth += 1,
            ')' | '>' | ']' => depth -= 1,
            ',' if depth == 0 => {
                out.push(&text[start..i]);
                start = i + 1;
            }
            _ => {}
        }
    }
    out.push(&text[start..]);
    out
}

fn camel_case(name: &str) -> String {
    let name = name.trim_start_matches("r#");
    let mut out = String::new();
    let mut upper = false;
    for c in name.chars() {
        if c == '_' {
            upper = true;
        } else if upper {
            out.extend(c.to_uppercase());
            upper = false;
        } else {
            out.push(c);
        }
    }
    out
}

// ---- lib.rs ----------------------------------------------------------------------------------

pub struct Modules {
    pub utf16: bool,
    pub js: bool,
}

pub fn lib_rs(m: &Manifest, api: &PortApi, modules: &Modules) -> String {
    if m.kind == Kind::Pyo3 {
        return crate::codegen_py::lib_rs(m, api, modules);
    }
    let mut out = format!(
        "//! JS bindings for `{}`: generated from the signatures in `port.rs` by rust-anything.\n\
         //! Regenerate with `rust-anything refresh` after changing them.\n\n",
        m.unit
    );
    out.push_str(match m.kind {
        Kind::Wasm => "use wasm_bindgen::prelude::*;\n\n",
        _ => "use napi_derive::napi;\n\n",
    });
    if modules.js {
        out.push_str("pub mod js;\n");
    }
    out.push_str("pub mod port;\n");
    if modules.utf16 {
        out.push_str("pub mod utf16;\n");
    }
    if m.kind == Kind::Napi {
        out.push_str(NAPI_RUN);
        if api.all().any(|f| f.is_async) {
            out.push_str(NAPI_RUN_ASYNC);
        }
    }
    let mut scopes: std::collections::HashMap<&str, Vec<LocalType>> =
        std::collections::HashMap::new();
    for f in &api.functions {
        out.push('\n');
        let _ = writeln!(out, "/// `{}`.", f.js_name);
        let null = m
            .exports
            .iter()
            .find(|e| e.name == f.js_name)
            .is_some_and(|e| {
                let types = scopes
                    .entry(e.file.as_str())
                    .or_insert_with(|| crate::codegen_tswire::types_for(m, &e.file));
                none_is_null(Some(&e.returns), types)
            });
        bind(&mut out, api, m.kind, f, null);
    }
    for c in &api.classes {
        bind_class(&mut out, api, m.kind, c);
    }
    out
}

/// Whether `None` from the port must reach JS as `null` rather than `undefined`: the source
/// declares `T | null` and not `undefined`, through aliases and `Promise` as the binary wire reads
/// them (`OptJs`), so both paths of one function agree.
fn none_is_null(returns: Option<&str>, types: &[LocalType]) -> bool {
    let Some(returns) = returns else { return false };
    let mut members = Vec::new();
    flatten_union(&crate::ts::shape::parse(returns), types, 0, &mut members);
    // A member left unresolved (an import, `any`, too deep) may be `undefined`: keep `undefined`.
    members.iter().any(|m| matches!(m, Shape::Null))
        && !members
            .iter()
            .any(|m| matches!(m, Shape::Undefined | Shape::Any | Shape::Ref(..)))
}

/// The members of a union, with named types resolved from `types` and nested unions flattened.
fn flatten_union(s: &Shape, types: &[LocalType], depth: usize, out: &mut Vec<Shape>) {
    match s {
        _ if depth > 6 => out.push(Shape::Any),
        Shape::Union(members) => {
            for m in members {
                flatten_union(m, types, depth + 1, out);
            }
        }
        Shape::Ref(name, args) => match crate::ts::shape::resolve(name, args, types) {
            Shape::Ref(n, _) if n == *name => out.push(s.clone()),
            resolved => flatten_union(&resolved, types, depth + 1, out),
        },
        _ => out.push(s.clone()),
    }
}

pub(crate) fn mentions_json_value(source: &str) -> bool {
    source
        .split(|c: char| !c.is_alphanumeric() && c != '_')
        .any(|word| word == "serde_json" || word == "Value")
}

pub(crate) fn uses_json_value(api: &PortApi, ty: &str) -> bool {
    api.uses_json_value || mentions_json_value(ty)
}

/// The body of a binding: decode structured arguments, call, encode the result.
fn body(
    api: &PortApi,
    f: &PortFn,
    target: &str,
    kind: Kind,
    constructor: bool,
    none_is_null: bool,
) -> String {
    let mut body = String::new();
    for (n, t) in &f.params {
        // The port's own type names may only resolve inside `port.rs`: let inference pick the type.
        if wire(t) == Wire::Json {
            let helper = if uses_json_value(api, t) {
                "from_json"
            } else {
                "from_plain_json"
            };
            let _ = writeln!(body, "        let {n} = crate::js::{helper}(&{n})?;");
        }
    }
    let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
    let call = format!(
        "{target}({}){}{}",
        args.join(", "),
        if f.is_async { ".await" } else { "" },
        if f.fallible { "?" } else { "" }
    );
    // A unit result: call it, then return `()` (`let out = ()` is a clippy error).
    if !constructor && f.ret.trim() == "()" {
        let _ = writeln!(body, "        {call};\n        Ok(())");
        return body;
    }
    let _ = writeln!(body, "        let out = {call};");
    let result = match (constructor, wire(&f.ret), kind) {
        (true, _, Kind::Napi) => "Ok(Self { inner: out })",
        (true, _, Kind::Wasm) => "Ok(out)",
        (false, Wire::Json, _) => {
            if uses_json_value(api, &f.ret) {
                "crate::js::to_json(&out)"
            } else {
                "crate::js::to_plain_json(&out)"
            }
        }
        (false, Wire::Units, Kind::Napi) => "Ok(napi::bindgen_prelude::Uint16Array::new(out))",
        // napi turns `None` into `null` itself.
        (false, Wire::Native, Kind::Napi) if option_inner(&f.ret).is_some() && none_is_null => {
            "Ok(out)"
        }
        (false, Wire::Native, Kind::Napi) if option_inner(&f.ret).is_some() => {
            "Ok(out.map_or(napi::bindgen_prelude::Either::B(()), napi::bindgen_prelude::Either::A))"
        }
        _ => "Ok(out)",
    };
    let _ = writeln!(body, "        {result}");
    body
}

fn binding_params(f: &PortFn) -> Vec<String> {
    f.params
        .iter()
        .map(|(n, t)| match wire(t) {
            Wire::Json => format!("{n}: String"),
            _ => format!("{n}: {t}"),
        })
        .collect()
}

fn binding_ret(f: &PortFn, kind: Kind, none_is_null: bool) -> String {
    match (wire(&f.ret), kind) {
        (Wire::Json, _) => "String".to_string(),
        (Wire::Units, Kind::Napi) => "napi::bindgen_prelude::Uint16Array".to_string(),
        // napi turns `None` into `null`, right for a source declared `T | null`; otherwise
        // `undefined`, as JS code returning nothing gives.
        (Wire::Native, Kind::Napi) if option_inner(&f.ret).is_some() && !none_is_null => {
            format!(
                "napi::bindgen_prelude::Either<{}, ()>",
                option_inner(&f.ret).unwrap_or_default()
            )
        }
        _ => f.ret.clone(),
    }
}

/// `T` of `Option<T>`.
fn option_inner(ty: &str) -> Option<String> {
    let ty: String = ty.chars().filter(|c| !c.is_whitespace()).collect();
    ty.strip_prefix("Option<")?
        .strip_suffix('>')
        .map(str::to_string)
}

fn bind_class(out: &mut String, api: &PortApi, kind: Kind, c: &PortClass) {
    let (name, js) = (&c.rust_name, &c.js_name);
    let snake = snake_case(name);
    let ctor_params = binding_params(&c.constructor).join(", ");
    let ctor_args: Vec<&str> = c
        .constructor
        .params
        .iter()
        .map(|(n, _)| n.as_str())
        .collect();
    match kind {
        Kind::Napi => {
            let _ = writeln!(
                out,
                "\n/// Class `{js}`.\n#[napi(js_name = \"{js}\")]\npub struct {name} {{\n    inner: port::{name},\n}}\n"
            );
            let _ = writeln!(out, "#[napi]\nimpl {name} {{");
            let _ = writeln!(
                out,
                "    #[napi(constructor)]\n    pub fn new({ctor_params}) -> napi::Result<Self> {{"
            );
            let _ = writeln!(
                out,
                "        run(move || {{\n{}        }})\n    }}",
                indent(&body(
                    api,
                    &c.constructor,
                    &format!("port::{name}::new"),
                    kind,
                    true,
                    false
                ))
            );
            for (m, mutable) in &c.methods {
                let receiver = if *mutable { "&mut self" } else { "&self" };
                let params = binding_params(m);
                let sig = if params.is_empty() {
                    receiver.to_string()
                } else {
                    format!("{receiver}, {}", params.join(", "))
                };
                let _ = writeln!(out, "\n    #[napi(js_name = \"{}\")]", m.js_name);
                let _ = writeln!(
                    out,
                    "    pub fn {}({sig}) -> napi::Result<{}> {{",
                    m.rust_name,
                    binding_ret(m, kind, false)
                );
                let borrow = if *mutable {
                    "&mut self.inner"
                } else {
                    "&self.inner"
                };
                let _ = writeln!(out, "        let inner = {borrow};");
                let _ = writeln!(
                    out,
                    "        run(move || {{\n{}        }})\n    }}",
                    indent(&body(
                        api,
                        m,
                        &format!("inner.{}", m.rust_name),
                        kind,
                        false,
                        false
                    ))
                );
            }
            out.push_str("}\n");
        }
        // PyO3 bindings come from `codegen_py`.
        Kind::Wasm | Kind::Pyo3 | Kind::CAbi | Kind::Ffi => {
            let _ = writeln!(
                out,
                "\nfn {snake}_new_inner({ctor_params}) -> Result<port::{name}, String> {{\n{}}}",
                dedent(&body(
                    api,
                    &c.constructor,
                    &format!("port::{name}::new"),
                    kind,
                    true,
                    false
                ))
            );
            for (m, mutable) in &c.methods {
                let params = binding_params(m);
                let receiver = if *mutable {
                    format!("inner: &mut port::{name}")
                } else {
                    format!("inner: &port::{name}")
                };
                let sig = std::iter::once(receiver)
                    .chain(params)
                    .collect::<Vec<_>>()
                    .join(", ");
                let _ = writeln!(
                    out,
                    "\nfn {snake}_{}_inner({sig}) -> Result<{}, String> {{\n{}}}",
                    m.rust_name.trim_start_matches("r#"),
                    binding_ret(m, kind, false),
                    dedent(&body(
                        api,
                        m,
                        &format!("inner.{}", m.rust_name),
                        kind,
                        false,
                        false
                    ))
                );
            }
            let _ = writeln!(
                out,
                "\n/// Class `{js}`.\n#[wasm_bindgen(js_name = \"{js}\")]\npub struct {name} {{\n    inner: port::{name},\n}}\n"
            );
            let _ = writeln!(out, "#[wasm_bindgen(js_class = \"{js}\")]\nimpl {name} {{");
            let _ = writeln!(
                out,
                "    #[wasm_bindgen(constructor)]\n    pub fn new({ctor_params}) -> Result<{name}, JsError> {{"
            );
            let _ = writeln!(
                out,
                "        let inner = {snake}_new_inner({}).map_err(|e| JsError::new(&e))?;\n        Ok(Self {{ inner }})\n    }}",
                ctor_args.join(", ")
            );
            for (m, mutable) in &c.methods {
                let receiver = if *mutable { "&mut self" } else { "&self" };
                let params = binding_params(m);
                let sig = if params.is_empty() {
                    receiver.to_string()
                } else {
                    format!("{receiver}, {}", params.join(", "))
                };
                let args: Vec<&str> = m.params.iter().map(|(n, _)| n.as_str()).collect();
                let borrow = if *mutable {
                    "&mut self.inner"
                } else {
                    "&self.inner"
                };
                let call_args = std::iter::once(borrow)
                    .chain(args)
                    .collect::<Vec<_>>()
                    .join(", ");
                let _ = writeln!(out, "\n    #[wasm_bindgen(js_name = \"{}\")]", m.js_name);
                let _ = writeln!(
                    out,
                    "    pub fn {}({sig}) -> Result<{}, JsError> {{",
                    m.rust_name,
                    binding_ret(m, kind, false)
                );
                let _ = writeln!(
                    out,
                    "        {snake}_{}_inner({call_args}).map_err(|e| JsError::new(&e))\n    }}",
                    m.rust_name.trim_start_matches("r#")
                );
            }
            out.push_str("}\n");
        }
    }
}

fn indent(text: &str) -> String {
    text.lines().map(|l| format!("    {l}\n")).collect()
}

fn dedent(text: &str) -> String {
    text.lines()
        .map(|l| format!("{}\n", l.strip_prefix("    ").unwrap_or(l)))
        .collect()
}

/// A Rust value as the `serde_json::Value` JS reads back (`index.cjs` revives its markers): a
/// number keeps NaN, infinities and -0, `None` is `null` or `undefined` as the source declares.
fn js_value(ty: &str, x: &str, none_is_null: bool) -> String {
    let t: String = ty.chars().filter(|c| !c.is_whitespace()).collect();
    match t.as_str() {
        "()" => "crate::js::undefined()".into(),
        "f64" => format!("crate::js::number({x})"),
        "Vec<f64>" => {
            format!("serde_json::Value::Array({x}.iter().map(|n| crate::js::number(*n)).collect())")
        }
        _ => match option_inner(&t) {
            Some(inner) => format!(
                "match &{x} {{ Some(v) => {}, None => {} }}",
                js_value(&inner, "(*v)", none_is_null),
                if none_is_null {
                    "serde_json::Value::Null"
                } else {
                    "crate::js::undefined()"
                }
            ),
            None => format!("serde_json::to_value(&{x}).map_err(|e| e.to_string())?"),
        },
    }
}

/// The binding of a function whose port changes arguments in place or prints. Every argument
/// comes in as it would for a plain function; the result is one JSON text,
/// `{"ret": .., "after": {"<position>": ..}, "error": null | "..", "stdout": ".."}`, which
/// `index.cjs` unpacks: it writes each changed argument back into the caller's object, prints
/// `stdout`, then returns `ret` or throws `error`.
fn bind_effects(out: &mut String, kind: Kind, f: &PortFn, none_is_null: bool) {
    let visible = f.visible();
    let params: Vec<String> = visible
        .iter()
        .map(|(n, t, _)| match wire(t) {
            Wire::Json => format!("{n}: String"),
            _ => format!("{n}: {t}"),
        })
        .collect();
    let mut body = String::new();
    for (n, t, mutable) in &visible {
        let keyword = if *mutable { "mut " } else { "" };
        if wire(t) == Wire::Json {
            let _ = writeln!(
                body,
                "        let {keyword}{n} = crate::js::from_json(&{n})?;"
            );
        } else if *mutable {
            let _ = writeln!(body, "        let mut {n} = {n};");
        }
    }
    if f.prints() {
        body.push_str("        let mut stdout = String::new();\n");
    }
    let args: Vec<String> = f
        .params
        .iter()
        .map(|(n, t)| {
            if t.trim_start().starts_with("&mut ") {
                format!("&mut {n}")
            } else {
                n.clone()
            }
        })
        .collect();
    let call = format!(
        "port::{}({}){}",
        f.rust_name,
        args.join(", "),
        if f.is_async { ".await" } else { "" }
    );
    let ret = f.ret.trim();
    let ok = if ret == "()" {
        "crate::js::undefined()".to_string()
    } else {
        js_value(ret, "out", none_is_null)
    };
    if f.fallible {
        let _ = writeln!(
            body,
            "        let (ret, error): (serde_json::Value, Option<String>) = match {call} {{\n            \
             Ok({}) => ({ok}, None),\n            Err(e) => (crate::js::undefined(), Some(e)),\n        }};",
            if ret == "()" { "_" } else { "out" }
        );
    } else if ret == "()" {
        let _ = writeln!(body, "        {call};");
        body.push_str(
            "        let (ret, error): (serde_json::Value, Option<String>) = (crate::js::undefined(), None);\n",
        );
    } else {
        let _ = writeln!(body, "        let out = {call};");
        let _ = writeln!(
            body,
            "        let (ret, error): (serde_json::Value, Option<String>) = ({ok}, None);"
        );
    }
    body.push_str("        let mut after = serde_json::Map::new();\n");
    for (i, (n, t, mutable)) in visible.iter().enumerate() {
        if *mutable {
            let _ = writeln!(
                body,
                "        after.insert(\"{i}\".to_string(), {});",
                js_value(t, n, false)
            );
        }
    }
    let stdout = if f.prints() {
        "stdout"
    } else {
        "String::new()"
    };
    let _ = writeln!(
        body,
        "        crate::js::to_json(&serde_json::json!({{ \"ret\": ret, \"after\": after, \"error\": error, \"stdout\": {stdout} }}))"
    );
    let asyncness = if f.is_async { "async " } else { "" };
    match kind {
        Kind::Napi => {
            let _ = writeln!(out, "#[napi(js_name = \"{}\")]", f.js_name);
            let _ = writeln!(
                out,
                "pub {asyncness}fn {}({}) -> napi::Result<String> {{",
                f.rust_name,
                params.join(", ")
            );
            if f.is_async {
                let _ = writeln!(
                    out,
                    "    run_async(async move {{\n{body}    }})\n    .await"
                );
            } else {
                let _ = writeln!(out, "    run(move || {{\n{body}    }})");
            }
            out.push_str("}\n");
        }
        Kind::Wasm | Kind::Pyo3 | Kind::CAbi | Kind::Ffi => {
            let inner = format!("{}_inner", f.rust_name.trim_start_matches("r#"));
            let _ = writeln!(
                out,
                "{asyncness}fn {inner}({}) -> Result<String, String> {{\n{}}}\n",
                params.join(", "),
                dedent(&body)
            );
            let _ = writeln!(out, "#[wasm_bindgen(js_name = \"{}\")]", f.js_name);
            let _ = writeln!(
                out,
                "pub {asyncness}fn {}({}) -> Result<String, JsError> {{",
                f.rust_name,
                params.join(", ")
            );
            let names: Vec<&str> = visible.iter().map(|(n, _, _)| *n).collect();
            let _ = writeln!(
                out,
                "    {inner}({}){}.map_err(|e| JsError::new(&e))",
                names.join(", "),
                if f.is_async { ".await" } else { "" }
            );
            out.push_str("}\n");
        }
    }
}

fn bind(out: &mut String, api: &PortApi, kind: Kind, f: &PortFn, none_is_null: bool) {
    if f.has_effects() {
        bind_effects(out, kind, f, none_is_null);
        return;
    }
    let params = binding_params(f).join(", ");
    let ret = binding_ret(f, kind, none_is_null);
    let body = body(
        api,
        f,
        &format!("port::{}", f.rust_name),
        kind,
        false,
        none_is_null,
    );
    let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
    let asyncness = if f.is_async { "async " } else { "" };
    match kind {
        Kind::Napi => {
            let _ = writeln!(out, "#[napi(js_name = \"{}\")]", f.js_name);
            let _ = writeln!(
                out,
                "pub {asyncness}fn {}({params}) -> napi::Result<{ret}> {{",
                f.rust_name
            );
            if f.is_async {
                let _ = writeln!(
                    out,
                    "    run_async(async move {{\n{body}    }})\n    .await"
                );
            } else {
                let _ = writeln!(out, "    run(move || {{\n{body}    }})");
            }
            out.push_str("}\n");
        }
        // PyO3 bindings come from `codegen_py`.
        Kind::Wasm | Kind::Pyo3 | Kind::CAbi | Kind::Ffi => {
            // `?` needs a function boundary: the body lives in a private helper.
            let inner = format!("{}_inner", f.rust_name.trim_start_matches("r#"));
            let _ = writeln!(
                out,
                "{asyncness}fn {inner}({params}) -> Result<{ret}, String> {{\n{}}}\n",
                dedent(&body)
            );
            let _ = writeln!(out, "#[wasm_bindgen(js_name = \"{}\")]", f.js_name);
            let _ = writeln!(
                out,
                "pub {asyncness}fn {}({params}) -> Result<{ret}, JsError> {{",
                f.rust_name
            );
            let _ = writeln!(
                out,
                "    {inner}({}){}.map_err(|e| JsError::new(&e))",
                args.join(", "),
                if f.is_async { ".await" } else { "" }
            );
            out.push_str("}\n");
        }
    }
}

/// napi: a panic must not unwind into Node (it aborts the process, and in shadow mode the
/// app), and `Err` becomes a JS error.
const NAPI_RUN: &str = r#"
fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
    payload
        .downcast_ref::<&str>()
        .map(|s| (*s).to_string())
        .or_else(|| payload.downcast_ref::<String>().cloned())
        .unwrap_or_else(|| "unknown panic".into())
}

#[allow(dead_code)]
fn run<T>(f: impl FnOnce() -> Result<T, String>) -> napi::Result<T> {
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
        Ok(result) => result.map_err(napi::Error::from_reason),
        Err(payload) => Err(napi::Error::from_reason(format!("Rust panic: {}", panic_message(&*payload)))),
    }
}

"#;

const NAPI_RUN_ASYNC: &str = r#"
#[allow(dead_code)]
async fn run_async<T>(f: impl std::future::Future<Output = Result<T, String>>) -> napi::Result<T> {
    use futures::FutureExt as _;
    match std::panic::AssertUnwindSafe(f).catch_unwind().await {
        Ok(result) => result.map_err(napi::Error::from_reason),
        Err(payload) => Err(napi::Error::from_reason(format!("Rust panic: {}", panic_message(&*payload)))),
    }
}
"#;

// ---- index.cjs -------------------------------------------------------------------------------

fn spec(f: &PortFn) -> (String, &'static str) {
    let args: Vec<&str> = f
        .params
        .iter()
        .map(|(_, t)| if wire(t) == Wire::Json { "1" } else { "0" })
        .collect();
    let ret = match wire(&f.ret) {
        Wire::Json => "'json'",
        Wire::Units => "'units'",
        Wire::Native => "'raw'",
    };
    (format!("[{}]", args.join(", ")), ret)
}

fn needs_wrap(f: &PortFn) -> bool {
    wire(&f.ret) != Wire::Native || f.params.iter().any(|(_, t)| wire(t) == Wire::Json)
}

pub fn index_cjs(m: &Manifest, api: &PortApi) -> String {
    let load = match m.kind {
        Kind::Napi => format!(
            "// Loads the native module built by `rust-anything build`.\nconst native = require('./{}.node')\n",
            m.lib_name()
        ),
        Kind::Wasm | Kind::Pyo3 | Kind::CAbi | Kind::Ffi => format!(
            "// Loads the wasm-bindgen (nodejs target) output built by `rust-anything build`.\nconst native = require('./pkg/{}.js')\n",
            m.lib_name()
        ),
    };
    let functions: Vec<String> = api
        .functions
        .iter()
        .filter(|f| needs_wrap(f) && !f.has_effects())
        .map(|f| {
            let (args, ret) = spec(f);
            format!("  {}: [{args}, {ret}, {}],", f.js_name, f.is_async)
        })
        .collect();
    // Functions the port runs for their effect on the arguments and the output: structured
    // arguments by position, the positions changed in place, and whether the call is async.
    let effects: Vec<String> = api
        .functions
        .iter()
        .filter(|f| f.has_effects())
        .map(|f| {
            let visible = f.visible();
            // The structured arguments as `prepare` wants them (one 0/1 per argument), and the
            // positions of the arguments changed in place.
            let structured: Vec<&str> = visible
                .iter()
                .map(|(_, t, _)| if wire(t) == Wire::Json { "1" } else { "0" })
                .collect();
            let changed: Vec<String> = visible
                .iter()
                .enumerate()
                .filter(|(_, (_, _, m))| *m)
                .map(|(i, _)| i.to_string())
                .collect();
            format!(
                "  {}: [[{}], [{}], {}],",
                f.js_name,
                structured.join(", "),
                changed.join(", "),
                f.is_async
            )
        })
        .collect();
    let classes: Vec<String> = api
        .classes
        .iter()
        .filter(|c| needs_wrap(&c.constructor) || c.methods.iter().any(|(m, _)| needs_wrap(m)))
        .map(|c| {
            let methods: Vec<String> = c
                .methods
                .iter()
                .map(|(m, _)| {
                    let (args, ret) = spec(m);
                    format!("{}: [{args}, {ret}]", m.js_name)
                })
                .collect();
            format!(
                "  {}: [{}, {{ {} }}],",
                c.js_name,
                spec(&c.constructor).0,
                methods.join(", ")
            )
        })
        .collect();
    if functions.is_empty() && classes.is_empty() && effects.is_empty() {
        return format!("{load}module.exports = native\n");
    }
    format!(
        "{load}{CODEC_CJS}\nmodule.exports = {{ ...native }}\nconst specs = {{\n{}\n}}\nconst classes = {{\n{}\n}}\n{WRAP_CJS}\
         const effects = {{\n{}\n}}\n{EFFECTS_CJS}",
        functions.join("\n"),
        classes.join("\n"),
        effects.join("\n")
    )
}

/// The last layer of `index.cjs`: errors keep their JS class (`TypeError: x` from Rust throws a
/// `TypeError`), panics carry `code: 'RUST_PANIC'`, async exports reject instead of throwing, and
/// a string a Rust `String` cannot hold (a lone surrogate) is refused instead of altered.
/// The parameters a Rust `String` holds, by position: a lone surrogate is refused there.
pub(crate) fn string_params(f: &PortFn) -> Vec<usize> {
    f.params
        .iter()
        .enumerate()
        .filter(|(_, (_, t))| {
            let t: String = t.chars().filter(|c| !c.is_whitespace()).collect();
            matches!(t.as_str(), "String" | "Option<String>" | "Vec<String>")
        })
        .map(|(i, _)| i)
        .collect()
}

pub(crate) fn changed_params<'a>(
    f: &'a ExportedFn,
    api: &PortApi,
) -> Vec<(usize, &'a crate::ts::exports::Param)> {
    match api.functions.iter().find(|p| p.js_name == f.name) {
        Some(port) => port
            .visible()
            .iter()
            .enumerate()
            .filter(|(_, (_, _, mutable))| *mutable)
            .enumerate()
            .filter_map(|(n, (i, _))| f.params.get(i).map(|p| (n, p)))
            .collect(),
        None => f
            .params
            .iter()
            .filter(|p| f.mutates.contains(&p.name))
            .enumerate()
            .collect(),
    }
}

/// `wired` functions already check their arguments and errors in their wire wrapper.
pub fn guard_cjs(api: &PortApi, wired: &[String]) -> String {
    if api.functions.is_empty() {
        return String::new();
    }
    let guards: Vec<String> = api
        .functions
        .iter()
        .filter(|f| !wired.contains(&f.js_name))
        .map(|f| {
            let strings: Vec<String> = string_params(f).iter().map(ToString::to_string).collect();
            format!(
                "  {}: [{}, [{}]],",
                f.js_name,
                f.is_async,
                strings.join(", ")
            )
        })
        .collect();
    format!("const guards = {{\n{}\n}}\n{GUARD_CJS}", guards.join("\n"))
}

const GUARD_CJS: &str = r#"const JS_ERRORS = /^(TypeError|RangeError|SyntaxError|ReferenceError|URIError|EvalError): ([\s\S]*)$/
const jsError = e => {
  const message = typeof e?.message === 'string' ? e.message : ''
  const typed = JS_ERRORS.exec(message)
  if (typed) return new globalThis[typed[1]](typed[2])
  if (/Expected$/.test(e?.code)) return Object.assign(new TypeError(message), { code: e.code })
  if (message.startsWith('Rust panic:')) e.code = 'RUST_PANIC'
  return e
}
const illFormed = v => typeof v === 'string' ? !v.isWellFormed() : Array.isArray(v) && v.some(illFormed)
for (const [name, [isAsync, strings]] of Object.entries(guards)) {
  const f = module.exports[name]
  if (typeof f !== 'function') continue
  const check = a => {
    for (const i of strings) {
      if (illFormed(a[i])) throw new TypeError(`argument ${i + 1} of ${name} has a lone surrogate, which a Rust String cannot hold`)
    }
  }
  module.exports[name] = isAsync
    ? { [name]: async function (...a) { check(a); try { return await f(...a) } catch (e) { throw jsError(e) } } }[name]
    : { [name]: function (...a) { check(a); try { return f(...a) } catch (e) { throw jsError(e) } } }[name]
}
"#;

const CODEC_CJS: &str = r#"
// Structured values cross as JSON text. JSON has no `undefined`, NaN, -0, bigint, Date, Map, Set
// or bytes, and Rust strings no lone surrogates: those travel as one-key marker objects
// (`{"$undefined": true}`, `{"$num": "NaN"}`, `{"$map": [[k, v]]}`, `{"$bytes": [...]}`, ...),
// the same markers recordings use. Plain marker-shaped objects are escaped under `$object`.
const MARKERS = ['$undefined', '$utf16', '$num', '$bigint', '$date', '$bytes', '$buffer', '$map', '$set', '$object']
const single = (v, key) => Object.keys(v).length === 1 && key in v
const looksLikeMarker = v => {
  const keys = Object.keys(v)
  return keys.length === 1 && MARKERS.includes(keys[0])
}
const enc = (v, key = '', skipToJson = false) => {
  if (v === undefined) return { $undefined: true }
  if (typeof v === 'bigint') return { $bigint: String(v) }
  if (typeof v === 'number') return Number.isFinite(v) && !Object.is(v, -0) ? v : { $num: Object.is(v, -0) ? '-0' : String(v) }
  if (typeof v === 'string' && !v.isWellFormed()) return { $utf16: Array.from({ length: v.length }, (_, i) => v.charCodeAt(i)) }
  if (v === null || typeof v !== 'object') return v
  if (Array.isArray(v)) return v.map((x, i) => enc(x, String(i)))
  if (v instanceof Date) return { $date: Number.isNaN(v.getTime()) ? 'Invalid' : v.toISOString() }
  if (typeof Buffer !== 'undefined' && Buffer.isBuffer(v)) return { $buffer: Array.from(v) }
  if (v instanceof Uint8Array) return { $bytes: Array.from(v) }
  if (v instanceof Map) return { $map: [...v].map(([k, x]) => [enc(k), enc(x)]) }
  if (v instanceof Set) return { $set: [...v].map(x => enc(x)) }
  if (!skipToJson && typeof v.toJSON === 'function') return enc(v.toJSON(key), key, true)
  const plain = Object.fromEntries(
    Object.entries(v)
      .filter(([, x]) => typeof x !== 'function')
      .map(([k, x]) => [k, enc(x, k)])
  )
  return looksLikeMarker(plain) ? { $object: plain } : plain
}
const encode = v => JSON.stringify(enc(v))
const revive = v => Array.isArray(v) ? v.map(revive)
  : v !== null && typeof v === 'object'
    ? (single(v, '$object') && v.$object !== null && typeof v.$object === 'object' && !Array.isArray(v.$object)
        ? Object.fromEntries(Object.entries(v.$object).map(([k, x]) => [k, revive(x)]))
      : single(v, '$undefined') ? undefined
      : single(v, '$utf16') ? fromUnits(v.$utf16)
      : single(v, '$num') ? Number(v.$num)
      : single(v, '$bigint') ? BigInt(v.$bigint)
      : single(v, '$date') ? new Date(v.$date)
      : single(v, '$bytes') ? Uint8Array.from(v.$bytes)
      : single(v, '$buffer') ? Buffer.from(v.$buffer)
      : single(v, '$map') ? new Map(v.$map.map(([k, x]) => [revive(k), revive(x)]))
      : single(v, '$set') ? new Set(v.$set.map(revive))
      : Object.fromEntries(Object.entries(v).map(([k, x]) => [k, revive(x)])))
    : v
// Most results carry no marker: skip the walk unless the text has one.
const decode = text => {
  const value = JSON.parse(text)
  return text.includes('"$') ? revive(value) : value
}
const fromUnits = (units) => {
  let out = ''
  for (let i = 0; i < units.length; i += 8192)
    out += String.fromCharCode.apply(null, Array.prototype.slice.call(units, i, i + 8192))
  return out
}
"#;

/// How a call that changes its arguments or prints reaches the caller. The binding returns what
/// the port did as one JSON text; each argument it changed is written back into the caller's own
/// object (nested objects keep their identity where the shape did not change), what it printed
/// goes to `process.stdout`, then the result is returned or the error thrown.
const EFFECTS_CJS: &str = r#"const kindOf = v => Array.isArray(v) ? 'array' : v instanceof Map ? 'map' : v instanceof Set ? 'set'
  : v instanceof Date ? 'date' : ArrayBuffer.isView(v) ? 'typed'
  : v !== null && typeof v === 'object' ? 'object' : 'value'
const merge = (old, fresh) => kindOf(old) !== 'value' && kindOf(old) === kindOf(fresh) && copyBack(old, fresh) ? old : fresh
const copyBack = (target, source) => {
  switch (kindOf(target)) {
    case 'array':
      target.length = source.length
      for (let i = 0; i < source.length; i++) target[i] = merge(target[i], source[i])
      return true
    case 'object': {
      const keys = Object.keys(source)
      const same = Object.keys(target).length === keys.length && Object.keys(target).every((k, i) => k === keys[i])
      const old = { ...target }
      if (!same) for (const k of Object.keys(target)) delete target[k]
      for (const k of keys) target[k] = merge(old[k], source[k])
      return true
    }
    case 'map': {
      const old = new Map(target)
      target.clear()
      for (const [k, v] of source) target.set(k, merge(old.get(k), v))
      return true
    }
    case 'set':
      target.clear()
      for (const v of source) target.add(v)
      return true
    case 'date':
      target.setTime(source.getTime())
      return true
    case 'typed':
      if (target.length !== source.length) return false
      for (let i = 0; i < source.length; i++) target[i] = source[i]
      return true
  }
  return false
}
for (const [name, [structured, changed, isAsync]] of Object.entries(effects)) {
  const call = native[name]
  const finish = (a, text) => {
    const r = decode(text)
    for (const i of changed) if (r.after[i] !== undefined || String(i) in r.after) copyBack(a[i], r.after[i])
    if (r.stdout) process.stdout.write(r.stdout)
    if (r.error !== null) throw new Error(r.error)
    return r.ret
  }
  module.exports[name] = isAsync
    ? async (...a) => finish(a, await call(...prepare(a, structured)))
    : (...a) => finish(a, call(...prepare(a, structured)))
}
"#;

const WRAP_CJS: &str = r#"const convert = result => result === 'json' ? decode : result === 'units' ? fromUnits : x => x
// An omitted structured argument is `undefined`, not a missing value.
const prepare = (a, structured) => Array.from({ length: Math.max(a.length, structured.length) }, (_, i) => structured[i] ? encode(a[i]) : a[i])
// Functions: [structured arguments, result kind, async].
for (const [name, [structured, result, isAsync]] of Object.entries(specs)) {
  const call = native[name]
  const out = convert(result)
  module.exports[name] = isAsync
    ? async (...a) => out(await call(...prepare(a, structured)))
    : (...a) => out(call(...prepare(a, structured)))
}
// Classes: a JS class around the native one, converting arguments and results.
const INNER = Symbol('native')
for (const [name, [ctor, methods]] of Object.entries(classes)) {
  const Native = native[name]
  const Wrapped = { [name]: class { constructor(...a) { this[INNER] = new Native(...prepare(a, ctor)) } } }[name]
  for (const [method, [structured, result]] of Object.entries(methods)) {
    const out = convert(result)
    Wrapped.prototype[method] = function (...a) { return out(this[INNER][method](...prepare(a, structured))) }
  }
  module.exports[name] = Wrapped
}
"#;

// ---- js.rs -----------------------------------------------------------------------------------

pub const JS_RS: &str = concat!(
    r#"//! JS values that JSON cannot express, and the JSON transport of the bindings.

#![forbid(unsafe_code)]

const MARKER_KEYS: [&str; 10] = [
    "$undefined",
    "$utf16",
    "$num",
    "$bigint",
    "$date",
    "$bytes",
    "$buffer",
    "$map",
    "$set",
    "$object",
];

fn is_marker_object(o: &serde_json::Map<String, serde_json::Value>) -> bool {
    o.len() == 1 && o.keys().next().is_some_and(|k| MARKER_KEYS.contains(&k.as_str()))
}

fn parse_json_value(text: &str) -> Result<serde_json::Value, String> {
    let mut de = serde_json::Deserializer::from_str(text);
    de.disable_recursion_limit();
    let value = <serde_json::Value as serde::Deserialize>::deserialize(&mut de)
        .map_err(|e| format!("TypeError: {e}"))?;
    de.end().map_err(|e| format!("TypeError: {e}"))?;
    Ok(value)
}

fn unwrap_object_markers(value: serde_json::Value) -> serde_json::Value {
    match value {
        serde_json::Value::Array(items) => {
            serde_json::Value::Array(items.into_iter().map(unwrap_object_markers).collect())
        }
        serde_json::Value::Object(mut o) => {
            if o.len() == 1
                && o.get("$object")
                    .and_then(serde_json::Value::as_object)
                    .is_some_and(is_marker_object)
                && let Some(serde_json::Value::Object(inner)) = o.remove("$object")
            {
                return serde_json::Value::Object(
                    inner
                        .into_iter()
                        .map(|(k, v)| (k, unwrap_object_markers(v)))
                        .collect(),
                );
            }
            serde_json::Value::Object(
                o.into_iter()
                    .map(|(k, v)| (k, unwrap_object_markers(v)))
                    .collect(),
            )
        }
        other => other,
    }
}

fn is_json_marker_key_token(key_token: &str) -> bool {
    if let Some(inner) = key_token.strip_prefix('"').and_then(|s| s.strip_suffix('"'))
        && !inner.contains('\\')
    {
        return MARKER_KEYS.contains(&inner);
    }
    serde_json::from_str::<String>(key_token)
        .ok()
        .is_some_and(|k| MARKER_KEYS.contains(&k.as_str()))
}

struct JsonMarkerEscaper<'a> {
    bytes: &'a [u8],
    pos: usize,
    /// Output offsets of the objects to wrap under `$object`, spliced in at the end.
    wraps: Vec<usize>,
}

impl<'a> JsonMarkerEscaper<'a> {
    fn skip_ws(&mut self) {
        while matches!(self.bytes.get(self.pos), Some(b' ' | b'\t' | b'\n' | b'\r')) {
            self.pos += 1;
        }
    }

    fn scan_string(&mut self) -> &'a str {
        let start = self.pos;
        self.pos += 1;
        while let Some(&b) = self.bytes.get(self.pos) {
            self.pos += 1;
            if b == b'\\' {
                if self.pos < self.bytes.len() {
                    self.pos += 1;
                }
            } else if b == b'"' {
                break;
            }
        }
        std::str::from_utf8(&self.bytes[start..self.pos]).unwrap_or("")
    }

    fn write_escaped(&mut self, out: &mut String) {
        self.skip_ws();
        match self.bytes.get(self.pos) {
            Some(b'{') => self.write_object(out),
            Some(b'[') => self.write_array(out),
            Some(b'"') => out.push_str(self.scan_string()),
            Some(_) => {
                let start = self.pos;
                while let Some(&b) = self.bytes.get(self.pos) {
                    if matches!(b, b',' | b'}' | b']' | b' ' | b'\t' | b'\n' | b'\r') {
                        break;
                    }
                    self.pos += 1;
                }
                if let Ok(tok) = std::str::from_utf8(&self.bytes[start..self.pos]) {
                    out.push_str(tok);
                }
            }
            None => {}
        }
    }

    fn write_array(&mut self, out: &mut String) {
        self.pos += 1;
        out.push('[');
        let mut first = true;
        loop {
            self.skip_ws();
            if self.bytes.get(self.pos) == Some(&b']') {
                self.pos += 1;
                break;
            }
            if !first {
                out.push(',');
            }
            first = false;
            self.write_escaped(out);
            self.skip_ws();
            match self.bytes.get(self.pos) {
                Some(b',') => self.pos += 1,
                Some(b']') => {
                    self.pos += 1;
                    break;
                }
                _ => break,
            }
        }
        out.push(']');
    }

    fn write_object(&mut self, out: &mut String) {
        self.pos += 1;
        self.skip_ws();
        if self.bytes.get(self.pos) == Some(&b'}') {
            self.pos += 1;
            out.push_str("{}");
            return;
        }
        let obj_start = out.len();
        out.push('{');
        let mut entry_count = 0usize;
        let mut first_key: Option<&'a str> = None;
        loop {
            self.skip_ws();
            if self.bytes.get(self.pos) != Some(&b'"') {
                break;
            }
            if entry_count > 0 {
                out.push(',');
            }
            let key = self.scan_string();
            if entry_count == 0 {
                first_key = Some(key);
            }
            entry_count += 1;
            out.push_str(key);
            out.push(':');
            self.skip_ws();
            if self.bytes.get(self.pos) == Some(&b':') {
                self.pos += 1;
            }
            self.write_escaped(out);
            self.skip_ws();
            match self.bytes.get(self.pos) {
                Some(b',') => self.pos += 1,
                Some(b'}') => {
                    self.pos += 1;
                    break;
                }
                _ => break,
            }
        }
        out.push('}');
        if entry_count == 1 && first_key.is_some_and(is_json_marker_key_token) {
            self.wraps.push(obj_start);
            out.push('}');
        }
    }
}

fn escape_json_markers(text: &str) -> String {
    let mut escaper = JsonMarkerEscaper {
        bytes: text.as_bytes(),
        pos: 0,
        wraps: Vec::new(),
    };
    let mut out = String::with_capacity(text.len());
    escaper.write_escaped(&mut out);
    if escaper.wraps.is_empty() {
        return out;
    }
    escaper.wraps.sort_unstable();
    let prefix = "{\"$object\":";
    let mut wrapped = String::with_capacity(out.len() + escaper.wraps.len() * prefix.len());
    let mut done = 0;
    for at in escaper.wraps {
        wrapped.push_str(&out[done..at]);
        wrapped.push_str(prefix);
        done = at;
    }
    wrapped.push_str(&out[done..]);
    wrapped
}

/// Reads a structured argument sent by `index.cjs`.
pub fn from_json<T: serde::de::DeserializeOwned>(text: &str) -> Result<T, String> {
    if text == "{\"$undefined\":true}" {
        if let Ok(value) = serde_json::from_str::<T>(text) {
            return Ok(value);
        }
        return serde_json::from_str::<T>("null").map_err(|e| format!("TypeError: {e}"));
    }
    let mut de = serde_json::Deserializer::from_str(text);
    de.disable_recursion_limit();
    let value = <T as serde::Deserialize>::deserialize(&mut de).map_err(|e| format!("TypeError: {e}"))?;
    de.end().map_err(|e| format!("TypeError: {e}"))?;
    Ok(value)
}

/// Reads a typed structured argument sent by `index.cjs`, unwrapping `$object` marker escapes.
pub fn from_plain_json<T: serde::de::DeserializeOwned>(text: &str) -> Result<T, String> {
    if text == "{\"$undefined\":true}" {
        return serde_json::from_str::<T>("null").map_err(|e| format!("TypeError: {e}"));
    }
    if !text.contains("\"$object\"") {
        return from_json(text);
    }
    let value = unwrap_object_markers(parse_json_value(text)?);
    serde_json::from_value(value).map_err(|e| format!("TypeError: {e}"))
}

/// Writes a structured result for `index.cjs`.
pub fn to_json<T: serde::Serialize>(value: &T) -> Result<String, String> {
    serde_json::to_string(value).map_err(|e| e.to_string())
}

/// Writes a typed structured result for `index.cjs`, escaping marker-shaped objects under `$object`.
pub fn to_plain_json<T: serde::Serialize>(value: &T) -> Result<String, String> {
    let text = serde_json::to_string(value).map_err(|e| e.to_string())?;
    if !text.contains("\"$") && !text.contains("\\u0024") {
        return Ok(text);
    }
    Ok(escape_json_markers(&text))
}

/// JS `undefined` inside a structured value: `{ a: undefined }` is not `{ a: null }`.
pub fn undefined() -> serde_json::Value {
    serde_json::json!({ "$undefined": true })
}

/// Whether a structured value received from JS was `undefined`.
pub fn is_undefined(value: &serde_json::Value) -> bool {
    value.as_object().is_some_and(|o| {
        o.len() == 1 && o.get("$undefined") == Some(&serde_json::Value::Bool(true))
    })
}

/// A JS string from UTF-16 code units: a plain string when well-formed, else a marker that
/// `index.cjs` turns into the exact JS string, lone surrogates included.
pub fn utf16_string(units: &[u16]) -> serde_json::Value {
    match String::from_utf16(units) {
        Ok(s) => serde_json::Value::String(s),
        Err(_) => serde_json::json!({ "$utf16": units }),
    }
}

/// The UTF-16 code units of a string received from JS, plain or marked.
pub fn string_units(value: &serde_json::Value) -> Option<Vec<u16>> {
    match value {
        serde_json::Value::String(s) => Some(s.encode_utf16().collect()),
        serde_json::Value::Object(o) if o.len() == 1 => o
            .get("$utf16")?
            .as_array()?
            .iter()
            .map(|u| u.as_u64().and_then(|u| u16::try_from(u).ok()))
            .collect(),
        _ => None,
    }
}

/// A JS number inside a structured value. JSON has no NaN, Infinity or -0: those cross as
/// `{"$num": "NaN"}` and friends, which `index.cjs` turns back into numbers.
pub fn number(n: f64) -> serde_json::Value {
    if n.is_nan() {
        serde_json::json!({ "$num": "NaN" })
    } else if n.is_infinite() {
        serde_json::json!({ "$num": if n > 0.0 { "Infinity" } else { "-Infinity" } })
    } else if n == 0.0 && n.is_sign_negative() {
        serde_json::json!({ "$num": "-0" })
    } else if n.fract() == 0.0 && n.abs() < 9_007_199_254_740_992.0 {
        serde_json::Value::from(n as i64)
    } else {
        serde_json::Value::from(n)
    }
}

/// JS `Array.prototype.sort(compare)`, as V8 runs it.
///
/// With a consistent comparator any stable sort agrees with JS. With one that returns NaN or
/// contradicts itself, the order depends on the algorithm: under 64 elements this reproduces
/// V8's TimSort exactly (one run, then binary insertion); longer arrays use Rust's stable sort.
pub fn sort<T>(items: &mut [T], mut compare: impl FnMut(&T, &T) -> f64) {
    let n = items.len();
    if n < 2 {
        return;
    }
    if n >= 64 {
        items.sort_by(|a, b| compare(a, b).partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal));
        return;
    }
    // CountAndMakeRun: the leading ascending run, or strictly descending run (reversed).
    let mut run = 2;
    let descending = compare(&items[1], &items[0]) < 0.0;
    while run < n {
        let order = compare(&items[run], &items[run - 1]);
        if (descending && order >= 0.0) || (!descending && order < 0.0) {
            break;
        }
        run += 1;
    }
    if descending {
        items[..run].reverse();
    }
    // BinaryInsertionSort of the rest.
    for start in run..n {
        let (mut left, mut right) = (0, start);
        while left < right {
            let mid = left + ((right - left) >> 1);
            if compare(&items[start], &items[mid]) < 0.0 {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        items[left..=start].rotate_right(1);
    }
}

/// A number received from JS inside a structured value, plain or marked.
pub fn as_number(value: &serde_json::Value) -> Option<f64> {
    match value {
        serde_json::Value::Number(n) => n.as_f64(),
        serde_json::Value::Object(o) if o.len() == 1 => match o.get("$num")?.as_str()? {
            "NaN" => Some(f64::NAN),
            "Infinity" => Some(f64::INFINITY),
            "-Infinity" => Some(f64::NEG_INFINITY),
            "-0" => Some(-0.0),
            _ => None,
        },
        _ => None,
    }
}
"#,
    include_str!("js_number.rs")
);

// ---- Cargo.toml ------------------------------------------------------------------------------

/// Dependencies the bindings need, as `(name, TOML value)`. `js` is whether the crate has
/// `src/js.rs`: `bridge` writes it when a function takes JSON, and keeps one that is already there.
pub fn required_deps(kind: Kind, api: &PortApi, js: bool) -> Vec<(&'static str, String)> {
    let wire = kind == Kind::Napi && api.functions.iter().any(|f| !f.is_async);
    let json = api.needs_json() || wire || js;
    let any_async = api.all().any(|f| f.is_async);
    let mut deps = Vec::new();
    match kind {
        Kind::Napi => {
            deps.push((
                "napi",
                if any_async {
                    r#"{ version = "3", features = ["async"] }"#.into()
                } else {
                    r#""3""#.into()
                },
            ));
            deps.push(("napi-derive", r#""3""#.into()));
            if any_async {
                deps.push(("futures", r#""0.3""#.into()));
            }
        }
        Kind::Pyo3 => {
            // abi3: one build for every Python from 3.9 on.
            deps.push((
                "pyo3",
                r#"{ version = "0.30", features = ["extension-module", "abi3-py39"] }"#.into(),
            ));
        }
        // The C ABI needs no binding crate.
        Kind::CAbi | Kind::Ffi => {}
        Kind::Wasm => {
            deps.push(("wasm-bindgen", r#""0.2""#.into()));
            if any_async {
                deps.push(("wasm-bindgen-futures", r#""0.4""#.into()));
            }
        }
    }
    // `serde` itself is used only by `src/js.rs`. The binary wire needs `serde_json` alone, and an
    // unused `serde` is a warning on every build, clippy and gate run.
    if js || api.needs_json() {
        deps.push(("serde", r#""1""#.into()));
    }
    if json {
        // JS objects keep insertion order; serde_json sorts keys unless told otherwise. Its
        // default float parser can be off by one ULP; `float_roundtrip` makes it exact.
        deps.push((
            "serde_json",
            r#"{ version = "1", features = ["preserve_order", "float_roundtrip", "unbounded_depth"] }"#.into(),
        ));
    }
    deps
}

/// The cargo feature that compiles a PyO3 crate's `#[pymodule]`. On by default, so the crate
/// builds as a Python extension; a front door that links several units into one binary turns it
/// off (`default-features = false`), since every module defines the same `PyInit__native`.
pub const PYTHON_MODULE: &str = "python-module";
const PYTHON_MODULE_FEATURE: &str =
    "\n[features]\ndefault = [\"python-module\"]\npython-module = []\n";

pub fn cargo_toml(m: &Manifest, api: &PortApi) -> String {
    // A new crate gets `src/js.rs` exactly when a function takes JSON.
    let deps: String = required_deps(m.kind, api, api.needs_json())
        .iter()
        .map(|(name, value)| format!("{name} = {value}\n"))
        .collect();
    let build = if m.kind == Kind::Napi {
        "\n[build-dependencies]\nnapi-build = \"2\"\n"
    } else if m.kind == Kind::Pyo3 {
        PYTHON_MODULE_FEATURE
    } else {
        ""
    };
    format!(
        "[package]\nname = \"{}\"\nversion = \"0.1.0\"\nedition = \"2024\"\nrust-version = \"{MIN_RUST}\"\npublish = false\ndescription = \"Rust port of `{}`, generated by rust-anything\"\n\n\
         [lib]\ncrate-type = [\"cdylib\", \"rlib\"]\n\n[dependencies]\n{deps}{build}\n\
         [profile.release]\nlto = true\n\n[lints.clippy]\nall = {{ level = \"warn\", priority = -1 }}\n\n[lints.rust]\nunused_lifetimes = \"warn\"\ntrivial_numeric_casts = \"warn\"\n",
        m.crate_name, m.unit
    )
}

/// Adds missing required dependencies to an existing Cargo.toml, keeping everything else.
pub fn ensure_deps(cargo: &str, kind: Kind, api: &PortApi, js: bool) -> Result<String, String> {
    let mut doc: toml_edit::DocumentMut = cargo.parse().map_err(|e| format!("Cargo.toml: {e}"))?;
    let deps = doc
        .entry("dependencies")
        .or_insert_with(|| toml_edit::Item::Table(toml_edit::Table::new()))
        .as_table_mut()
        .ok_or("Cargo.toml: [dependencies] is not a table")?;
    for (name, value) in required_deps(kind, api, js) {
        let wanted: toml_edit::Item = format!("x = {value}")
            .parse::<toml_edit::DocumentMut>()
            .map_err(|e| e.to_string())?["x"]
            .clone();
        match deps.get(name) {
            None => {
                deps.insert(name, wanted);
            }
            // napi needs the `async` feature once an async function appears.
            Some(_) if name == "napi" && value.contains("async") => {
                deps.insert(name, wanted);
            }
            Some(_) => {}
        }
    }
    if kind == Kind::Pyo3 {
        add_python_module_feature(&mut doc)?;
    }
    add_cdylib(&mut doc)?;
    Ok(doc.to_string())
}

/// The bindings load from a `cdylib`, which `app lift` takes out of a unit's `crate-type` when it
/// makes the unit a plain library: put it back, keeping the kinds the crate has (`rlib` when it
/// sets none, which is what `rust/app` links against).
fn add_cdylib(doc: &mut toml_edit::DocumentMut) -> Result<(), String> {
    let lib = doc
        .entry("lib")
        .or_insert_with(|| toml_edit::Item::Table(toml_edit::Table::new()))
        .as_table_like_mut()
        .ok_or("Cargo.toml: [lib] is not a table")?;
    let mut kinds = match lib.get("crate-type") {
        None => toml_edit::Array::from_iter(["rlib"]),
        Some(item) => item
            .as_array()
            .ok_or("Cargo.toml: [lib] crate-type is not an array")?
            .clone(),
    };
    if kinds.iter().any(|k| k.as_str() == Some("cdylib")) {
        return Ok(());
    }
    kinds.insert(0, "cdylib");
    lib.insert("crate-type", toml_edit::value(kinds));
    Ok(())
}

/// A crate made before the feature existed gets it, on by default: its regenerated `lib.rs`
/// gates the module on it, and without it the crate would build with no module at all.
fn add_python_module_feature(doc: &mut toml_edit::DocumentMut) -> Result<(), String> {
    let features = doc
        .entry("features")
        .or_insert_with(|| toml_edit::Item::Table(toml_edit::Table::new()))
        .as_table_mut()
        .ok_or("Cargo.toml: [features] is not a table")?;
    if !features.contains_key(PYTHON_MODULE) {
        features.insert(PYTHON_MODULE, toml_edit::value(toml_edit::Array::new()));
    }
    let default = features
        .entry("default")
        .or_insert_with(|| toml_edit::value(toml_edit::Array::new()))
        .as_array_mut()
        .ok_or("Cargo.toml: `default` features is not a list")?;
    if !default.iter().any(|f| f.as_str() == Some(PYTHON_MODULE)) {
        default.push(PYTHON_MODULE);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reads_port_signatures() {
        let source = "//! doc\n\n#![forbid(unsafe_code)]\n\n/// Port of `fuzzyScore` (`a.ts:1`).\n\
            pub fn fuzzy_score(query: String, text: String) -> Result<f64, String> {\n    Ok(1.0)\n}\n\n\
            /// Port of `load` (`a.ts:9`).\npub async fn load(\n    path: Option<String>,\n    data: Vec<serde_json::Value>,\n) -> Result<serde_json::Value, String> {\n    todo!()\n}\n\n\
            fn helper(x: Vec<u8>) -> u8 { 0 }\n\npub fn plain_name(a: f64) -> Vec<u16> {\n    vec![]\n}\n";
        let fns = parse_port(source).functions;
        assert_eq!(fns.len(), 3);
        assert_eq!(fns[0].js_name, "fuzzyScore");
        assert_eq!(
            fns[0].params,
            [
                ("query".into(), "String".into()),
                ("text".into(), "String".into())
            ]
        );
        assert_eq!(
            (fns[0].ret.as_str(), fns[0].fallible, fns[0].is_async),
            ("f64", true, false)
        );
        assert_eq!(fns[1].params[1].1, "Vec<serde_json::Value>");
        assert_eq!(
            (fns[1].ret.as_str(), fns[1].is_async),
            ("serde_json::Value", true)
        );
        assert_eq!(
            (
                fns[2].js_name.as_str(),
                fns[2].ret.as_str(),
                fns[2].fallible
            ),
            ("plainName", "Vec<u16>", false)
        );
    }

    #[test]
    fn none_is_null_only_where_the_source_says_null() {
        let none: Vec<LocalType> = Vec::new();
        assert!(none_is_null(
            Some("\"length\" | \"other-work\" | null"),
            &none
        ));
        assert!(none_is_null(Some("string | null"), &none));
        assert!(none_is_null(Some("null"), &none));
        assert!(!none_is_null(Some("string | undefined"), &none));
        assert!(!none_is_null(Some("string | null | undefined"), &none));
        assert!(!none_is_null(Some("string"), &none));
        assert!(!none_is_null(None, &none));
        // The wire resolves aliases and unwraps `Promise`; the other path must too.
        let types = crate::ts::exports::local_types(
            "a.ts",
            "type Maybe = string | null\n\
             type Loose = Maybe | undefined\n\
             export function f(): Maybe { return null }\n",
        );
        assert!(none_is_null(Some("Maybe"), &types));
        assert!(none_is_null(Some("Promise<string | null>"), &types));
        assert!(none_is_null(Some("Promise<Maybe>"), &types));
        assert!(!none_is_null(Some("Loose"), &types));
        assert!(!none_is_null(Some("Promise<string | undefined>"), &types));
        assert!(!none_is_null(Some("Unknown"), &types));
        // A member that does not resolve may be `undefined`: keep the old answer.
        assert!(!none_is_null(Some("string | null | Unknown"), &types));
        assert!(!none_is_null(Some("Promise<Maybe | Unknown>"), &types));
        // So may one past the depth limit.
        let chain = (0..8)
            .map(|i| format!("type D{i} = D{}\n", i + 1))
            .chain(["type D8 = string | null\n".to_string()])
            .collect::<String>();
        let deep = crate::ts::exports::local_types("d.ts", &chain);
        assert!(none_is_null(Some("D7"), &deep));
        assert!(!none_is_null(Some("D0"), &deep));
    }

    #[test]
    fn binds_an_option_by_the_source_return_type() {
        let api = parse_port(
            "/// Port of `refusal`.\npub fn refusal(raw: String) -> Result<Option<String>, String> {\n    Ok(None)\n}\n",
        );
        let f = &api.functions[0];
        let (mut null, mut undefined) = (String::new(), String::new());
        bind(&mut null, &api, Kind::Napi, f, true);
        bind(&mut undefined, &api, Kind::Napi, f, false);
        assert!(null.contains("-> napi::Result<Option<String>>"), "{null}");
        assert!(!null.contains("Either"), "{null}");
        assert!(undefined.contains("Either<String, ()>"), "{undefined}");
    }

    #[test]
    fn a_path_a_port_imports_is_read_with_its_path() {
        let api = parse_port(
            "use std::path::PathBuf;\n\n/// Port of `locate`.\n\
             pub fn locate(start: PathBuf, roots: Vec<PathBuf>) -> Result<Option<PathBuf>, String> {\n    todo!()\n}\n",
        );
        let locate = &api.functions[0];
        assert_eq!(locate.params[0].1, "std::path::PathBuf");
        assert_eq!(locate.params[1].1, "Vec<std::path::PathBuf>");
        assert_eq!(locate.ret, "Option<std::path::PathBuf>");
        // Spelled with its path already, or defined by the port: left alone.
        let spelled = parse_port(
            "/// Port of `a`.\npub fn a(p: std::path::PathBuf) -> Result<(), String> {\n    todo!()\n}\n",
        );
        assert_eq!(spelled.functions[0].params[0].1, "std::path::PathBuf");
        let own = parse_port(
            "pub struct PathBuf {\n    pub n: i64,\n}\n\n/// Port of `b`.\npub fn b(p: PathBuf) -> Result<(), String> {\n    todo!()\n}\n",
        );
        assert_eq!(own.functions[0].params[0].1, "PathBuf");
    }

    #[test]
    fn type_names_a_port_imports_are_read_with_their_paths() {
        // The bindings repeat these types in another file, which has none of the port's
        // `use` lines.
        let api = parse_port(
            "use std::collections::HashMap;\nuse serde_json::Value;\n\n\
             /// Port of `merge`.\n\
             pub fn merge(\n    base: Value,\n    extra: Option<HashMap<String, Value>>,\n    \
             raw: serde_json::Value,\n) -> Result<Vec<Value>, String> {\n    todo!()\n}\n",
        );
        let merge = &api.functions[0];
        let types: Vec<&str> = merge.params.iter().map(|(_, ty)| ty.as_str()).collect();
        assert_eq!(
            types,
            [
                "serde_json::Value",
                "Option<std::collections::HashMap<String, serde_json::Value>>",
                "serde_json::Value",
            ]
        );
        assert_eq!(merge.ret, "Vec<serde_json::Value>");

        // A type the port defines under one of those names is the port's own.
        let own = parse_port(
            "pub struct Value {\n    pub n: i64,\n}\n\n\
             /// Port of `wrap`.\npub fn wrap(n: i64) -> Result<Value, String> {\n    todo!()\n}\n",
        );
        assert_eq!(own.functions[0].ret, "Value");
        for declared in ["pub type Value = i64;", "pub enum Value {\n    One,\n}"] {
            let own = parse_port(&format!(
                "{declared}\n\n/// Port of `wrap`.\npub fn wrap(n: i64) -> Result<Value, String> {{\n    todo!()\n}}\n"
            ));
            assert_eq!(own.functions[0].ret, "Value", "{declared}");
        }

        // `::` may have whitespace after it: the name behind it already has its path.
        let spaced = parse_port(
            "/// Port of `keep`.\npub fn keep(x: serde_json:: Value) -> Result<serde_json ::Value, String> {\n    todo!()\n}\n",
        );
        assert_eq!(spaced.functions[0].params[0].1, "serde_json:: Value");
        assert_eq!(spaced.functions[0].ret, "serde_json ::Value");
    }

    #[test]
    fn picks_wires() {
        assert_eq!(wire("Vec<String>"), Wire::Native);
        assert_eq!(wire("Option < f64 >"), Wire::Native);
        assert_eq!(wire("Vec<serde_json::Value>"), Wire::Json);
        assert_eq!(wire("Vec<bool>"), Wire::Json);
        assert_eq!(wire("Vec<u16>"), Wire::Units);
    }

    #[test]
    fn a_python_crate_gets_the_module_feature_and_an_older_one_is_given_it() {
        let fns = parse_port("/// Port of `a`.\npub fn a(x: String) -> String {\n    x\n}\n");
        let older = "[package]\nname = \"x\"\n\n[dependencies]\n";
        let out = ensure_deps(older, Kind::Pyo3, &fns, fns.needs_json()).unwrap();
        assert!(out.contains("[features]") && out.contains("python-module = []"));
        assert!(out.contains("default = [\"python-module\"]"));
        // Run again, and on a crate that already has it: nothing is added twice.
        assert_eq!(
            ensure_deps(&out, Kind::Pyo3, &fns, fns.needs_json()).unwrap(),
            out
        );
        // Features the crate has of its own stay.
        let own = format!("{older}\n[features]\ndefault = [\"fast\"]\nfast = []\n");
        let out = ensure_deps(&own, Kind::Pyo3, &fns, fns.needs_json()).unwrap();
        assert!(out.contains("default = [\"fast\", \"python-module\"]"));
        // Other kinds have no module to switch off.
        assert!(
            !ensure_deps(older, Kind::Napi, &fns, fns.needs_json())
                .unwrap()
                .contains("python-module")
        );
    }

    #[test]
    fn a_crate_the_lift_made_a_plain_library_gets_its_cdylib_back() {
        let fns = parse_port("/// Port of `a`.\npub fn a(x: String) -> String {\n    x\n}\n");
        let crate_type = |cargo: &str| {
            let doc: toml_edit::DocumentMut = cargo.parse().unwrap();
            doc["lib"]["crate-type"]
                .as_array()
                .map(|a| {
                    a.iter()
                        .filter_map(|k| k.as_str().map(str::to_string))
                        .collect::<Vec<String>>()
                })
                .unwrap_or_default()
        };
        // What `app lift` leaves: no `[lib]` at all.
        let lifted = "[package]\nname = \"x\"\n\n[dependencies]\n";
        for kind in [Kind::Pyo3, Kind::Napi, Kind::Wasm] {
            let out = ensure_deps(lifted, kind, &fns, fns.needs_json()).unwrap();
            assert_eq!(crate_type(&out), ["cdylib", "rlib"], "{out}");
            // Run again: nothing changes.
            assert_eq!(
                ensure_deps(&out, kind, &fns, fns.needs_json()).unwrap(),
                out
            );
        }
        // Kinds the crate sets stay, and a crate that has cdylib is left as it is.
        let own = "[package]\nname = \"x\"\n\n[lib]\ncrate-type = [\"staticlib\"]\n";
        let out = ensure_deps(own, Kind::Pyo3, &fns, fns.needs_json()).unwrap();
        assert_eq!(crate_type(&out), ["cdylib", "staticlib"]);
        let template = "[package]\nname = \"x\"\n\n[lib]\ncrate-type = [\"cdylib\", \"rlib\"]\n";
        let out = ensure_deps(template, Kind::Napi, &fns, fns.needs_json()).unwrap();
        assert!(out.contains("crate-type = [\"cdylib\", \"rlib\"]"), "{out}");
    }

    #[test]
    fn adds_missing_deps_only() {
        let fns = parse_port(
            "/// Port of `a`.\npub async fn a(x: serde_json::Value) -> Result<(), String> {\n}\n",
        );
        let cargo =
            "[package]\nname = \"x\"\n\n[dependencies]\nnapi = \"3\"\nindexmap = \"2\" # mine\n";
        let out = ensure_deps(cargo, Kind::Napi, &fns, fns.needs_json()).unwrap();
        assert!(out.contains("indexmap = \"2\" # mine"));
        assert!(out.contains("features = [\"async\"]"));
        assert!(out.contains("futures") && out.contains("preserve_order"));
    }

    #[test]
    fn a_napi_crate_gets_serde_only_when_a_function_takes_json() {
        // `js`: the crate has `src/js.rs`, which a new crate gets exactly when `needs_json()`.
        let names = |api: &PortApi, js: bool| -> Vec<&'static str> {
            required_deps(Kind::Napi, api, js)
                .into_iter()
                .map(|(name, _)| name)
                .collect()
        };
        // Numbers and strings cross the binary wire: `serde_json` for the wire, and nothing
        // uses `serde` itself, which would be an unused dependency on every build.
        let plain = parse_port(
            "/// Port of `add`.\npub fn add(a: f64, b: f64) -> Result<f64, String> {\n    Ok(a + b)\n}\n",
        );
        assert!(!plain.needs_json());
        let plain_deps = names(&plain, plain.needs_json());
        assert!(plain_deps.contains(&"serde_json"), "{plain_deps:?}");
        assert!(!plain_deps.contains(&"serde"), "{plain_deps:?}");
        // The same port in a crate that already has `src/js.rs` (`bridge` keeps it, and it uses
        // `serde`): without `serde` the crate would not compile.
        let kept_js = names(&plain, true);
        assert!(
            kept_js.contains(&"serde") && kept_js.contains(&"serde_json"),
            "{kept_js:?}"
        );
        // A JSON parameter gets `src/js.rs`, which uses `serde`.
        let json = parse_port(
            "/// Port of `f`.\npub fn f(v: serde_json::Value) -> Result<serde_json::Value, String> {\n    Ok(v)\n}\n",
        );
        assert!(json.needs_json());
        let json_deps = names(&json, json.needs_json());
        assert!(
            json_deps.contains(&"serde") && json_deps.contains(&"serde_json"),
            "{json_deps:?}"
        );
        // An async-only napi crate has no wire and no JSON: neither is added.
        let only_async = parse_port(
            "/// Port of `a`.\npub async fn a(x: f64) -> Result<f64, String> {\n    Ok(x)\n}\n",
        );
        let async_deps = names(&only_async, only_async.needs_json());
        assert!(
            !async_deps.contains(&"serde") && !async_deps.contains(&"serde_json"),
            "{async_deps:?}"
        );
    }

    #[test]
    fn camel_case_joins_snake_case_words() {
        assert_eq!(camel_case("a_b_c"), "aBC");
        assert_eq!(camel_case("snake_case_name"), "snakeCaseName");
        assert_eq!(camel_case("parse_http_2_xml"), "parseHttp2Xml");
        assert_eq!(camel_case("a__b"), "aB");
    }

    #[test]
    fn camel_case_drops_a_raw_identifier_prefix() {
        assert_eq!(camel_case("r#type"), "type");
        assert_eq!(camel_case("r#match_all"), "matchAll");
    }

    #[test]
    fn camel_case_keeps_names_without_underscores_and_drops_a_trailing_one() {
        assert_eq!(camel_case("name"), "name");
        assert_eq!(camel_case("alreadyCamel"), "alreadyCamel");
        assert_eq!(camel_case("name_"), "name");
        assert_eq!(camel_case(""), "");
    }

    #[test]
    fn indent_adds_four_spaces_to_every_line() {
        assert_eq!(indent("a\nb"), "    a\n    b\n");
        assert_eq!(indent("a\n  b\n"), "    a\n      b\n");
        assert_eq!(indent(""), "");
    }

    #[test]
    fn dedent_removes_four_spaces_and_leaves_shorter_indents_alone() {
        assert_eq!(dedent("    a\n        b\n"), "a\n    b\n");
        assert_eq!(dedent("  a\n   b\nc\n"), "  a\n   b\nc\n");
        assert_eq!(dedent("    a\n  b\n"), "a\n  b\n");
    }

    #[test]
    fn dedent_undoes_indent() {
        let text = "fn f() {\n    1\n}\n";
        assert_eq!(dedent(&indent(text)), text);
        assert_eq!(dedent(&indent("a\nb\n")), "a\nb\n");
    }

    #[test]
    fn the_cjs_codec_keeps_marker_shaped_data() {
        let script = format!(
            "{CODEC_CJS}\n{}",
            r#"
const assert = (ok, what) => { if (!ok) { console.error(what); process.exit(1) } }
const round = v => decode(encode(v))
const plain = [
  { $map: [['a', 1]] },
  { $set: [1, 2] },
  { $date: '2024-01-01T00:00:00.000Z' },
  { $undefined: true },
  { $num: '-0' },
  { $bigint: '7' },
  { $utf16: [0xd800] },
  { $bytes: [1, 2] },
  { $buffer: [3, 4] },
  { $object: 'abc' },
  { $object: { $map: [['nested', 2]] } },
]
for (const v of plain) {
  const out = round(v)
  assert(out !== null && typeof out === 'object', 'plain object ' + JSON.stringify(v))
  assert(!(out instanceof Map || out instanceof Set || out instanceof Date || out instanceof Uint8Array || Buffer.isBuffer(out)), 'not revived as marker ' + JSON.stringify(v))
  assert(JSON.stringify(out) === JSON.stringify(v), 'roundtrip mismatch ' + JSON.stringify(v))
}
assert(JSON.stringify(decode('{"$object":"abc"}')) === '{"$object":"abc"}', 'non-object $object is left intact')
const realMap = new Map([[{ $map: [['k', 1]] }, { $object: 2 }]])
const backMap = round(realMap)
assert(backMap instanceof Map && backMap.size === 1, 'real Map preserved')
const [[mk, mv]] = [...backMap.entries()]
assert(!(mk instanceof Map) && JSON.stringify(mk) === '{"$map":[["k",1]]}', 'map key stays plain object')
assert(JSON.stringify(mv) === '{"$object":2}', 'map value stays plain object')
assert(round(new URL('https://example.com/a')) === 'https://example.com/a', 'toJSON is called before object walk')
const withToJson = round({ toJSON() { return { $map: [['k', 1]] } } })
assert(!(withToJson instanceof Map) && JSON.stringify(withToJson) === '{"$map":[["k",1]]}', 'toJSON marker output stays plain')
const keyedToJson = round({ item: [{ toJSON(k) { return k } }] })
assert(keyedToJson.item[0] === '0', 'toJSON receives array index key')
const namedToJson = round({ field: { toJSON(k) { return k } } })
assert(namedToJson.field === 'field', 'toJSON receives object property key')
const nonReentrant = round({ toJSON() { return { toJSON() { throw new Error('nested root toJSON invoked') }, ok: 1 } } })
assert(JSON.stringify(nonReentrant) === '{"ok":1}', 'toJSON replacement is not re-projected at the root')
const dt = new Date('2024-01-01T00:00:00.000Z')
assert(round(dt) instanceof Date && round(dt).toISOString() === dt.toISOString(), 'Date skips string toJSON and stays Date')
assert(Buffer.isBuffer(round(Buffer.from('hi'))) && round(Buffer.from('hi')).toString() === 'hi', 'Buffer skips Buffer.prototype.toJSON')
"#
        );
        let Ok(out) = std::process::Command::new("node")
            .args(["-e", &script])
            .output()
        else {
            return;
        };
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    #[test]
    fn typed_and_value_bindings_choose_plain_vs_raw_json_helpers() {
        let typed_api = parse_port(
            "/// Port of `typed`.\n\
             pub fn typed(m: HashMap<String, String>) -> Result<HashMap<String, String>, String> {\n    Ok(m)\n}\n",
        );
        let typed = body(
            &typed_api,
            &typed_api.functions[0],
            "crate::port::typed",
            Kind::Napi,
            false,
            false,
        );
        assert!(typed.contains("crate::js::from_plain_json(&m)?"), "{typed}");
        assert!(typed.contains("crate::js::to_plain_json(&out)"), "{typed}");

        for raw_src in [
            "/// Port of `raw`.\n\
             pub fn raw(v: serde_json::Value) -> Result<serde_json::Value, String> {\n    Ok(v)\n}\n",
            "pub type Payload = serde_json::Value;\n\
             /// Port of `raw`.\n\
             pub fn raw(p: Payload) -> Result<Payload, String> {\n    Ok(p)\n}\n",
            "use serde_json::*;\n\
             /// Port of `raw`.\n\
             pub fn raw(m: HashMap<String, Value>) -> Result<HashMap<String, Value>, String> {\n    Ok(m)\n}\n",
        ] {
            let raw_api = parse_port(raw_src);
            let raw = body(
                &raw_api,
                &raw_api.functions[0],
                "crate::port::raw",
                Kind::Napi,
                false,
                false,
            );
            assert!(raw.contains("crate::js::from_json("), "{raw}");
            assert!(raw.contains("crate::js::to_json(&out)"), "{raw}");
        }
    }
}