wasm_bindgen_cli_support/
wasm2es6js.rs1use anyhow::{bail, Error};
2use base64::{prelude::BASE64_STANDARD, Engine as _};
3use std::collections::HashSet;
4use std::fmt::Write;
5use walrus::Module;
6
7pub struct Config {
8 base64: bool,
9 fetch_path: Option<String>,
10}
11
12pub struct Output {
13 module: Module,
14 base64: bool,
15 fetch_path: Option<String>,
16}
17
18impl Config {
19 pub fn new() -> Config {
20 Config {
21 base64: false,
22 fetch_path: None,
23 }
24 }
25
26 pub fn base64(&mut self, base64: bool) -> &mut Self {
27 self.base64 = base64;
28 self
29 }
30
31 pub fn fetch(&mut self, path: Option<String>) -> &mut Self {
32 self.fetch_path = path;
33 self
34 }
35
36 pub fn generate(&mut self, wasm: &[u8]) -> Result<Output, Error> {
37 if !self.base64 && self.fetch_path.is_none() {
38 bail!("one of --base64 or --fetch is required");
39 }
40 let module = Module::from_buffer(wasm)?;
41 Ok(Output {
42 module,
43 base64: self.base64,
44 fetch_path: self.fetch_path.clone(),
45 })
46 }
47}
48
49fn push_index_identifier(i: usize, s: &mut String) {
52 let letter = b'a' + ((i % 26) as u8);
53 s.push(letter as char);
54 if i >= 26 {
55 write!(s, "{}", i / 26).unwrap();
56 }
57}
58
59fn args_are_optional(name: &str) -> bool {
60 name == "__wbindgen_thread_destroy"
61}
62
63pub fn interface(module: &Module) -> Result<String, Error> {
64 let mut exports = String::new();
65 module_export_types(module, |name, ty| {
66 writeln!(exports, " readonly {name}: {ty};").unwrap();
67 });
68 Ok(exports)
69}
70
71pub fn typescript(module: &Module) -> Result<String, Error> {
72 let mut exports = "/* tslint:disable */\n/* eslint-disable */\n".to_string();
73 module_export_types(module, |name, ty| {
74 writeln!(exports, "export const {name}: {ty};").unwrap();
75 });
76 Ok(exports)
77}
78
79fn module_export_types(module: &Module, mut export: impl FnMut(&str, &str)) {
82 for entry in module.exports.iter() {
83 match entry.item {
84 walrus::ExportItem::Function(id) => {
85 let func = module.funcs.get(id);
86 let ty = module.types.get(func.ty());
87 let ts_type = function_type_to_ts(ty, args_are_optional(&entry.name));
88 export(&entry.name, &ts_type);
89 }
90 walrus::ExportItem::Memory(_) => export(&entry.name, "WebAssembly.Memory"),
91 walrus::ExportItem::Table(_) => export(&entry.name, "WebAssembly.Table"),
92 walrus::ExportItem::Global(_) => continue,
93 walrus::ExportItem::Tag(_) => export(&entry.name, "WebAssembly.Tag"),
94 };
95 }
96}
97fn val_type_to_ts(ty: walrus::ValType) -> &'static str {
98 match ty {
101 walrus::ValType::I32 | walrus::ValType::F32 | walrus::ValType::F64 => "number",
102 walrus::ValType::I64 => "bigint",
103 walrus::ValType::Ref(_) => "any",
105 walrus::ValType::V128 => "any",
110 }
111}
112fn function_type_to_ts(function: &walrus::Type, all_args_optional: bool) -> String {
113 let mut out = String::new();
114
115 out.push('(');
117 for (i, arg_type) in function.params().iter().enumerate() {
118 if i > 0 {
119 out.push_str(", ");
120 }
121
122 push_index_identifier(i, &mut out);
123 if all_args_optional {
124 out.push('?');
125 }
126 out.push_str(": ");
127 out.push_str(val_type_to_ts(*arg_type));
128 }
129 out.push(')');
130
131 out.push_str(" => ");
133
134 let results = function.results();
136 match results.len() {
139 0 => out.push_str("void"),
140 1 => out.push_str(val_type_to_ts(results[0])),
141 _ => {
142 out.push('[');
143 for (i, result) in results.iter().enumerate() {
144 if i > 0 {
145 out.push_str(", ");
146 }
147 out.push_str(val_type_to_ts(*result));
148 }
149 out.push(']');
150 }
151 }
152
153 out
154}
155
156impl Output {
157 pub fn typescript(&self) -> Result<String, Error> {
158 let mut ts = typescript(&self.module)?;
159 if self.base64 {
160 ts.push_str("export const booted: Promise<boolean>;\n");
161 }
162 Ok(ts)
163 }
164
165 pub fn js_and_wasm(mut self) -> Result<(String, Option<Vec<u8>>), Error> {
166 let mut js_imports = String::new();
167 let mut exports = String::new();
168 let mut set_exports = String::new();
169 let mut imports = String::new();
170
171 let mut set = HashSet::new();
172 for entry in self.module.imports.iter() {
173 if !set.insert(&entry.module) {
174 continue;
175 }
176
177 let mut name = String::new();
178 push_index_identifier(set.len(), &mut name);
179
180 js_imports.push_str(&format!(
181 "import * as import_{name} from '{}';\n",
182 entry.module
183 ));
184 imports.push_str(&format!("'{}': import_{name}, ", entry.module));
185 }
186
187 for entry in self.module.exports.iter() {
188 exports.push_str("export let ");
189 exports.push_str(&entry.name);
190 exports.push_str(";\n");
191 set_exports.push_str(&entry.name);
192 set_exports.push_str(" = wasm.exports.");
193 set_exports.push_str(&entry.name);
194 set_exports.push_str(";\n");
195 }
196
197 if self.unstart() {
216 set_exports.push_str("wasm.exports.__wasm2es6js_start();\n");
217 }
218
219 let inst = format!(
220 "
221 WebAssembly.instantiate(bytes,{{ {imports} }})
222 .then(obj => {{
223 const wasm = obj.instance;
224 {set_exports}
225 }})
226 ",
227 );
228 let wasm = self.module.emit_wasm();
229 let (bytes, booted) = if self.base64 {
230 (
231 format!(
232 "
233 let bytes;
234 const base64 = \"{base64}\";
235 if (typeof Buffer === 'undefined') {{
236 bytes = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
237 }} else {{
238 bytes = Buffer.from(base64, 'base64');
239 }}
240 ",
241 base64 = BASE64_STANDARD.encode(&wasm)
242 ),
243 inst,
244 )
245 } else if let Some(ref path) = self.fetch_path {
246 (
247 String::new(),
248 format!(
249 "
250 fetch('{path}')
251 .then(res => res.arrayBuffer())
252 .then(bytes => {inst})
253 "
254 ),
255 )
256 } else {
257 bail!("the option --base64 or --fetch is required");
258 };
259 let js = format!(
260 "\
261 {js_imports}
262 {bytes}
263 export const booted = {booted};
264 {exports}
265 ",
266 );
267 let wasm = if self.base64 { None } else { Some(wasm) };
268 Ok((js, wasm))
269 }
270
271 fn unstart(&mut self) -> bool {
275 let start = match self.module.start.take() {
276 Some(id) => id,
277 None => return false,
278 };
279 self.module.exports.add("__wasm2es6js_start", start);
280 true
281 }
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287
288 #[test]
289 fn test_push_index_identifier() {
290 fn index_identifier(i: usize) -> String {
291 let mut s = String::new();
292 push_index_identifier(i, &mut s);
293 s
294 }
295
296 assert_eq!(index_identifier(0), "a");
297 assert_eq!(index_identifier(1), "b");
298 assert_eq!(index_identifier(25), "z");
299 assert_eq!(index_identifier(26), "a1");
300 assert_eq!(index_identifier(27), "b1");
301 assert_eq!(index_identifier(51), "z1");
302 assert_eq!(index_identifier(52), "a2");
303 assert_eq!(index_identifier(53), "b2");
304 assert_eq!(index_identifier(260), "a10");
305 assert_eq!(index_identifier(261), "b10");
306 }
307}