Wisp is in pre-release, self-hosted since GitHub suspended us. Install it, or see the changelog.

Wisp

Server Functions and Errors

Server Functions

#[remote] on a Rust fn in a page block or src/*.rs makes it callable from browser code, with no endpoint, fetch or import. In src/lib, use import { user } from 'wisp:remote'.

---
let name = "";
#[remote]
fn user(id: u64) -> Result<User> {
    USERS.get(id).map(|r| r.value).or_404()
}
---

<button on:click="user(5).then((u) => (name = u.name))">Load</button>
<p>{:name}</p>
  • The call is a POST to /_app/r/<hash> with a JSON object of arguments by name ({"id":5}). A bad type or failed #[validate] is a 422.
  • It answers like an endpoint (Json value, None is 404, nothing is 204) and works like an action (cx, async). The same-origin check and before run first.
  • Errors reject with status, message (and errors for 422). redirect("/x") navigates.
  • Names are global to browser code; a duplicate, or a name JS or Wisp has (fetch, goto), is a build error.

Queries, Commands and Batches

A #[remote] fn cannot be named like something the browser module uses (get, query, batch, command, live, undo, fail, answer, headers, …), the name of a script helper (preload, announce, modal, outside, inview, shortcut, optimistic, keepscroll, swr, tweened, spring, crossfade, fromAction, MediaQuery, prefersReducedMotion) or a JavaScript reserved word.

#[remote] is a command (a POST). #[remote(get)] is a query: a GET with its arguments as JSON in the query (?id=5&q=%22tea%22), an etag and a 304. Markup reads a query, and it stays fresh:

// src/likes.rs
#[remote(get)]
fn likes(id: u64) -> u64 {
    LIKES.lock().get(&id).copied().unwrap_or(0)
}

#[remote]
fn like(id: u64) {
    *LIKES.lock().entry(id).or_insert(0) += 1;
}
<p>{:likes(5).value} likes</p>
<button on:click="likes(5).value++; like(5)">Like</button>
  • likes(5) is one shared query per arguments. await likes(5) gives its value. Markup reads .value, .error and .loading.
  • Each command sends the URLs of the queries something reads (x-wisp-refresh, at most 16). The server runs them after the command and answers in the same response (x-wisp-refreshed): one round trip. The command sends the first URLs that fit in the header. It sends at most 16. Each URL counts its length plus 3, and the sum must stay under 4000. The server answers those. The browser asks again for each other URL after the command succeeds. If the first URL alone does not fit (3997 characters or longer), the command sends none. The server answers none. The browser asks again for all of them.
  • .refresh() asks again; setting .value shows a guess until the next answer. A query's String argument is plain text in the URL, so ?q=123 reads as the text 123 (not a number to parse), on a refresh as on a first load.
  • #[remote(batch)] fn title(ids: Vec<u64>) -> Vec<String> takes one Vec and answers a Vec in its order. An item that is None answers null, and the TypeScript type is T | null. The browser calls it with one item (await title(3) or {:title(id).value}), and the calls of one tick go as one GET (?ids=[1,2,3]), or more than one for a long list.
  • A remote call runs before in hooks.rs and, for a command, the same-origin check. One in a page's block also passes that page's and its layouts' guards (SIGNED_IN, MIDDLEWARE, RATE_LIMIT). One of src/*.rs belongs to no page, so none of those run: check inside the fn (cx.signed_in()?, cx.limit(&LIMIT)?) or in before.

Forms Every Page Shares

A #[remote] fn of src/*.rs that returns nothing (or Result<()>, or a Response) and that a form posts to is an action of every page. A form in any page, layout or component posts to it by name, with no JavaScript. It is then that form's command only: not served at /_app/r, not in wisp:remote, and calling it from browser code is a build error. The page's guard, once, SIGNED_IN, MIDDLEWARE and RATE_LIMIT hold for it.

// src/news.rs
#[remote]
fn subscribe(email: Email) { SUBSCRIBERS.add(Subscriber { email })?; redirect("/") }
<form action="?/subscribe" fields />
  • It is read as an action's form is: #[validate] rules, the page again as a 422 with each problem, guard, once, use:enhance. fields works in a page's form.
  • A page's own #[action] of the same name wins.
  • A form that posts to a query, or to a command that returns a value, is a build error.

Form Objects

#[remote(form)] on a fn of src/*.rs makes it an action of every page, also when no form posts to it yet. It returns as an action does. Browser code gets a form object, not a call. Put use: and its name on the form:

// src/todos.rs
#[remote(form)]
fn add(#[validate(len = 1..=80)] text: String) { TODOS.add(Todo { text })?; }
<form action="?/add" method="post" use:add>
  <input name="text">
  <p>{:add.fields.text.issues().map((i) => i.message).join(' ')}</p>
  <button disabled={:add.pending > 0}>Add</button>
</form>
  • Without JavaScript, the form posts as any action form does.
  • With it, use:add marks the form. A form without the mark posts as any action form does. The form object sends a marked form's post itself and asks for JSON. The form must have method="post" written and post to ?/add. It does not send a post with another target (also from <base target>), or from a button with formaction, formmethod, formtarget or formenctype. A 422 sets add.fields.<name>.issues() (a list of { message }, at most 20 for each field, each at most 1000 characters). A 2xx sets add.result (the JSON answer, else undefined), resets the form and updates the page. A redirect navigates.
  • add.pending is the number of posts out. Markup that reads these values shows the change.
  • A network failure throws (the browser reports it) and the form keeps its values.
  • use:add and use:enhance on one form: the form object sends the post, and the use:enhance function does not run.
  • A page's own #[action] of the same name wins. A page with a +server.rs POST handler gets no form commands: its POST goes to the endpoint.
  • An action that returns nothing answers 200 with the page. Then a reload after a post without JavaScript sends the post again. End with redirect(..) to send a 303.
  • A #[remote(form)] fn in a page's block is a build error.

Prerendered Queries

#[remote(prerender)] on a fn makes it data fixed at build time. wisp build (and wisp build --static) runs it once per input and writes each answer as a JSON file. A call reads the file of its argument, so the server does no work per call:

// src/blog.rs
#[remote(prerender)]
fn post(id: u64) -> String { format!("Post {id}") }
fn post_inputs() -> Vec<u64> { (1..=3).collect() }
import { post } from 'wisp:remote';
const text = await post(2);
  • Every answer is public: anyone can read its file, with no SIGNED_IN, MIDDLEWARE or RATE_LIMIT. Put no private data in it.
  • The fn goes in src/*.rs. A #[remote(prerender)] fn in a page's block is a build error: "the answer is a public file: put it in src/*.rs".
  • The fn takes no cx (no cookies, headers or user), at most one argument, and returns a value that is JSON. Each of these is a build error otherwise.
  • The argument is a String, &str, bool or integer. Another type (a float, a struct) is a build error. An integer past ±2^53 fails the build, because JavaScript cannot hold it exactly.
  • With an argument, fn post_inputs() -> Vec<T> beside it lists the inputs. At most 1024 inputs, each answer at most 4 MiB, and all answers at most 64 MiB. Past one of them, the build fails and names the fn.
  • A file's name is FNV-1a (64 bit) of the argument's JSON. Two equal inputs fail the build. Two different inputs with one name (a hash collision) fail it too, with their values.
  • A call with an argument that is not in the inputs gets a 404, and no code of the app runs. A method other than GET or HEAD gets a 405.
  • A fn that panics or fails at build fails the build and names the call.
  • wisp dev, a release build without wisp build, and an edge build (--target) do not write the files: they run the fn for each call. The call returns a Promise, not a query.
  • With a base path (WISP_BASE), the call asks for the file under the base. The static export writes it at _app/r/ in its folder, as it writes the pages.
  • Only an app with one gets its browser code.

Server Rendering Off

With const SSR: bool = false; in the block, the server runs the statements and sends layouts, <head>, the markup as an unpainted <template> and the values it names. The browser draws it.

  • The markup is browser code ({:x}, {:#each}). ${…}, {#if}, {#each} or a component given ${…} is a build error (Rust is fine in <title>/<head>).
  • For pages that depend on the browser (size, localStorage) or that +page.js fills. wisp build --spa serves them from a static host.

Errors and Source Maps

  • An error while a script starts, or in +page.js, shows the nearest +error.wisp. Handler errors go to the console.
  • In dev each browser module has a //# sourceMappingURL, so DevTools shows the .wisp file.
  • Release has none unless wisp build --sourcemap.

Is This Page Useful?

View This Page's Source

Type to search every docs page and heading.