The official browser adaptation package for Puddi. Call JavaScript from Puddi and expose Puddi handlers to the page. Make requests, work with URLs and history, and save browser state.
Use Puddi v0.1.2 with the browser target. The page needs WebAssembly GC. HTTP requests and awaiting JavaScript promises also need WebAssembly JSPI.
pud add github.com/puddi-lang/puddi-web@0.2.0In src/main.pud, use the package to read the current URL and populate a heading.
import puddi_web.location
import puddi_web.ui
fn main() -> Result<(), AnyErr> {
let heading = ui.required("#heading")?
let name = location.current()?.query("name").unwrap_or("Puddi")
heading.set_text("Hello {name}")
Ok(())
}
Build and download the matching host adapter into the same directory as the generated puddi.mjs.
pud build --target browser
curl -fL https://github.com/puddi-lang/puddi-web/releases/download/v0.2.0/puddi-web.mjs \
-o target/browser/puddi-web.mjsKeep your HTML in your project and copy it over target/browser/index.html after each build. Replace my-app.wasm with the filename produced by pud build.
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Puddi Web</title>
<h1 id="heading">Loading</h1>
<script type="module">
import { loadWeb } from "./puddi-web.mjs";
try {
const app = await loadWeb("./my-app.wasm");
if (await app.run() !== 0) throw new Error("The program exited with an error");
} catch (error) {
document.querySelector("#heading").textContent = "Could not start the app";
console.error(error);
}
</script>
</html>Serve the output over HTTP during development, for example with python3 -m http.server --bind 127.0.0.1 --directory target/browser 8000, then open localhost with a sample query. Deploy the same directory to any static host that serves ES modules and WebAssembly. The host adapter has no npm dependencies.
Field Notes is a responsive draft editor. It fetches a writing prompt from the same site, restores a local draft, and updates the URL with the note title when you save.
git clone --branch v0.2.0 https://github.com/puddi-lang/puddi-web.git
cd puddi-web/examples/field-notes
node build.mjs
python3 -m http.server --bind 127.0.0.1 --directory target/browser 8000Open Field Notes in a recent Chromium-based browser. The example builder uses pud on PATH. Set PUD to use a specific executable.
Particle Field is an interactive WebGL showcase. Puddi seeds up to 32,768 particles and blends between three shapes. The example uses the JS bridge for setup and a numeric Wasm export for each frame.
| Module | Operations |
|---|---|
puddi_web.js |
call(name, args), call_async(name, args), expose(name, handler), and unexpose(name) |
puddi_web.http |
get(url), post_json(url, value), and Request.new(method, url) with headers, a text or JSON body, credentials, and timeout |
puddi_web.location |
current(), resolve(input), push(url), and replace(url). A Url provides the absolute URL, origin, path, search, fragment, query(name), query_all(name), and with_query(name, value). |
puddi_web.storage |
Store.local(namespace) and Store.session(namespace) with get, set, remove, get_json, and set_json |
puddi_web.ui |
required(selector) binds an element, text(tag, content) creates an element with plain text, and on_submit(form, handler) runs a synchronous handler after native form validation and prevents navigation. |
Pass an object of named functions as loadWeb(source, { bindings }). Puddi calls those functions with positional JSON arguments. Use js.call for immediate results and js.call_async(...).await for promises.
import puddi_web.js
import std.json.{Json}
async fn main() -> Result<(), AnyErr> {
let prefix = js.call_async("loadPrefix", []).await?.as_str().unwrap_or("")
js.expose("format", |args| {
match args.get(0).and_then(|value| value.as_str()) {
Some(title) -> Ok(Json.String("{prefix} {title}"))
None -> Err("expected a title")
}
})?
Ok(())
}
import { loadWeb } from "./puddi-web.mjs";
const app = await loadWeb("./my-app.wasm", {
bindings: {
async loadPrefix() { return "Note"; },
},
});
if (await app.run() !== 0) throw new Error("Could not start the app");
console.log(app.callPuddi("format", "Coastline")); // Note CoastlineEach app instance has its own bindings and exposed handlers. js.expose takes a synchronous fn(List<Json>) -> Result<Json, Str>. It rejects duplicate names. js.unexpose(name) removes the handler and releases its captured values. A JS binding can call an exposed handler on the same instance before returning.
Values follow JSON semantics with finite numbers and well-formed Unicode. Pass large integer identifiers as strings to preserve precision. A JS binding that returns undefined produces JSON null. JS exceptions, promise rejections, and invalid results become WebError in Puddi. callPuddi throws a PuddiCallError with exportName and code for an unavailable bridge, an unknown handler, a handler error, or a trap.
send().await returns a response for any HTTP status. Use response.ok() or response.require_ok()? when a successful status is required. Read the body with text() or json(). Header lookup is case-insensitive. Responses are buffered as UTF-8 text.
Relative URLs resolve against the page's base URL. The browser applies its usual CORS and credentials rules. Requests default to same-origin credentials and a 15-second deadline, including body reads. A timeout of zero disables the deadline.
import puddi_web.http
import std.json.{Json}
async fn read_settings() -> Result<Json, AnyErr> {
let response = http.Request.new("GET", "./settings.json")
.header("Accept", "application/json")
.timeout_ms(5_000)
.send().await?
let data = response.require_ok()?.json()?
Ok(data)
}
query returns the first value and query_all preserves duplicates in order. with_query changes a copy of the URL. Pass None to remove the named parameter. History operations update the current document under the browser's same-origin rules. URL Standard · HTML History API
Store keys are scoped to the browser origin, storage type, and application namespace. Reads distinguish a missing key (Ok(None)) from a stored empty string. Access, quota, and JSON errors are returned as WebError. HTML Web Storage
Use std.dom directly for richer DOM changes. Bind form listeners once per page with Puddi 0.1.2. WebError is available from puddi_web and supports ? conversion into AnyErr.
loadWeb accepts the same options as the generated load function, including output, imports, and additional host operations. Pair this release of the adapter with this release of the package. The adapter runs on the browser's main thread.
Available under either the MIT License or the Apache License 2.0.