feat(widgets-rs): widget-web, PsychoScript's browser bindings as a crate here

A new Rust workspace, packages/widgets-rs, with crates/widget-web: psychoscript-web from PsychoScript's web branch
(e16ce7e), renamed (lib widget_web), on psychoscript 0.1 from crates.io instead of a path to a patched copy.

psychoscript 0.1 always has typed arrays, so the two Runtime::typed_arrays(true) calls go, and the test that a plain
run has none now says every run has them. Otherwise the code is as it was.

The tests read the fixtures (packages/widget/test/fixtures) and the preludes (packages/widget/src) in place instead of
copies. The views they compare byte for byte, the copies' <name>.wire files (JSON.stringify(view)), are now written
from each fixture's view in the test, the same bytes for all 46.
This commit is contained in:
Sebastian Herrlinger 2026-11-26 14:58:25 +01:00
parent 9e274cdc0f
commit f90b351ae8
21 changed files with 7006 additions and 0 deletions

1
packages/widgets-rs/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/target/

1372
packages/widgets-rs/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,12 @@
[workspace]
resolver = "3"
members = ["crates/widget-web"]
[workspace.package]
edition = "2024"
rust-version = "1.99.1"
license = "MIT"
[profile.release]
lto = "thin"
codegen-units = 1

View file

@ -0,0 +1,35 @@
[package]
name = "widget-web"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish = false
description = "PsychoScript in the browser: wasm-bindgen bindings that compile a program once and run it with a JSON input, or live with __host, single-threaded"
[lib]
name = "widget_web"
crate-type = ["cdylib", "rlib"]
[features]
default = ["language"]
# The language: `Program` and `LiveRun`. The web package builds it into `widget_web_bg.wasm`.
language = ["dep:psychoscript", "dep:serde", "dep:url", "dep:web-time", "dep:ryu-js"]
[dependencies]
psychoscript = { version = "0.1", optional = true }
serde = { version = "1", optional = true }
serde_json = { version = "1", features = ["preserve_order"] }
url = { version = "2.5", optional = true }
# ECMAScript `Number::toString`, for keys and numbers in native view trees (`tree`).
ryu-js = { version = "1", optional = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen = "0.2"
js-sys = "0.3"
web-time = { version = "1.1", optional = true }
# The tree tests read numbers like 123456789012345680000 from the fixtures: they must parse exactly; the live tests
# read views 100 levels deep.
[dev-dependencies]
serde_json = { version = "1", features = ["preserve_order", "float_roundtrip", "unbounded_depth"] }

View file

@ -0,0 +1,105 @@
# widget-web
PsychoScript in the browser: wasm-bindgen bindings over the `psychoscript` crate (crates.io, 0.1) for hosts that run on
one thread (a Web Worker) and hand programs JSON. The web counterpart of PsychoScript's `psychoscript-mobile`; the
widget host that uses it is `packages/widgets-rs/web`.
## JavaScript API (`wasm-bindgen --target web`)
```ts
class Program {
constructor(source: string, inputName?: string) // compile once; throws PsychoScriptError
run(inputJson: string, timeoutMs?: number, maxOutputBytes?: number): string // one run, its completion value as JSON
runStep(inputJson: string, timeoutMs?: number, maxOutputBytes?: number): string // a native widget step (below)
runDraw(inputJson: string, timeoutMs?: number, maxOutputBytes?: number): string // a native draw step's commands
startLive(inputJson: string, options?: { sliceBudgetMs?: number; maxPostsPerSecond?: number; httpsHosts?: string[];
allowLocalNetwork?: boolean; native?: boolean }): LiveRun
}
class LiveRun {
pump(maxMs: number): number // -3 ended (see exit()), -2 still computing: pump again soon,
// -1 waiting with no timer, else ms until its next sleep ends
takeBytes(): Uint8Array // the GPU batches' bytes in that outbox, which they name by [offset, length]
takeOutbox(): string // JSON array: { type: "post", message } | { type: "warning", message }
// | { type: "fetch", id, url, method, headers, body?|body64?, timeoutMs, maxResponseBytes }
// | { type: "cancel", id }
deliver(messageJson: string): void
fetchDone(id: number, metaJson: string /* { status, url, headers } */, body: Uint8Array): void
fetchFailed(id: number, kind: "Network" | "Timeout" | "TooLarge", message: string): void
pause(): void; resume(): void; stop(): void; isPaused(): boolean; nowMs(): number
exit(): string | undefined // { type: "finished", result } | { type: "failed", error } | { type: "stopped" }
}
```
Errors are `Error`s named `PsychoScriptError` with `type` (`syntax`, `runtime`, `timeout`, `outputTooLarge`,
`invalidInput`, `sliceBudget`, `invalidState`, `view`), `kind` (the language's diagnostic kind), 1-based
`line`/`column`, and `phase: "view"` for a `view` error.
Widgets run as a native host of widget protocol 2 (`specs/v2/widgets.md`, Native hosts): functions cross as
markers, and this crate builds the tree clients get (`src/tree.rs`). `runStep` runs a program ending in
`return __widget_native_step(__input())` with `__widget_emit(view, failure?)` as a second host global: the result is the
run's, its functions left out as JSON leaves them, with `view` (the emitted view's tree) added. `runDraw` runs a draw step
the same way and gives the commands the program emitted, as JSON reads them (`null` for none). A live run with
`native: true` builds each posted `render`'s tree (`post` returns whether it has handlers) and maps a `draw`'s `key` to
its canvas's id; its `render` and `draw` posts go out under the post rate (a bucket of 8 refilled at
`maxPostsPerSecond`, 240; waiting posts coalesce by render and by canvas key, and go out at the run's end unless it is
stopped); GPU batches (`{ type: "frame", gpu }`, `{ type: "gpu", ops, bytes }`, widgets-gpu.md) take no token but
never overtake a waiting post, and go as they are for the client's host checks: their ops as JSON reads them, with
their non-finite numbers (which JSON writes as `null`) listed by path in `nonFinite` for the client to put back, an
`ArrayBuffer`'s bytes (read in place) in the byte outbox (`takeBytes`), other bytes `null`; a render carries its GPU canvases' ids by
key (`gpu`). Every run has typed arrays (the language's). A
`draw` without a string `key`, over 2,000 commands or with an invalid command (type `draw`), ends the run. Draws, live posts and
`runDraw` alike, are checked and normalised by the spec's draw command checks (`src/draw.rs`; `tests/draw.rs` runs the
89 shared cases of `packages/widget/test/fixtures/draw.json`). A key that isn't a string, number or boolean, or a view over 100 levels, fails with type `view` (a step
once it has run; a live run at once); a function anywhere but a node's handler props, in any host call's argument,
throws the runtime's `TypeError` `Argument <n> to <name> contains a function, which cannot be passed to the host.`,
located at the call (`HostError::located`, sync and async calls alike), as the host's other errors are. `tests/tree.rs` runs the 58 conformance fixtures (`packages/widget/test/fixtures/wire`). The tests read the fixtures
and preludes in place from `packages/widget`.
A live run has `__host.post/receive/sleep/now/fetch` as in `psychoscript-mobile` (and `widgets-live.md`), but nothing
runs by itself: the host calls `pump` after a delivery, a fetch answer, a resume, or when the returned timer is due,
and again while it returns `-2`. In the browser the language yields about every millisecond of compute (see below),
so `pump(8)` returns within ~8 ms and the worker's event loop stays responsive; a stretch of compute longer than the
slice budget (50 ms) with no wait on the host stops the run with `sliceBudget`. Pausing freezes `now()` and sleeps,
and holds deliveries and fetch answers; `resume` queues `{ type: "resumed", pausedMs }` first.
`fetch` rules are checked here (`src/fetch.rs`): https only, the declared hosts (an entry may name a port), no URL
credentials, no local names or non-public literal addresses (unless `allowLocalNetwork`, dev mode: then those too,
over `http:` as well, when an entry other than `*` declares them), the six methods, no cookie headers, 256 KB out / 2 MB in, 4 in flight and 10 a
second; the browser carries the request and the final URL after redirects is checked again. Snapshots
(`suspend`/`toBytes`) aren't offered: `Suspender::suspend` blocks on a condition variable, which a single-threaded
host can't do while it is the thread that must reach the safe point.
The native parts are plain Rust and tested natively: `cargo test -p widget-web` (from `packages/widgets-rs`).
## The language in the browser
`psychoscript` 0.1 supports `wasm32-unknown-unknown` itself; this crate relies on two things it does there:
1. **Clocks:** `std::time` panics on `wasm32-unknown-unknown`, so the language reads its clocks through `web-time`
(`performance.now()`, `Date.now()`).
2. **Yielding instead of offloading:** a run driven as a future moves compute past 1 ms to a worker thread. A
browser can't start one, so on wasm32 the run instead wakes its own waker and returns `Pending` at that stop; the
executor polls it again to continue. This is what lets a single-threaded host bound and interleave stretches of
compute.
Also: local time zone in a browser is UTC (there is no `TZ` or `/etc/localtime`); `crypto.getRandomValues`
falls back to the run's generator (there is no `/dev/urandom`); a program nested too deeply to compile on the
caller's stack fails with "nested too deeply" (no thread with a larger stack).
## Size
`packages/widgets-rs/web/scripts/build-wasm.sh` (release, thin LTO, `wasm-opt -O3`):
| Module | Raw | gzip -9 | brotli -q 11 |
| --- | --- | --- | --- |
| `widget_web_bg.wasm` (language) | 9.54 MB | 3.19 MB | 2.21 MB |
| of which code | 3.84 MB | 1.36 MB | 0.93 MB |
| of which data | 5.69 MB | 1.83 MB | 1.24 MB |
The data is mostly ICU4X's compiled data for every CLDR locale (date/time names and patterns for
`toLocale*String`/`Intl.DateTimeFormat`, collation for `localeCompare`). Data segments are copied into each
instance's linear memory, so they also set each worker's baseline memory (~7 MB). Trimming them to a few locales
(baked data from `icu4x-datagen` through `ICU4X_DATA_DIR`, no code change) would save most of the data row (an
estimated 4–5 MB raw, ~1.5 MB gzip, ~1 MB brotli, and as much memory per worker), at the cost of formatting and
collating other locales like their nearest kept one: a difference from the native build and the reference, so it
needs a decision first. `-Oz` instead of `-O3` in wasm-opt saves under 1%.

View file

@ -0,0 +1,30 @@
//! Times compiling and running widget steps natively: `cargo run --release -p widget-web --example step --
//! <program.js> <data.json>` (the program is prelude + "\n" + source).
use std::time::Instant;
use widget_web::Program;
fn main() {
let args: Vec<String> = std::env::args().collect();
let program = std::fs::read_to_string(&args[1]).expect("a program file");
let data = std::fs::read_to_string(&args[2]).expect("a data file");
let t = Instant::now();
let p = Program::new(&(program + "\nreturn __widget_step(__input())"), None).expect("compiles");
println!("compile {:.2} ms", t.elapsed().as_secs_f64() * 1000.0);
for i in 0..5 {
let t = Instant::now();
let out = p
.run(
&format!(r#"{{"phase":"init","data":{data}}}"#),
Some(250),
None,
)
.expect("runs");
println!(
"init #{i} {:.2} ms, {} bytes",
t.elapsed().as_secs_f64() * 1000.0,
out.len()
);
}
}

View file

@ -0,0 +1,385 @@
//! A draw's commands checked (widgets.md, Canvas, "Draw command checks"), the same in every host: from the values as
//! they crossed to the normalised commands clients get, as JSON, or the exact failure (a program error in phase
//! `draw`). Shared cases: `packages/widget/test/fixtures/draw.json`.
use std::fmt::Write as _;
use psychoscript::HostValue;
/// The most commands a draw may have (widgets-live.md, "Lifecycle and budgets").
pub(crate) const MAX_COMMANDS: usize = 2000;
const TOKENS: [&str; 9] = [
"text", "muted", "accent", "bg", "surface", "border", "success", "warning", "error",
];
type Item = Option<HostValue>;
type Checked = Result<(), String>;
/// A draw step's commands: read as JSON reads them first (functions and `undefined` fields left out, `undefined` and
/// function items and non-finite numbers `null`), then checked.
pub(crate) fn check_read(commands: &HostValue) -> Result<String, String> {
check(&json(commands))
}
/// A draw's commands, as they crossed: the normalised commands as JSON, or the failure's message.
pub(crate) fn check(commands: &HostValue) -> Result<String, String> {
let HostValue::Array(list) = commands else {
return Err("draw commands must be a list".into());
};
if list.len() > MAX_COMMANDS {
return Err(format!(
"{} draw commands is over the budget of {MAX_COMMANDS} per frame",
list.len()
));
}
let mut out = String::with_capacity(list.len() * 24 + 2);
out.push('[');
for (i, c) in list.iter().enumerate() {
if i > 0 {
out.push(',');
}
command(c.as_ref(), &mut out).map_err(|e| format!("draw command {i}: {e}"))?;
}
out.push(']');
Ok(out)
}
/// `v` as JSON reads it.
fn json(v: &HostValue) -> HostValue {
match v {
HostValue::Number(n) if !n.is_finite() => HostValue::Null,
HostValue::Array(items) => HostValue::Array(
items
.iter()
.map(|i| match i {
None
| Some(
HostValue::Undefined | HostValue::FunctionMarker | HostValue::Function(_),
) => Some(HostValue::Null),
Some(i) => Some(json(i)),
})
.collect(),
),
HostValue::Object(fields) => HostValue::Object(
fields
.iter()
.filter(|(_, v)| {
!matches!(
v,
HostValue::Undefined | HostValue::FunctionMarker | HostValue::Function(_)
)
})
.map(|(k, v)| (k.clone(), json(v)))
.collect(),
),
other => other.clone(),
}
}
/// An object's field: `None` when absent or `undefined`; `null` is a value.
fn field<'a>(v: &'a HostValue, name: &str) -> Option<&'a HostValue> {
v.get(name).filter(|v| !matches!(v, HostValue::Undefined))
}
fn number(n: f64, out: &mut String) {
out.push_str(ryu_js::Buffer::new().format_finite(n));
}
fn string(s: &str, out: &mut String) {
let _ = write!(out, "{}", serde_json::Value::from(s));
}
fn finite(v: Option<&HostValue>, what: &str) -> Result<f64, String> {
match v {
Some(HostValue::Number(n)) if n.is_finite() => Ok(*n),
_ => Err(format!("{what} must be a finite number")),
}
}
fn color(v: Option<&HostValue>, out: &mut String) -> Checked {
if let Some(HostValue::String(s)) = v
&& let Some(s) = s.as_str()
&& match s.strip_prefix('#') {
None => TOKENS.contains(&s),
Some(hex) => {
matches!(hex.len(), 3 | 6 | 8) && hex.bytes().all(|b| b.is_ascii_hexdigit())
}
}
{
string(s, out);
return Ok(());
}
Err("not a color".into())
}
fn command(v: Option<&HostValue>, out: &mut String) -> Checked {
let Some(HostValue::Array(a)) = v else {
return Err("a command is an array".into());
};
let Some(Some(HostValue::String(op))) = a.first() else {
return Err("a command starts with its name".into());
};
let op = op.to_string_lossy();
let op = &*op;
// The arguments a command takes after its name, and how many of them may be left off.
let (count, optional) = match op {
"save" | "restore" => (0, 0),
"rotate" | "alpha" => (1, 0),
"translate" | "scale" | "path" => (2, 0),
"circle" => (4, 0),
"rect" | "line" | "image" => (5, 0),
"rrect" => (6, 0),
"text" => (4, 1),
_ => return Err(format!("unknown draw command \"{op}\"")),
};
if a.len() > count + 1 {
return Err(format!("\"{op}\" has more than {count} arguments"));
}
if a.len() < count + 1 - optional {
return Err(format!("\"{op}\" is missing argument {}", a.len()));
}
let at = |i: usize| a.get(i).and_then(Item::as_ref);
let n = |i: usize| finite(at(i), &format!("\"{op}\" argument {i}"));
out.push('[');
string(op, out);
match op {
"save" | "restore" => {}
"alpha" => {
out.push(',');
number(n(1)?.clamp(0.0, 1.0), out);
}
"path" => {
let Some(HostValue::Array(segments)) = at(1) else {
return Err("\"path\" takes a list of segments".into());
};
out.push_str(",[");
for (i, s) in segments.iter().enumerate() {
if i > 0 {
out.push(',');
}
segment(s.as_ref(), out)?;
}
out.push_str("],");
paint(at(2), out)?;
}
"text" => {
let (x, y) = (n(1)?, n(2)?);
let Some(HostValue::String(text)) = at(3) else {
return Err("\"text\" argument 3 must be a string".into());
};
out.push(',');
number(x, out);
out.push(',');
number(y, out);
out.push(',');
string(&text.to_string_lossy(), out);
out.push(',');
style(at(4), out)?;
}
"image" => {
let Some(HostValue::String(src)) = at(1) else {
return Err("\"image\" takes a src".into());
};
out.push(',');
string(&src.to_string_lossy(), out);
for i in 2..=5 {
out.push(',');
number(n(i)?, out);
}
}
_ => {
// Numbers, then a paint for the shapes.
let shape = matches!(op, "rect" | "rrect" | "circle" | "line");
let numbers = if shape { count - 1 } else { count };
for i in 1..=numbers {
out.push(',');
number(n(i)?, out);
}
if shape {
out.push(',');
paint(at(count), out)?;
}
}
}
out.push(']');
Ok(())
}
fn segment(v: Option<&HostValue>, out: &mut String) -> Checked {
let Some(HostValue::Array(s)) = v else {
return Err("a path segment is an array".into());
};
let verb = match s.first() {
Some(Some(HostValue::String(verb))) => verb.as_str(),
_ => None,
};
let count = match verb {
Some("M" | "L") => 2,
Some("Q") => 4,
Some("C") => 6,
Some("Z") => 0,
_ => return Err("unknown path segment".into()),
};
let verb = verb.unwrap_or_default();
if s.len() != count + 1 {
return Err(format!(
"a \"{verb}\" path segment takes {count} coordinates"
));
}
out.push('[');
string(verb, out);
for c in &s[1..] {
out.push(',');
number(finite(c.as_ref(), "a path coordinate")?, out);
}
out.push(']');
Ok(())
}
/// Writes `"name":` before a field, with the comma when one came before.
fn key(name: &str, first: &mut bool, out: &mut String) {
if !std::mem::take(first) {
out.push(',');
}
out.push('"');
out.push_str(name);
out.push_str("\":");
}
fn paint(v: Option<&HostValue>, out: &mut String) -> Checked {
let Some(m @ HostValue::Object(_)) = v else {
return Err("a paint is an object".into());
};
out.push('{');
let first = &mut true;
if let Some(fill) = field(m, "fill") {
key("fill", first, out);
match fill {
HostValue::Object(_) => gradient(fill, out)?,
_ => color(Some(fill), out)?,
}
}
if let Some(stroke) = field(m, "stroke") {
key("stroke", first, out);
color(Some(stroke), out)?;
}
if let Some(width) = field(m, "width") {
let width = finite(Some(width), "a stroke's width")?.max(0.0);
key("width", first, out);
number(width, out);
}
if let Some(cap) = field(m, "cap") {
let Some(cap @ ("butt" | "round")) = cap.as_str() else {
return Err("a stroke's cap must be \"butt\" or \"round\"".into());
};
key("cap", first, out);
string(cap, out);
}
out.push('}');
Ok(())
}
fn gradient(m: &HostValue, out: &mut String) -> Checked {
let coordinates = |name: &str, count: usize| -> Result<Option<Vec<f64>>, String> {
let Some(list) = field(m, name) else {
return Ok(None);
};
match list {
HostValue::Array(items) if items.len() == count => items
.iter()
.map(|i| finite(i.as_ref(), name))
.collect::<Result<Vec<_>, _>>()
.map(Some),
_ => Err(format!("a {name} gradient takes {count} numbers")),
}
};
// Both are checked when present; with both, it is linear.
let (linear, radial) = (coordinates("linear", 4)?, coordinates("radial", 3)?);
let (name, shape) = match (linear, radial) {
(Some(c), _) => ("linear", c),
(None, Some(c)) => ("radial", c),
(None, None) => return Err("a gradient needs linear or radial".into()),
};
let Some(HostValue::Array(stops)) = field(m, "stops") else {
return Err("a gradient needs stops".into());
};
out.push_str("{\"");
out.push_str(name);
out.push_str("\":[");
for (i, c) in shape.iter().enumerate() {
if i > 0 {
out.push(',');
}
number(*c, out);
}
out.push_str("],\"stops\":[");
for (i, stop) in stops.iter().enumerate() {
let Some(HostValue::Array(pair)) = stop else {
return Err("a stop is [offset, color]".into());
};
if pair.len() != 2 {
return Err("a stop is [offset, color]".into());
}
if i > 0 {
out.push(',');
}
let offset = finite(pair[0].as_ref(), "a stop's offset")?.clamp(0.0, 1.0);
out.push('[');
number(offset, out);
out.push(',');
color(pair[1].as_ref(), out)?;
out.push(']');
}
out.push_str("]}");
Ok(())
}
/// A text's style: left off, `undefined` or `null` is `{}`.
fn style(v: Option<&HostValue>, out: &mut String) -> Checked {
let m = match v {
None | Some(HostValue::Undefined | HostValue::Null) => {
out.push_str("{}");
return Ok(());
}
Some(m @ HostValue::Object(_)) => m,
Some(_) => return Err("a text style is an object".into()),
};
out.push('{');
let first = &mut true;
if let Some(size) = field(m, "size") {
let size = finite(Some(size), "a text size")?.clamp(1.0, 512.0);
key("size", first, out);
number(size, out);
}
if let Some(weight) = field(m, "weight") {
let Some(weight) = weight
.as_f64()
.filter(|w| [400.0, 500.0, 600.0, 700.0].contains(w))
else {
return Err("a text weight must be 400, 500, 600 or 700".into());
};
key("weight", first, out);
number(weight, out);
}
if let Some(align) = field(m, "align") {
let Some(align @ ("left" | "center" | "right")) = align.as_str() else {
return Err("a text align must be \"left\", \"center\" or \"right\"".into());
};
key("align", first, out);
string(align, out);
}
if let Some(c) = field(m, "color") {
key("color", first, out);
color(Some(c), out)?;
}
if let Some(mono) = field(m, "mono") {
let HostValue::Bool(mono) = mono else {
return Err("a text mono must be true or false".into());
};
key("mono", first, out);
out.push_str(if *mono { "true" } else { "false" });
}
out.push('}');
Ok(())
}

View file

@ -0,0 +1,165 @@
use std::fmt;
use psychoscript::{Diagnostic, DiagnosticKind};
/// Why a program didn't compile or a run failed: the same cases as `psychoscript-mobile`'s error. In JavaScript it is
/// an `Error` whose `name` is `"PsychoScriptError"`, with `type` (the variant, lowercase: `"syntax"`, `"runtime"`,
/// `"timeout"`, `"outputTooLarge"`, `"invalidInput"`, `"sliceBudget"`, `"invalidState"`, `"view"`, `"draw"`), `kind` (the
/// language's diagnostic kind), `line`/`column` (1-based) when known, and `phase` when it is a phase's own (`"view"`, `"draw"`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
/// The source doesn't parse, or uses unsupported syntax (`ParseError`, `UnsupportedSyntax`).
Syntax {
kind: String,
reason: String,
line: Option<u32>,
column: Option<u32>,
},
/// The run threw, or returned what isn't JSON data.
Runtime {
kind: String,
reason: String,
line: Option<u32>,
column: Option<u32>,
},
/// The run went past `timeout_ms` of active time.
Timeout { reason: String, timeout_ms: u64 },
/// The result is over `max_output_bytes` of JSON.
OutputTooLarge {
reason: String,
max_output_bytes: u64,
},
/// The input isn't JSON, or the options are invalid.
InvalidInput { reason: String },
/// A live run computed for more than `budget_ms` without waiting on its host, and was stopped.
SliceBudget { reason: String, budget_ms: u64 },
/// A live run's method its state doesn't allow.
InvalidState { reason: String },
/// A widget's view breaks a rule of views (widgets.md, "Keys and depth"): a program error in phase `view`.
View { reason: String },
/// A live widget's draw post is invalid (more than 2,000 commands): a program error in phase `draw`.
Draw { reason: String },
}
impl Error {
pub(crate) fn from_diagnostic(d: Diagnostic, timeout_ms: Option<u64>) -> Error {
let kind = d.kind.name().to_owned();
let reason = d.message_lossy();
let (line, column) = d.location.map_or((None, None), |(l, c)| (Some(l), Some(c)));
match d.kind {
DiagnosticKind::TimeoutExceeded => Error::Timeout {
reason,
timeout_ms: timeout_ms.unwrap_or(0),
},
DiagnosticKind::ParseError | DiagnosticKind::UnsupportedSyntax => Error::Syntax {
kind,
reason,
line,
column,
},
_ => Error::Runtime {
kind,
reason,
line,
column,
},
}
}
pub(crate) fn invalid_input(reason: impl Into<String>) -> Error {
Error::InvalidInput {
reason: reason.into(),
}
}
/// The message, as the language gives it.
pub fn reason(&self) -> &str {
match self {
Error::Syntax { reason, .. }
| Error::Runtime { reason, .. }
| Error::Timeout { reason, .. }
| Error::OutputTooLarge { reason, .. }
| Error::InvalidInput { reason }
| Error::SliceBudget { reason, .. }
| Error::InvalidState { reason }
| Error::View { reason }
| Error::Draw { reason } => reason,
}
}
/// The variant's name, as JavaScript sees it in `type`.
pub fn type_name(&self) -> &'static str {
match self {
Error::Syntax { .. } => "syntax",
Error::Runtime { .. } => "runtime",
Error::Timeout { .. } => "timeout",
Error::OutputTooLarge { .. } => "outputTooLarge",
Error::InvalidInput { .. } => "invalidInput",
Error::SliceBudget { .. } => "sliceBudget",
Error::InvalidState { .. } => "invalidState",
Error::View { .. } => "view",
Error::Draw { .. } => "draw",
}
}
/// The language's diagnostic kind, when there is one.
pub fn kind(&self) -> Option<&str> {
match self {
Error::Syntax { kind, .. } | Error::Runtime { kind, .. } => Some(kind),
Error::Timeout { .. } => Some("TimeoutExceeded"),
_ => None,
}
}
/// The widget phase it belongs to, when it isn't the step's or the run's: `"view"` or `"draw"`.
pub fn phase(&self) -> Option<&'static str> {
match self {
Error::View { .. } => Some("view"),
Error::Draw { .. } => Some("draw"),
_ => None,
}
}
/// Where in the source, 1-based, when known.
pub fn location(&self) -> Option<(u32, u32)> {
match self {
Error::Syntax {
line: Some(l),
column: Some(c),
..
}
| Error::Runtime {
line: Some(l),
column: Some(c),
..
} => Some((*l, *c)),
_ => None,
}
}
/// `{ type, kind?, message, line?, column?, phase? }`, as JSON.
pub fn to_json(&self) -> String {
let mut out = serde_json::Map::new();
out.insert("type".into(), self.type_name().into());
if let Some(kind) = self.kind() {
out.insert("kind".into(), kind.into());
}
out.insert("message".into(), self.reason().into());
if let Some((l, c)) = self.location() {
out.insert("line".into(), l.into());
out.insert("column".into(), c.into());
}
if let Some(phase) = self.phase() {
out.insert("phase".into(), phase.into());
}
serde_json::Value::Object(out).to_string()
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.reason())
}
}
impl std::error::Error for Error {}

View file

@ -0,0 +1,697 @@
//! `__host.fetch(request)`'s rules, enforced here; the browser's `fetch` carries the request (the web package calls it
//! with `credentials: "omit"`, no referrer, no cache).
//!
//! `https:` only; the host on the run's allow-list (exact names, `*.` suffix wildcards, `*` for any; an entry may name a
//! port); no URL credentials; no localhost or `.local` names, no private, loopback or link-local literal addresses,
//! unless the host turned on dev mode (`Policy::local_network`): then those destinations, over `http:` too, when an
//! entry other than `*` declares them (widgets-live.md, "Local network in dev mode"); methods GET,
//! POST, PUT, PATCH, DELETE, HEAD; no cookie headers either way; request body <= 256 KB, response body <= 2 MB; 15 s
//! per request; at most 4 in flight and 10 a second per run. Rejections are errors with `kind` (`CapabilityDenied`,
//! `Network`, `Timeout`, `TooLarge`, `RateLimited`) and `message`.
//!
//! What a browser can't do: resolve names (a public name that resolves to a private address isn't caught here, though
//! Chromium's Private Network Access blocks most such requests), or show redirect hops: the browser follows them
//! (at most 20), and the final URL is checked against the same rules before the program sees anything.
use std::collections::VecDeque;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::time::Duration;
use psychoscript::{HostError, HostString, HostValue};
use url::Url;
use crate::time::Instant;
pub const MAX_REQUEST_BYTES: usize = 256 * 1024;
pub const MAX_RESPONSE_BYTES: usize = 2 * 1024 * 1024;
pub const TIMEOUT: Duration = Duration::from_secs(15);
pub const MAX_IN_FLIGHT: usize = 4;
pub const MAX_PER_SECOND: usize = 10;
const METHODS: [&str; 6] = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"];
/// Request headers the program can't set: cookies and credentials, and what the browser owns.
const DROPPED_HEADERS: [&str; 13] = [
"cookie",
"cookie2",
"host",
"content-length",
"connection",
"keep-alive",
"transfer-encoding",
"te",
"trailer",
"upgrade",
"proxy-authorization",
"proxy-connection",
"origin",
];
/// Whether `ip` is a public unicast address a widget may reach.
pub fn public(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => public_v4(v4),
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
Some(v4) => public_v4(v4),
None => public_v6(v6),
},
}
}
fn public_v4(ip: Ipv4Addr) -> bool {
let [a, b, c, _] = ip.octets();
!(ip.is_loopback()
|| ip.is_private()
|| ip.is_link_local()
|| ip.is_unspecified()
|| ip.is_broadcast()
|| ip.is_multicast()
|| ip.is_documentation()
|| a == 0
|| (a == 100 && (64..128).contains(&b))
|| (a == 192 && b == 0 && c == 0)
|| a >= 240)
}
fn public_v6(ip: Ipv6Addr) -> bool {
let first = ip.segments()[0];
!(ip.is_loopback()
|| ip.is_unspecified()
|| ip.is_multicast()
|| (first & 0xfe00) == 0xfc00
|| (first & 0xffc0) == 0xfe80
|| (first & 0xffc0) == 0xfec0
|| (first == 0x2001 && ip.segments()[1] == 0x0db8)
|| ip.to_ipv4().is_some_and(|v4| !public_v4(v4)))
}
/// A rejection the program sees: an error with `kind` and `message`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Rejection {
pub kind: &'static str,
pub message: String,
}
impl Rejection {
pub fn new(kind: &'static str, message: impl Into<String>) -> Rejection {
Rejection {
kind,
message: message.into(),
}
}
pub fn denied(message: impl Into<String>) -> Rejection {
Rejection::new("CapabilityDenied", message)
}
pub fn rate_limited(message: impl Into<String>) -> Rejection {
Rejection::new("RateLimited", message)
}
/// The kind a transport failure names (`Network`, `Timeout`, `TooLarge`), `Network` for any other.
pub fn transport(kind: &str, message: impl Into<String>) -> Rejection {
let kind = match kind {
"Timeout" => "Timeout",
"TooLarge" => "TooLarge",
_ => "Network",
};
Rejection::new(kind, message)
}
pub fn value(self) -> HostValue {
HostValue::Error(Box::new(
HostError::named(self.kind, self.message.as_str())
.with_field("kind", HostValue::String(self.kind.into())),
))
}
}
/// A request body: text as the program gave it, or bytes from `body64`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Body {
Text(String),
Bytes(Vec<u8>),
}
impl Body {
fn len(&self) -> usize {
match self {
Body::Text(t) => t.len(),
Body::Bytes(b) => b.len(),
}
}
}
/// A request as the program gave it, checked for shape and against the rules.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Request {
pub url: Url,
pub method: String,
pub headers: Vec<(String, String)>,
pub body: Option<Body>,
}
impl Request {
pub fn parse(value: Option<&HostValue>, policy: &Policy) -> Result<Request, Rejection> {
let bad = |m: &str| Rejection::new("Network", format!("invalid request: {m}"));
let Some(value) = value else {
return Err(bad("expected { url, method?, headers?, body? }"));
};
let url = match value {
HostValue::String(s) => s.to_string_lossy().into_owned(),
_ => value
.get("url")
.and_then(HostValue::as_str)
.ok_or_else(|| bad("no url"))?
.to_owned(),
};
let url = Url::parse(&url).map_err(|e| bad(&format!("{url}: {e}")))?;
check_url(&url, policy)?;
let method = match value.get("method") {
None | Some(HostValue::Undefined | HostValue::Null) => "GET".to_owned(),
Some(m) => m
.as_str()
.ok_or_else(|| bad("method isn't a string"))?
.to_ascii_uppercase(),
};
if !METHODS.contains(&method.as_str()) {
return Err(Rejection::denied(format!(
"method {method} isn't allowed (GET, POST, PUT, PATCH, DELETE, HEAD)"
)));
}
let mut headers = Vec::new();
if let Some(HostValue::Object(fields)) = value.get("headers") {
for (name, v) in fields {
let name = name.to_string_lossy().to_ascii_lowercase();
let value = match v {
HostValue::String(s) => s.to_string_lossy().into_owned(),
HostValue::Number(n) => n.to_string(),
HostValue::Bool(b) => b.to_string(),
_ => continue,
};
if !DROPPED_HEADERS.contains(&name.as_str()) && !name.starts_with("sec-") {
headers.push((name, value));
}
}
}
let body = match (value.get("body"), value.get("body64")) {
(Some(HostValue::String(s)), _) => Some(Body::Text(s.to_string_lossy().into_owned())),
(_, Some(HostValue::String(s))) => Some(Body::Bytes(
base64_decode(&s.to_string_lossy()).ok_or_else(|| bad("body64 isn't base64"))?,
)),
_ => None,
};
if body.as_ref().is_some_and(|b| b.len() > MAX_REQUEST_BYTES) {
return Err(Rejection::new(
"TooLarge",
format!("the request body is over {} KB", MAX_REQUEST_BYTES / 1024),
));
}
if body.is_some() && matches!(method.as_str(), "GET" | "HEAD") {
return Err(bad(&format!("a {method} request can't have a body")));
}
Ok(Request {
url,
method,
headers,
body,
})
}
/// `{ id, url, method, headers: [[name, value]], body? | body64?, timeoutMs, maxResponseBytes }` for the
/// browser side.
pub fn to_json(&self, id: u64) -> String {
let mut out = serde_json::Map::new();
out.insert("type".into(), "fetch".into());
out.insert("id".into(), id.into());
out.insert("url".into(), self.url.as_str().into());
out.insert("method".into(), self.method.as_str().into());
out.insert(
"headers".into(),
serde_json::Value::Array(
self.headers
.iter()
.map(|(n, v)| serde_json::json!([n, v]))
.collect(),
),
);
match &self.body {
Some(Body::Text(t)) => {
out.insert("body".into(), t.as_str().into());
}
Some(Body::Bytes(b)) => {
out.insert("body64".into(), base64_encode(b).into());
}
None => {}
}
out.insert("timeoutMs".into(), (TIMEOUT.as_millis() as u64).into());
out.insert("maxResponseBytes".into(), MAX_RESPONSE_BYTES.into());
serde_json::Value::Object(out).to_string()
}
}
/// What a run's `fetch` may reach: the widget template's declared hosts and, in dev mode (`local_network`), the local
/// network among them.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Policy {
/// Exact names or addresses, `*.` suffixes, `*` for any; an entry may name a port (`localhost:4097`,
/// `[::1]:8080`), and then matches only that port.
pub hosts: Vec<String>,
/// Dev mode: also loopback, private and link-local destinations and local names (`localhost`, `*.local`), over
/// `http:` too, when an entry other than `*` declares them.
pub local_network: bool,
}
/// An allow-list entry: its host pattern (lowercase, no brackets or trailing dot) and port, if it names one.
fn entry(raw: &str) -> (String, Option<u16>) {
let e = raw.trim().to_ascii_lowercase();
let (host, port) = if let Some(rest) = e.strip_prefix('[') {
match rest.split_once(']') {
Some((h, tail)) => (
h.to_owned(),
tail.strip_prefix(':').and_then(|p| p.parse().ok()),
),
None => (rest.to_owned(), None),
}
} else {
match e.rsplit_once(':') {
// One colon and digits after it: a port. More colons: a bare IPv6 address.
Some((h, p))
if !h.contains(':') && !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) =>
{
(h.to_owned(), p.parse().ok())
}
_ => (e.clone(), None),
}
};
(host.trim_end_matches('.').to_owned(), port)
}
/// Whether `host` (at `port`) is on `allowed`: exact names, `*.` suffixes (not the bare domain), `*` unless
/// `explicit`; an entry with a port matches only that port.
pub fn host_allowed(host: &str, port: Option<u16>, allowed: &[String], explicit: bool) -> bool {
let host = host
.trim_matches(['[', ']'])
.trim_end_matches('.')
.to_ascii_lowercase();
allowed.iter().any(|raw| {
let (pattern, want) = entry(raw);
if want.is_some() && want != port {
return false;
}
match pattern.strip_prefix("*.") {
_ if pattern == "*" => !explicit,
Some(suffix) => {
host.len() > suffix.len() + 1
&& host.ends_with(suffix)
&& host[..host.len() - suffix.len()].ends_with('.')
}
None => host == pattern,
}
})
}
/// Whether a URL's host is on the local network: a loopback, private, link-local or other non-public address, or a
/// local name.
fn local(host: &url::Host<&str>) -> bool {
match host {
url::Host::Ipv4(ip) => !public_v4(*ip),
url::Host::Ipv6(ip) => !public(IpAddr::V6(*ip)),
url::Host::Domain(d) => {
let d = d.trim_end_matches('.').to_ascii_lowercase();
d == "localhost"
|| d.ends_with(".localhost")
|| d.ends_with(".local")
|| d.ends_with(".internal")
|| !d.contains('.')
}
}
}
/// A URL the run may reach: no credentials and a declared host; `https:` to a public destination, or in dev mode a
/// declared local one over `https:` or `http:`.
pub fn check_url(url: &Url, policy: &Policy) -> Result<(), Rejection> {
if !url.username().is_empty() || url.password().is_some() {
return Err(Rejection::denied("URLs with credentials aren't allowed"));
}
let Some(host) = url.host() else {
return Err(Rejection::denied("the URL has no host"));
};
let is_local = local(&host);
let dev = policy.local_network && is_local;
if url.scheme() != "https" && !(dev && url.scheme() == "http") {
return Err(Rejection::denied(format!(
"only https: URLs, not {}:",
url.scheme()
)));
}
let name = match &host {
url::Host::Domain(d) => (*d).to_owned(),
url::Host::Ipv4(ip) => ip.to_string(),
url::Host::Ipv6(ip) => ip.to_string(),
};
if !host_allowed(&name, url.port_or_known_default(), &policy.hosts, is_local) {
return Err(Rejection::denied(format!(
"{name}{} isn't among the hosts this widget may reach",
url.port().map(|p| format!(":{p}")).unwrap_or_default()
)));
}
if is_local && !dev {
return Err(Rejection::denied(match host {
url::Host::Domain(_) => format!("{name} is a local name (the local network is off)"),
_ => format!("{name} isn't a public address (the local network is off)"),
}));
}
Ok(())
}
/// A run's fetch budget: in flight, and started in the last second.
#[derive(Default)]
pub struct Budget {
pub in_flight: usize,
recent: VecDeque<Instant>,
}
impl Budget {
pub fn admit(&mut self) -> Result<(), Rejection> {
let now = Instant::now();
while self
.recent
.front()
.is_some_and(|t| now.duration_since(*t) >= Duration::from_secs(1))
{
self.recent.pop_front();
}
if self.in_flight >= MAX_IN_FLIGHT {
return Err(Rejection::rate_limited(format!(
"at most {MAX_IN_FLIGHT} requests in flight"
)));
}
if self.recent.len() >= MAX_PER_SECOND {
return Err(Rejection::rate_limited(format!(
"at most {MAX_PER_SECOND} requests a second"
)));
}
self.in_flight += 1;
self.recent.push_back(now);
Ok(())
}
}
/// What the browser got: `{ status, url, headers }` (the final URL after redirects; headers as `[[name, value]]` or
/// an object) as JSON, and the body bytes. Checked, then made `{ status, url, headers, body | body64 }`: the body as
/// text when it's UTF-8, else base64.
pub fn response(meta_json: &str, body: Vec<u8>, policy: &Policy) -> Result<HostValue, Rejection> {
let meta: serde_json::Value = serde_json::from_str(meta_json)
.map_err(|e| Rejection::new("Network", format!("bad response from the host: {e}")))?;
let status = meta
.get("status")
.and_then(serde_json::Value::as_f64)
.unwrap_or(0.0);
let url = meta
.get("url")
.and_then(serde_json::Value::as_str)
.unwrap_or("");
let url = Url::parse(url)
.map_err(|e| Rejection::new("Network", format!("bad final URL {url}: {e}")))?;
check_url(&url, policy).map_err(|r| Rejection::denied(format!("redirected: {}", r.message)))?;
if body.len() > MAX_RESPONSE_BYTES {
return Err(Rejection::new(
"TooLarge",
format!("the response body is over {} MB", MAX_RESPONSE_BYTES >> 20),
));
}
let mut headers: Vec<(HostString, HostValue)> = Vec::new();
let pairs: Vec<(String, String)> = match meta.get("headers") {
Some(serde_json::Value::Array(items)) => items
.iter()
.filter_map(|p| {
Some((
p.get(0)?.as_str()?.to_owned(),
p.get(1)?.as_str()?.to_owned(),
))
})
.collect(),
Some(serde_json::Value::Object(map)) => map
.iter()
.filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_owned())))
.collect(),
_ => Vec::new(),
};
for (name, value) in pairs {
let name = name.to_ascii_lowercase();
if name == "set-cookie" || name == "set-cookie2" {
continue;
}
match headers
.iter_mut()
.find(|(k, _)| k.as_str() == Some(name.as_str()))
{
Some((_, HostValue::String(v))) => {
*v = format!("{}, {}", v.to_string_lossy(), value).into()
}
_ => headers.push((name.into(), HostValue::String(value.into()))),
}
}
let body = match String::from_utf8(body) {
Ok(text) => ("body", HostValue::String(text.into())),
Err(e) => (
"body64",
HostValue::String(base64_encode(e.as_bytes()).into()),
),
};
Ok(HostValue::object([
("status", HostValue::Number(status)),
("url", HostValue::String(url.as_str().into())),
("headers", HostValue::Object(headers)),
body,
]))
}
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
fn base64_encode(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let n = (u32::from(chunk[0]) << 16)
| (u32::from(*chunk.get(1).unwrap_or(&0)) << 8)
| u32::from(*chunk.get(2).unwrap_or(&0));
for i in 0..4 {
if i <= chunk.len() {
out.push(ALPHABET[(n >> (18 - 6 * i)) as usize & 63] as char);
} else {
out.push('=');
}
}
}
out
}
fn base64_decode(text: &str) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(text.len() / 4 * 3);
let (mut n, mut bits) = (0u32, 0);
for c in text
.bytes()
.filter(|c| !c.is_ascii_whitespace() && *c != b'=')
{
let v = ALPHABET.iter().position(|a| *a == c)? as u32;
n = (n << 6) | v;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((n >> bits) as u8);
}
}
Some(out)
}
#[cfg(test)]
mod tests {
use super::*;
fn hosts(list: &[&str]) -> Vec<String> {
list.iter().map(|s| (*s).to_owned()).collect()
}
fn policy(list: &[&str], local_network: bool) -> Policy {
Policy {
hosts: hosts(list),
local_network,
}
}
#[test]
fn hosts_match_exactly_or_by_suffix() {
let allowed = hosts(&["api.github.com", "*.coingecko.com"]);
let ok = |h: &str| host_allowed(h, Some(443), &allowed, false);
assert!(ok("api.github.com"));
assert!(ok("API.GitHub.com."));
assert!(!ok("github.com"));
assert!(ok("pro.api.coingecko.com"));
assert!(!ok("coingecko.com"));
assert!(!ok("evilcoingecko.com"));
assert!(host_allowed(
"anything.example",
Some(443),
&hosts(&["*"]),
false
));
assert!(!host_allowed("localhost", Some(80), &hosts(&["*"]), true));
}
#[test]
fn entries_may_name_a_port() {
let allowed = hosts(&[
"localhost:4097",
"[::1]:8080",
"127.0.0.1",
"api.example.com:8443",
]);
assert!(host_allowed("localhost", Some(4097), &allowed, true));
assert!(!host_allowed("localhost", Some(4098), &allowed, true));
assert!(host_allowed("::1", Some(8080), &allowed, true));
assert!(!host_allowed("::1", Some(80), &allowed, true));
assert!(host_allowed("127.0.0.1", Some(3000), &allowed, true));
assert!(host_allowed("api.example.com", Some(8443), &allowed, false));
assert!(!host_allowed("api.example.com", Some(443), &allowed, false));
assert!(host_allowed(
"fe80::1",
Some(80),
&hosts(&["fe80::1"]),
true
));
}
#[test]
fn urls_follow_the_rules() {
let any = policy(&["*"], false);
let check = |u: &str| check_url(&Url::parse(u).unwrap(), &any).map_err(|r| r.kind);
assert_eq!(check("https://example.com/x"), Ok(()));
assert_eq!(check("http://example.com/x"), Err("CapabilityDenied"));
assert_eq!(
check("https://user:pw@example.com/"),
Err("CapabilityDenied")
);
assert_eq!(check("https://localhost/"), Err("CapabilityDenied"));
assert_eq!(check("https://printer.local/"), Err("CapabilityDenied"));
assert_eq!(check("https://10.0.0.1/"), Err("CapabilityDenied"));
assert_eq!(check("https://[::1]/"), Err("CapabilityDenied"));
assert_eq!(check("https://169.254.169.254/"), Err("CapabilityDenied"));
assert_eq!(check("https://1.1.1.1/"), Ok(()));
// A declared local host is still refused while the local network is off.
let declared = policy(&["localhost:4097", "10.0.0.5"], false);
let off = |u: &str| check_url(&Url::parse(u).unwrap(), &declared).map_err(|r| r.message);
assert!(
off("http://localhost:4097/")
.unwrap_err()
.contains("only https")
);
assert!(
off("https://localhost:4097/")
.unwrap_err()
.contains("local network is off")
);
assert!(
off("https://10.0.0.5/")
.unwrap_err()
.contains("local network is off")
);
}
#[test]
fn dev_mode_lets_declared_local_hosts_through() {
let dev = policy(
&[
"localhost:4097",
"127.0.0.1",
"*.local",
"192.168.1.20:8000",
"*",
],
true,
);
let check = |u: &str| check_url(&Url::parse(u).unwrap(), &dev).map_err(|r| r.message);
assert_eq!(check("http://localhost:4097/api"), Ok(()));
assert_eq!(check("https://localhost:4097/api"), Ok(()));
assert!(
check("http://localhost:4098/")
.unwrap_err()
.contains("isn't among the hosts")
);
assert_eq!(check("http://127.0.0.1:5173/"), Ok(()));
assert_eq!(check("http://printer.local/status"), Ok(()));
assert_eq!(check("http://192.168.1.20:8000/"), Ok(()));
// `*` doesn't declare the local network, and plain http stays local-only.
assert!(
check("http://10.0.0.1/")
.unwrap_err()
.contains("isn't among the hosts")
);
assert!(
check("http://example.com/")
.unwrap_err()
.contains("only https")
);
assert_eq!(check("https://example.com/"), Ok(()));
// Redirects end where the same rules allow.
let to_local = response(
r#"{"status":200,"url":"http://localhost:4097/x"}"#,
Vec::new(),
&policy(&["api.example.com"], true),
);
assert_eq!(to_local.unwrap_err().kind, "CapabilityDenied");
}
#[test]
fn responses_are_checked_and_shaped() {
let allowed = policy(&["api.example.com"], false);
let ok = response(
r#"{"status":200,"url":"https://api.example.com/a","headers":[["Content-Type","text/plain"],["Set-Cookie","a=b"]]}"#,
b"hi".to_vec(),
&allowed,
)
.unwrap();
assert_eq!(ok.get("body").and_then(HostValue::as_str), Some("hi"));
let headers = ok.get("headers").unwrap();
assert!(headers.get("set-cookie").is_none());
assert_eq!(
headers.get("content-type").and_then(HostValue::as_str),
Some("text/plain")
);
let binary = response(
r#"{"status":200,"url":"https://api.example.com/a"}"#,
vec![0xff, 0x00],
&allowed,
)
.unwrap();
assert_eq!(
binary.get("body64").and_then(HostValue::as_str),
Some("/wA=")
);
let redirected = response(
r#"{"status":200,"url":"https://elsewhere.com/"}"#,
Vec::new(),
&allowed,
);
assert_eq!(redirected.unwrap_err().kind, "CapabilityDenied");
let big = response(
r#"{"status":200,"url":"https://api.example.com/"}"#,
vec![b'a'; MAX_RESPONSE_BYTES + 1],
&allowed,
);
assert_eq!(big.unwrap_err().kind, "TooLarge");
}
#[test]
fn budget_limits_in_flight_and_rate() {
let mut b = Budget::default();
for _ in 0..MAX_IN_FLIGHT {
b.admit().unwrap();
}
assert_eq!(b.admit().unwrap_err().kind, "RateLimited");
b.in_flight = 0;
for _ in MAX_IN_FLIGHT..MAX_PER_SECOND {
b.admit().unwrap();
b.in_flight = 0;
}
assert_eq!(b.admit().unwrap_err().kind, "RateLimited");
}
}

View file

@ -0,0 +1,280 @@
//! JSON text to and from [`HostValue`]s, with no `serde_json::Value` in between: a run's input, delivered messages,
//! and posted ones.
use std::fmt;
use psychoscript::{HostError, HostString, HostValue};
use serde::de::{Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};
/// JSON text read as a host value: numbers as `f64`, objects keeping their keys' order.
pub(crate) struct Input(pub(crate) HostValue);
impl Input {
pub(crate) fn parse(text: &str) -> Result<HostValue, serde_json::Error> {
serde_json::from_str::<Input>(text).map(|i| i.0)
}
}
impl<'de> Deserialize<'de> for Input {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Input, D::Error> {
d.deserialize_any(Json).map(Input)
}
}
struct Json;
impl<'de> Visitor<'de> for Json {
type Value = HostValue;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("JSON")
}
fn visit_unit<E>(self) -> Result<HostValue, E> {
Ok(HostValue::Null)
}
fn visit_bool<E>(self, b: bool) -> Result<HostValue, E> {
Ok(HostValue::Bool(b))
}
fn visit_i64<E>(self, n: i64) -> Result<HostValue, E> {
Ok(HostValue::Number(n as f64))
}
fn visit_u64<E>(self, n: u64) -> Result<HostValue, E> {
Ok(HostValue::Number(n as f64))
}
fn visit_f64<E>(self, n: f64) -> Result<HostValue, E> {
Ok(HostValue::Number(n))
}
fn visit_str<E>(self, s: &str) -> Result<HostValue, E> {
Ok(HostValue::String(s.into()))
}
fn visit_string<E>(self, s: String) -> Result<HostValue, E> {
Ok(HostValue::String(s.into()))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<HostValue, A::Error> {
let mut items = Vec::with_capacity(seq.size_hint().unwrap_or(0));
while let Some(Input(item)) = seq.next_element()? {
items.push(Some(item));
}
Ok(HostValue::Array(items))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<HostValue, A::Error> {
let mut fields: Vec<(HostString, HostValue)> =
Vec::with_capacity(map.size_hint().unwrap_or(0));
// A repeated key stays repeated: the run sets it again, so its last value wins at its first
// place, as with `JSON.parse`.
while let Some((key, Input(value))) = map.next_entry::<String, Input>()? {
fields.push((key.into(), value));
}
Ok(HostValue::Object(fields))
}
}
/// A host call's argument as `JSON.stringify` writes it (`undefined` is left out of objects, `null` in arrays and at
/// the top; non-finite numbers are `null`), or `None` when it holds a function, which a host call's argument may not.
pub(crate) fn write_checked(value: &HostValue) -> Option<String> {
let mut out = String::new();
write_into(value, &mut out, &mut false).then_some(out)
}
/// A GPU batch's ops as [`write_checked`] writes them, and, when they hold non-finite numbers (which it writes as
/// `null`), those numbers by path from the ops, `[[path, "NaN" | "Infinity" | "-Infinity"], …]`: ops are read as JSON
/// reads them except that numbers stay as they are (widgets-gpu.md, Transport), so the client puts them back.
pub(crate) fn write_ops(value: &HostValue) -> Option<(String, Option<String>)> {
let mut out = String::new();
let mut seen = false;
if !write_into(value, &mut out, &mut seen) {
return None;
}
if !seen {
return Some((out, None));
}
let mut list = String::from("[");
non_finite(value, &mut Vec::new(), &mut list);
list.push(']');
Some((out, Some(list)))
}
/// A step on the way to a value inside ops: a list index or an object key.
enum Step<'a> {
Index(usize),
Key(&'a HostString),
}
/// Lists the non-finite numbers in `value`, at `path`, where [`write_into`] writes them.
fn non_finite<'a>(value: &'a HostValue, path: &mut Vec<Step<'a>>, list: &mut String) {
match value {
HostValue::Number(n) if !n.is_finite() => {
if list.len() > 1 {
list.push(',');
}
list.push_str("[[");
for (i, step) in path.iter().enumerate() {
if i > 0 {
list.push(',');
}
match step {
Step::Index(i) => list.push_str(&i.to_string()),
Step::Key(k) => string(&k.to_string_lossy(), list),
}
}
list.push_str("],");
list.push_str(if n.is_nan() {
r#""NaN""#
} else if *n > 0.0 {
r#""Infinity""#
} else {
r#""-Infinity""#
});
list.push(']');
}
HostValue::Array(items) => {
for (i, item) in items.iter().enumerate() {
if let Some(item) = item.as_ref().filter(|item| !skipped(item)) {
path.push(Step::Index(i));
non_finite(item, path, list);
path.pop();
}
}
}
HostValue::Object(fields) => {
for (k, v) in fields.iter().filter(|(_, v)| !skipped(v)) {
path.push(Step::Key(k));
non_finite(v, path, list);
path.pop();
}
}
_ => {}
}
}
fn is_function(v: &HostValue) -> bool {
matches!(v, HostValue::Function(_) | HostValue::FunctionMarker)
}
/// What a host call throws for a function in its argument `n` (from 1), as the runtime does without `"mark"`
/// (widgets.md, "Native hosts"): its `TypeError`, located at the call, with the function's name as the program called
/// it.
pub(crate) fn carried(n: usize, name: &str) -> HostValue {
HostError::located(
"TypeError",
format!("Argument {n} to {name} contains a function, which cannot be passed to the host."),
)
}
/// Fails with [`carried`] for the first of `args`, from index `from`, that is or holds a function.
pub(crate) fn unmarked(args: &[HostValue], name: &str, from: usize) -> Result<(), HostValue> {
match args.iter().skip(from).position(has_function) {
Some(i) => Err(carried(from + i + 1, name)),
None => Ok(()),
}
}
fn has_function(v: &HostValue) -> bool {
match v {
HostValue::Function(_) | HostValue::FunctionMarker => true,
HostValue::Array(items) => items.iter().flatten().any(has_function),
HostValue::Object(fields) => fields.iter().any(|(_, v)| has_function(v)),
HostValue::Map(entries) => entries
.iter()
.any(|(k, v)| has_function(k) || has_function(v)),
HostValue::Set(items) => items.iter().any(has_function),
_ => false,
}
}
/// Writes `value`; false when it holds a function. `seen`: set when it writes a non-finite number (as `null`).
fn write_into(value: &HostValue, out: &mut String, seen: &mut bool) -> bool {
match value {
HostValue::Null => out.push_str("null"),
HostValue::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
HostValue::Number(n) => {
*seen |= !n.is_finite();
number(*n, out)
}
HostValue::String(s) => string(&s.to_string_lossy(), out),
HostValue::Array(items) => {
out.push('[');
for (i, item) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
match item {
Some(item) if is_function(item) => return false,
Some(item) if !skipped(item) => {
if !write_into(item, out, seen) {
return false;
}
}
_ => out.push_str("null"),
}
}
out.push(']');
}
HostValue::Object(fields) => {
out.push('{');
let mut first = true;
for (k, v) in fields.iter() {
if is_function(v) {
return false;
}
if skipped(v) {
continue;
}
if !first {
out.push(',');
}
first = false;
string(&k.to_string_lossy(), out);
out.push(':');
if !write_into(v, out, seen) {
return false;
}
}
out.push('}');
}
HostValue::Function(_) | HostValue::FunctionMarker => return false,
HostValue::Map(_) | HostValue::Set(_) if has_function(value) => return false,
other => match other.to_json() {
Some(json) => out.push_str(&json.to_string()),
None => out.push_str("null"),
},
}
true
}
/// What `JSON.stringify` leaves out of an object, functions aside.
fn skipped(v: &HostValue) -> bool {
matches!(
v,
HostValue::Undefined
| HostValue::Durable(_)
| HostValue::Namespace(_)
| HostValue::Interrupt
)
}
fn number(n: f64, out: &mut String) {
use std::fmt::Write as _;
if !n.is_finite() {
out.push_str("null");
} else if n.fract() == 0.0 && n.abs() < 9.0e15 {
let _ = write!(out, "{}", n as i64);
} else {
out.push_str(
&serde_json::Number::from_f64(n).map_or_else(|| "null".to_owned(), |n| n.to_string()),
);
}
}
fn string(s: &str, out: &mut String) {
out.push_str(&serde_json::to_string(s).unwrap_or_else(|_| "\"\"".to_owned()));
}

View file

@ -0,0 +1,36 @@
//! PsychoScript in the browser: wasm-bindgen bindings over the `psychoscript` crate, the web counterpart of
//! `psychoscript-mobile`, for hosts that run on one thread (a Web Worker) and hand programs JSON.
//!
//! With feature `language` (default): [`Program`] compiles a source once; [`Program::run`] runs it with its JSON
//! input behind one sync host function (`__input()` unless named otherwise) and returns its completion value as JSON;
//! [`Program::start_live`] starts a [`LiveRun`] instead, a long-running program with `__host` (`post`, `receive`,
//! `sleep`, `now`, `fetch`) that the host drives from its event loop with [`LiveRun::pump`].
//!
//! The native parts are plain Rust (tested natively); `wasm` holds the JavaScript bindings, built for
//! `wasm32-unknown-unknown` only.
#[cfg(feature = "language")]
mod draw;
#[cfg(feature = "language")]
mod error;
#[cfg(feature = "language")]
pub mod fetch;
#[cfg(feature = "language")]
mod json;
#[cfg(feature = "language")]
mod live;
#[cfg(feature = "language")]
mod program;
#[cfg(feature = "language")]
mod time;
#[cfg(feature = "language")]
pub mod tree;
#[cfg(target_arch = "wasm32")]
mod wasm;
#[cfg(feature = "language")]
pub use error::Error;
#[cfg(feature = "language")]
pub use live::{LiveExit, LiveOptions, LiveRun, Pump};
#[cfg(feature = "language")]
pub use program::Program;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,255 @@
use std::sync::{Arc, Mutex, PoisonError};
use psychoscript::{
Compiled, Data, HostError, HostFunction, HostResult, HostValue, Limits, Runtime,
};
use crate::draw;
use crate::error::Error;
use crate::json::{self, Input};
use crate::live::{LiveOptions, LiveRun, MARK, WIDGET_DEPTH};
use crate::tree::{Walk, WalkError};
/// A program compiled once, to run as often as needed: each run has its own VM. A run reads its JSON input through
/// one sync host function, `input_name` (`__input` by default), and its result is the program's completion value.
#[derive(Debug, Clone)]
pub struct Program {
compiled: Compiled,
input_name: String,
}
impl Program {
/// Compiles `source`. Fails with `Syntax` when it doesn't parse.
pub fn new(source: &str, input_name: Option<String>) -> Result<Program, Error> {
let compiled = Runtime::make()
.compile(source)
.map_err(|d| Error::from_diagnostic(d, None))?;
Ok(Program {
compiled,
input_name: input_name.unwrap_or_else(|| "__input".to_owned()),
})
}
/// Runs the program to its end with `input_json` behind its input function, under `timeout_ms` of active time,
/// and returns its result as JSON (`undefined` as `null`), at most `max_output_bytes` of it.
pub fn run(
&self,
input_json: &str,
timeout_ms: Option<u64>,
max_output_bytes: Option<u64>,
) -> Result<String, Error> {
let out = self.execute(input_json, timeout_ms, None)?.to_json_string();
limit(out, max_output_bytes)
}
/// [`Program::run`] for a widget step run natively (`return __widget_native_step(__input())`, widgets.md, "Native
/// hosts"): functions cross as markers, and `__widget_emit(view)` hands over the view as built, which goes out as
/// the tree clients get, built while it is written ([`crate::tree`]). The result is the run's, its functions left
/// out as JSON leaves them, with `view` added when one was emitted (`init` and `event` steps; draw steps run with
/// [`Program::run_draw`]). A view that breaks a rule of views (or that the prelude found too deep to hand over, `__widget_emit(null,
/// message)`) fails the step with [`Error::View`] once it has run; a function where none may go, or a key
/// `encodeURIComponent` can't encode, is thrown from `__widget_emit` as the runtime's own error.
pub fn run_step(
&self,
input_json: &str,
timeout_ms: Option<u64>,
max_output_bytes: Option<u64>,
) -> Result<String, Error> {
let emitted = Arc::new(Mutex::new(Emitted::default()));
let result = self.execute(input_json, timeout_ms, Some(&emitted));
let emitted = std::mem::take(&mut *emitted.lock().unwrap_or_else(PoisonError::into_inner));
if let Some(failure) = emitted.failure {
return Err(failure);
}
let mut out = result?.to_json_string();
if let Some(view) = emitted.view
&& out.ends_with('}')
{
out.pop();
if out.len() > 1 {
out.push(',');
}
out.push_str("\"view\":");
out.push_str(&view);
out.push('}');
}
limit(out, max_output_bytes)
}
/// A widget draw step run natively (`return __widget_native_step(__input())` on a `draw` input, widgets.md,
/// "Native hosts"): functions cross as markers, and the commands the program gives `__widget_emit(commands)`, read
/// as JSON reads them and checked (widgets.md, Canvas, "Draw command checks"), come back normalised, or `null` when
/// it gave none; invalid ones fail with [`Error::Draw`]. The run's own result isn't read.
pub fn run_draw(
&self,
input_json: &str,
timeout_ms: Option<u64>,
max_output_bytes: Option<u64>,
) -> Result<String, Error> {
let emitted = Arc::new(Mutex::new(Emitted {
draw: true,
..Emitted::default()
}));
let result = self.execute(input_json, timeout_ms, Some(&emitted));
let emitted = std::mem::take(&mut *emitted.lock().unwrap_or_else(PoisonError::into_inner));
if let Some(failure) = emitted.failure {
return Err(failure);
}
result?;
limit(
emitted.view.unwrap_or_else(|| "null".to_owned()),
max_output_bytes,
)
}
/// One run's result; with `emitted`, a native step's: functions cross as markers, and `__widget_emit` writes the
/// view there.
fn execute(
&self,
input_json: &str,
timeout_ms: Option<u64>,
emitted: Option<&Arc<Mutex<Emitted>>>,
) -> Result<Data, Error> {
if timeout_ms == Some(0) {
return Err(Error::invalid_input("timeout_ms must be at least 1"));
}
let first = Input::parse(input_json)
.map_err(|e| Error::invalid_input(format!("the input isn't JSON: {e}")))?;
let slot = Arc::new(Mutex::new(Slot {
text: input_json.into(),
first: Some(first),
}));
let name = self.input_name.clone();
let emit = emitted.cloned();
let mut runtime = Runtime::make()
.globals(move |_run| {
let slot = slot.clone();
let input_name = name.clone();
let mut globals = vec![(
name.clone(),
HostFunction::new(move |args: Vec<HostValue>, _call| -> HostResult {
json::unmarked(&args, &input_name, 0)?;
Ok(slot.lock().unwrap_or_else(PoisonError::into_inner).read())
}),
)];
if let Some(emitted) = emit.clone() {
globals.push((
EMIT.to_owned(),
HostFunction::new(move |args: Vec<HostValue>, _call| {
emitted
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take(&args)
})
.length(1),
));
}
globals
})
.limits(Limits {
timeout_ms,
max_value_depth: emitted.is_some().then_some(WIDGET_DEPTH),
..Limits::default()
});
if emitted.is_some() {
// A widget step: handler functions cross as markers.
runtime = runtime.translate(MARK);
}
let outcome = runtime.execute(&self.compiled);
drop(runtime);
outcome
.result
.map_err(|d| Error::from_diagnostic(d, timeout_ms))
}
}
/// The host global a native step hands its view to.
const EMIT: &str = "__widget_emit";
/// What a native step's `__widget_emit` took: the view's wire JSON (a draw step's commands as JSON), or why the view
/// failed.
#[derive(Default)]
struct Emitted {
/// A draw step: `__widget_emit(commands)`.
draw: bool,
view: Option<String>,
failure: Option<Error>,
}
impl Emitted {
/// `__widget_emit(view, failure?)`: a string `failure` fails the view with it; else the view is walked. In a draw
/// step, `__widget_emit(commands)`.
fn take(&mut self, args: &[HostValue]) -> HostResult {
json::unmarked(args, EMIT, 1)?;
if self.draw {
match draw::check_read(args.first().unwrap_or(&HostValue::Undefined)) {
Ok(commands) => self.view = Some(commands),
Err(reason) => self.failure = Some(Error::Draw { reason }),
}
return Ok(HostValue::Undefined);
}
if let Some(HostValue::String(failure)) = args.get(1) {
self.failure = Some(Error::View {
reason: failure.to_string_lossy().into_owned(),
});
return Ok(HostValue::Undefined);
}
let mut out = String::new();
match Walk::new().run(args.first().unwrap_or(&HostValue::Undefined), &mut out) {
Ok(_) => self.view = Some(out),
Err(WalkError::View(reason)) => {
self.failure = Some(Error::View {
reason: reason.to_owned(),
})
}
Err(WalkError::Function) => return Err(json::carried(1, EMIT)),
Err(WalkError::Uri) => return Err(uri_error()),
}
Ok(HostValue::Undefined)
}
}
/// The prelude's error for a key `encodeURIComponent` can't encode, located at the call.
pub(crate) fn uri_error() -> HostValue {
HostError::located("URIError", "URI malformed")
}
/// `out`, unless it's over `max_output_bytes`.
fn limit(out: String, max_output_bytes: Option<u64>) -> Result<String, Error> {
match max_output_bytes {
Some(max) if out.len() as u64 > max => Err(Error::OutputTooLarge {
reason: format!(
"the result is {} bytes of JSON, over the limit of {max}",
out.len()
),
max_output_bytes: max,
}),
_ => Ok(out),
}
}
impl Program {
/// Starts the program as a [`LiveRun`] with `input_json` behind its input function and `__host`.
pub fn start_live(&self, input_json: &str, options: LiveOptions) -> Result<LiveRun, Error> {
LiveRun::start(
self.compiled.clone(),
self.input_name.clone(),
input_json,
options,
)
}
}
/// A run's input: the parsed value, handed over whole on the first read, and the text to read it again from.
struct Slot {
text: Arc<str>,
first: Option<HostValue>,
}
impl Slot {
fn read(&mut self) -> HostValue {
self.first
.take()
.unwrap_or_else(|| Input::parse(&self.text).unwrap_or_default())
}
}

View file

@ -0,0 +1,6 @@
//! `std::time::Instant` panics in a browser: `web-time` reads `performance.now()` there.
#[cfg(not(target_arch = "wasm32"))]
pub use std::time::Instant;
#[cfg(target_arch = "wasm32")]
pub use web_time::Instant;

View file

@ -0,0 +1,598 @@
//! Building the view tree clients get, natively (widgets.md, "Native hosts"): from a view as the program built it
//! (handler props as function markers, `key`s, `children` as written) straight to the wire JSON, while writing it. It
//! makes exactly what the prelude's `__widget_tree` makes: props in order without `key`, `id`, `pointer`, `onPress`,
//! `onChange`, `onPointer` and `children`; then `id` (the node's path) on controls, `pointer: true` on a canvas with a
//! handler, and `children` last, flattened. It also tells which ids have handlers and the canvas ids by key.
//!
//! It holds views to the rules of views (widgets.md, "Keys and depth"): a key is a string, a number or a boolean, and
//! a view nests at most [`LEVELS`] levels. A function anywhere but a node's handler props fails, as it fails a host
//! call's argument without `"mark"`.
//!
//! The walk is generic over the value it reads ([`View`]): a host call's argument ([`HostValue`]), or JSON in tests.
//! Numbers and strings are written as `JSON.stringify` writes them.
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt::Write as _;
use psychoscript::{HostString, HostValue};
/// The most levels a view nests (widgets.md, "Keys and depth").
pub const LEVELS: u32 = 100;
/// The failure of a view deeper than [`LEVELS`].
pub const DEEP: &str = "The view nests more than 100 levels";
/// The failure of a view with a key of another type.
pub const KEY: &str = "A node's key must be a string, a number or a boolean";
/// What a value is, as far as the walk cares.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
/// `undefined`, or a hole: falsy, left out of an object, `null` in an array.
Undefined,
/// A program function (the function marker): only a node's handler prop may hold one, which makes the node's id a
/// handler's.
Function,
Null,
Bool,
Number,
String,
Array,
Object,
/// Another object (a `Date`, a `Map`, ...): written as JSON writes it ([`View::write_other`]).
Other,
}
/// A string as the walk reads it: UTF-8, or UTF-16 code units when it has an unpaired surrogate.
pub enum Text<'a> {
Str(&'a str),
Units(Cow<'a, [u16]>),
}
/// A value the walk can read.
pub trait View: Sized {
fn kind(&self) -> Kind;
fn boolean(&self) -> bool;
fn number(&self) -> f64;
fn text(&self) -> Text<'_>;
/// An array's items in order; `None` for a hole.
fn items(&self) -> impl Iterator<Item = Option<&Self>>;
/// An object's props in order.
fn props(&self) -> impl Iterator<Item = (Text<'_>, &Self)>;
/// An object's prop by name.
fn get(&self, name: &str) -> Option<&Self>;
/// A [`Kind::Other`] value as JSON.
fn write_other(&self, out: &mut String) {
out.push_str("null");
}
}
/// The controls (widgets.md, Events): handler prop, event, whether it always has an id, whether a `key` gives one.
fn control(kind: &str) -> Option<(&'static str, &'static str, bool, bool)> {
Some(match kind {
"button" => ("onPress", "press", true, false),
"card" => ("onPress", "press", false, false),
"checkbox" => ("onChange", "change", true, false),
"slider" => ("onChange", "change", true, false),
"select" => ("onChange", "change", true, false),
"input" => ("onChange", "change", true, false),
"carousel" => ("onChange", "change", false, false),
"canvas" => ("onPointer", "pointer", false, true),
_ => return None,
})
}
const HANDLERS: [&str; 3] = ["onPress", "onChange", "onPointer"];
/// What the walk learned of a view besides its JSON.
#[derive(Debug, Default)]
pub struct Tree {
/// Some id has a handler.
pub has_handlers: bool,
/// The ids with handlers and their events, in the order met (a later node with the same id overrides), when asked
/// for ([`Walk::handlers`]).
pub handlers: Option<Vec<(String, &'static str)>>,
/// The first canvas with each `String(key)`: its id and how it is drawn.
pub canvases: HashMap<String, (String, Drawn)>,
}
/// How a canvas is drawn (widgets.md, Canvas; widgets-gpu.md): one way only.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Drawn {
/// By draw commands.
Commands,
/// By its `wgsl`.
Wgsl,
/// By the program's WebGPU calls (`gpu: true`).
Gpu,
}
/// Why a view didn't walk.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum WalkError {
/// It breaks a rule of views ([`KEY`], [`DEEP`]): a program error in phase `view`.
View(&'static str),
/// A function where none may go: the host call fails with the runtime's `TypeError`.
Function,
/// A key `encodeURIComponent` can't encode (a lone surrogate): the prelude's `URIError`.
Uri,
}
/// One walk of one view.
pub struct Walk {
tree: Tree,
path: String,
}
impl Walk {
pub fn new() -> Self {
Walk {
tree: Tree::default(),
path: String::with_capacity(64),
}
}
/// Also collect every handler id with its event (for tests; a host only needs [`Tree::has_handlers`]).
pub fn handlers(mut self) -> Self {
self.tree.handlers = Some(Vec::new());
self
}
/// Writes the wire JSON of view `root` to `out`, and returns what it learned. `out` holds part of it on an error.
pub fn run<V: View>(mut self, root: &V, out: &mut String) -> Result<Tree, WalkError> {
self.path.clear();
if root.kind() != Kind::Object {
write_json(root, out)?;
return Ok(self.tree);
}
match root.get("key") {
Some(key) if keyed(key)? => segment(key, &mut self.path)?,
_ => self.path.push('0'),
}
self.node(root, 1, out)?;
Ok(self.tree)
}
/// Node `v` at `self.path`, at `level`, its key checked.
fn node<V: View>(&mut self, v: &V, level: u32, out: &mut String) -> Result<(), WalkError> {
out.push('{');
let mut first = true;
let mut kind = None;
let mut children = None;
for (text, prop) in v.props() {
let name = match &text {
Text::Str(s) => Some(*s),
Text::Units(_) => None,
};
match name {
Some("type") if prop.kind() == Kind::String => {
if let Text::Str(s) = prop.text() {
kind = control(s).map(|c| (s == "canvas", c));
}
}
Some("children") => {
children = Some(prop);
continue;
}
Some(n) if HANDLERS.contains(&n) => continue,
Some("key" | "id" | "pointer") => {
if carries_function(prop) {
return Err(WalkError::Function);
}
continue;
}
_ => {}
}
match prop.kind() {
Kind::Undefined => continue,
Kind::Function => return Err(WalkError::Function),
_ => {}
}
if !first {
out.push(',');
}
first = false;
write_text(&text, out);
out.push(':');
write_json(prop, out)?;
}
if let Some((canvas, (handler, event, always, by_key))) = kind {
let handled = v.get(handler).is_some_and(|h| h.kind() == Kind::Function);
let key = if by_key {
v.get("key")
.filter(|k| !matches!(k.kind(), Kind::Undefined | Kind::Null))
} else {
None
};
if handled || always || key.is_some() {
if !first {
out.push(',');
}
first = false;
// A path is ASCII without quotes or backslashes: `0`, `/`, digits, `.`, `~` and encoded keys.
out.push_str("\"id\":\"");
out.push_str(&self.path);
out.push('"');
if handled {
self.tree.has_handlers = true;
if let Some(list) = &mut self.tree.handlers {
list.push((self.path.clone(), event));
}
if canvas {
out.push_str(",\"pointer\":true");
}
}
if let Some(key) = key {
let name = string_of(key);
if !self.tree.canvases.contains_key(&name) {
let drawn = if v.get("wgsl").is_some_and(|w| w.kind() == Kind::String) {
Drawn::Wgsl
} else if v
.get("gpu")
.is_some_and(|g| g.kind() == Kind::Bool && g.boolean())
{
Drawn::Gpu
} else {
Drawn::Commands
};
self.tree.canvases.insert(name, (self.path.clone(), drawn));
}
}
}
}
if let Some(list) = children.filter(|c| c.kind() != Kind::Undefined) {
if !first {
out.push(',');
}
out.push_str("\"children\":[");
let mut seen: HashMap<String, u32> = HashMap::new();
let mut any = false;
if list.kind() == Kind::Array {
self.flatten(list, "", level + 1, out, &mut seen, &mut any)?;
} else {
self.item(list, "0", level + 1, out, &mut seen, &mut any)?;
}
out.push(']');
}
out.push('}');
Ok(())
}
/// An array of children at `prefix` (`""`, `"2."`, `"2.1."`), its items at `level`.
fn flatten<V: View>(
&mut self,
list: &V,
prefix: &str,
level: u32,
out: &mut String,
seen: &mut HashMap<String, u32>,
any: &mut bool,
) -> Result<(), WalkError> {
let mut index = String::new();
for (i, item) in list.items().enumerate() {
let Some(item) = item else { continue };
index.clear();
index.push_str(prefix);
let _ = write!(index, "{i}");
self.item(item, &index, level, out, seen, any)?;
}
Ok(())
}
/// One item among a node's children, at `index` and `level`: skipped when falsy, flattened when an array.
fn item<V: View>(
&mut self,
item: &V,
index: &str,
level: u32,
out: &mut String,
seen: &mut HashMap<String, u32>,
any: &mut bool,
) -> Result<(), WalkError> {
if falsy(item) {
return Ok(());
}
let kind = item.kind();
if level > LEVELS && matches!(kind, Kind::Array | Kind::Object | Kind::Other) {
return Err(WalkError::View(DEEP));
}
if kind == Kind::Array {
let mut deeper = String::with_capacity(index.len() + 1);
deeper.push_str(index);
deeper.push('.');
return self.flatten(item, &deeper, level + 1, out, seen, any);
}
if *any {
out.push(',');
}
*any = true;
if kind != Kind::Object {
// A string, a number, `true`, or another object.
return write_json(item, out);
}
let len = self.path.len();
self.path.push('/');
match item.get("key") {
Some(key) if keyed(key)? => {
let at = self.path.len();
segment(key, &mut self.path)?;
let n = seen.entry(self.path[at..].to_owned()).or_insert(0);
*n += 1;
if *n > 1 {
let _ = write!(self.path, "~{n}");
}
}
_ => self.path.push_str(index),
}
let done = self.node(item, level, out);
self.path.truncate(len);
done
}
}
impl Default for Walk {
fn default() -> Self {
Self::new()
}
}
/// Whether `key` names a node: `undefined` and `null` don't, a string, a number or a boolean does, and anything else
/// fails the view.
fn keyed<V: View>(key: &V) -> Result<bool, WalkError> {
match key.kind() {
Kind::Undefined | Kind::Null => Ok(false),
Kind::String | Kind::Number | Kind::Bool => Ok(true),
Kind::Function | Kind::Array | Kind::Object | Kind::Other => Err(WalkError::View(KEY)),
}
}
/// Whether `v` is or holds a function.
fn carries_function<V: View>(v: &V) -> bool {
match v.kind() {
Kind::Function => true,
Kind::Array => v.items().flatten().any(carries_function),
Kind::Object => v.props().any(|(_, p)| carries_function(p)),
_ => false,
}
}
/// JavaScript's truthiness, for children.
fn falsy<V: View>(v: &V) -> bool {
match v.kind() {
Kind::Undefined | Kind::Null => true,
Kind::Bool => !v.boolean(),
Kind::Number => {
let n = v.number();
n == 0.0 || n.is_nan()
}
Kind::String => match v.text() {
Text::Str(s) => s.is_empty(),
Text::Units(u) => u.is_empty(),
},
Kind::Function | Kind::Array | Kind::Object | Kind::Other => false,
}
}
/// `":" + encodeURIComponent(String(key))` of a key (a string, a number or a boolean), appended to `out`.
fn segment<V: View>(key: &V, out: &mut String) -> Result<(), WalkError> {
out.push(':');
match key.kind() {
Kind::String => match key.text() {
Text::Str(s) => encode(s, out),
Text::Units(_) => return Err(WalkError::Uri),
},
_ => encode(&string_of(key), out),
}
Ok(())
}
/// `String(key)` of a key (a string, a number or a boolean), lossy for a lone surrogate (which `segment` refuses first).
fn string_of<V: View>(v: &V) -> String {
match v.kind() {
Kind::String => match v.text() {
Text::Str(s) => s.to_owned(),
Text::Units(u) => String::from_utf16_lossy(&u),
},
Kind::Number => number(v.number()),
Kind::Bool => (if v.boolean() { "true" } else { "false" }).to_owned(),
_ => String::new(),
}
}
/// ECMAScript `Number::toString`.
fn number(n: f64) -> String {
let mut buffer = ryu_js::Buffer::new();
buffer.format(n).to_owned()
}
/// `encodeURIComponent` of well-formed text: UTF-8 bytes percent-encoded, uppercase, except `A-Z a-z 0-9 - _ . ! ~ * ' ( )`.
fn encode(s: &str, out: &mut String) {
for &b in s.as_bytes() {
if b.is_ascii_alphanumeric()
|| matches!(
b,
b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')'
)
{
out.push(b as char);
} else {
let _ = write!(out, "%{b:02X}");
}
}
}
/// A value of a view as `JSON.stringify` writes it (`undefined` left out of objects, `null` in arrays, non-finite
/// numbers `null`); a function fails.
fn write_json<V: View>(v: &V, out: &mut String) -> Result<(), WalkError> {
match v.kind() {
Kind::Function => return Err(WalkError::Function),
Kind::Undefined | Kind::Null => out.push_str("null"),
Kind::Bool => out.push_str(if v.boolean() { "true" } else { "false" }),
Kind::Number => {
let n = v.number();
if n.is_finite() {
out.push_str(ryu_js::Buffer::new().format_finite(n));
} else {
out.push_str("null");
}
}
Kind::String => write_text(&v.text(), out),
Kind::Other => v.write_other(out),
Kind::Array => {
out.push('[');
for (i, item) in v.items().enumerate() {
if i > 0 {
out.push(',');
}
match item {
Some(item) => write_json(item, out)?,
None => out.push_str("null"),
}
}
out.push(']');
}
Kind::Object => {
out.push('{');
let mut first = true;
for (name, prop) in v.props() {
match prop.kind() {
Kind::Undefined => continue,
Kind::Function => return Err(WalkError::Function),
_ => {}
}
if !first {
out.push(',');
}
first = false;
write_text(&name, out);
out.push(':');
write_json(prop, out)?;
}
out.push('}');
}
}
Ok(())
}
fn write_text(t: &Text<'_>, out: &mut String) {
match t {
Text::Str(s) => write_str(s, out),
Text::Units(u) => write_units(u, out),
}
}
/// A string as `JSON.stringify` quotes it.
fn write_str(s: &str, out: &mut String) {
out.push('"');
let mut start = 0;
for (i, b) in s.bytes().enumerate() {
let escape = match b {
b'"' => "\\\"",
b'\\' => "\\\\",
b'\n' => "\\n",
b'\r' => "\\r",
b'\t' => "\\t",
0x08 => "\\b",
0x0c => "\\f",
0..=0x1f => "",
_ => continue,
};
out.push_str(&s[start..i]);
if escape.is_empty() {
let _ = write!(out, "\\u{b:04x}");
} else {
out.push_str(escape);
}
start = i + 1;
}
out.push_str(&s[start..]);
out.push('"');
}
/// UTF-16 text with unpaired surrogates, as `JSON.stringify` quotes it (`\udxxx` for each lone one).
fn write_units(units: &[u16], out: &mut String) {
out.push('"');
for unit in char::decode_utf16(units.iter().copied()) {
match unit {
Ok(c) => {
let mut buf = [0u8; 4];
let s: &str = c.encode_utf8(&mut buf);
let mut quoted = String::new();
write_str(s, &mut quoted);
out.push_str(&quoted[1..quoted.len() - 1]);
}
Err(e) => {
let _ = write!(out, "\\u{:04x}", e.unpaired_surrogate());
}
}
}
out.push('"');
}
fn host_text(s: &HostString) -> Text<'_> {
match s.as_str() {
Some(s) => Text::Str(s),
None => Text::Units(s.to_utf16()),
}
}
impl View for HostValue {
fn kind(&self) -> Kind {
match self {
HostValue::Null => Kind::Null,
HostValue::Bool(_) => Kind::Bool,
HostValue::Number(_) => Kind::Number,
HostValue::String(_) => Kind::String,
HostValue::Array(_) => Kind::Array,
HostValue::Object(_) => Kind::Object,
HostValue::Function(_) | HostValue::FunctionMarker => Kind::Function,
HostValue::Undefined
| HostValue::Interrupt
| HostValue::Durable(_)
| HostValue::Namespace(_) => Kind::Undefined,
_ => Kind::Other,
}
}
fn boolean(&self) -> bool {
matches!(self, HostValue::Bool(true))
}
fn number(&self) -> f64 {
match self {
HostValue::Number(n) => *n,
_ => f64::NAN,
}
}
fn text(&self) -> Text<'_> {
match self {
HostValue::String(s) => host_text(s),
_ => Text::Str(""),
}
}
fn items(&self) -> impl Iterator<Item = Option<&Self>> {
let items: &[Option<HostValue>] = match self {
HostValue::Array(items) => items,
_ => &[],
};
items.iter().map(Option::as_ref)
}
fn props(&self) -> impl Iterator<Item = (Text<'_>, &Self)> {
let props: &[(HostString, HostValue)] = match self {
HostValue::Object(props) => props,
_ => &[],
};
props.iter().map(|(k, v)| (host_text(k), v))
}
fn get(&self, name: &str) -> Option<&Self> {
match self {
HostValue::Object(props) => props.iter().rev().find(|(k, _)| k == name).map(|(_, v)| v),
_ => None,
}
}
fn write_other(&self, out: &mut String) {
match self.to_json() {
Some(json) => {
let _ = write!(out, "{json}");
}
None => out.push_str("null"),
}
}
}

View file

@ -0,0 +1,208 @@
//! The JavaScript bindings (`wasm32-unknown-unknown`, wasm-bindgen). Errors are thrown as `Error`s named
//! `PsychoScriptError` with `type`, `kind`, `line`, `column` and `phase` (see [`crate::Error`]).
use wasm_bindgen::prelude::*;
#[cfg(feature = "language")]
use crate::{Error, LiveOptions, LiveRun, Program, Pump};
fn set(target: &JsValue, key: &str, value: JsValue) {
let _ = js_sys::Reflect::set(target, &JsValue::from_str(key), &value);
}
#[cfg(feature = "language")]
fn thrown(e: Error) -> JsValue {
let error = js_sys::Error::new(e.reason());
error.set_name("PsychoScriptError");
let value: JsValue = error.into();
set(&value, "type", e.type_name().into());
if let Some(kind) = e.kind() {
set(&value, "kind", kind.into());
}
if let Some((line, column)) = e.location() {
set(&value, "line", line.into());
set(&value, "column", column.into());
}
if let Some(phase) = e.phase() {
set(&value, "phase", phase.into());
}
value
}
/// A program compiled once, to run as often as needed (each run has its own VM).
#[cfg(feature = "language")]
#[wasm_bindgen(js_name = Program)]
pub struct JsProgram(Program);
#[cfg(feature = "language")]
#[wasm_bindgen(js_class = Program)]
impl JsProgram {
/// Compiles `source`; its runs read their input through `inputName()` (`__input` by default).
#[wasm_bindgen(constructor)]
pub fn new(source: &str, input_name: Option<String>) -> Result<JsProgram, JsValue> {
Program::new(source, input_name)
.map(JsProgram)
.map_err(thrown)
}
/// Runs the program with `inputJson` behind its input function; returns its completion value as JSON.
pub fn run(
&self,
input_json: &str,
timeout_ms: Option<f64>,
max_output_bytes: Option<f64>,
) -> Result<String, JsValue> {
self.0
.run(
input_json,
timeout_ms.map(|t| t.max(1.0) as u64),
max_output_bytes.map(|m| m.max(0.0) as u64),
)
.map_err(thrown)
}
/// Runs a widget step natively (`return __widget_native_step(__input())`, widgets.md "Native hosts"): as `run`,
/// with the view the program gave `__widget_emit` added as `view`, written as the tree clients get.
#[wasm_bindgen(js_name = runStep)]
pub fn run_step(
&self,
input_json: &str,
timeout_ms: Option<f64>,
max_output_bytes: Option<f64>,
) -> Result<String, JsValue> {
self.0
.run_step(
input_json,
timeout_ms.map(|t| t.max(1.0) as u64),
max_output_bytes.map(|m| m.max(0.0) as u64),
)
.map_err(thrown)
}
/// Runs a widget draw step natively: the commands the program gave `__widget_emit`, as JSON (`null` for none).
#[wasm_bindgen(js_name = runDraw)]
pub fn run_draw(
&self,
input_json: &str,
timeout_ms: Option<f64>,
max_output_bytes: Option<f64>,
) -> Result<String, JsValue> {
self.0
.run_draw(
input_json,
timeout_ms.map(|t| t.max(1.0) as u64),
max_output_bytes.map(|m| m.max(0.0) as u64),
)
.map_err(thrown)
}
/// Starts the program as a live run with `inputJson` behind its input function and `__host`. `options`:
/// `{ sliceBudgetMs = 50, maxPostsPerSecond = 240, httpsHosts?: string[], allowLocalNetwork = false,
/// native = false }` (`native`: a `__widget_live(__input(), true)` run, widgets.md "Native hosts").
#[wasm_bindgen(js_name = startLive)]
pub fn start_live(&self, input_json: &str, options: JsValue) -> Result<JsLiveRun, JsValue> {
let mut o = LiveOptions::default();
if options.is_object() {
let get = |k: &str| js_sys::Reflect::get(&options, &JsValue::from_str(k)).ok();
if let Some(n) = get("sliceBudgetMs").and_then(|v| v.as_f64()) {
o.slice_budget_ms = n.max(1.0) as u64;
}
if let Some(n) = get("maxPostsPerSecond").and_then(|v| v.as_f64()) {
o.max_posts_per_second = n.max(0.0) as u32;
}
o.allow_local_network =
get("allowLocalNetwork").is_some_and(|v| v.as_bool() == Some(true));
o.native = get("native").is_some_and(|v| v.as_bool() == Some(true));
if let Some(hosts) = get("httpsHosts").filter(js_sys::Array::is_array) {
o.https_hosts = Some(
js_sys::Array::from(&hosts)
.iter()
.filter_map(|h| h.as_string())
.collect(),
);
}
}
self.0
.start_live(input_json, o)
.map(JsLiveRun)
.map_err(thrown)
}
}
/// A long-running program, driven by `pump` (see `LiveRun` in the crate docs).
#[cfg(feature = "language")]
#[wasm_bindgen(js_name = LiveRun)]
pub struct JsLiveRun(LiveRun);
#[cfg(feature = "language")]
#[wasm_bindgen(js_class = LiveRun)]
impl JsLiveRun {
/// Runs the program for up to `maxMs`. Returns `-3` once it ended (`exit()` says how), `-2` while still computing
/// (pump again soon), `-1` when it waits on the host with no timer, else the ms until its next timer.
pub fn pump(&mut self, max_ms: f64) -> f64 {
match self.0.pump(max_ms) {
Pump::Ended => -3.0,
Pump::Again => -2.0,
Pump::Wait(None) => -1.0,
Pump::Wait(Some(ms)) => ms,
}
}
/// Queues a JSON message for `__host.receive()`. Pump afterwards.
pub fn deliver(&mut self, message_json: &str) -> Result<(), JsValue> {
self.0.deliver(message_json).map_err(thrown)
}
/// What the program posted and the requests it made since the last call, as a JSON array.
#[wasm_bindgen(js_name = takeOutbox)]
pub fn take_outbox(&mut self) -> String {
self.0.take_outbox()
}
/// The bytes of the GPU batches in the outbox `takeOutbox` just gave (`bytes: [offset, length]`): call it right
/// after.
#[wasm_bindgen(js_name = takeBytes)]
pub fn take_bytes(&mut self) -> Vec<u8> {
self.0.take_bytes()
}
/// Answers fetch `id`: `metaJson` is `{ status, url, headers }` (the final URL), `body` the body's bytes.
#[wasm_bindgen(js_name = fetchDone)]
pub fn fetch_done(&mut self, id: f64, meta_json: &str, body: Vec<u8>) {
self.0.fetch_done(id as u64, meta_json, body);
}
/// Fails fetch `id` with `kind` (`Network`, `Timeout`, `TooLarge`).
#[wasm_bindgen(js_name = fetchFailed)]
pub fn fetch_failed(&mut self, id: f64, kind: &str, message: &str) {
self.0.fetch_failed(id as u64, kind, message);
}
pub fn pause(&mut self) -> Result<(), JsValue> {
self.0.pause().map_err(thrown)
}
pub fn resume(&mut self) -> Result<(), JsValue> {
self.0.resume().map_err(thrown)
}
pub fn stop(&mut self) {
self.0.stop();
}
#[wasm_bindgen(js_name = isPaused)]
pub fn is_paused(&self) -> bool {
self.0.is_paused()
}
#[wasm_bindgen(js_name = nowMs)]
pub fn now_ms(&self) -> f64 {
self.0.now_ms()
}
/// How the run ended, as JSON (`{ type: "finished", result }`, `{ type: "failed", error }`,
/// `{ type: "stopped" }`), or `undefined` while it runs.
pub fn exit(&self) -> Option<String> {
self.0.exit().map(|e| e.to_json())
}
}

View file

@ -0,0 +1,139 @@
//! The draw command checks against the shared fixtures (`packages/widget/test/fixtures/draw.json`, read in place):
//! every case through a draw step (the commands read as JSON reads them) and a live `widget.draw` (as they
//! cross) gives exactly its normalised commands, or fails with exactly its message in phase `draw`.
use std::path::Path;
use std::time::{Duration, Instant};
use serde_json::Value;
use widget_web::{Error, LiveExit, LiveOptions, Program, Pump};
const SPECIAL: [&str; 4] = ["NaN", "Infinity", "-Infinity", "undefined"];
/// The case's commands as a JavaScript expression, `"$NaN"` and the like as those values.
fn expression(case: &Value) -> String {
if let Some(repeat) = case.get("repeat") {
return format!(
"Array.from({{ length: {} }}, () => {})",
repeat["count"], repeat["command"]
);
}
let mut text = case["commands"].to_string();
for name in SPECIAL {
text = text.replace(&format!("\"${name}\""), name);
}
text
}
/// What the case expects: the normalised commands, or the failure's message.
fn expected(case: &Value) -> Result<Value, String> {
if let Some(error) = case.get("error") {
return Err(error.as_str().unwrap().to_owned());
}
let valid = &case["valid"];
Ok(match valid.get("repeat") {
Some(repeat) => Value::Array(vec![
repeat["command"].clone();
repeat["count"].as_u64().unwrap() as usize
]),
None => valid.clone(),
})
}
/// A file of `@opencode/widget` (`packages/widget`), read in place.
fn read(name: &str) -> String {
std::fs::read_to_string(
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../../widget")
.join(name),
)
.unwrap()
}
/// A step program's prelude; a live one's adds the live prelude (`packages/widget/src`).
fn prelude() -> String {
read("src/prelude.js")
}
fn live_prelude() -> String {
format!(
"{}\n{}",
read("src/prelude.js"),
read("src/prelude-live.js")
)
}
fn parse(text: &str) -> Value {
serde_json::from_str(text).expect("JSON")
}
fn failure(error: &Error) -> String {
assert_eq!(error.phase(), Some("draw"), "{error}");
error.reason().to_owned()
}
fn step(expression: &str) -> Result<Value, String> {
let program = format!(
"{}\nfunction view() {{ return ui.canvas({{ key: \"c\", height: 1 }}) }}\nfunction draw() {{ return {expression} }}\nreturn __widget_native_step(__input())",
prelude()
);
let input = r#"{"phase":"draw","data":null,"state":{},"frame":{"id":":c","t":0,"dt":0,"width":10,"height":10,"scale":1,"pointer":null,"dark":false}}"#;
Program::new(&program, None)
.unwrap()
.run_draw(input, None, None)
.map(|out| parse(&out))
.map_err(|e| failure(&e))
}
fn live(expression: &str) -> Result<Value, String> {
let program = format!(
"{}\nasync function main() {{\n widget.render(ui.canvas({{ key: \"c\", height: 1 }}))\n widget.draw(\"c\", {expression})\n}}\nreturn await __widget_live(__input(), true)",
live_prelude()
);
let mut run = Program::new(&program, None)
.unwrap()
.start_live(
r#"{"data":null}"#,
LiveOptions {
native: true,
..Default::default()
},
)
.unwrap();
let deadline = Instant::now() + Duration::from_secs(5);
let mut posts = Vec::new();
loop {
let pump = run.pump(8.0);
let out = parse(&run.take_outbox());
posts.extend(out.as_array().unwrap().iter().cloned());
if pump == Pump::Ended || Instant::now() > deadline {
break;
}
std::thread::sleep(Duration::from_micros(200));
}
match run.exit() {
Some(LiveExit::Failed { error }) => Err(failure(error)),
Some(LiveExit::Finished { .. }) => Ok(posts
.iter()
.find(|e| e["message"]["type"] == "draw")
.map(|e| {
assert_eq!(e["message"]["id"], ":c");
e["message"]["commands"].clone()
})
.unwrap_or(Value::Array(Vec::new()))),
other => panic!("{other:?}"),
}
}
#[test]
fn every_draw_fixture_checks_alike_in_a_step_and_a_live_draw() {
let fixture = parse(&read("test/fixtures/draw.json"));
let cases = fixture["cases"].as_array().unwrap();
assert_eq!(cases.len(), 89);
for case in cases {
let name = case["name"].as_str().unwrap();
let (expression, want) = (expression(case), expected(case));
assert_eq!(step(&expression), want, "step: {name}");
assert_eq!(live(&expression), want, "live: {name}");
}
}

View file

@ -0,0 +1,909 @@
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use widget_web::{LiveExit, LiveOptions, LiveRun, Program, Pump};
const LOOP: &str = r#"
const input = __input()
__host.post({ type: "hello", n: input.n })
while (true) {
const m = await __host.receive()
if (m.type === "sleep") { const t = __host.now(); await __host.sleep(m.ms); __host.post({ type: "slept", took: __host.now() - t }) }
if (m.type === "flood") { for (let i = 0; i < 300; i++) __host.post({ i }); __host.post({ type: "flooded" }) }
if (m.type === "throw") throw new TypeError("bad frame")
if (m.type === "resumed") __host.post({ type: "resumed", pausedMs: m.pausedMs })
if (m.type === "fetch") {
try { __host.post({ type: "fetched", response: await __host.fetch(m.request) }) }
catch (e) { __host.post({ type: "rejected", kind: e.kind, message: e.message }) }
}
if (m.type === "done") return { ok: true }
}
"#;
fn start(options: LiveOptions) -> LiveRun {
Program::new(LOOP, None)
.unwrap()
.start_live(r#"{"n":7}"#, options)
.unwrap()
}
/// Pumps until the run waits with nothing woken, or ends; returns what it posted meanwhile.
fn settle(run: &mut LiveRun) -> Vec<Value> {
let mut out = Vec::new();
let deadline = Instant::now() + Duration::from_secs(5);
loop {
let pump = run.pump(8.0);
let outbox = run.take_outbox();
// Views of 100 levels nest past serde_json's default limit of 128.
let mut reader = serde_json::Deserializer::from_str(&outbox);
reader.disable_recursion_limit();
let batch: Vec<Value> = serde::Deserialize::deserialize(&mut reader).unwrap();
out.extend(batch);
match pump {
Pump::Ended => return out,
Pump::Wait(_) if !run.woken() => return out,
_ if Instant::now() > deadline => panic!("the run didn't settle"),
_ => std::thread::sleep(Duration::from_micros(200)),
}
}
}
fn posts(out: &[Value]) -> Vec<Value> {
out.iter()
.filter(|e| e["type"] == "post")
.map(|e| e["message"].clone())
.collect()
}
#[test]
fn posts_receives_and_finishes() {
let mut run = start(LiveOptions::default());
assert_eq!(
posts(&settle(&mut run)),
vec![json!({ "type": "hello", "n": 7 })]
);
run.deliver(r#"{"type":"done"}"#).unwrap();
settle(&mut run);
assert_eq!(
run.exit(),
Some(&LiveExit::Finished {
result_json: r#"{"ok":true}"#.into()
})
);
assert!(run.deliver("{}").is_err());
}
#[test]
fn sleeps_report_their_timer_and_pause_freezes_them() {
let mut run = start(LiveOptions::default());
settle(&mut run);
run.deliver(r#"{"type":"sleep","ms":40}"#).unwrap();
assert!(posts(&settle(&mut run)).is_empty());
let Pump::Wait(Some(left)) = run.pump(8.0) else {
panic!("expected a timer")
};
assert!(left > 0.0 && left <= 40.0, "{left}");
run.pause().unwrap();
assert_eq!(run.pump(8.0), Pump::Wait(None));
std::thread::sleep(Duration::from_millis(60));
assert!(
posts(&settle(&mut run)).is_empty(),
"a paused sleep doesn't end"
);
run.resume().unwrap();
let mut seen = Vec::new();
let deadline = Instant::now() + Duration::from_secs(2);
while seen.len() < 2 && Instant::now() < deadline {
seen.extend(posts(&settle(&mut run)));
std::thread::sleep(Duration::from_millis(5));
}
assert_eq!(seen[0]["type"], "slept");
assert!(seen[0]["took"].as_f64().unwrap() < 55.0, "{seen:?}");
assert_eq!(seen[1]["type"], "resumed");
assert!(seen[1]["pausedMs"].as_f64().unwrap() >= 55.0);
}
#[test]
fn deliveries_wait_while_paused() {
let mut run = start(LiveOptions::default());
settle(&mut run);
run.pause().unwrap();
run.deliver(r#"{"type":"throw"}"#).unwrap();
settle(&mut run);
assert!(run.exit().is_none());
run.resume().unwrap();
settle(&mut run);
match run.exit() {
Some(LiveExit::Failed { error }) => {
assert!(error.reason().contains("bad frame"), "{error}")
}
other => panic!("{other:?}"),
}
}
/// A generic run has no post rate: the widget rule lives in native runs.
#[test]
fn generic_runs_post_without_a_rate() {
let mut run = start(LiveOptions::default());
settle(&mut run);
run.deliver(r#"{"type":"flood"}"#).unwrap();
let out = settle(&mut run);
assert_eq!(posts(&out).len(), 301);
assert_eq!(out.iter().filter(|e| e["type"] == "warning").count(), 0);
}
#[test]
fn fetches_need_the_capability_and_go_through_the_host() {
let mut denied = start(LiveOptions::default());
settle(&mut denied);
denied
.deliver(r#"{"type":"fetch","request":{"url":"https://api.example.com/x"}}"#)
.unwrap();
assert_eq!(posts(&settle(&mut denied))[0]["kind"], "CapabilityDenied");
let mut run = start(LiveOptions {
https_hosts: Some(vec!["api.example.com".into()]),
..Default::default()
});
settle(&mut run);
run.deliver(r#"{"type":"fetch","request":{"url":"https://other.example.com/x"}}"#)
.unwrap();
assert_eq!(posts(&settle(&mut run))[0]["kind"], "CapabilityDenied");
run.deliver(
r#"{"type":"fetch","request":{"url":"https://api.example.com/x","method":"post","headers":{"Cookie":"a","X-Key":"k"},"body":"hi"}}"#,
)
.unwrap();
let out = settle(&mut run);
let request = out
.iter()
.find(|e| e["type"] == "fetch")
.expect("a fetch for the host");
assert_eq!(request["method"], "POST");
assert_eq!(request["headers"], json!([["x-key", "k"]]));
assert_eq!(request["body"], "hi");
let id = request["id"].as_u64().unwrap();
run.fetch_done(
id,
r#"{"status":201,"url":"https://api.example.com/x","headers":[["content-type","application/json"]]}"#,
br#"{"a":1}"#.to_vec(),
);
let fetched = posts(&settle(&mut run));
assert_eq!(fetched[0]["response"]["status"], 201);
assert_eq!(fetched[0]["response"]["body"], r#"{"a":1}"#);
run.deliver(r#"{"type":"fetch","request":{"url":"https://api.example.com/slow"}}"#)
.unwrap();
let id = settle(&mut run)[0]["id"].as_u64().unwrap();
run.fetch_failed(id, "Timeout", "no response within 15 s");
assert_eq!(posts(&settle(&mut run))[0]["kind"], "Timeout");
run.deliver(r#"{"type":"fetch","request":{"url":"https://api.example.com/never"}}"#)
.unwrap();
let id = settle(&mut run)[0]["id"].as_u64().unwrap();
run.stop();
assert_eq!(run.exit(), Some(&LiveExit::Stopped));
let out: Vec<Value> = serde_json::from_str(&run.take_outbox()).unwrap();
assert_eq!(out, vec![json!({ "type": "cancel", "id": id })]);
}
#[test]
fn native_runs_build_render_trees_and_draw_by_key() {
const NATIVE: &str = r#"
const view = { type: "column", children: [
[null, { type: "canvas", key: "board", height: 10, onPointer: () => {} }],
{ type: "canvas", key: "sky", wgsl: "fn shade(p: vec2f) -> vec4f { return vec4f(1.0); }", height: 10 },
] }
const interactive = __host.post({ type: "render", node: view })
const still = __host.post({ type: "render", node: { ...view, children: [view.children[1]] } })
__host.post({ type: "render", node: view })
__host.post({ type: "draw", key: "board", commands: [["rect", 0, 0, 1, 1, { fill: "accent" }]] })
const caught = []
for (const key of ["nope", "sky"]) {
try { __host.post({ type: "draw", key, commands: [] }) } catch (e) { caught.push(e.message) }
}
// A function anywhere but a node's handler props fails the call with the runtime's TypeError.
const functions = [
() => __host.post({ type: "send", value: { f: () => 1 } }),
() => __host.post({ type: "draw", key: "board", commands: [["rect", 0, 0, 1, 1, { fill: () => 1 }]] }),
() => __host.post({ type: "render", node: { type: "text", text: "x", extra: [() => 1] } }),
() => __host.post({ type: "render", node: { type: "button", label: "b", id: () => 1 } }),
() => __host.post({ type: "render", node: { type: "column", children: [() => 1] } }),
() => __host.post({ type: "render", node: view }, () => 1),
() => __host.now(() => 1),
]
// A real TypeError, sync or async.
const named = (e) => (e instanceof TypeError && e.constructor === TypeError ? "" : "not a TypeError: ") + e.name + ": " + e.message
for (const f of functions) {
try { f() } catch (e) { caught.push(named(e)) }
}
try { await __host.sleep(() => 1) } catch (e) { caught.push(named(e)) }
__host.post({ type: "result", interactive, still, caught })
"#;
let mut run = Program::new(NATIVE, None)
.unwrap()
.start_live(
"null",
LiveOptions {
native: true,
..Default::default()
},
)
.unwrap();
let out = posts(&settle(&mut run));
assert_eq!(
out[0],
json!({ "type": "render", "node": { "type": "column", "children": [
{ "type": "canvas", "height": 10, "id": "0/:board", "pointer": true },
{ "type": "canvas", "wgsl": "fn shade(p: vec2f) -> vec4f { return vec4f(1.0); }", "height": 10, "id": "0/:sky" },
] } })
);
assert_eq!(out[1]["node"]["children"][0]["id"], "0/:sky");
assert_eq!(out[2], out[0]);
assert_eq!(
out[3],
json!({ "type": "draw", "id": "0/:board", "commands": [["rect", 0, 0, 1, 1, { "fill": "accent" }]] })
);
assert_eq!(
out[4],
json!({ "type": "result", "interactive": true, "still": false, "caught": [
"No canvas with key \"nope\" in the rendered view",
"Canvas \"sky\" is drawn by its wgsl; it takes no draw commands",
"TypeError: Argument 1 to __host.post contains a function, which cannot be passed to the host.",
"TypeError: Argument 1 to __host.post contains a function, which cannot be passed to the host.",
"TypeError: Argument 1 to __host.post contains a function, which cannot be passed to the host.",
"TypeError: Argument 1 to __host.post contains a function, which cannot be passed to the host.",
"TypeError: Argument 1 to __host.post contains a function, which cannot be passed to the host.",
"TypeError: Argument 2 to __host.post contains a function, which cannot be passed to the host.",
"TypeError: Argument 1 to __host.now contains a function, which cannot be passed to the host.",
"TypeError: Argument 1 to __host.sleep contains a function, which cannot be passed to the host.",
] })
);
assert_eq!(out.len(), 5);
}
/// A live program on the prelude, started natively with a post rate of `rate` a second.
fn start_widget(source: &str, rate: u32) -> LiveRun {
let program = format!(
"{}\n{source}\nreturn await __widget_live(__input(), true)",
live_prelude()
);
Program::new(&program, None)
.unwrap()
.start_live(
r#"{"data":null}"#,
LiveOptions {
native: true,
max_posts_per_second: rate,
..Default::default()
},
)
.unwrap()
}
/// Pumps `run` as a host does, its timers included, for `ms` or until it ends; returns what it posted meanwhile.
fn run_for(run: &mut LiveRun, ms: u64) -> Vec<Value> {
let mut out = Vec::new();
let deadline = Instant::now() + Duration::from_millis(ms);
loop {
let pump = run.pump(8.0);
out.extend(posts(&parse(&run.take_outbox())));
if pump == Pump::Ended || Instant::now() >= deadline {
return out;
}
std::thread::sleep(Duration::from_micros(500));
}
}
fn parse(outbox: &str) -> Vec<Value> {
let mut reader = serde_json::Deserializer::from_str(outbox);
reader.disable_recursion_limit();
serde::Deserialize::deserialize(&mut reader).unwrap()
}
/// The texts of the text views rendered in `out`.
fn texts(out: &[Value]) -> Vec<String> {
out.iter()
.filter(|m| m["type"] == "render" && m["node"]["type"] == "text")
.map(|m| m["node"]["text"].as_str().unwrap_or_default().to_owned())
.collect()
}
/// The post rate (widgets-live.md): 30 renders at 10 a second: 8 at once (the burst), then the latest alone a tenth of
/// a second later; ending sends what waits first, before an answer.
#[test]
fn renders_over_the_post_rate_wait_and_coalesce() {
let mut run = start_widget(
"async function main() {\n for (let i = 0; i < 30; i++) widget.render(ui.text(String(i)))\n await widget.sleep(1000)\n widget.submit(1)\n}",
10,
);
let first: Vec<String> = (0..8).map(|i| i.to_string()).collect();
let mut out = run_for(&mut run, 60);
assert_eq!(texts(&out), first);
out.extend(run_for(&mut run, 100));
assert_eq!(texts(&out), [first.clone(), vec!["29".into()]].concat());
out.extend(run_for(&mut run, 3000));
assert_eq!(out.last().unwrap()["type"], "submit");
assert!(matches!(run.exit(), Some(LiveExit::Finished { .. })));
for last in ["widget.submit(1)", "return"] {
let mut run = start_widget(
&format!(
"async function main() {{\n for (let i = 0; i < 30; i++) widget.render(ui.text(String(i)))\n {last}\n}}"
),
10,
);
let out = run_for(&mut run, 3000);
assert_eq!(
texts(&out),
[first.clone(), vec!["29".into()]].concat(),
"{last}"
);
let after: Vec<&str> = out
.iter()
.skip(9)
.filter_map(|m| m["type"].as_str())
.collect();
let want: &[&str] = if last == "return" { &[] } else { &["submit"] };
assert_eq!(after, want, "{last}");
}
// A client stop drops what waits.
let mut run = start_widget(
"async function main() {\n for (let i = 0; i < 30; i++) widget.render(ui.text(String(i)))\n await widget.sleep(1000)\n}",
10,
);
let out = run_for(&mut run, 30);
run.stop();
assert_eq!(texts(&out), first);
assert_eq!(run.take_outbox(), "[]");
}
/// Draws coalesce by canvas key; a frame request under load is never counted or held.
#[test]
fn a_frame_request_under_load_is_answered_and_draws_coalesce_by_canvas() {
let mut run = start_widget(
r#"async function main() {
widget.render(ui.column([ui.canvas({ key: "a", height: 1 }), ui.canvas({ key: "b", height: 1 })]))
for (let i = 0; i < 20; i++) { widget.draw("a", [["alpha", i / 100]]); widget.draw("b", [["alpha", i / 50]]) }
const frame = await widget.frame()
widget.render(ui.text("frame " + frame.t))
}"#,
10,
);
let mut out = run_for(&mut run, 20);
// The render and 7 draws took the burst; the frame request went out at once, ahead of the waiting draws.
let kinds: Vec<&str> = out.iter().map(|m| m["type"].as_str().unwrap()).collect();
assert_eq!(
kinds,
[vec!["render"], vec!["draw"; 7], vec!["frame"]].concat()
);
run.deliver(r#"{"type":"frame","frame":{"t":1,"dt":0,"width":2,"height":2,"scale":1,"pointer":null,"dark":true,"fullscreen":false,"close":null}}"#)
.unwrap();
out.extend(run_for(&mut run, 3000));
let draws: Vec<Value> = out
.iter()
.filter(|m| m["type"] == "draw")
.map(|m| json!([m["id"], m["commands"]]))
.collect();
assert_eq!(draws.len(), 9);
assert_eq!(
draws[7..],
[
json!(["0/:b", [["alpha", 0.38]]]),
json!(["0/:a", [["alpha", 0.19]]])
]
);
assert_eq!(texts(&out), ["frame 1"]);
assert_eq!(out.last().unwrap()["type"], "render");
assert!(matches!(run.exit(), Some(LiveExit::Finished { .. })));
}
/// A 120 Hz game posting a render and two draws a frame (360 a second): every frame request goes out, the counted posts
/// stay within the rate, and the last frame's view and drawings arrive.
#[test]
fn a_game_at_120_hz_runs_every_frame_and_shows_its_last_one() {
let mut run = start_widget(
r#"async function main() {
for (let n = 0; n < 120; n++) {
const frame = await widget.frame()
widget.render(ui.column([ui.text("n " + n), ui.canvas({ key: "a", height: 1 }), ui.canvas({ key: "b", height: 1 })]))
widget.draw("a", [["alpha", n / 1000]])
widget.draw("b", [["alpha", n / 200]])
}
}"#,
240,
);
let started = Instant::now();
let mut out: Vec<Value> = Vec::new();
let (mut frames, mut answered) = (0, 0);
let mut counted_in_a_second = 0;
while run.exit().is_none() && started.elapsed() < Duration::from_secs(5) {
let tick = Instant::now();
let posted = run_for(&mut run, 0);
frames += posted.iter().filter(|m| m["type"] == "frame").count();
if started.elapsed() <= Duration::from_secs(1) {
counted_in_a_second += posted
.iter()
.filter(|m| m["type"] == "render" || m["type"] == "draw")
.count();
}
out.extend(posted);
// Each frame request is answered on the next display frame, as the page does.
if answered < frames && run.exit().is_none() {
answered += 1;
run.deliver(&format!(
r#"{{"type":"frame","frame":{{"t":{},"dt":0.008,"width":2,"height":2,"scale":1,"pointer":null,"dark":true,"fullscreen":false,"close":null}}}}"#,
answered as f64 / 120.0
))
.unwrap();
}
std::thread::sleep(Duration::from_secs_f64(1.0 / 120.0).saturating_sub(tick.elapsed()));
}
out.extend(run_for(&mut run, 0));
assert_eq!(frames, 120);
assert!(counted_in_a_second <= 240 + 8 + 3, "{counted_in_a_second}");
assert!(
matches!(run.exit(), Some(LiveExit::Finished { .. })),
"{:?}",
run.exit()
);
let last_render = out.iter().rev().find(|m| m["type"] == "render").unwrap();
assert_eq!(last_render["node"]["children"][0]["text"], "n 119");
let last_b = out
.iter()
.rev()
.find(|m| m["type"] == "draw" && m["id"] == "0/:b")
.unwrap();
assert_eq!(last_b["commands"], json!([["alpha", 0.595]]));
}
/// A draw post without a string key is an invalid post: the run ends.
#[test]
fn a_draw_post_without_a_string_key_ends_the_run() {
for post in [
r#"__host.post({ type: "draw", id: "0", commands: [] })"#,
r#"__host.post({ type: "draw", key: 1, commands: [] })"#,
] {
let mut run = start_widget(
&format!(
"async function main() {{\n widget.render(ui.canvas({{ key: \"c\", height: 1 }}))\n try {{ {post} }} catch (e) {{ widget.send(\"caught\") }}\n}}"
),
240,
);
let out = run_for(&mut run, 3000);
assert_eq!(out.len(), 1, "{post}: {out:?}");
match run.exit() {
Some(LiveExit::Failed { error }) => {
assert_eq!(error.reason(), "A draw post needs a string key", "{post}")
}
other => panic!("{post}: {other:?}"),
}
}
}
/// A draw post goes to the client as its canvas's id and commands only; one over 2,000 commands is an invalid post,
/// which ends the run in phase `draw`, what waits for the post rate going out first.
#[test]
fn draw_posts_carry_id_and_commands_and_end_the_run_over_2000_commands() {
let mut run = start_widget(
r#"async function main() {
widget.render(ui.canvas({ key: "c", height: 1 }))
__host.post({ type: "draw", key: "c", commands: [["rect", 0, 0, 1, 1, { fill: "accent" }]], extra: 1 })
for (let i = 0; i < 10; i++) widget.render(ui.canvas({ key: "c", height: i + 1 }))
try { widget.draw("c", Array.from({ length: 2001 }, () => ["save"])) } catch (e) { widget.send("caught") }
widget.send("after")
}"#,
240,
);
let out = run_for(&mut run, 3000);
assert_eq!(
out[1],
json!({ "type": "draw", "id": ":c", "commands": [["rect", 0, 0, 1, 1, { "fill": "accent" }]] })
);
// The latest render goes out (at once or when the run ends); nothing after the invalid draw does.
assert_eq!(out.last().unwrap()["node"]["height"], 10, "{out:?}");
assert!(out.iter().all(|m| m["type"] != "send"), "{out:?}");
match run.exit() {
Some(LiveExit::Failed { error }) => {
assert_eq!(error.phase(), Some("draw"));
assert_eq!(
error.reason(),
"2001 draw commands is over the budget of 2000 per frame"
);
}
other => panic!("{other:?}"),
}
}
/// Every command is checked when the program posts it, with the other hosts' rules and messages: the first invalid one
/// ends the run in phase `draw`, named by its index; valid ones of every kind go through.
#[test]
fn an_invalid_draw_command_ends_the_run_in_phase_draw() {
let draw = |commands: &str| {
let mut run = start_widget(
&format!(
"async function main() {{\n widget.render(ui.canvas({{ key: \"c\", height: 1 }}))\n __host.post({{ type: \"draw\", key: \"c\"{commands} }})\n widget.send(\"after\")\n}}"
),
240,
);
let out = run_for(&mut run, 3000);
match run.exit() {
Some(LiveExit::Failed { error }) => {
assert_eq!(error.phase(), Some("draw"), "{commands}");
assert!(
out.iter()
.all(|m| m["type"] != "send" && m["type"] != "draw"),
"{out:?}"
);
Err(error.reason().to_owned())
}
Some(LiveExit::Finished { .. }) => {
Ok(out.into_iter().find(|m| m["type"] == "draw").unwrap())
}
other => panic!("{commands}: {other:?}"),
}
};
for (commands, message) in [
(
r#", commands: [["save"], ["rect", 0, 0, 1, 1, "accent"]]"#,
"draw command 1: a paint is an object",
),
(
r#", commands: [["blur", 1]]"#,
"draw command 0: unknown draw command \"blur\"",
),
(
r#", commands: [["alpha", "x"]]"#,
"draw command 0: \"alpha\" argument 1 must be a finite number",
),
(
r#", commands: [["rect", 0, 0, 1, NaN, {}]]"#,
"draw command 0: \"rect\" argument 4 must be a finite number",
),
(
r##", commands: [["circle", 0, 0, 1, { fill: "#12" }]]"##,
"draw command 0: not a color",
),
(
r#", commands: [["line", 0, 0, 1, 1, { stroke: "accent", width: "2" }]]"#,
"draw command 0: a stroke's width must be a finite number",
),
(
r#", commands: [["rect", 0, 0, 1, 1, { fill: { linear: [0, 0, 1], stops: [] } }]]"#,
"draw command 0: a linear gradient takes 4 numbers",
),
(
r#", commands: [["rect", 0, 0, 1, 1, { fill: { radial: [0, 0, 1], stops: [[0]] } }]]"#,
"draw command 0: a stop is [offset, color]",
),
(
r#", commands: [["path", [["M", 0, 0], ["X", 1]], {}]]"#,
"draw command 0: unknown path segment",
),
(
r#", commands: [["text", 0, 0]]"#,
"draw command 0: \"text\" is missing argument 3",
),
(
r#", commands: [["text", 0, 0, "t", { size: "big" }]]"#,
"draw command 0: a text size must be a finite number",
),
(
r#", commands: [["image", 1, 0, 0, 1, 1]]"#,
"draw command 0: \"image\" takes a src",
),
(
r#", commands: [5]"#,
"draw command 0: a command is an array",
),
(
r#", commands: [[1]]"#,
"draw command 0: a command starts with its name",
),
(r#", commands: "x""#, "draw commands must be a list"),
("", "draw commands must be a list"),
] {
assert_eq!(draw(commands), Err(message.to_owned()), "{commands}");
}
// Every kind, as the prelude's builder writes it, goes through as it was posted.
let valid = r##"ui.draw().save().translate(1, 2).rotate(0.5).scale(2).alpha(0.5).rect(0, 0, 1, 1, "accent").rrect(0, 0, 4, 4, 1, { fill: { linear: [0, 0, 1, 1], stops: [[0, "#fff"], [1, "#000000aa"]] }, stroke: "border", width: 2, cap: "round" }).circle(1, 1, 1, { fill: { radial: [1, 1, 1], stops: [[0, "bg"]] } }).line(0, 0, 1, 1, "muted").path([["M", 0, 0], ["L", 1, 1], ["Q", 1, 0, 2, 2], ["C", 0, 0, 1, 1, 2, 2], ["Z"]], "success").text(0, 10, "hi", { size: 12, weight: 600, align: "center", color: "#abc", mono: true }).image("a.png", 0, 0, 1, 1).restore().commands"##;
let posted = draw(&format!(", commands: {valid}")).expect("valid commands");
assert_eq!(posted["commands"].as_array().unwrap().len(), 13);
}
/// GPU batches (widgets-gpu.md, Transport) go out at once, in a frame request or on their own, as they are for the
/// client's checks: their ops as JSON and an `ArrayBuffer`'s bytes in the byte outbox, named by `[offset, length]`;
/// other bytes `null`, a batch that isn't an object whole. A render names its GPU canvases' ids by key.
#[test]
fn gpu_batches_carry_their_ops_and_bytes() {
let mut run = start_widget(
r#"async function main() {
widget.render(ui.column([ui.canvas({ key: "scene", gpu: true, height: 10 }), ui.canvas({ key: "flat", height: 10 })]))
const data = new Float32Array([1, 2])
__host.post({ type: "gpu", ops: [["context", 1, "scene", "bgra8unorm", "opaque"], ["buffer", 3, 8, 40], ["writeBuffer", 3, 0, 0, 8]], bytes: data.buffer })
__host.post({ type: "frame", gpu: { ops: [["writeBuffer", 3, 0, 0, 4]], bytes: new Uint32Array([7]).buffer } })
__host.post({ type: "gpu", ops: "x", bytes: new Uint8Array(2) })
__host.post({ type: "gpu", bytes: new ArrayBuffer(1) })
__host.post({ type: "frame", gpu: 5 })
try { widget.draw("scene", []) } catch (e) { widget.send(e.message) }
try { __host.post({ type: "gpu", ops: [["shader", 4, () => 1]], bytes: new ArrayBuffer(0) }) } catch (e) { widget.send(e.name) }
}"#,
240,
);
let mut out = Vec::new();
let mut bytes = Vec::new();
let deadline = Instant::now() + Duration::from_secs(5);
loop {
let pump = run.pump(8.0);
out.extend(posts(&parse(&run.take_outbox())));
bytes.extend(run.take_bytes());
if pump == Pump::Ended || Instant::now() > deadline {
break;
}
}
assert_eq!(
out[0]["gpu"],
json!({ "scene": out[0]["node"]["children"][0]["id"] })
);
assert_eq!(
out[1],
json!({ "type": "gpu", "batch": { "ops": [
["context", 1, "scene", "bgra8unorm", "opaque"],
["buffer", 3, 8, 40],
["writeBuffer", 3, 0, 0, 8],
], "bytes": [0, 8] } })
);
assert_eq!(
out[2],
json!({ "type": "frame", "gpu": { "ops": [["writeBuffer", 3, 0, 0, 4]], "bytes": [8, 4] } })
);
assert_eq!(
out[3],
json!({ "type": "gpu", "batch": { "ops": "x", "bytes": null } })
);
assert_eq!(
out[4],
json!({ "type": "gpu", "batch": { "bytes": [12, 1] } })
);
assert_eq!(out[5], json!({ "type": "frame", "gpu": 5 }));
let floats: Vec<u8> = [1.0f32, 2.0].iter().flat_map(|f| f.to_le_bytes()).collect();
assert_eq!(
bytes,
[floats, 7u32.to_le_bytes().to_vec(), vec![0]].concat()
);
assert_eq!(
out[6]["value"],
"Canvas \"scene\" is drawn by the GPU; it takes no draw commands"
);
assert_eq!(out[7]["value"], "TypeError");
}
/// A GPU batch's ops cross as JSON reads them (widgets-gpu.md, Transport): an `undefined` list item is `null`, an
/// `undefined` member is absent. Numbers stay as they are: a non-finite one, written `null`, is listed by its path in
/// `nonFinite` for the client to put back; a batch without one has no `nonFinite`.
#[test]
fn gpu_batch_ops_keep_non_finite_numbers_by_path() {
let mut run = start_widget(
r#"async function main() {
widget.render(ui.canvas({ key: "scene", gpu: true, height: 10 }))
__host.post({ type: "gpu", ops: [["pass", { colorAttachments: [undefined, { clearValue: [0, NaN, Infinity], "a\"b": -Infinity, gone: undefined }] }], ["buffer", 1, NaN, 4]], bytes: new ArrayBuffer(0) })
__host.post({ type: "frame", gpu: { ops: NaN, bytes: new ArrayBuffer(0) } })
__host.post({ type: "gpu", ops: [["buffer", 2, null, 4]], bytes: new ArrayBuffer(0) })
}"#,
240,
);
let out = run_for(&mut run, 200);
assert_eq!(
out[1],
json!({ "type": "gpu", "batch": {
"ops": [["pass", { "colorAttachments": [null, { "clearValue": [0, null, null], "a\"b": null }] }], ["buffer", 1, null, 4]],
"nonFinite": [
[[0, 1, "colorAttachments", 1, "clearValue", 1], "NaN"],
[[0, 1, "colorAttachments", 1, "clearValue", 2], "Infinity"],
[[0, 1, "colorAttachments", 1, "a\"b"], "-Infinity"],
[[1, 2], "NaN"],
],
"bytes": [0, 0],
} })
);
assert_eq!(
out[2],
json!({ "type": "frame", "gpu": { "ops": null, "nonFinite": [[[], "NaN"]], "bytes": [0, 0] } })
);
assert_eq!(
out[3],
json!({ "type": "gpu", "batch": { "ops": [["buffer", 2, null, 4]], "bytes": [0, 0] } })
);
}
/// A GPU batch never overtakes a waiting render or draw: it waits behind them (taking no token) and goes out right
/// after the post before it, with its bytes; a frame request without a batch still goes out at once.
#[test]
fn gpu_batches_wait_in_order_behind_waiting_posts() {
let mut run = start_widget(
r#"async function main() {
for (let i = 0; i < 10; i++) widget.render(ui.column([ui.text(String(i)), ui.canvas({ key: "scene", gpu: true, height: 1 })]))
__host.post({ type: "gpu", ops: [["context", 1, "scene", "bgra8unorm", "opaque"]], bytes: new Uint8Array([9, 8]).buffer })
__host.post({ type: "frame" })
__host.post({ type: "frame", gpu: { ops: [["submit"]], bytes: new Uint8Array([7]).buffer } })
await widget.sleep(1000)
}"#,
10,
);
let (mut out, mut bytes) = (Vec::new(), Vec::new());
let collect = |run: &mut LiveRun, ms, out: &mut Vec<Value>, bytes: &mut Vec<u8>| {
out.extend(run_for(run, ms));
bytes.extend(run.take_bytes());
};
collect(&mut run, 30, &mut out, &mut bytes);
let kinds = |out: &[Value]| -> Vec<String> {
out.iter()
.map(|m| match m["type"].as_str().unwrap() {
"render" => format!(
"render {}",
m["node"]["children"][0]["text"].as_str().unwrap()
),
other => other.to_owned(),
})
.collect()
};
// The burst's 8 renders, and the bare frame request at once; the batches wait behind render 9.
assert_eq!(
kinds(&out),
[
"render 0", "render 1", "render 2", "render 3", "render 4", "render 5", "render 6",
"render 7", "frame"
]
);
assert!(out[8].get("gpu").is_none());
collect(&mut run, 150, &mut out, &mut bytes);
assert_eq!(kinds(&out)[9..], ["render 9", "gpu", "frame"]);
assert_eq!(out[10]["batch"]["bytes"], json!([0, 2]));
assert_eq!(out[11]["gpu"]["bytes"], json!([2, 1]));
assert_eq!(bytes, [9, 8, 7]);
}
/// A live program on the live prelude, run natively.
fn widget(source: &str) -> (Vec<Value>, Option<LiveExit>) {
let program = format!(
"{}\n{source}\nreturn await __widget_live(__input(), true)",
live_prelude()
);
let mut run = Program::new(&program, None)
.unwrap()
.start_live(
r#"{"data":null}"#,
LiveOptions {
native: true,
..Default::default()
},
)
.unwrap();
let out = posts(&settle(&mut run));
(out, run.exit().cloned())
}
/// Uncaught, a function where none may go fails the run as the runtime's TypeError, at the call, sync or async; so
/// does a draw to an unknown canvas key.
#[test]
fn a_function_posted_where_none_may_go_fails_the_run_at_the_call() {
for (call, line) in [
("widget.send({ f: () => 1 })", 2),
("__host.post({ type: \"send\", value: 1 }, () => 1)", 2),
("await __host.sleep(() => 1)", 2),
("await __host.receive(() => 1)", 2),
("__host.now(() => 1)", 2),
] {
let (_, exit) = widget(&format!("async function main() {{\n {call}\n}}"));
let Some(LiveExit::Failed { error }) = exit else {
panic!("{call}: {exit:?}")
};
assert!(
error.reason().starts_with("TypeError: Argument ")
&& error
.reason()
.contains(" contains a function, which cannot be passed to the host.")
&& error.location().is_some() == (line > 0),
"{call}: {error}"
);
if line > 0 && !call.starts_with("widget.") {
assert_eq!(
error.location().map(|(l, _)| l),
Some(prelude_lines() + 1 + line),
"{call}"
);
}
}
let (_, exit) = widget(
"async function main() {\n __host.post({ type: \"draw\", key: \"nope\", commands: [] })\n}",
);
let Some(LiveExit::Failed { error }) = exit else {
panic!("{exit:?}")
};
assert_eq!(
(error.reason(), error.location().map(|(l, _)| l)),
(
format!(
"Error: No canvas with key \"nope\" in the rendered view (line {}, col 3)",
prelude_lines() + 3
)
.as_str(),
Some(prelude_lines() + 3)
)
);
}
/// What a live program has before its source (`packages/widget/src`, read in place): the prelude, a newline, the
/// live prelude.
fn live_prelude() -> String {
let read = |name: &str| {
std::fs::read_to_string(
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../../widget/src")
.join(name),
)
.unwrap()
};
format!("{}\n{}", read("prelude.js"), read("prelude-live.js"))
}
/// The live prelude's lines; it ends with a newline, so with the joining one the widget template starts two lines on.
fn prelude_lines() -> u32 {
live_prelude().lines().count() as u32
}
#[test]
fn a_render_that_breaks_a_rule_of_views_ends_the_run_in_phase_view() {
let view = |reason: &str| {
Some(LiveExit::Failed {
error: widget_web::Error::View {
reason: reason.into(),
},
})
};
// Rendered first, then the key of another type: the first render went out, the run ends at the second.
let (out, exit) = widget(
r#"async function main() {
widget.render(ui.text("first"))
try { widget.render(ui.column([ui.button("b", { key: {} })])) } catch (e) { widget.send("caught " + e.message) }
widget.send("after")
}"#,
);
assert_eq!(
out,
vec![json!({ "type": "render", "node": { "type": "text", "text": "first" } })]
);
assert_eq!(exit, view(widget_web::tree::KEY));
// 100 levels render; 101 end the run.
let deep = |levels: usize| {
format!(
"async function main() {{\n let node = ui.text(\"x\")\n for (let i = 1; i < {levels}; i++) node = ui.column([node])\n widget.render(node)\n}}"
)
};
let (out, exit) = widget(&deep(100));
assert_eq!(
(out.len(), exit),
(
1,
Some(LiveExit::Finished {
result_json: "null".into()
})
)
);
let (out, exit) = widget(&deep(101));
assert!(out.is_empty());
assert_eq!(exit, view(widget_web::tree::DEEP));
// Deep only in a prop, past the boundary of 202: the boundary's own error, which the program gets.
let (_, exit) = widget(
r#"async function main() {
widget.render(ui.text("x", { extra: JSON.parse("[".repeat(210) + "]".repeat(210)) }))
}"#,
);
match exit {
Some(LiveExit::Failed { error }) => {
assert!(
error.reason().contains("exceeds the maximum value depth"),
"{error}"
)
}
other => panic!("{other:?}"),
}
}

View file

@ -0,0 +1,112 @@
use widget_web::{Error, LiveOptions, Program, Pump};
const STEP: &str = r#"
function __widget_step(input) {
if (input.phase === "init") return { state: { n: 0 }, view: { type: "text", text: "0" } }
const n = input.state.n + 1
return { state: { n }, view: { type: "text", text: String(n) } }
}
return __widget_step(__input())
"#;
#[test]
fn runs_a_step_per_input() {
let program = Program::new(STEP, None).unwrap();
let init = program
.run(r#"{"phase":"init","data":{}}"#, Some(250), None)
.unwrap();
assert_eq!(
init,
r#"{"state":{"n":0},"view":{"type":"text","text":"0"}}"#
);
let next = program
.run(
r#"{"phase":"event","data":{},"state":{"n":4},"event":{"id":"x","type":"press"}}"#,
Some(250),
None,
)
.unwrap();
assert_eq!(
next,
r#"{"state":{"n":5},"view":{"type":"text","text":"5"}}"#
);
}
#[test]
fn syntax_errors_have_a_place() {
let e = Program::new("let x = ;", None).unwrap_err();
assert!(matches!(e, Error::Syntax { line: Some(1), .. }), "{e:?}");
assert_eq!(e.type_name(), "syntax");
}
#[test]
fn runs_time_out_and_throw() {
let spin = Program::new("while (true) {}", None).unwrap();
assert!(matches!(
spin.run("null", Some(20), None),
Err(Error::Timeout { timeout_ms: 20, .. })
));
let throws = Program::new("throw new TypeError('bad')", None).unwrap();
let e = throws.run("null", None, None).unwrap_err();
assert_eq!(e.kind(), Some("ExecutionFailure"));
assert!(e.reason().contains("TypeError: bad"), "{e}");
assert!(e.to_json().contains(r#""type":"runtime""#));
}
#[test]
fn inputs_and_outputs_are_checked() {
let echo = Program::new("return __input()", None).unwrap();
assert!(matches!(
echo.run("{", None, None),
Err(Error::InvalidInput { .. })
));
assert!(matches!(
echo.run(r#""a long string""#, None, Some(4)),
Err(Error::OutputTooLarge {
max_output_bytes: 4,
..
})
));
let named = Program::new("return input().a", Some("input".into())).unwrap();
assert_eq!(
named.run(r#"{"a":[1,"x"]}"#, None, None).unwrap(),
r#"[1,"x"]"#
);
}
/// Typed arrays are the language's (psychoscript 0.1): plain runs and widget runs (`run_step`, native live runs)
/// alike have them.
#[test]
fn every_run_has_typed_arrays() {
let probe = "typeof Float32Array + \" \" + typeof ArrayBuffer";
let plain = Program::new(&format!("return {probe}"), None).unwrap();
assert_eq!(
plain.run("null", None, None).unwrap(),
r#""function function""#
);
let step = Program::new(
&format!("__widget_emit({{ type: \"text\", text: {probe} }})\nreturn {{ state: {{}} }}"),
None,
)
.unwrap();
assert!(
step.run_step("null", None, None)
.unwrap()
.contains(r#""text":"function function""#)
);
let mut live = Program::new(
&format!("__host.post({{ type: \"probe\", text: {probe} }})"),
None,
)
.unwrap()
.start_live(
"null",
LiveOptions {
native: true,
..Default::default()
},
)
.unwrap();
while live.pump(8.0) != Pump::Ended {}
assert!(live.take_outbox().contains(r#""text":"function function""#));
}

View file

@ -0,0 +1,549 @@
//! The native host against the conformance fixtures (`packages/widget/test/fixtures/wire`, read in place, with
//! `packages/widget/src/prelude.js`). Each fixture holds a widget template `source` and a step `input`, `built` (the
//! view as emitted, each function as `"$function"`) when it crosses, and either `view`, `handlers`, `canvases` and
//! `result`, or `error`. The view the walk must write byte for byte is `JSON.stringify(JSON.parse(..).view)`
//! ([`stringify`]).
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use psychoscript::{
HostFunction, HostValue, Limits, Runtime, Translate, TranslateFunctions, TranslatePromises,
};
use serde_json::Value;
use widget_web::tree::{DEEP, Walk, WalkError};
use widget_web::{Error, Program};
const ENTRY: &str = "\nreturn __widget_native_step(__input())";
/// `@opencode/widget` (`packages/widget`).
fn widget() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../widget")
}
fn dir() -> PathBuf {
widget().join("test/fixtures/wire")
}
/// A fixture's JSON as `JSON.stringify` writes it once `JSON.parse` has read it: numbers as ECMAScript writes them
/// (`Number::toString`), an object's array-index keys first in ascending order, then the others in order.
fn stringify(v: &Value, out: &mut String) {
match v {
Value::Number(n) => {
out.push_str(ryu_js::Buffer::new().format(n.as_f64().expect("a number")));
}
Value::Array(items) => {
out.push('[');
for (i, item) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
stringify(item, out);
}
out.push(']');
}
Value::Object(props) => {
let index = |k: &str| {
k.parse::<u32>()
.ok()
.filter(|i| *i != u32::MAX && i.to_string() == k)
};
let mut keys: Vec<&String> = props.keys().collect();
keys.sort_by_key(|k| index(k).map_or((1, 0), |i| (0, i)));
out.push('{');
for (i, k) in keys.into_iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push_str(&serde_json::to_string(k).unwrap());
out.push(':');
stringify(&props[k], out);
}
out.push('}');
}
// null, booleans, and strings, which `serde_json` escapes as `JSON.stringify` does.
other => out.push_str(&serde_json::to_string(other).unwrap()),
}
}
/// A fixture's `built` as the host value `__widget_emit` gets.
fn host(v: &Value) -> HostValue {
match v {
Value::Null => HostValue::Null,
Value::Bool(b) => HostValue::Bool(*b),
Value::Number(n) => HostValue::Number(n.as_f64().unwrap_or(f64::NAN)),
Value::String(s) => match s.as_str() {
"$function" => HostValue::FunctionMarker,
"$NaN" => HostValue::Number(f64::NAN),
"$Infinity" => HostValue::Number(f64::INFINITY),
"$-Infinity" => HostValue::Number(f64::NEG_INFINITY),
s => HostValue::String(s.into()),
},
Value::Array(items) => HostValue::Array(items.iter().map(|i| Some(host(i))).collect()),
Value::Object(props) => HostValue::Object(
props
.iter()
.map(|(k, v)| (k.as_str().into(), host(v)))
.collect(),
),
}
}
/// An emitted view as a fixture's `built` writes it.
fn built(v: &HostValue) -> Value {
match v {
HostValue::Null | HostValue::Undefined => Value::Null,
HostValue::Bool(b) => Value::Bool(*b),
HostValue::Number(n) if n.is_nan() => "$NaN".into(),
HostValue::Number(n) if n.is_infinite() => {
(if *n > 0.0 { "$Infinity" } else { "$-Infinity" }).into()
}
HostValue::Number(n) if n.fract() == 0.0 && n.abs() < 9e15 => (*n as i64).into(),
HostValue::Number(n) => (*n).into(),
HostValue::String(s) => s.to_string_lossy().into_owned().into(),
HostValue::FunctionMarker => "$function".into(),
HostValue::Array(items) => Value::Array(
items
.iter()
.map(|i| i.as_ref().map_or(Value::Null, built))
.collect(),
),
HostValue::Object(props) => Value::Object(
props
.iter()
.filter(|(_, v)| !matches!(v, HostValue::Undefined))
.map(|(k, v)| (k.to_string_lossy().into_owned(), built(v)))
.collect(),
),
other => panic!("not in a view: {other:?}"),
}
}
struct Fixture {
name: String,
json: Value,
wire: Option<String>,
}
impl Fixture {
fn map(&self, field: &str) -> BTreeMap<String, String> {
self.json[field]
.as_object()
.into_iter()
.flatten()
.map(|(k, v)| (k.clone(), v.as_str().unwrap_or_default().to_owned()))
.collect()
}
fn program(&self) -> String {
format!(
"{}\n{}{ENTRY}",
prelude(),
self.json["source"].as_str().unwrap_or_default()
)
}
}
fn fixtures() -> Vec<Fixture> {
let mut out = Vec::new();
for entry in std::fs::read_dir(dir()).expect("the fixtures") {
let path = entry.expect("an entry").path();
if path.extension().and_then(|e| e.to_str()) != Some("json") {
continue;
}
// The depth fixtures nest past serde_json's default limit of 128.
let text = std::fs::read_to_string(&path).expect("read");
let mut reader = serde_json::Deserializer::from_str(&text);
reader.disable_recursion_limit();
let json: Value = serde::Deserialize::deserialize(&mut reader).expect("JSON");
out.push(Fixture {
name: json["name"].as_str().unwrap_or_default().to_owned(),
wire: json.get("view").map(|view| {
let mut wire = String::new();
stringify(view, &mut wire);
wire
}),
json,
});
}
out.sort_by(|a, b| a.name.cmp(&b.name));
assert_eq!(out.len(), 58);
out
}
/// The prelude a fixture's program starts with (`packages/widget/src/prelude.js`).
fn prelude() -> String {
std::fs::read_to_string(widget().join("src/prelude.js")).expect("the prelude")
}
/// What the walk of `view` gives: its JSON, handlers (id -> event) and canvases (key -> id).
type Walked = Result<(String, BTreeMap<String, String>, BTreeMap<String, String>), WalkError>;
fn walk(view: &HostValue) -> Walked {
let mut out = String::new();
let tree = Walk::new().handlers().run(view, &mut out)?;
// A later node with the same id takes it, as in the prelude's table.
let handlers = tree
.handlers
.unwrap_or_default()
.into_iter()
.map(|(id, event)| (id, event.to_owned()))
.collect();
let canvases = tree
.canvases
.into_iter()
.map(|(k, (id, _))| (k, id))
.collect();
Ok((out, handlers, canvases))
}
/// What a fixture expects of the walk of its view.
fn expected(f: &Fixture) -> Walked {
let error = &f.json["error"];
if error["view"] == true {
let message = error["message"].as_str().unwrap_or_default();
return Err(WalkError::View(
[widget_web::tree::KEY, DEEP]
.into_iter()
.find(|m| *m == message)
.expect("a view failure"),
));
}
if error["message"]
.as_str()
.is_some_and(|m| m.contains("contains a function"))
{
return Err(WalkError::Function);
}
Ok((
f.wire.clone().unwrap_or_default(),
f.map("handlers"),
f.map("canvases"),
))
}
#[test]
fn every_fixture_walks_from_its_built_view() {
let mut walked = 0;
for f in fixtures() {
if f.json.get("built").is_none() {
continue;
}
let got = walk(&host(&f.json["built"]));
let want = expected(&f);
match (&got, &want) {
// A failing step's view: its error, unless the run fails for another reason (the result's).
(Ok(_), Ok(_)) if f.wire.is_none() => {}
_ => assert_eq!(got, want, "{}", f.name),
}
walked += 1;
}
assert_eq!(walked, 57);
}
/// Each fixture's program run natively on its input with real function markers: the view `__widget_emit` gets is
/// `built` and walks to the fixture's (view byte for byte, handlers, canvases), and `Program::run_step` gives the
/// fixture's `result` and view, or fails with its `error`.
#[test]
fn every_fixture_runs_natively_to_its_view_result_or_error() {
let mut count = 0;
for f in fixtures() {
let program = f.program();
// The run with an `__widget_emit` that keeps what it gets.
let input = host(&f.json["input"]);
let emitted: Arc<Mutex<Vec<Vec<HostValue>>>> = Arc::default();
let keep = emitted.clone();
let runtime = Runtime::make()
.globals(move |_run| {
let input = input.clone();
let keep = keep.clone();
[
("__input", HostFunction::new(move |_, _| input.clone())),
(
"__widget_emit",
HostFunction::new(move |args, _| {
keep.lock().unwrap().push(args);
HostValue::Undefined
}),
),
]
})
.translate(Translate {
functions: TranslateFunctions::Mark,
promises: TranslatePromises::Error,
})
.limits(Limits {
max_value_depth: Some(202),
..Limits::default()
});
let _ = runtime.execute(program.as_str());
let emitted = std::mem::take(&mut *emitted.lock().unwrap());
if let Some(want) = f.json.get("built") {
assert_eq!(emitted.len(), 1, "{}: one emit", f.name);
assert_eq!(&built(&emitted[0][0]), want, "{}: built", f.name);
let got = walk(&emitted[0][0]);
match expected(&f) {
Ok(_) if f.wire.is_none() => assert!(got.is_ok(), "{}", f.name),
want => assert_eq!(got, want, "{}", f.name),
}
} else {
// Too deep to cross: the prelude hands over the reason instead.
assert_eq!(emitted.len(), 1, "{}: one emit", f.name);
assert!(
matches!(&emitted[0][..], [HostValue::Null, HostValue::String(s)] if s == DEEP)
);
}
// The host's own entry point.
let step = Program::new(&program, None).unwrap().run_step(
&f.json["input"].to_string(),
None,
None,
);
let error = &f.json["error"];
match step {
Ok(text) => {
assert!(error.is_null(), "{}: expected {error}, got {text}", f.name);
let wire = f.wire.as_deref().expect("a view");
assert!(
text.ends_with(&format!(",\"view\":{wire}}}")),
"{}: the view in {text}",
f.name
);
let mut reader = serde_json::Deserializer::from_str(&text);
reader.disable_recursion_limit();
let mut output: Value = serde::Deserialize::deserialize(&mut reader).expect("JSON");
output.as_object_mut().unwrap().shift_remove("view");
assert_eq!(output, f.json["result"], "{}: the result", f.name);
}
Err(e) => {
let want = error["message"].as_str().unwrap_or("(no error)");
assert_eq!(
(matches!(e, Error::View { .. }), e.reason()),
(error["view"] == true, want),
"{}",
f.name
);
}
}
count += 1;
}
assert_eq!(count, 58);
}
/// The walk counts levels itself, for views the boundary lets through (its default depth stops them at 16 levels).
#[test]
fn a_view_nests_at_most_100_levels() {
let leaf = || HostValue::object([("type", HostValue::String("text".into()))]);
let column = |child: HostValue| {
HostValue::object([
("type", HostValue::String("column".into())),
("children", HostValue::array([child])),
])
};
let nest = |levels: usize, wrap: &dyn Fn(HostValue) -> HostValue| {
(1..levels).fold(leaf(), |node, _| wrap(node))
};
assert!(
Walk::new()
.run(&nest(100, &column), &mut String::new())
.is_ok()
);
assert_eq!(
Walk::new()
.run(&nest(101, &column), &mut String::new())
.err(),
Some(WalkError::View(DEEP))
);
// An array inside children counts as a level: 50 columns of `[[node]]` put the leaf at level 101.
let arrays = |child: HostValue| column(HostValue::array([child]));
assert!(
Walk::new()
.run(&nest(50, &arrays), &mut String::new())
.is_ok()
);
assert_eq!(
Walk::new()
.run(&nest(51, &arrays), &mut String::new())
.err(),
Some(WalkError::View(DEEP))
);
// Strings don't count: a string at level 101 is fine.
let strings = (1..100).fold(column(HostValue::String("x".into())), |node, _| {
column(node)
});
assert!(Walk::new().run(&strings, &mut String::new()).is_ok());
}
/// A widget step's boundary is 202 values deep (widgets.md, "Native hosts"): a view of 100 levels crosses and walks,
/// one of 101 fails in phase view, nested children or arrays alike; a prop deeper than the boundary fails where it
/// crosses.
#[test]
fn a_native_step_takes_views_of_100_levels() {
let step = |view: &str| {
let program = format!("{}\nfunction view() {{\n{view}\n}}{ENTRY}", prelude());
Program::new(&program, None).unwrap().run_step(
r#"{"phase":"init","data":null}"#,
None,
None,
)
};
let nested = |levels: usize, wrap: &str| {
format!(
"let node = ui.button(\"deep\", {{ onPress: (s) => s }})\nfor (let i = 1; i < {levels}; i++) node = {wrap}\nreturn node"
)
};
let id = vec!["0"; 100].join("/");
let out = step(&nested(100, "ui.column([node])")).expect("100 levels");
assert!(out.contains(&format!("\"id\":\"{id}\"")), "{out}");
let id = std::iter::once("0")
.chain(vec!["0.0"; 49])
.collect::<Vec<_>>()
.join("/");
let out = step(&nested(50, "ui.column([[node]])")).expect("100 levels in arrays");
assert!(out.contains(&format!("\"id\":\"{id}\"")), "{out}");
assert_eq!(
step(&nested(101, "ui.column([node])")),
Err(Error::View {
reason: DEEP.into()
})
);
assert_eq!(
step(&nested(51, "ui.column([[node]])")),
Err(Error::View {
reason: DEEP.into()
})
);
let too_deep =
step(r#"return ui.text("x", { extra: JSON.parse("[".repeat(210) + "]".repeat(210)) })"#);
assert!(
matches!(&too_deep, Err(e) if e.reason().contains("exceeds the maximum value depth of 202")),
"{too_deep:?}"
);
}
/// A function where none may go is the runtime's own `TypeError` to a program that catches it.
#[test]
fn a_caught_function_error_is_a_real_type_error() {
let program = format!(
"{}\nfunction view() {{\n try {{ __widget_emit(ui.text(\"x\", {{ f: () => 1 }})) }} catch (e) {{\n return ui.text([e instanceof TypeError, e.constructor === TypeError, e.name, e.message].join(\" | \"))\n }}\n}}{ENTRY}",
prelude()
);
let out = Program::new(&program, None)
.unwrap()
.run_step(r#"{"phase":"init","data":null}"#, None, None)
.unwrap();
assert!(
out.ends_with(r#""view":{"type":"text","text":"true | true | TypeError | Argument 1 to __widget_emit contains a function, which cannot be passed to the host."}}"#),
"{out}"
);
}
#[test]
fn a_key_with_a_lone_surrogate_is_a_program_error() {
let lone = psychoscript::HostString::from_utf16(&[0xd800]);
let view = HostValue::object([
("type", HostValue::String("column".into())),
(
"children",
HostValue::Array(vec![Some(HostValue::object([
("type", HostValue::String("text".into())),
("key", HostValue::String(lone)),
]))]),
),
]);
assert_eq!(
Walk::new().run(&view, &mut String::new()).err(),
Some(WalkError::Uri)
);
}
/// The walk's cost on the biggest fixtures:
/// `cargo test --release -p widget-web --test tree -- --ignored --nocapture`.
#[test]
#[ignore = "timings: run in release with --ignored"]
fn timings() {
let all = fixtures();
for name in ["grid-200", "builtin-suggestions"] {
let f = all.iter().find(|f| f.name == name).expect(name);
let view = host(&f.json["built"]);
let mut out = String::new();
let runs = 400;
let mut best = f64::MAX;
for _ in 0..runs {
out.clear();
let t = Instant::now();
Walk::new().run(&view, &mut out).expect("walks");
best = best.min(t.elapsed().as_secs_f64() * 1e6);
}
println!("{name}: {best:.1} µs (min of {runs}), {} bytes", out.len());
}
}
/// A native draw step: the commands `__widget_emit` gets are read as JSON reads them (functions and `undefined` fields
/// left out, an `undefined` item `null`), then checked and normalised; `[]` when `draw` returns nothing. The checks
/// themselves: `tests/draw.rs`.
#[test]
fn a_draw_step_emits_its_commands_as_json_reads_them() {
let draw = |source: &str| {
let program = format!("{}\n{source}{ENTRY}", prelude());
Program::new(&program, None).unwrap().run_draw(
r#"{"phase":"draw","data":null,"state":{},"frame":{"id":"0/:c","width":2,"height":2}}"#,
None,
None,
)
};
assert_eq!(
draw(r##"function draw(state, data, frame) {
return ui.draw().rect(0, 0, 1, 1, "accent").commands.concat([["text", 1, 2, frame.key, undefined], ["rect", 0, 0, 1, 1, { u: undefined, f: () => 1, fill: "#fff" }]])
}"##)
.unwrap(),
r##"[["rect",0,0,1,1,{"fill":"accent"}],["text",1,2,"c",{}],["rect",0,0,1,1,{"fill":"#fff"}]]"##
);
assert_eq!(
draw("function draw() {\n return [[\"text\", 1, NaN, \"t\"]]\n}"),
Err(Error::Draw {
reason: "draw command 0: \"text\" argument 2 must be a finite number".into()
})
);
assert_eq!(draw("function draw() {}").unwrap(), "[]");
assert_eq!(draw("").unwrap(), "[]");
assert!(draw("function draw() { throw new Error('no') }").is_err());
}
/// Whole native steps on the biggest fixtures (the view emitted and walked here, functions as markers), and a draw
/// step of the heatmap (its commands emitted).
#[test]
#[ignore = "timings: run in release with --ignored"]
fn step_timings() {
let all = fixtures();
for name in ["grid-200", "builtin-suggestions", "builtin-heatmap"] {
let f = all.iter().find(|f| f.name == name).expect(name);
let input = f.json["input"].to_string();
let native = Program::new(&f.program(), None).unwrap();
let mut best = f64::MAX;
let mut output = String::new();
for _ in 0..200 {
let t = Instant::now();
output = native.run_step(&input, None, None).expect("runs");
best = best.min(t.elapsed().as_secs_f64() * 1e6);
}
println!("{name}: native step {best:.0} µs (min of 200)");
if name == "builtin-heatmap" {
let state: Value = serde_json::from_str::<Value>(&output).unwrap()["state"].clone();
let draw = serde_json::json!({ "phase": "draw", "data": f.json["input"]["data"], "state": state,
"frame": { "id": "0", "t": 0, "dt": 0, "width": 640, "height": 320, "scale": 2, "pointer": null,
"dark": true, "fullscreen": false, "close": null } })
.to_string();
let mut best = f64::MAX;
for _ in 0..200 {
let t = Instant::now();
native.run_draw(&draw, None, None).expect("draws");
best = best.min(t.elapsed().as_secs_f64() * 1e6);
}
println!("{name}: native draw step {best:.0} µs (min of 200)");
}
}
}

View file

@ -0,0 +1,4 @@
[toolchain]
channel = "1.99.1"
profile = "minimal"
components = ["rustfmt", "clippy"]