mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
hanzoskills.com/llms.txt now opens with the install line, the API reference index and the company index, so an agent that lands on any one of the three can find the rest. robots.txt claimed 537 documents while llms.txt counts 920. The number is gone from robots.txt; llms.txt derives it. public/ is regenerated from scripts/site.py, which it had fallen behind: the copy-prompt menu and agent bar were in the generator and not in the committed pages. tests/site.mjs passes against the result. Co-authored-by: Hanzo Dev <[email protected]>
526 lines
27 KiB
HTML
526 lines
27 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>wasm-rust-toolchain</title>
|
|
<meta name="color-scheme" content="dark">
|
|
<style>
|
|
/* Committed to one visual world: a dark instrument panel. No light variant —
|
|
the dot field and the hairline rules only read on black, and a naive
|
|
inversion would wash both out. Every colour is painted explicitly so the page
|
|
never borrows a host background. */
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
|
|
|
|
:root{
|
|
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
|
|
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
|
|
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
|
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
|
|
--font-zen-pixel-square:'Zen Pixel Square',monospace;
|
|
--mono:var(--font-zen-mono);
|
|
--sans:var(--font-zen-sans);
|
|
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
|
|
--r:999px; --r-soft:14px;
|
|
}
|
|
*{box-sizing:border-box}
|
|
html{-webkit-text-size-adjust:100%}
|
|
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
|
|
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
|
|
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
|
|
|
|
/* The dot field. A halftone made of one repeating radial-gradient, faded out
|
|
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
|
|
/* No overflow clip here: the dot field is inset to the box already, and a clip
|
|
would cut off the copy-prompt menu. */
|
|
.hero{position:relative;border-bottom:1px solid var(--line)}
|
|
.hero::before{content:"";position:absolute;inset:0;
|
|
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
|
|
background-size:7px 7px;
|
|
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
pointer-events:none}
|
|
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
|
|
|
|
nav{border-bottom:1px solid var(--line)}
|
|
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
|
|
justify-content:space-between;align-items:center;gap:1rem}
|
|
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--ink);text-decoration:none;
|
|
display:inline-flex;align-items:center;gap:.6rem}
|
|
.brand i{font-style:normal;color:var(--faint)}
|
|
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
|
|
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--soft);text-decoration:none}
|
|
nav a.up:hover{color:var(--ink)}
|
|
|
|
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
|
|
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
|
|
h1 em{font-style:normal;color:var(--faint)}
|
|
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
|
|
|
|
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
|
|
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
|
|
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
|
|
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
|
|
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
|
|
line-height:1.2;font-weight:400}
|
|
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
|
|
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
|
|
.btn.solid:hover{background:#d8d8d4}
|
|
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
|
|
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
|
|
|
|
/* Copy-prompt selector. Each row copies the prompt for its own target. */
|
|
.copy{position:relative;display:inline-flex}
|
|
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
|
|
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
|
|
padding:.4rem;display:flex;flex-direction:column;
|
|
box-shadow:0 12px 32px rgba(0,0,0,.75)}
|
|
.menu[hidden]{display:none}
|
|
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
|
|
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
|
|
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
|
|
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
|
|
white-space:nowrap}
|
|
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
|
|
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
|
|
.mi:hover .mark{color:var(--ink)}
|
|
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
|
|
letter-spacing:.1em;text-transform:uppercase}
|
|
|
|
/* Works-with bar: one scrolling row, name and mark per agent. */
|
|
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
|
|
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
|
|
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
|
|
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
|
|
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
|
|
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
|
|
display:flex;align-items:center}
|
|
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
|
|
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
|
|
-webkit-overflow-scrolling:touch;
|
|
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
|
|
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
|
|
.bar::-webkit-scrollbar{display:none}
|
|
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
|
|
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
|
|
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
|
|
text-decoration:none;background:var(--ground)}
|
|
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
|
|
.agent .mark{width:.95rem;height:.95rem}
|
|
|
|
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
|
|
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
|
|
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
|
|
p{margin:0 0 1rem;max-width:70ch}
|
|
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
|
|
li{margin:.22rem 0}
|
|
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
|
|
text-decoration-color:var(--line-hi)}
|
|
a:hover{text-decoration-color:var(--ink)}
|
|
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
|
|
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
|
|
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
|
|
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
|
|
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
|
|
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
|
|
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
|
|
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
|
|
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
|
|
display:block;overflow-x:auto}
|
|
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
|
|
|
|
.curl{display:block;background:var(--panel);border:1px solid var(--line);
|
|
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
|
|
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
|
|
white-space:pre;line-height:1.9}
|
|
.curl b{color:var(--ink);font-weight:400}
|
|
.curl i{font-style:normal;color:var(--faint)}
|
|
|
|
/* index */
|
|
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
|
|
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
|
|
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
|
|
#q:focus{outline:none;border-color:var(--soft)}
|
|
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
|
|
text-transform:uppercase;margin:0 0 2rem}
|
|
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
|
|
padding-bottom:.45rem}
|
|
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
|
|
border-radius:var(--r-soft);text-decoration:none}
|
|
.row:hover{background:#0a0a0a}
|
|
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
|
|
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
|
|
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
|
|
color:var(--faint);font-size:.85rem}
|
|
footer a{color:var(--soft)}
|
|
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
|
|
margin:0 0 2rem;font-size:.85rem}
|
|
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
|
|
border-bottom:1px solid var(--line);padding-bottom:.4rem}
|
|
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
|
|
.fmap a:hover{text-decoration:underline}
|
|
.fmap div{color:var(--faint);line-height:1.5}
|
|
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
|
|
|
|
@media (max-width:640px){
|
|
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
|
|
.btns{gap:.5rem}
|
|
.btn{padding:.75rem 1.15rem;font-size:.68rem}
|
|
.copy,.copy .btn{width:100%;justify-content:center}
|
|
.menu{left:0;right:0;min-width:0}
|
|
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
|
|
.strip b{border-right:0;padding-right:0}
|
|
.bar{width:100%}
|
|
}
|
|
</style>
|
|
<link rel="alternate" type="text/markdown" href="/wasm-rust-toolchain.md">
|
|
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/wasm-rust-toolchain">
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/wasm-rust-toolchain.md
|
|
Index: https://hanzoskills.com/llms.txt
|
|
Corpus: https://hanzoskills.com/all.md
|
|
Append .md to any path for the markdown twin. -->
|
|
<body>
|
|
<nav><div class="in">
|
|
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
|
|
<a class="up" href="/">All skills</a>
|
|
</div></nav>
|
|
|
|
<div class="wrap">
|
|
<h1>wasm-rust-toolchain</h1><p class="lede">Rust to WebAssembly compilation using wasm-pack, wasm-bindgen, optimization, and JavaScript interop</p><h1>Rust WebAssembly Toolchain</h1>
|
|
<p><strong>Scope</strong>: Compiling Rust to wasm with wasm-pack, wasm-bindgen for JS interop, optimization, and debugging <strong>Lines</strong>: ~340 <strong>Last Updated</strong>: 2025-10-25 <strong>Format Version</strong>: 1.0 (Atomic)</p>
|
|
<hr>
|
|
<h2>When to Use This Skill</h2>
|
|
<p>Activate this skill when:</p>
|
|
<ul><li>Building Rust libraries for browser JavaScript consumption</li><li>Creating npm packages from Rust code</li><li>Setting up wasm-bindgen for JS/Rust interop</li><li>Optimizing Rust-generated wasm binaries</li><li>Debugging Rust wasm modules in browser DevTools</li><li>Handling errors across the Rust/JS boundary</li><li>Publishing Rust wasm packages to npm</li><li>Using no_std for minimal wasm output</li></ul>
|
|
<h2>Core Concepts</h2>
|
|
<h3>Concept 1: Compilation Targets</h3>
|
|
<p><strong>wasm32-unknown-unknown</strong>: Raw wasm without JS bindings <strong>wasm32-wasi</strong>: WASI runtime target <strong>wasm-pack target</strong>: Browser/Node.js with JS glue code</p>
|
|
<pre><code class="lang-bash"># Add wasm targets
|
|
rustup target add wasm32-unknown-unknown
|
|
rustup target add wasm32-wasi
|
|
|
|
# Raw wasm (no JS bindings)
|
|
cargo build --target wasm32-unknown-unknown --release
|
|
|
|
# With wasm-pack (generates JS bindings)
|
|
wasm-pack build --target web</code></pre>
|
|
<pre><code class="lang-rust">// Cargo.toml for wasm-pack projects
|
|
[package]
|
|
name = "my-wasm-lib"
|
|
version = "0.1.0"
|
|
edition = "2021"
|
|
|
|
[lib]
|
|
crate-type = ["cdylib"] # Dynamic library for wasm
|
|
|
|
[dependencies]
|
|
wasm-bindgen = "0.2"
|
|
|
|
[profile.release]
|
|
opt-level = "z" # Optimize for size
|
|
lto = true # Link-time optimization
|
|
codegen-units = 1 # Single codegen unit for smaller binary</code></pre>
|
|
<h3>Concept 2: wasm-bindgen Fundamentals</h3>
|
|
<p><strong>Purpose</strong>: Bridge between Rust and JavaScript</p>
|
|
<p><strong>Key features</strong>:</p>
|
|
<ul><li>Export Rust functions to JS</li><li>Import JS functions to Rust</li><li>Handle complex types (strings, objects, arrays)</li><li>Generate TypeScript definitions</li></ul>
|
|
<pre><code class="lang-rust">use wasm_bindgen::prelude::*;
|
|
|
|
// Export Rust function to JS
|
|
#[wasm_bindgen]
|
|
pub fn greet(name: &str) -> String {
|
|
format!("Hello, {}!", name)
|
|
}
|
|
|
|
// Import JS function to Rust
|
|
#[wasm_bindgen]
|
|
extern "C" {
|
|
#[wasm_bindgen(js_namespace = console)]
|
|
fn log(s: &str);
|
|
|
|
#[wasm_bindgen(js_namespace = Date, js_name = now)]
|
|
fn date_now() -> f64;
|
|
}
|
|
|
|
// Use imported functions
|
|
#[wasm_bindgen]
|
|
pub fn log_timestamp() {
|
|
let timestamp = date_now();
|
|
log(&format!("Current timestamp: {}", timestamp));
|
|
}</code></pre>
|
|
<h3>Concept 3: Type Conversions</h3>
|
|
<p><strong>Supported types</strong>:</p>
|
|
<ul><li>Primitives: i32, f64, bool</li><li>String/str via owned conversion</li><li>JsValue for arbitrary JS values</li><li>Custom structs with #[wasm_bindgen]</li></ul>
|
|
<pre><code class="lang-rust">use wasm_bindgen::prelude::*;
|
|
|
|
#[wasm_bindgen]
|
|
pub struct User {
|
|
name: String,
|
|
age: u32,
|
|
}
|
|
|
|
#[wasm_bindgen]
|
|
impl User {
|
|
#[wasm_bindgen(constructor)]
|
|
pub fn new(name: String, age: u32) -> User {
|
|
User { name, age }
|
|
}
|
|
|
|
#[wasm_bindgen(getter)]
|
|
pub fn name(&self) -> String {
|
|
self.name.clone()
|
|
}
|
|
|
|
#[wasm_bindgen(getter)]
|
|
pub fn age(&self) -> u32 {
|
|
self.age
|
|
}
|
|
|
|
pub fn greet(&self) -> String {
|
|
format!("Hi, I'm {} and I'm {} years old", self.name, self.age)
|
|
}
|
|
}</code></pre>
|
|
<pre><code class="lang-javascript">// Generated JavaScript usage
|
|
import { User } from './pkg/my_wasm_lib.js';
|
|
|
|
const user = new User("Alice", 30);
|
|
console.log(user.name); // "Alice"
|
|
console.log(user.greet()); // "Hi, I'm Alice and I'm 30 years old"</code></pre>
|
|
<h3>Concept 4: Error Handling</h3>
|
|
<p><strong>Result types</strong>: Converted to JS exceptions</p>
|
|
<pre><code class="lang-rust">use wasm_bindgen::prelude::*;
|
|
|
|
#[wasm_bindgen]
|
|
pub fn divide(a: f64, b: f64) -> Result<f64, JsValue> {
|
|
if b == 0.0 {
|
|
return Err(JsValue::from_str("Division by zero"));
|
|
}
|
|
Ok(a / b)
|
|
}
|
|
|
|
// Custom error type
|
|
#[wasm_bindgen]
|
|
pub fn parse_number(s: &str) -> Result<i32, JsValue> {
|
|
s.parse::<i32>()
|
|
.map_err(|e| JsValue::from_str(&format!("Parse error: {}", e)))
|
|
}</code></pre>
|
|
<pre><code class="lang-javascript">// JS catches as exceptions
|
|
try {
|
|
const result = divide(10, 0);
|
|
} catch (e) {
|
|
console.error(e); // "Division by zero"
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>Patterns</h2>
|
|
<h3>Pattern 1: wasm-pack Project Setup</h3>
|
|
<p><strong>When to use</strong>: Starting new Rust wasm library</p>
|
|
<pre><code class="lang-bash"># Install wasm-pack
|
|
⚠️ **SECURITY**: Piping curl to shell is dangerous. For production:</code></pre>
|
|
<h1>Download script first</h1>
|
|
<p>curl -O https://rustwasm.github.io/wasm-pack/installer/init.sh</p>
|
|
<h1>Verify checksum</h1>
|
|
<p>sha256sum init.sh</p>
|
|
<h1>Review content</h1>
|
|
<p>less init.sh</p>
|
|
<h1>Then execute</h1>
|
|
<p>bash init.sh</p>
|
|
<pre><code>For development/learning only:</code></pre>
|
|
<p>curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh</p>
|
|
<h1>Create new project</h1>
|
|
<p>cargo new --lib my-wasm-lib cd my-wasm-lib</p>
|
|
<h1>Add to Cargo.toml</h1>
|
|
<h1>[lib]</h1>
|
|
<h1>crate-type = ["cdylib"]</h1>
|
|
<h1>[dependencies]</h1>
|
|
<h1>wasm-bindgen = "0.2"</h1>
|
|
<h1>Build for different targets</h1>
|
|
<p>wasm-pack build --target web # ES modules for browsers wasm-pack build --target bundler # For webpack/rollup wasm-pack build --target nodejs # Node.js wasm-pack build --target no-modules # Script tag loading</p>
|
|
<pre><code>
|
|
**Benefits**:
|
|
- Automatic JS/TS generation
|
|
- npm-ready package structure
|
|
- Multiple deployment targets
|
|
|
|
### Pattern 2: Async Functions
|
|
|
|
**Use case**: Calling async Rust from JavaScript
|
|
</code></pre>
|
|
<p>use wasm_bindgen::prelude::*; use wasm_bindgen_futures::JsFuture; use web_sys::{Request, RequestInit, Response};</p>
|
|
<p>#[wasm_bindgen] pub async fn fetch_data(url: String) -> Result<JsValue, JsValue> { let mut opts = RequestInit::new(); opts.method("GET");</p>
|
|
<p> let request = Request::new_with_str_and_init(&url, &opts)?;</p>
|
|
<p> let window = web_sys::window().unwrap(); let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?; let resp: Response = resp_value.dyn_into()?;</p>
|
|
<p> let json = JsFuture::from(resp.json()?).await?; Ok(json) }</p>
|
|
<pre><code></code></pre>
|
|
<p>// JavaScript calls async function import { fetch_data } from './pkg';</p>
|
|
<p>async function loadData() { try { const data = await fetch_data('https://api.example.com/data'); console.log(data); } catch (error) { console.error('Fetch failed:', error); } }</p>
|
|
<pre><code>
|
|
### Pattern 3: Size Optimization Pipeline
|
|
|
|
**Use case**: Minimizing wasm bundle size
|
|
</code></pre>
|
|
<h1>Cargo.toml</h1>
|
|
<p>[profile.release] opt-level = "z" # Optimize for size lto = true # Link-time optimization codegen-units = 1 # Single codegen unit panic = "abort" # No panic unwinding strip = true # Strip symbols</p>
|
|
<p>[dependencies] wasm-bindgen = "0.2"</p>
|
|
<h1>Avoid large dependencies</h1>
|
|
<pre><code></code></pre>
|
|
<h1>Build with optimizations</h1>
|
|
<p>wasm-pack build --release --target web</p>
|
|
<h1>Further optimize with wasm-opt</h1>
|
|
<p>wasm-opt -Oz pkg/my_wasm_lib_bg.wasm \ -o pkg/my_wasm_lib_bg.wasm</p>
|
|
<h1>Check size reduction</h1>
|
|
<p>ls -lh pkg/*.wasm</p>
|
|
<pre><code>
|
|
**Results**: Often 50-80% size reduction
|
|
|
|
### Pattern 4: Console Logging
|
|
|
|
**Use case**: Debugging wasm in browser
|
|
</code></pre>
|
|
<p>use wasm_bindgen::prelude::*;</p>
|
|
<p>// Simple console.log #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = console)] fn log(s: &str);</p>
|
|
<p> #[wasm_bindgen(js_namespace = console, js_name = log)] fn log_u32(a: u32);</p>
|
|
<p> #[wasm_bindgen(js_namespace = console, js_name = log)] fn log_many(a: &str, b: &str); }</p>
|
|
<p>// Helper macro macro_rules! console_log { ($($t:tt)<em>) => { log(&format!($($t)</em>)) } }</p>
|
|
<p>#[wasm_bindgen] pub fn debug_example(value: i32) { console_log!("Debug value: {}", value); }</p>
|
|
<pre><code>
|
|
### Pattern 5: Working with Arrays
|
|
|
|
**Use case**: Passing arrays between Rust and JS
|
|
</code></pre>
|
|
<p>use wasm_bindgen::prelude::*;</p>
|
|
<p>// JS array to Rust Vec #[wasm_bindgen] pub fn sum_array(arr: &[i32]) -> i32 { arr.iter().sum() }</p>
|
|
<p>// Return Rust Vec as JS array (requires serde) #[wasm_bindgen] pub fn create_range(n: i32) -> Vec<i32> { (0..n).collect() }</p>
|
|
<p>// Typed arrays for performance use js_sys::Uint8Array;</p>
|
|
<p>#[wasm_bindgen] pub fn process_bytes(data: Uint8Array) -> Uint8Array { let mut bytes = data.to_vec(); // Process bytes for byte in &mut bytes { *byte = byte.wrapping_add(1); } // Return as Uint8Array Uint8Array::from(&bytes[..]) }</p>
|
|
<pre><code>
|
|
### Pattern 6: Source Maps for Debugging
|
|
|
|
**Use case**: Debugging Rust code in browser DevTools
|
|
</code></pre>
|
|
<h1>Build with source maps</h1>
|
|
<p>RUSTFLAGS="-C debuginfo=2" wasm-pack build --dev --target web</p>
|
|
<h1>DevTools will show original Rust source</h1>
|
|
<h1>Set breakpoints in .rs files</h1>
|
|
<pre><code></code></pre>
|
|
<p>// Rust source visible in browser #[wasm_bindgen] pub fn complex_calculation(x: f64) -> f64 { let step1 = x * 2.0; // Breakpoint here shows x value let step2 = step1 + 10.0; step2.sqrt() }</p>
|
|
<pre><code>
|
|
### Pattern 7: no_std for Minimal Binaries
|
|
|
|
**When to use**: Extremely size-constrained environments
|
|
</code></pre>
|
|
<p>#![no_std]</p>
|
|
<p>extern crate alloc; use alloc::string::String; use alloc::format; use wasm_bindgen::prelude::*;</p>
|
|
<p>#[wasm_bindgen] pub fn minimal_greet(name: &str) -> String { format!("Hello, {}!", name) }</p>
|
|
<pre><code>
|
|
**Benefits**:
|
|
- Smaller binary size (no std library)
|
|
- Faster compilation
|
|
- Explicit allocation control
|
|
|
|
### Pattern 8: Testing wasm Code
|
|
|
|
**Use case**: Unit testing Rust wasm modules
|
|
</code></pre>
|
|
<p>#[cfg(test)] mod tests { use super::*;</p>
|
|
<p> #[test] fn test_greet() { assert_eq!(greet("World"), "Hello, World!"); } }</p>
|
|
<p>// Browser tests with wasm-pack #[cfg(test)] mod wasm_tests { use wasm_bindgen_test::*;</p>
|
|
<p> #[wasm_bindgen_test] fn test_in_browser() { assert_eq!(1 + 1, 2); } }</p>
|
|
<pre><code></code></pre>
|
|
<h1>Run native tests</h1>
|
|
<p>cargo test</p>
|
|
<h1>Run in headless browser</h1>
|
|
<p>wasm-pack test --headless --firefox wasm-pack test --headless --chrome</p>
|
|
<pre><code>
|
|
---
|
|
|
|
## Quick Reference
|
|
|
|
### wasm-pack Commands
|
|
</code></pre>
|
|
<p>Command | Purpose ---------------------------------|---------------------------------- wasm-pack new my-lib | Create new project wasm-pack build | Build for bundler target wasm-pack build --target web | Build for ES modules wasm-pack build --target nodejs | Build for Node.js wasm-pack test --headless --firefox | Run browser tests wasm-pack publish | Publish to npm</p>
|
|
<pre><code>
|
|
### Build Targets
|
|
</code></pre>
|
|
<p>Target | Use Case | Import Style ------------|---------------------------|--------------------------- web | ES modules in browsers | import <em> from './pkg' bundler | Webpack/Rollup/Parcel | import </em> from 'pkg' nodejs | Node.js applications | const pkg = require('pkg') no-modules | Script tag (legacy) | <script src="pkg.js"></p>
|
|
<pre><code>
|
|
### Key Guidelines
|
|
</code></pre>
|
|
<p>✅ DO: Use wasm-pack for browser projects ✅ DO: Enable LTO and size optimization in release ✅ DO: Use wasm-opt for production builds ✅ DO: Return Result<T, JsValue> for fallible functions ✅ DO: Use console logging for debugging</p>
|
|
<p>❌ DON'T: Include large dependencies unnecessarily ❌ DON'T: Forget to handle errors from JS boundary ❌ DON'T: Use blocking operations in async contexts</p>
|
|
<pre><code>
|
|
---
|
|
|
|
## Anti-Patterns
|
|
|
|
### Critical Violations
|
|
</code></pre>
|
|
<p>// ❌ NEVER: Block async execution #[wasm_bindgen] pub async fn bad_async() -> Result<(), JsValue> { std::thread::sleep(std::time::Duration::from_secs(5)); // Blocks! Ok(()) }</p>
|
|
<p>// ✅ CORRECT: Use web timers use wasm_bindgen_futures::JsFuture; use web_sys::window;</p>
|
|
<p>#[wasm_bindgen] pub async fn good_async() -> Result<(), JsValue> { let promise = js_sys::Promise::new(&mut |resolve, _| { window() .unwrap() .set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, 5000) .unwrap(); }); JsFuture::from(promise).await?; Ok(()) }</p>
|
|
<pre><code>
|
|
❌ **Blocking in wasm**: Freezes browser, terrible UX
|
|
✅ **Correct approach**: Use browser APIs and async
|
|
|
|
### Common Mistakes
|
|
</code></pre>
|
|
<p>// ❌ Don't: Clone strings excessively #[wasm_bindgen] pub fn process_many_strings(input: String) -> String { let copy1 = input.clone(); // Unnecessary allocation let copy2 = copy1.clone(); // Another allocation copy2.to_uppercase() }</p>
|
|
<p>// ✅ Correct: Use references #[wasm_bindgen] pub fn process_strings_efficiently(input: &str) -> String { input.to_uppercase() // Single allocation for result }</p>
|
|
<pre><code>
|
|
❌ **Excessive cloning**: Slower, uses more memory
|
|
✅ **Better**: Use string slices (&str) when possible
|
|
|
|
### Size Bloat Anti-Pattern
|
|
</code></pre>
|
|
<h1>❌ Don't: Include heavy dependencies</h1>
|
|
<p>[dependencies] wasm-bindgen = "0.2" tokio = { version = "1", features = ["full"] } # Huge! serde_json = "1" # Large regex = "1" # Large</p>
|
|
<h1>✅ Correct: Minimal dependencies</h1>
|
|
<p>[dependencies] wasm-bindgen = "0.2" serde-wasm-bindgen = "0.5" # Lighter than serde_json</p>
|
|
<pre><code>
|
|
❌ **Heavy dependencies**: 500KB+ wasm files
|
|
✅ **Better**: Use lightweight, wasm-specific crates
|
|
|
|
---
|
|
|
|
## Related Skills
|
|
|
|
- `wasm-fundamentals.md` - Core WebAssembly concepts and module structure
|
|
- `wasm-browser-integration.md` - Loading and using wasm in browsers
|
|
- `rust-memory-management.md` - Understanding ownership for wasm
|
|
- `frontend-state-management.md` - Managing state with Rust wasm
|
|
- `test-unit.md` - Unit testing strategies for Rust code
|
|
|
|
---
|
|
|
|
**Last Updated**: 2025-10-25
|
|
**Format Version**: 1.0 (Atomic)
|
|
</code></pre>
|
|
<footer>
|
|
<div class="fmap">
|
|
<div><b>Build</b>
|
|
<a href="https://hanzo.app">hanzo.app</a> app builder
|
|
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
|
|
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
|
|
<div><b>Run</b>
|
|
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
|
|
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
|
|
<div><b>Account</b>
|
|
<a href="https://hanzo.id">hanzo.id</a> sign in
|
|
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
|
|
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
|
|
<div><b>Company</b>
|
|
<a href="https://hanzo.ai">hanzo.ai</a> canonical
|
|
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
|
|
</div>
|
|
<div class="fend"><a href="/wasm-rust-toolchain.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |