Roc Solid
Markup in Roc · pages on a native server · components in WebAssembly

The platform · reference

Platform reference

Every module the server platform exposes, and every effect in each: its type and what it does. The build reads it all from the modules' types and ## doc comments, so this page says what the code says, and a new effect appears as soon as it exists.

40 modules, 167 effects and 194 pure functions. An effect is a function whose name ends in !: it does something (reads the database, sends a request, makes a signal), so only another effect can call it. Pure functions only compute; each module folds them away. A module marked browser too is the browser platform's as well (web/platform, copied into the server's by the build). For effects at work, with examples, see the guides: the server, HTTP, the database, live and channels, actors, Kv, settings, crypto, and plugins.

Requests and HTTP#

Server browser too

web/platform/Server.roc

The server: what it knows about a request, and how it answers. An app's respond! gets each request from its platform (from_http) and gives back the answer; its routes, endpoints and middleware (rocx writes them from routes/) take and make these in between. A component talks to the server through endpoints (Endpoint).

Server.failed! : Request, Str => Response

The answer to a request that failed on the server's side (a query, a service that didn't answer), for a handler that makes its own answers (a route's respond!, a package's handler): why goes on the server's log, an error with the request's path, method and route, and the client gets a plain 500 (failed_text), never why: a database's text can name the app's tables, columns and values. An endpoint's handler answers Err(Failed(why)), which does the same (Endpoint.Refusal).

Err(DbErr(why)) => Server.failed!(request, why)
Server.flash! : {} => Try(Flash, [NoFlash])

The flash a plain form's post came back with, on the page the redirect lands on: the next page a browser asks for after it (clear_flash). On the server it waits in the server's memory, its id in the request's cookie, and the first page that reads it takes it (it is read once); the page notes it for the browser (a script hydration reads), so both render the same. A field the page has as an <input type="password"> is left out of that note, and the page never fills such an input in again. Err(NoFlash) on any other page. use_submission! reads it for you.

Server.flash_back! : Request, { url : Str, input : Str, status : U16, body : Str } => Response

The answer to a plain form's post, instead of the endpoint's own: back to the page it was posted from (Referer, when it is this site's; / otherwise), with a 303, and the flash (url posted to, the form's body as posted, the answer's status and body) kept for that page to read (flash!): in the server's memory for a minute, under a random id that a cookie (rocx-flash, HttpOnly) holds, and nothing else. However long what was typed, it is kept.

Server.request! : {} => Request

The request being answered: on the server, the one the host is answering (a page's, an endpoint's, a GET a page reads as it renders), its peer too; empty, a GET of /, anywhere else. The host hands it over as text, so a body that isn't UTF-8 comes with U+FFFD where it isn't: an endpoint is given its request's bytes as they came.

36 pure functions
from_host : Str, Str -> Request
from_http : Str, Str, Str, List(U8) -> Request
for_host : Response -> { status : U16, headers : Str, kind : U8, text : Str, bytes : List(U8), upstream : { method : Str, url : Str, headers : Str }, page : {} => Html, feed : { send! : Str => Bool, sleep! : U64 => {} } => {} }
response : U16, List({ name : Str, value : Str }), Str -> Response
bytes : U16, List({ name : Str, value : Str }), List(U8) -> Response
forward : Upstream, List({ name : Str, value : Str }) -> Response
stored : Str, Str, Request, List({ name : Str, value : Str }) -> Response
passed_on : Request -> List({ name : Str, value : Str })
text_of : Request -> Str
events : Events(Str) -> Response
body_text : Response -> Str
changes : Request -> Bool
wants_html : Request -> Bool
redirect : Str -> Response
refused : U16, Str -> Response
failed_text : Str
cookie_defaults : CookieOpts
set_cookie : Response, Str, Str, CookieOpts -> Response
clear_cookie : Response, Str, CookieOpts -> Response
with_cookie : Response, Str, Str -> Response
secure_cookies : Response -> Response
without_cookie : Response, Str -> Response
form_json : Str -> Str
form_fields : Str -> List({ name : Str, value : Str })
files : Request -> List(Upload)
file : Request, Str -> Try(Upload, [NoFile])
multipart : Request -> Try({ fields : List({ name : Str, value : Str }), files : List(Upload) }, [NotMultipart])
clear_flash : Request, Response -> Response
explain : Problem -> Str
same_origin : Request -> Bool
encode_segment : Str -> Str
encode_param : a -> Str where [a.Json.Encodable(e)]
decode_segment : Str -> Str
header : Request, Str -> Try(Str, [Missing])
cookie : Request, Str -> Try(Str, [Missing])
unwritable : Str

Endpoint browser too

web/platform/Endpoint.roc

An HTTP endpoint: a method at a path, which a route's +server.roc defines (get!, post!, put!, patch!, delete!; events!, a stream of events, asked for with GET). Anyone may call it over HTTP. The app calls it through what rocx writes from the routes (Generated/Api.roc), as a function of its params: its contract, the method, the URL and the types its handler's annotation gives, and nothing the handler does, so any module may import it (D-037). A component reads a GET endpoint as a plain value (Api.get_board({}).read!()): while the server renders the page, the server answers it, and the page carries the answer to the browser. It sends any endpoint (Api.post_card({}).send!(card), a refusal as a value; a GET too, with {}), or listens to one's events (listen!), through the platform's Call. On the server, a handler sends one of the app's own endpoints with send! too, answered in-process by its route, behind its middleware (D-103), and a channel's messages are published to it (publish!).

A handler is given the request, the context its middleware handed on, its path's params and its body, and answers Ok(result), sent as JSON with the status 200, or a Refusal: a status and why, a failure on the server's side (Failed: why is logged, never sent), or an answer of its own (Answer: a redirect that sets a cookie).

Its arg is one type whoever sends it: JSON (an action, a script) is read as JSON; a form's fields (a plain form, or one the runtime sent) are read by the arg's type too (FormBody, D-038), a number from its text, a box left unticked Bool.False, the values a name has as a List. The endpoint keeps that reader (form), made where its arg's type is known (remote, local).

A form's fields may be given ahead of time (with_fields, Solid Router's action.with): they go in the URL the form posts to, and its own fields after them.

Its arg may be checked as well as typed (checked, D-093): read by rules of the app's (a form of packages/forms), from a form's fields or a JSON object alike, and refused with their issues (422, as JSON) when it doesn't pass them. Generated/Api makes it so for a method whose route file names its body's rules (post_body = Signup.form).

Endpoint.read! : Endpoint(context, {}, result) => result where [result.Json.Parseable([InvalidJson(Str)])]

A GET endpoint's answer, as a plain value, for a component or a computation (create_memo!(|| Api.get_profile({ id }).read!())): one definition of a page's data, the endpoint's, read where the page renders.

  • While the server renders the page, the server answers it in-process. The GET goes through the endpoint's route, as the browser's would, with accept: application/json and the page's cookies and headers, behind the route's middleware. The answer is noted for the page.
  • Hydrating, the browser reads that answer from the page and asks nothing.
  • Asked again later (refresh!), the browser GETs the endpoint's URL.

An answer that isn't 200 fails the computation: the nearest <Errored> shows its status and why (GET /api/likes: 500: the database is down). One no <Errored> of the page's catches reaches the app's root one (rocx writes it), and the page is the app's error page (+error.rocx), answered with the refusal's status when it is a 4xx (GET /notes/9: 404: Not found is a 404, as a path no page has is: Errored.status_of), else 500. A boundary of the page's own that catches it shows its fallback, as it would in the browser, and the page is answered as it is (200, unless the fallback says otherwise with <HttpStatusCode>). A redirect, while the page renders (a signed-out visitor sent to sign in), is the page's answer instead. with_query adds a query; endpoint.send!({}) gives a refusal as a value, for a computation that shows it itself.

Endpoint.send! : Endpoint(context, arg, result), arg => Try(result, Server.Problem) where [arg.Json.Encodable(e), result.Json.Parseable([InvalidJson(Str)])]

Its answer, a refusal as a value: Ok(result), or Err(Refused(404, why)) and the like (Api.post_api_shout({}).send!({ word })). From a handler, in the browser, it is sent with the platform's Call.fetch!; the handler stops until the answer is in, and runs again then. A GET (Api.get_board({}).send!({})) is asked as read! asks it, while the page renders too, for a computation that shows a refusal itself. On the server, from the code answering a request (a handler, an MCP tool), one of the app's own endpoints is answered in-process, by its route, as the browser's request would be: behind the app's middleware and the endpoint's, with the request's headers (its cookies, its authorization), so what guards the endpoint guards this call too (D-103).

Endpoint.listen! : Endpoint(context, {}, Events(event)), ([Event(event), Ended, Failed(Server.Problem)] => {}) => {} where [event.Json.Parseable([InvalidJson(Str)])]

From a component, in the browser: listens to an endpoint's events with the platform's Call.listen! (Api.events_api_count_to({ to }).listen!(heard!)): heard! is given each event as it comes, typed, then Ended, or what went wrong.

Endpoint.subscribe! : Endpoint(context, {}, Channel(who, message, said)), (Channel.Event(message) => {}) => {} where [message.Json.Parseable([InvalidJson(Str)])]

From a component, in the browser: subscribes to a channel (a route's channel!), from an effect, until the effect runs again or its component goes (create_effect!(|| org!(), |org| Api.channel_org_org_news({ org }).subscribe!(heard!))). heard! is given what its subscription hears (Channel.Event), in order, one at a time: Resync when it should read its data again, then each Message; or why it hears nothing.

Every subscription in a tab shares one stream (/rocx/live), which the runtime opens once the page has rendered, and opens again, a little later each time, when it drops. When what the page subscribes to changes, the runtime tells the stream so (a post), and the route's on_close! hears Dropped for a channel the page no longer subscribes to. Two components on one channel share its subscription. A message it can't read as message is a Resync. On a host with no server (a static copy), it is Refused(404, …), asked for once. On the server, it does nothing.

Endpoint.say! : Endpoint(context, {}, Channel(who, message, said)), said => {} where [said.Json.Encodable(e)]

From a component, in the browser: says said on a channel, to the server, where its route's receive! hears it, if its check lets the page in (Api.channel_rooms_room({ room }).say!(Moved({ x, y }))). What a page says in one frame goes in one request (POST /rocx/live/send); nothing waits for it, and a refusal is a warning in the console. Not on the server.

Endpoint.resync! : Endpoint(context, {}, Channel(who, message, said)) => {}

From a component, in the browser: asks the server for a Resync on a channel this tab subscribes to (and the route's on_open! messages after it), as when the page saw it missed something (a gap in the numbers its messages carry). Every subscriber to it in the tab hears it. Not on the server.

Endpoint.publish! : Endpoint(context, {}, Channel(who, message, said)), message => {} where [message.Json.Encodable(e)]

On the server: publishes message to every page subscribed to a channel (Api.channel_org_org_news({ org: "acme" }).publish!(news)), from a request, a job or an actor: only those subscribed with the same params hear it. A subscriber hears the messages on a channel in the order they were published; one that falls too far behind (256) hears Resync instead of what it missed. In the server's memory (Live): published while nobody listens, it is gone.

Endpoint.publish_latest! : Endpoint(context, {}, Channel(who, message, said)), Str, message => {} where [message.Json.Encodable(e)]

On the server: publishes message as publish! does, but only the latest with each key matters (where each member's cursor is, say: its key, the member). A subscriber behind gets only the newest with each key, and never a Resync for these: what it missed is replaced. They aren't ordered with the channel's other messages.

Endpoint.channel! : Endpoint(context, {}, Channel(who, message, said)), Server.Request, context, { opened! : who, Str => List(message), received! : who, Str, Str => Try({}, Refusal), closes : Bool } => Server.Response where [who.Json.Encodable(e), message.Json.Encodable(f)]

On the server: the answer to the host's question about a subscription (/rocx/live), as the generated routes give it, behind the route's middleware: its check, given the context that handed on; then, as the host asks (x-rocx-channel), who it let in and what it is sent first (open), who it is now (check), or what a page said, for received! (receive). A refusal is its status and why, or the answer it is (a redirect).

Its hooks: opened!, the messages a subscriber is sent first; received!, what a page said, as JSON (receiving reads it as the channel's said); closes, whether the host tells the route when a subscription ends.

Endpoint.closed! : Endpoint(context, {}, Channel(who, message, said)), Server.Request, (who, Str, Channel.Closed => {}) => Server.Response where [who.Json.Parseable([InvalidJson(Str)])]

On the server: a subscription has ended, as the host tells it (x-rocx-channel: close, its body who the check said it was and why it ended): the route's on_close!, given them. Its middleware doesn't run, nor its check: a subscription refused at a beat ends too.

Endpoint.respond! : Endpoint(context, arg, result), Server.Request, context => Server.Response where [arg.Json.Parseable([InvalidJson(Str)]), result.Json.Encodable(e)]

On the server: the answer to a request to it, given the context its middleware handed on. Its arg is the body, read when it says it is JSON (application/json, or a type ending +json) or a form (application/x-www-form-urlencoded: its fields, as a browser posts them, read by the arg's type, FormBody; a field it lacks or can't read is a 400 naming it). Any other body (an upload: application/octet-stream, video/mp4, or no type at all) isn't read: the arg is {}, and the handler reads request.body, the bytes as they came. No body is {} too. A checked endpoint (checked) reads a form's fields, or a JSON object's, by its rules instead, and refuses what doesn't pass them with their issues (422, JSON); a JSON body that isn't an object of fields is a 400. Its result is sent as JSON, a refusal as its status and why (text; JSON for Json), or as the answer it is. A body it doesn't read, for a handler that wants an arg, is 415.

A form a browser posted without the runtime (a plain <form method="post">: a form's body, accept: text/html) gets neither its result nor its refusal, which would be a page of JSON or of text: it goes back to the page it came from, which reads them with what was typed (Server.flash_back!, Server.flash!, use_submission!). A form the runtime sent (x-rocx-submission) gets them, and a redirect of its handler's own comes back as 200 with x-rocx-redirect (fetch would follow it before anyone could read it), for the runtime to go there. An answer of its own is otherwise sent as it is.

Endpoint.respond_as_is! : Endpoint(context, arg, Server.Response), Server.Request, context => Server.Response where [arg.Json.Parseable([InvalidJson(Str)])]

On the server: as respond!, for an endpoint whose result is an answer of its own: a handler annotated => Try(Server.Response, Endpoint.Refusal) (D-106), which rocx build answers with this. Its Ok is sent as it is, as Err(Answer(…)) is (a redirect of its own comes back to a form the runtime sent as 200 with x-rocx-redirect); its refusals are respond!'s. A text, a file, a redirect that sets a cookie: an answer that isn't JSON, without its success being an Err.

Endpoint.stream! : Endpoint(context, {}, Events(event)), Server.Request, context => Server.Response where [event.Json.Encodable(e)]

On the server: the answer to a request for an endpoint's events (events!, asked with accept: text/event-stream), given the context its middleware handed on: a stream, each event sent as JSON as it comes; a refusal as its status and why, or as the answer it is.

20 pure functions
local : Str, Str, (Server.Request, context, arg => Try(result, Refusal)) -> Endpoint(context, arg, result) where [arg.FormBody.Readable]
local_json : Str, Str, (Server.Request, context, arg => Try(result, Refusal)) -> Endpoint(context, arg, result)
remote : Str, Str -> Endpoint(context, arg, result) where [arg.FormBody.Readable]
bind : Endpoint(context, arg, result), (Server.Request, context, arg => Try(result, Refusal)) -> Endpoint(context, arg, result)
read_params : List({ name : Str, value : Str }) -> Try(params, Str) where [params.FormBody.Readable]
checked : Endpoint(context, arg, result), rules -> Endpoint(context, arg, result) where [rules.parse : rules, List({ name : Str, value : Str }) -> Try(arg, issues), rules.json_schema : rules -> Str, issues.Json.Encodable(e)]
checked_schema : Endpoint(context, arg, result) -> Try(Str, [Unchecked])
form_of : Endpoint(context, arg, result) -> (List({ name : Str, value : Str }) -> Try(arg, Str))
with_query : Endpoint(context, arg, result), Str -> Endpoint(context, arg, result)
receiving : Endpoint(context, {}, Channel(who, message, said)), (who, Str, said => Try({}, Refusal)) -> (who, Str, Str => Try({}, Refusal)) where [said.Json.Parseable([InvalidJson(Str)])]
channel_asked : Server.Request -> Str
url_of : Endpoint(context, arg, result) -> Str
base_of : Endpoint(context, arg, result) -> Str
with_fields : Endpoint(context, arg, result), bound -> Endpoint(context, arg, result) where [bound.Json.Encodable(e)]
to_request : Endpoint(context, arg, result), arg -> { method : Str, url : Str, headers : List({ name : Str, value : Str }), body : Str } where [arg.Json.Encodable(e)]
answer : Endpoint(context, arg, result), Try({ status : U16, headers : List({ name : Str, value : Str }), body : Str }, [HttpErr(Str)]) -> Try(result, Server.Problem) where [result.Json.Parseable([InvalidJson(Str)])]
for_runtime : Server.Request, Server.Response -> Server.Response
posted_by : Server.Request -> [PlainForm, Runtime, Other]
refused : Refusal -> (U16, Str)
not_allowed : Server.Request, List(Str) -> Server.Response

Middleware browser too

web/platform/Middleware.roc

Code that runs around an answer. A middleware gets the request, the context so far and what comes next: it answers itself (a guard: a redirect, a refusal), or calls next! with the context it hands on (who is signed in), or changes what comes back (a header).

signed_in = Middleware.make(|request, context, next!|
    match Session.user!(request) {
        Ok(user) => next!(request, { facts: context.facts, user })
        Err(_) => Server.redirect("/sign-in")
    })

a.then(b) is a, then b; Middleware.when(Server.changes, guard) is guard for some requests alone. Middleware is named by folder, as routes are (D-103): a +middleware.roc under routes/ (middleware = Middlewares.member) runs around every page, endpoint and channel in its folder and the folders below it, outermost first; the one in routes/ itself runs around every request the app answers: every URL is a route file (D-116), a package's handlers and the OpenAPI document included, so a folder's middleware is around them as around the app's own. A folder in brackets, (members), adds nothing to the path: pages and their endpoints under api/ share one that way. What a middleware hands on is typed: a handler that reads context.user compiles only behind one that adds it.

Middleware.run! : Middleware(given, handed), Server.Request, given, (Server.Request, handed => Server.Response) => Server.Response

Runs it around last!: what answers once every middleware has passed the request on.

5 pure functions
make : (Server.Request, given, (Server.Request, handed => Server.Response) => Server.Response) -> Middleware(given, handed)
then : Middleware(a, b), Middleware(b, c) -> Middleware(a, c)
when : (Server.Request -> Bool), Middleware(context, context) -> Middleware(context, context)
same_origin : {} -> Middleware(context, context)
headers : List({ name : Str, value : Str }) -> Middleware(context, context)

Router browser too

web/platform/Router.roc

Solid Router's, on both sides. Where the page is (useLocation): on the server, the request's path and query; in the browser, the location the page on screen was rendered for, which each navigation in place changes (D-040). A trailing slash is dropped (/syntax/ is /syntax), as the server drops it from what it answers. Navigating (useNavigate, useIsRouting); and submissions to an endpoint: the latest (useSubmission), all of them (useSubmissions), and a handler's own, without a form (useAction).

Router.location! : {} => Location

Where the page is: on the server, the request's path and query; in the browser, the location the page on screen was rendered for (location.pathname without the site's base, and location.search). Tracked: a hole or a memo that reads it runs again when a navigation in place changes it.

Router.navigate! : Str => {}

Navigates to to (Solid Router's useNavigate), from a handler: a path (Paths makes them), a path with a query, or a query alone (?days=30, on the page's own path). One of the app's pages is rendered in place, the old page staying until the new one's document is in (is_routing!); anything else (another site, a path no page has) the browser loads. Queued with the handler's writes, so a handler that waits for the server and runs again navigates once. Called while computing, it fails: rendering mustn't navigate. On the server no handler runs, and it does nothing.

<button on:click={|| navigate!(Paths.tasks_id({ id: task!().id }))}>Open</button>
Router.navigate_with! : Str, { replace : Bool, scroll : Bool } => {}

navigate! with Solid Router's options: replace replaces the history entry instead of pushing one; scroll: Bool.False leaves the scroll where it is (else the new page starts at the top, or at the element its hash names).

navigate_with!(Paths.lists_id({ id: list.id }), { replace: Bool.True, scroll: Bool.True })
Router.is_routing! : {} => Bool

Whether a navigation in place is on its way (Solid Router's useIsRouting), tracked: true from the click until the new page is on screen, or the navigation fails or is overtaken; false on the server and while hydrating.

<div class="progress" class:on={Router.is_routing!({})} aria-hidden="true"></div>
Router.use_before_leave! : (Leave => {}) => {}

Runs listener! before each navigation away from the page (Solid Router's useBeforeLeave, D-040), as a handler: a link, navigate!, <Navigate>, a GET form, a submission's redirect, a change of the query alone, back and forward. It is given the navigation (Leave: to, from, options, delta), which it may stop (leave.prevent!()), and let go later (leave.retry!(force), from another handler: an app's own dialog). Called in a component (or a computation), it listens while that is there, and stops when it goes. Listeners are asked in the order they came.

use_before_leave!(|leave|
    if dirty!() {
        leave.prevent!()
        set_leaving!(Ok(leave))
    }
)

A listener decides from what the page has (a signal, a memo already in): the navigation is decided once each has run, and one that waits for the server can't hold it (it isn't run again when the answer is in; a dev build says so). A load (leaving the site, reloading, closing the tab) the page can't hold: the runtime asks each listener ahead of time, with to "" (and its writes dropped), again whenever what it read changes, and while one would stop it, the browser asks the visitor first, with its own words (beforeunload). On the server no navigation happens, and it does nothing.

Router.use_search_params! : {} => Search

The page's query (Solid Router's useSearchParams, D-040): get! and all! read it, tracked; set! and set_with! change it in place, from a handler. See Search.

search = use_search_params!({})
days! = || search.get!("days") ?? "7"
<button on:click={|| search.set!([("days", "30")])}>30 days</button>
Router.app! : { build : Str, dev : Bool, routes : Str } => {}

The app, told to the runtime as its page renders: Generated/Root.roc calls it first, and an app never does. build is the build's id (rocx build's hash of the app's sources): the server writes it on the page's bootstrap (data-build), and the browser loads a page of another build instead of rendering it. dev: rocx built it with --dev. routes: the app's pages, as JSON rocx build wrote (each page's path, /lists/[id], and its levels' code, from the root layout to the page), which the browser navigates in place to.

Router.use_submission! : Endpoint(context, arg, result) => Submission(arg, result)

The latest submission of a form to endpoint (Solid Router's useSubmission(action)): its pending!(), input!() (field!(name)), result!() and error!(). The runtime sends a method="post" form whose action is one of the app's endpoints (Endpoint.url_of) with fetch, and the page stays, whether a component asks for its submission or not (D-095): this is how the page shows how it went. (An endpoint the route table doesn't have, in an app with no routes/, is sent so while the component that asks is there.) Without the runtime, the form posts, and the endpoint sends the browser back to the page with a flash, which the submission is.

join = Api.post_api_members_join({})
submission = use_submission!(join)
<form method="post" action={Endpoint.url_of(join)}>…</form>
Router.use_submissions! : Endpoint(context, arg, result) => Submissions(arg, result)

Every submission to endpoint, each its own (Solid Router's useSubmissions(action)): its forms' (sent with fetch, as use_submission! says) and its actions' (use_action!). See Submissions.

moves = use_submissions!(Api.post_api_planner_move({}))
<p class:saving={moves.pending!()}>…</p>
Router.use_action! : Endpoint(context, arg, result) => (arg => {}) where [arg.Json.Encodable(e)]

Sends endpoint from a handler, without a form, and without the handler waiting for its answer (Solid Router's useAction(action)): each call is a submission of its own, which use_submissions! lists, sent once the handler is done (so a handler that waits for the server and runs again sends it once). Its arg goes as JSON (Endpoint.send!'s request). A result (200) has the page's reads read again before the submission is done; a refusal is its error (the error of its record in Submissions.all!, or Submission.error! of the latest).

move! = use_action!(Api.post_api_planner_move({}))
<li on:drop={|| move!({ card: dragged!(), day })}>…</li>

Called from anywhere but a handler, its function fails; on the server, no handler runs.

A top-level field of its arg holding the URL of a file the page has (one on:drop.files, on:paste.files or on:change.files gave, Html.File's url), or a list of them, sends the file: the action goes as a form with files (multipart/form-data), its other fields as a form's, and the endpoint reads the field as the file's name, its bytes with Server.file.

Router.revalidate! : List(Str) => {}

Which of the page's reads a submission's result reads again (Solid Router's revalidate keys), each a URL (Endpoint.url_of(Api.get_board({}))): a GET the page read is read again when its URL is one of them, or begins with one and a / or a ? ("/api/notes": every note). Without it, a result reads every GET the page read again, as before; with [], none, and the submission is done at once.

  • In an endpoint's handler, on the server: said in its answer (x-rocx-revalidate), for the runtime that sent the submission (a form's, or an action's).
  post! = |{ body, .. }| {
      Router.revalidate!([Endpoint.url_of(Api.get_board({}))])
      Ok(Board.moved!(body))
  }
  • In a handler, in the browser: those reads, read again now (Solid Router's revalidate(keys)), once the handler is done. Anywhere else in the browser it fails.
1 pure function
parse : Str -> Location

Http

server/platform/Http.roc

Requests to other servers over HTTP/1.1, plain or over TLS (https, the server's certificate checked against the web's certificate authorities): an API, an OAuth server, S3. One effect makes them, Http.fetch!(url, init), as JS's fetch does; init says what isn't a plain GET, each field left out has its default, and {} is a GET:

weather = Http.fetch!("${api}/forecast", { query: [("city", city)] })?.json()?
Http.fetch!(url, { method: Post, body: Http.json(order) })?

The host makes each request (server/host/src/client.rs), the call pausing while it waits, as with Db and Tcp, on a connection kept alive from an earlier request to the same place when there is one, and through the proxy init.proxy says (the environment's by default). Any status is an answer (Ok, an HttpResponse): a 404 or a 500 is the other server's to give, and res.ok says whether it is a success. An Err means there was none: it couldn't be reached, TLS failed, or it broke off (HttpErr); it didn't answer whole in time (TimedOut); its body was larger than allowed (TooLarge).

Request, Response, Opts, defaults, send!, send_request!, get, post_form, post_json, with_header, header and text are the API before fetch! (D-024), kept for the apps that use them, deprecated: each is fetch! underneath.

Http.fetch! : Str, Init => Try(HttpResponse, [HttpErr(Str), TimedOut, TooLarge])

Makes a request to url, as init says ({}: a GET, as fetch(url) makes), and reads its answer whole: any status is Ok (res.ok if it is 2xx). Err(HttpErr(why)) with no answer: no server there, TLS that failed, a URL that isn't http or https, or a header that can't be sent (a line break in it, or a colon in its name); Err(TimedOut), no whole answer within timeout_ms; Err(TooLarge), a body over max_bytes.

authed : Http.Init
authed = { headers: [("authorization", "Bearer ${token}")] }
res = Http.fetch!("${api}/notes/${id}", { ..authed, method: Delete })?
Http.fetch_chunks! : Str, Init, state, (state, Received => Try(state, err)) => Try(state, [HttpErr(Str), TimedOut, TooLarge, Stopped(err)])

Makes a request as fetch! does, and hands its answer to step! as it comes, rather than whole: its head (Head(res)), then each chunk of its body (Chunk(bytes)), each with what step! answered last (start first). What it answers after the last chunk is the result. An Err from step! ends the request there, its connection closed (Err(Stopped(why))). For a body too large to hold, or one to pass on as it comes (a model's answer, word by word, to a stream of events): no chunk is kept after step! has it.

lines = Http.fetch_chunks!(url, { max_bytes: 0, timeout_ms: 0 }, 0, |count, received|
    match received {
        Head(res) => if (res.ok) Ok(count) else Err(Status(res.status))
        Chunk(bytes) => Ok(count + bytes.count_if(|byte| byte == '\n'))
    })?

timeout_ms runs from the request to the body's last byte, and max_bytes counts every chunk: 0 for either is no limit, as a stream that runs long wants. The errors are fetch!'s, and Stopped.

Http.send! : Request, Opts => Try(Response, [HttpErr(Str), TimedOut, TooLarge])

deprecated: use Http.fetch!. Makes request as opts say: fetch! with the request's method (as written), headers and bytes.

Http.send_request! : Request => Try(Response, [HttpErr(Str), TimedOut, TooLarge])

deprecated: use Http.fetch! (this was fetch! before it). send! with defaults.

11 pure functions
json : a -> Body where [a.Json.Encodable([])]
form : List((Str, Str)) -> Body
plain_text : Str -> Body
bytes : List(U8) -> Body
defaults : Opts
get : Str -> Request
post_form : Str, List((Str, Str)) -> Request
post_json : Str, Str -> Request
with_header : Request, Str, Str -> Request
header : Response, Str -> Try(Str, [Missing])
text : Response -> Str

HttpResponse

server/platform/HttpResponse.roc

What another server answered a request (Http.fetch!), read whole, as fetch's Response is read: its status; ok, whether that is a success (2xx); its headers, each name in lower case; its body; and, from those, res.header(name), res.text(), res.json() and res.bytes().

res = Http.fetch!(url, {})?
if res.ok res.text() else "${res.status.to_str()}: ${res.header("content-type") ?? "?"}"

No effects: pure functions alone.

5 pure functions
new : U16, List((Str, Str)), List(U8) -> HttpResponse
header : HttpResponse, Str -> Try(Str, [Missing])
text : HttpResponse -> Str
json : HttpResponse -> Try(a, [InvalidJson(Str)]) where [a.Json.Parseable([InvalidJson(Str)])]
bytes : HttpResponse -> List(U8)

Events browser too

web/platform/Events.roc

Events a server sends a page as they happen, over one response (server-sent events): what an endpoint's events! answers, and a component listens to (Endpoint.listen!).

A stream is a loop: it sends an event (send!), sleeps (sleep!), and goes round again.

Events.stream(|{ send!, sleep! }| {
    var $count = 1
    while $count <= 3 {
        send!($count)?
        sleep!(300)
        $count = $count + 1
    }
    Ok({})
})

Nothing in it runs until the server sends it, as a call of its own that pauses while it sleeps, so a sleep holds up no other request. send! says when the page has gone (Err(Gone)): with ?, the loop ends there, and nothing more runs.

Events.run! : Events(a), { send! : a => Try({}, [Gone]), sleep! : U64 => {} } => Try({}, [Gone])

Sends the stream with send! and sleep!, to its end or until the page goes: what the feed Server.for_host gives a platform runs, on the thread the platform gives the stream.

5 pure functions
none : {} -> Events(a)
stream : ({ send! : a => Try({}, [Gone]), sleep! : U64 => {} } => Try({}, [Gone])) -> Events(a)
from_list : List(a), U64 -> Events(a)
map : Events(a), (a -> b) -> Events(b)
is_ended : Events(a) -> Bool

Call browser too

web/platform/Call.roc

Requests from a component: an HTTP request (fetch!), its answer read as a plain value, and a stream of events (listen!). While an answer is on its way, the computation or handler that asked stops, and runs again once it is in; if there is none, the nearest <Errored> shows why. Endpoint reads and sends an app's endpoints with them.

Call.fetch! : { method : Str, url : Str, headers : List({ name : Str, value : Str }), body : Str } => { status : U16, body : Str }

An HTTP request from the browser (an endpoint's, say: Endpoint.send!): its answer, read as a plain value. A handler or computation that asks stops until it is in, and runs again then; no answer at all (offline) shows the nearest <Errored>. On the server, while a page renders, a GET of one of the app's own paths is answered in-process and noted for the page (Endpoint.read!), and any other request is a handler's, which fails there; outside a render, a request of the code answering one (a handler's Endpoint.send!) to one of the app's own paths is answered in-process, by its route, behind its middleware (D-103).

Call.listen! : Str, ([Event(Str), Ended, Refused(U16, Str), Failed(Str)] => {}) => {}

Listens to a stream of events (server-sent events: an endpoint's events!) at url, from a handler: heard! runs, as a handler does, for each event's data as it comes, then once with Ended; or Refused(status, why) (an answer that isn't a stream), or Failed(why) (offline, or a stream cut off).

Submission browser too

web/platform/Submission.roc

A submission to an endpoint, as Solid Router's useSubmission gives it: whether it is on its way, what was sent, and the endpoint's result or refusal. Its fields are methods: submission.pending!(). Router.use_submission!(endpoint) is the latest one; Router.use_submissions!(endpoint) lists them all, each its own (Submissions).

With the runtime, a form posting to the endpoint is sent with fetch, as is an action (Router.use_action!), and the submission is one the runtime sent. Without it (before it loads, or with no JavaScript), the form posts as a form does, and the endpoint sends the browser back with a flash (Server.flash!): until the runtime sends one, the latest submission is that flash, when it is the endpoint's. On the server it is the flash, or none.

A submission the endpoint answers with its result (200) stays pending until the page's reads (Endpoint.read!) have been read again, so what the page shows next is the server's, all at once.

Submission.pending! : Submission(arg, result) => Bool

Whether it is on its way: sent, and not yet answered (or answered, and the page's reads being read again).

Submission.input! : Submission(arg, result) => Try(arg, [NoInput]) where [arg.Json.Parseable([InvalidJson(Str)])]

What was sent, as the endpoint reads it (its arg: a form's fields, as a record, or an action's arg). Err(NoInput) with no submission, or fields it doesn't read.

Submission.field! : Submission(arg, result), Str => Str

A field as it was typed (FormData.get), to put back in its input after a refusal: "" after a result that emptied its form (D-122: the form starts empty again, as the page a plain post comes back to has it, and as SvelteKit's does; input! still says what was sent; a form marked data-rocx-keep keeps it: emptied!), with no submission, no such field, or for an action's (its arg isn't a form's fields: input! reads it).

Submission.emptied! : Submission(arg, result) => Bool

Whether its form was emptied once the endpoint accepted it (D-122): its inputs show what the page wrote in them again. The form the runtime sent succeeded (a result, or a redirect), is still on the screen, and neither it nor what is around it says data-rocx-keep; or a plain post succeeded, and the page came back with the form as it writes it. Bool.False while it is on its way, after a refusal, with no submission, and for a form that keeps what was typed. What a page keeps of the form's fields follows it: packages/forms' LiveForm starts afresh then.

Submission.result! : Submission(arg, result) => Try(result, [NoResult]) where [result.Json.Parseable([InvalidJson(Str)])]

The endpoint's result, once it is in. Err(NoResult) before, without one, or after a refusal.

Submission.error! : Submission(arg, result) => Try(Server.Problem, [NoError])

What went wrong, once the answer is in: the endpoint's refusal (Refused(status, why)), or none at all (HttpErr). Err(NoError) before, without one, or after a result.

Submission.clear! : Submission(arg, result) => {}

Forgets it (Solid's clear), the flash too, from a handler: it leaves the endpoint's submissions, and there is none until the next is sent.

Submission.retry! : Submission(arg, result) => {}

Sends it again (Solid's retry), from a handler, with what it sent before: pending again, its answer to come. One still on its way isn't sent twice; with none (or the flash: a plain form's, which the runtime never had), nothing.

{if submission.error!().is_ok() { <button on:click={|| submission.retry!()}>Try again</button> }}
4 pure functions
of : Str, (List({ name : Str, value : Str }) -> Try(arg, Str)) -> Submission(arg, result)
url_of : Submission(arg, result) -> Str
form_body : List({ name : Str, value : Str }) -> Str
parse_input : (List({ name : Str, value : Str }) -> Try(arg, Str)), Str, Bool -> Try(arg, [NoInput]) where [arg.Json.Parseable([InvalidJson(Str)])]

OpenApi browser too

web/platform/OpenApi.roc

An app's endpoints as an OpenAPI document (3.2), which an app serves from a route of its own (routes/openapi.json/+server.roc calling OpenApi.document_route, D-116). rocx writes it from the routes (Api.openapi): each path and its params; each method there and what its handler's comment says; and the JSON Schemas of what it is sent and what it answers, from their types as the compiler has them, written down or inferred.

Roc has no reflection, but a type's parser is one for any format, and is handed each record's field names. This module's format (Schema) reads nothing: it writes the schema of each shape it is asked to read. A tag union's parser doesn't say what its tags are, so the format tries each name rocx found in the app's code (tags) and keeps the ones the union has.

No effects: pure functions alone.

11 pure functions
body : Endpoint(context, arg, result), List(Str) -> Str where [arg.parser_for : Schema -> (State -> Try({ value : arg, rest : State }, Problem))]
sent : Endpoint(context, arg, result), List(Str) -> Str where [arg.parser_for : Schema -> (State -> Try({ value : arg, rest : State }, Problem))]
answer : Endpoint(context, arg, result), List(Str) -> Str where [result.parser_for : Schema -> (State -> Try({ value : result, rest : State }, Problem))]
as_is : Endpoint(context, arg, Server.Response), List(Str) -> Str
events : Endpoint(context, {}, Events(event)), List(Str) -> Str where [event.parser_for : Schema -> (State -> Try({ value : event, rest : State }, Problem))]
operation : Str, Str, Str, Str, List(Str) -> Str
path : Str, List(Str), List(Str) -> Str
typed_path : Str, (params -> Endpoint(context, arg, result)), List(Str), List(Str) -> Str where [params.parser_for : Schema -> (State -> Try({ value : params, rest : State }, Problem))]
document : Str, List(Str) -> Str
document_route : Server.Request, Str -> Server.Response
page_route : Server.Request, [Swagger, Scalar] -> Server.Response

Data#

Db

server/platform/Db.roc

The app's database: Postgres, SQLite or Turso, as its program says (database, D-045, D-046). Its SQL is the app's, in its database's flavor: nothing is translated.

  • Postgres is at --database-url (or DATABASE_URL); without one the app has no database, and a server whose app or plugins have tables doesn't start, outside --dev and --debug.
  • SQLite is a file in the server's process, at the program's Sqlite(path) (or a sqlite:<path> --database-url), made when missing. Reads go on while a write does; writes take turns. So keep anything slow (Http.fetch!, a wait) out of a transaction: on SQLite it holds every other write back until it ends.
  • Turso is SQLite written again in Rust: the same SQL, at the program's Turso(path) (or a turso:<path> --database-url, which runs a SQLite app on Turso too). Its writes go on at once (MVCC, D-049): each transaction on a snapshot of its own, one that loses to another's write to the same row run again (transaction!). The server keeps the file to itself while it runs, and in MVCC mode it is Turso's alone (turso:<path>?mvcc=off once gives it back to SQLite, its writes then taking turns); no FTS5.

A statement's parameters are $1, $2, …, given as Values, in both. Postgres reads each as the type its place wants (where id = $1 reads Int(7) as an integer); SQLite is given each as it is (a Bool as 1 or 0). Rows come back as records: all! decodes each row's columns, by name, into the record its caller wants (one! the one row a statement reads, NotFound if none). A column that may be null is read as Nullable(a):

notes : Try(List({ id : I64, body : Str, note : Db.Nullable(Str) }), [DbErr(Str), BadRow(Str)])
notes = Db.all!("select id, body, note from notes", [])

match note.note {
    Null => "-"
    Some(text) => text
}

SQLite has no types of its own for a boolean, a time or JSON: a column declared boolean is read as a Bool, one declared json as its JSON, and a boolean worked out in a statement (exists (…)) is 0 or 1, an I64. A time is best kept as milliseconds (Time.now_millis!).

Each function's error is an open union ([DbErr(Str), ..others]), so a function ?s a statement beside other errors (packages/jobs' JobErr, the app's own) with nothing mapped, and its caller matches each.

Db.all! : Str, List(Value) => Try(List(row), [DbErr(Str), BadRow(Str), ..others]) where [row.Json.Parseable([InvalidJson(Str)])]

Every row a statement reads, each a record of its columns, by name. BadRow when a row doesn't fit the record: a column it lacks, a value of another type, or a null in a column the record doesn't read as Nullable(a) (the error names it).

Db.one! : Str, List(Value) => Try(row, [NotFound, DbErr(Str), BadRow(Str), ..others]) where [row.Json.Parseable([InvalidJson(Str)])]

The one row a statement reads, read as all! reads each (D-096): NotFound when it reads none. When it reads more than one, the first, in the statement's order: one that may read several says which it means (order by … limit 1). DbErr and BadRow are as all!'s.

task : Try({ title : Str, done : Bool }, [NotFound, DbErr(Str), BadRow(Str)])
task = Db.one!("select title, done from tasks where id = $1", [Int(id)])
Db.run! : Str, List(Value) => Try(U64, [DbErr(Str), ..others])

How many rows a statement changed (insert, update, delete), or the statement's error.

Db.script! : Str => Try({}, [DbErr(Str), ..others])

Runs sql, one statement after another (; between them), with no parameters: a schema, a migration. They run as one transaction: if one fails, none stays.

Db.connected! : {} => Bool

Whether the server has a database: a plugin that works without one (the job workers) does nothing instead.

Db.backend! : {} => [Postgres, Sqlite, None]

The database the server has, as its SQL: a package with SQL for both runs its flavor's. Turso's SQL is SQLite's, so a Turso app's answer is Sqlite (engine! tells them apart).

Db.engine! : {} => [Postgres, Sqlite, Turso, None]

The engine the server runs its statements on (D-046): Postgres, SQLite, or Turso (SQLite's SQL, Turso's engine). For what one engine has and the other hasn't (SQLite's FTS5), and for saying which: the SQL to run is backend!'s.

Db.notify! : Str, Str => Try({}, [DbErr(Str), ..others])

Tells channel's listeners (listen!) payload: when this call's transaction commits (never, if it rolls back), or at once outside one. On Postgres it is pg_notify, which other processes hear too; on SQLite it is the server's own.

Db.listen! : Str => Try({}, [DbErr(Str), ..others])

From now until this call ends, it hears what is notified on channel (notify!, or Postgres's pg_notify from anywhere) as messages on the topic db:<channel> (Live.next!): how a background loop sleeps until there is work.

Db.transaction! : ({} => Try(a, [DbErr(Str), ..others])) => Try(a, [DbErr(Str), ..others])

Runs body! in a transaction: what it writes, and the jobs it queues, stay only if it returns Ok; an Err (or a crash) rolls all of it back. Its error is the body's, or the database's. On SQLite it holds the write lock from its start (begin immediate): keep it short. On Turso (D-049) transactions write at once, each on its own snapshot: one that loses to another's write to the same row rolls back, and its body runs again after a short random pause (up to 100 times), so keep what isn't the database's (a fetch, a message) out of it.

Inside another transaction (a helper with a transaction of its own, called in one) it is a level of that one, a savepoint (D-076). Its Ok keeps what it wrote in the transaction around it, which commits it or not. Its Err, or a statement of it that fails, undoes what it wrote, notified and queued, and comes back to the body around it, which may handle it and go on. A crash still rolls back everything. On Turso a level that loses to another's write doesn't run again by itself: the whole transaction has lost, its statements fail from then on, and once the error reaches the outermost transaction!, that one runs again.

2 pure functions
array : List(Value) -> Value
unchecked : Str -> Str

Kv

server/platform/Kv.roc

The server's key-value store: values by key, kept in its memory for as long as you say, or until it stops. Never written anywhere, so a restart forgets them all: for what is cheap to lose and read often (a rate limit's counts, a cache, a one-time token, the dev mailbox). What must last goes in the database (Db).

A value is any type JSON can write, kept as JSON and read back as the type its reader asks for. Each operation is atomic: two requests incrementing one counter both count, two adding one key let one in, and a value taken is taken once. A key names its owner first, by convention (email:mailbox, guard:login:203.0.113.7), so a package's keys never meet an app's.

The store holds 64 MiB (--kv-max-mb, or KV_MAX_MB); past that the least recently read or written values go, so a cache can't grow without end. One instance of an app means one store.

Kv.set! : Str, value, Opts => {} where [value.Json.Encodable([])]

Keeps value under key for as long as opts says, replacing what was there (and its time to live).

Kv.get! : Str => Try(value, [NotFound, BadValue(Str)]) where [value.Json.Parseable([InvalidJson(Str)])]

The value under key. NotFound when there is none, or it has expired; BadValue when what is there isn't the type asked for (with why).

Kv.delete! : Str => {}

Forgets key. One that isn't there is forgotten already.

Kv.take! : Str => Try(value, [NotFound, BadValue(Str)]) where [value.Json.Parseable([InvalidJson(Str)])]

The value under key, forgotten as it is read: of two requests taking it at once, one gets it and the other NotFound. What one-time tokens are made of (OAuth's state, a sign-in link's nonce).

Kv.add! : Str, value, Opts => Try({}, [Exists]) where [value.Json.Encodable([])]

Keeps value under key only if nothing is there (or what was has expired): Exists otherwise. Of two requests adding one key at once, one gets Ok: a claim, or a request seen once (an idempotency key).

Kv.swap! : Str, was, value, Opts => Try({}, [Changed]) where [was.Json.Encodable([]), value.Json.Encodable([])]

Replaces the value under key with value, and its time to live, only if it is still was (compared as JSON, as this module writes it): Changed otherwise, or when nothing is there (add! puts a first one). A change that reads a value and writes the next one (a tally, a list of overrides) swaps, and on Changed reads again: of two at once, one wins and the other tries again with what it wrote, so none is lost (D-043). update! is that loop, done so that no writer starves.

Kv.update! : Str, value, (value -> value), Opts => Try({ was : value, now : value }, [Busy, BadValue(Str)]) where [value.Json.Encodable([]), value.Json.Parseable([InvalidJson(Str)])]

Changes the value under key with change, as one step as far as anyone else can tell: what is there (start when nothing is, or it has expired) is read, changed, and kept for as long as opts says only if nothing changed it meanwhile (swap!, or add! for a first one); if something did, it is read and changed again, so change may run more than once. It answers what was there and what is now; when change gives back what was there, nothing is written.

Kv.update!("visits", 0, |count| count + 1, {})?        # { was: 41, now: 42 }

A change that keeps losing to others isn't starved: after three lost tries each waits a moment first, up to 4 ms chosen at random, so writers that keep colliding spread out instead of trying again in step; after a thousand lost tries it gives up, Busy, nothing written. BadValue when what is there isn't the type (nothing written). Prefer it to a loop of your own around swap!.

Kv.increment! : Str, I64, Opts => Try(I64, [NotAnInteger(Str)])

Adds by to the integer under key, starting from 0 when there is none: the new value. A new counter's time to live starts then and isn't moved by later increments, so increment!(key, 1, { ttl_ms: 60_000 }) counts in windows of a minute (a rate limit). NotAnInteger when what is there is something else.

Kv.push! : Str, value, ListOpts => {} where [value.Json.Encodable([])]

Puts value at the front of the list under key, keeping its newest keep (at least one). A value that isn't a list is replaced by one. A new list's time to live starts then.

Kv.list! : Str => Try(List(value), [BadValue(Str)]) where [value.Json.Parseable([InvalidJson(Str)])]

The list under key, newest first; empty when there is none, or it has expired.

Plugins#

Plugin

server/platform/Plugin.roc

What a package adds to an app, as one value the app lists (App.program({ plugins: [...] })): paths answered before the app, under --dev or --debug (early); files served as they are, before the app and its middleware (files), and those of them every page loads (scripts); its tables (migrations); named functions run in a call of their own (calls); background loops; work run once the server has started (starts) and checks run after (checks); what it needs that the compiler can't see (needs); and the places it adds that a person may want to open (links), which the server lists under its address under --dev. Every field but name has a default, so a plugin says only what it adds. A package makes one from options of its own, whose fields without a default are required.

A plugin adds no routes (D-116): every URL an app answers is a file under its routes/. A package that answers requests offers handlers instead, which the app calls from a route file of its own, where it wants them and behind the middleware of the folder it puts them in:

# routes/(admin)/admin/jobs/+server.roc
respond! = |{ request, .. }| JobsPage.respond!(request, { mount: "/admin/jobs" })
plugin : Options -> Plugin.Value(context)
plugin = |options| {
    name: "acme",
    migrations: [{ name: "0001_notes", sql: notes }],
    loops: [{ name: "acme.sync", run!: |_context| sync!({}) }],
    needs: [Database, Env("ACME_KEY")],
}

A plugin's calls, loops, starts and checks are given the app's context (what its init! made, context), as its jobs and actors are. A plugin doesn't know its type.

When the server starts it checks every plugin at once, and any problem stops it, with the whole list: a name used twice; a call, loop or check not named <plugin>.<name>; an early path not under /__rocx/, or two at one method and path; a file's path that isn't one (/sw.js, ../x), two files at one path, a file at the root where the app has a route, a script that is none of the plugin's files; a need not met (an environment variable unset, no database or one of the other flavor, a plugin not in the list); needs that go round in a circle. It orders the plugins by what they need (the list's order breaking ties), applies their migrations after the platform's and before the app's, each recorded as <plugin>/<name>, makes the app's context (its init!), runs their starts with it (an Err stops the server), and names them on one line of the log (what each added at debug, under --debug: D-111).

Plugin.isolated! : Str, Str, U64 => Try(Str, Str)

Runs the call named name (<plugin>.<name>) with input, in a call of its own, within limit_ms milliseconds (0: no limit): Ok with its answer, or why not: its Err, the crash that ended it (crashed: …), or "timed out after …" (the first effect that waited past the limit cut it off).

Plugin.stopping! : {} => Bool

Whether the server is stopping: a loop's cue to end.

Plugin.keep! : Str, Str => {}

Keeps value in the server's memory under key (the plugin's name first: jobs:kinds), for its modules to read (kept!): what a plugin's starts keep of its options. Set a handful of times, at start: each value set stays until the server stops.

Plugin.kept! : Str => Try(Str, [NotFound])

What keep! kept under key; NotFound if nothing was.

3 pure functions
running : Value(context) -> Running(context)
url : Str, File -> Str
matches : Str, Str -> Bool

Background#

Process

server/platform/Process.roc

The server's process, for what runs beside its requests (D-151): a function run every so many milliseconds while the server runs (set_interval!), and one run once as it stops (on_stop!). Both are set while the server starts, in the app's init! or a plugin's start (which is given the app's context), and the host keeps them; nothing polls. A buffer kept in memory and written now and then, with a last write as the server stops:

init! = |started| {
    _ = Process.set_interval!(10_000, flush!)
    Process.on_stop!(flush!)
    Ok(started)
}

In memory, for this process: what must run on a schedule however often the server restarts (a daily report) is a job's schedule (packages/jobs' crons), kept in the database.

Process.set_interval! : U64, (() => {}) => (() => {})

Runs tick! every ms milliseconds once the server has started, until the function it returns is called (clear!()) or the server stops. Each run is a call of its own, as a background loop is (it may use the database, Kv, Http), and starts ms after the last one ended, so runs never overlap. A run that crashes is logged, and the next one runs as set. A run under way as the server stops finishes; none starts after (on_stop! is for a last one). clear!() may be called from anywhere: the run under way, if any, finishes, and none follows.

Set only while the server starts (the app's init!, a plugin's start): anywhere else it crashes the call, as the host would otherwise keep a function a crash could free.

Process.on_stop! : (() => {}) => {}

Runs last! once as the server stops (SIGTERM, ^C), after its intervals' last runs have ended: a call of its own, in the order these were set, within the server's grace for what is still running (10 seconds). What was kept for a later run (a buffer an interval writes) is written now. Its waits (the database, a request to another server) don't end because the server is stopping. Set only while the server starts, as set_interval!.

Actor

server/platform/Actor.roc

State that outlives a request, changed one turn at a time: an actor is a kind and a key (the cart of member 7, the counter called visits). Nobody makes one or ends one: a call to any key finds it as its last turn left it, or new (initial(key)), and it takes its turns one at a time, in the order they came. With a database, its state is kept in it (rocx_actors), and so are its timers (rocx_actor_timers), so both are there after a restart.

A kind is a type of the app's (D-068): one with name and initial (Actor.Kind). What its actors do is its methods, each its own input and its own reply, typed (D-066); its key is any type with to_str and from_quote (Actor.Keyed): text, or one of the app's (D-067).

Carts := [].{
    State : { items : List(Str) }

    ## The kind: its name (its actors' state is kept under it) and a new cart.
    name = |{}| "cart"
    initial = |_member| { items: [] }

    ## Its methods' type, once: the kind, the app's context (its `init!`'s), the key, the state.
    Method(input, reply) : Actor.Method(Carts, {}, Str, Carts.State, input, reply)

    add : Carts.Method(Str, U64)
    add = Actor.method("add", |{ state, input, .. }| { state: { items: state.items.append(input) }, reply: state.items.len() + 1 })

    clear : Carts.Method({}, {})
    clear = Actor.method("clear", |{ .. }| { state: { items: [] }, reply: {} })
}

count = Carts.add.ask!(member, "a book")?   # a U64
Carts.clear.tell!(member, {})

A key of the app's own type names its actor by its to_str (in the database too) and is read back by its from_quote, which also lets a string literal be a key, checked when the app is built:

Key := [YouTube, Instagram(Str)].{
    to_str = |key| match key { YouTube => "youtube"  Instagram(id) => "instagram:${id}" }
    from_quote = |written| …   # Try(Key, [BadQuotedBytes(Str)])
}

rocx build lists the methods an app's modules define (program.actors, each Actor.handler), so the server can run an actor when nobody waits on it: a tell, a timer. Each actor has a mailbox in the host, and its turns, whichever method each is, run one after another, each in a call of its own. Inputs, replies and state go to the host as JSON: an input a method doesn't take, or a crash in it, is logged as an error and told to its asker, and the actor goes on, its state as it was.

Actor.cancel! : Timer => {}

Stops a timer whose call hasn't been taken: one that is waiting, or one that has fired but whose turn hasn't come (its call is dropped). One that has been taken, or never was, is nothing to stop.

3 pure functions
method : Str, (Actor.Turn(kind, context, key, state, input) => { state : state, reply : reply }) -> Actor.Method(kind, context, key, state, input, reply)
handler : Actor.Method(kind, context, key, state, input, reply) -> Handler(context) where [kind.Kind(key, state), key.Keyed, state.Json.Encodable([]), state.Json.Parseable([InvalidJson(Str)]), input.Json.Parseable([InvalidJson(Str)]), reply.Json.Encodable([])]
call_of : Str, input -> Str where [input.Json.Encodable([])]

Live

server/platform/Live.roc

What happens now, told to whoever is listening, in the server's memory: messages on topics, and rooms that count who is in them. A stream (Events.stream) waits for the next message with next!; a request, a job or an actor publishes one.

Events.stream(|{ send!, .. }| {
    Live.join!("online")
    var $open = Bool.True
    while $open {
        send!({ online: Live.count!("online") })?
        $open = Live.next!(15_000) != Gone
    }
    Ok({})
})

What a call joins or listens to lasts until it ends: a stream's, until its client goes (or it crashes).

Live.publish! : Str, Str => {}

Sends message to every call listening to topic.

Live.listen! : Str => {}

From now on, this call hears what is published on topic (next!).

Live.join! : Str => {}

This call is in room until it ends, and listens to it; whoever listens to room hears join when one joins, and leave when one leaves.

Live.count! : Str => U64

How many are in room.

Live.next! : U64 => [Heard({ topic : Str, message : Str }), Quiet, Gone]

The next message on a topic this call listens to, or Quiet if none comes within ms milliseconds, or Gone if the client of the stream this call is sending has gone.

Crypto#

AesGcm

server/platform/AesGcm.roc

AES-GCM, by the host (ring): bytes sealed under a key, so that only that key opens them and any change to them is seen (a token kept in the database, say). seal! and open! are AES-256-GCM under a 32-byte key: each seal draws a fresh random 12-byte nonce, and what it gives is the nonce, the ciphertext, then the 16-byte tag (Web Crypto's output with the nonce in front). seal_with_nonce! is for a protocol that derives its own nonce (Web Push's).

AesGcm.seal! : List(U8), List(U8) => Try(List(U8), [BadKey])

plaintext, sealed under key; BadKey unless the key is 32 bytes.

AesGcm.open! : List(U8), List(U8) => Try(List(U8), [BadKey, Forged])

What seal! sealed. Forged: the nonce, the ciphertext or the tag was changed, or it wasn't sealed under this key.

AesGcm.seal_with_nonce! : List(U8), List(U8), List(U8) => Try(List(U8), [BadKey, BadNonce])

plaintext, sealed under key with the caller's 12-byte nonce, for a protocol that derives its nonces (RFC 8188's aes128gcm, which Web Push writes): AES-128-GCM under a 16-byte key, AES-256-GCM under a 32-byte one. It gives the ciphertext, then the 16-byte tag, with no nonce in front. A nonce must never be used twice under one key, which gives the key away: use seal!, which draws one, unless a protocol says otherwise. BadKey, BadNonce.

P256

server/platform/P256.roc

Elliptic-curve cryptography on P-256 (secp256r1, prime256v1), by the host (ring): what Web Push needs (packages/push): ECDH with a key pair made for one message (RFC 8291), ES256 signatures (its VAPID token, RFC 8292; any JWT signed with ES256), and a key pair to sign with (its VAPID keys). A public key is an uncompressed point, 65 bytes (4, then x and y), and a private key its 32-byte scalar, as browsers, Web Crypto's raw and JWK formats and web-push generate-vapid-keys write them (in base64url: Base64.url_decode).

P256.generate! : {} => { public_key : List(U8), private_key : List(U8) }

A new key pair, made by the host from the operating system's random bytes: public_key, an uncompressed point (65 bytes), and private_key, its 32-byte scalar, which sign! signs with and anyone with public_key can check. Keep the private key secret: in the server's environment, not in the app's code.

P256.ecdh! : List(U8) => Try({ public_key : List(U8), secret : List(U8) }, [BadKey])

ECDH with a key pair the host makes for this call alone and then forgets, as RFC 8291 wants for each message: its public key (65 bytes, for the other side), and the 32-byte secret it shares with peer (the shared point's x), which only the holder of peer's private key can compute too. BadKey unless peer is an uncompressed point on the curve.

P256.sign! : List(U8), List(U8), List(U8) => Try(List(U8), [BadKey])

ES256: the signature of message (ECDSA on P-256 over its SHA-256) by private_key, whose public key is public_key: 64 bytes, r then s, as JWS writes it (not DER). Each is different (ECDSA draws a random number), and each verifies. BadKey unless the two keys are a pair.

Random

server/platform/Random.roc

Random numbers from the operating system (for a salt, a token, an id). Shaped as basic-cli's, so packages written for it (roc-pg's random_u64!) take these as they are.

Random.seed_u64! : () => Try(U64, [RandomErr(Str)])

A random U64. Always Ok: the Try is basic-cli's shape.

Random.bytes! : U64 => List(U8)

count random bytes: a token, a key.

System#

Env

server/platform/Env.roc

The app's settings, from the process's environment: secrets, and what differs from one machine to another (APP_SECRET, an API's key), read alike in a request, a job or a schedule. And whether the server was started with --dev (or --debug), for what only development (or a test) may do, and where the app is (public_url!), for the links it sends.

Env.var! : Str => Try(Str, [NotFound])

The environment variable name, as the server was started with it; NotFound when it has none. The file --env-file names (rocx dev names the .env where it runs) is read into the environment first, so ANTHROPIC_API_KEY=… there is read here as if the shell had exported it; a variable the environment already has keeps its value. Without the flag no file is read, a .env beside the server neither (D-088, D-098).

Env.dev! : {} => Bool

Whether the server was started with --dev.

Env.debug! : {} => Bool

Whether the server was started with --debug, which tests start it with (its debug paths under /__rocx/), never a deployed server: what a plugin keeps for a test to read (the dev mailbox's mail) rather than doing.

Env.public_url! : {} => Str

Where the app is, as the world reaches it, for a link it sends (in an email, to another server): --public-url or PUBLIC_URL when the server was started with one (https://status.example.com: the proxy in front of it), without the / at its end; else where the server listens (http://127.0.0.1:8080), with the port it was given, or the one the system gave it for --port 0. Never a request's Host, which whoever asks writes.

Time

server/platform/Time.roc

The time: the clock of the machine the server runs on. The web platform has a Time too, with now_millis! and now_nanos! (the browser's clock), so a component's handler reads it on both; a component reads neither while rendering, as the page would then differ between the server and the browser.

Time.now_millis! : {} => U64

Milliseconds since the Unix epoch.

Time.now_nanos! : {} => U64

Nanoseconds since the Unix epoch, for timing what takes less than a millisecond (a query) and for OpenTelemetry's timestamps. Its clock doesn't go back while the server runs, so the difference of two readings is never negative:

started = Time.now_nanos!({})
rows = Db.all!(query, [])?
took = Time.now_nanos!({}) - started
Time.offset! : Str, I64 => Try(I64, [UnknownZone])

How far ahead of UTC the clocks of the time zone zone are at at (milliseconds since the epoch), in seconds, summer time counted: zone is an IANA name (Europe/Warsaw, America/New_York, UTC), and one the zone database doesn't have is UnknownZone. The time there is at plus it, in milliseconds:

now = Time.now_millis!({}).to_i64_wrap()
there = now + Time.offset!("Europe/Warsaw", now)? * 1000
Time.sleep! : U64 => {}

Waits ms milliseconds: the call that waits (a request, a job; a job's time limit ends the wait) pauses, and holds no thread (D-027), so the server goes on answering others. For a retry's pause, or an endpoint that is slow on purpose (a demo's latency).

Log

server/platform/Log.roc

The server's log, on stderr: an event a line, the app's and the platform's alike, in the format the app's program chose (logs: { format: Auto }, or Pretty, or Json). An event is a message and its fields, a record written as JSON:

Log.info!("gate failed", { path: request.path, error: why })

is, pretty (a person at a terminal; the time and the fields' names dimmed, the level coloured):

14:03:12 info  gate failed  path=/admin error="no session"

and as JSON (a server whose log is collected):

{"time":"2026-11-21T13:03:12.345Z","level":"info","msg":"gate failed","error":"no session","path":"/admin"}

A pretty line puts a request's path, method and status first, then the durations, then the rest (D-113). A duration is a number named <x>_ns, <x>_us or <x>_ms, shown without the suffix in the unit that reads best (duration_ns=12345 is duration=12µs). JSON keeps the fields as they are. An event with no message is its fields alone: a request's line, say.

The fields go beside time, level and msg; one named time, level or msg is written as fields.time (and so on), so it can't take their place. {} is no fields. Logging doesn't wait for stderr: the host writes the line on a thread of its own, in the order the events came.

Log.line! : Str => {}

A message with no fields, at info level.

Log.debug! : Str, fields => {} where [fields.Json.Encodable(e)]

Detail, for finding out why something happened.

Log.info! : Str, fields => {} where [fields.Json.Encodable(e)]

What happened, as it should.

Log.warn! : Str, fields => {} where [fields.Json.Encodable(e)]

What went wrong, and was dealt with: worth a look.

Log.error! : Str, fields => {} where [fields.Json.Encodable(e)]

What went wrong, and wasn't: someone should look.

Tcp

server/platform/Tcp.roc

A TCP connection, plain or over TLS: what a client of another server is built on (an SMTP server: packages/email's Smtp; Postgres: roc-pg; a WebSocket: packages/websocket). Shaped as basic-cli's, so packages written for it take a connection from here as they are: connect!, then write_bytes! and read_exactly!.

Each effect pauses the call until it is done, as the platform's others do, and its thread runs other calls meanwhile. A read or a write waits 60 s at most; read_within! waits as long as it is told. A connection belongs to the call that made it, and is closed when that call ends, if not before.

Tcp.connect! : Str, U16 => Try(Tcp, [TcpErr(Str)])

A connection to host at port.

Tcp.connect_tls! : Str, U16 => Try(Tcp, [TcpErr(Str)])

A connection over TLS (smtps, port 465), the server's certificate checked against the web's certificate authorities, for host.

Tcp.start_tls! : Tcp, Str => Try({}, [TcpErr(Str)])

Goes on over TLS, checking that the server is host: SMTP's STARTTLS.

Tcp.write_bytes! : Tcp, List(U8) => Try({}, [TcpErr(Str)])

Sends bytes, all of them, waiting until they are written.

Tcp.write_utf8! : Tcp, Str => Try({}, [TcpErr(Str)])

Sends text, as UTF-8.

Tcp.read_exactly! : Tcp, U64 => Try(List(U8), [UnexpectedEndOfInput, TcpErr(Str)])

Exactly count bytes, waiting for them all.

Tcp.read_up_to! : Tcp, U64 => Try(List(U8), [TcpErr(Str)])

What has come, count bytes at most, waiting for some: none once the other end has closed.

Tcp.read_until! : Tcp, U8 => Try(List(U8), [EndOfInput, TcpErr(Str)])

Up to and including the next byte ('\n': a line).

Tcp.read_within! : Tcp, U64, U64 => Try(List(U8), [TimedOut, TcpErr(Str)])

Up to max bytes, as soon as any arrive, waiting ms milliseconds at most: TimedOut when none came in that time, the connection still open and nothing lost, so a loop can send a heartbeat and read again; none once the other end has closed. A job's time limit still ends the wait.

Tcp.close! : Tcp => {}

Closes the connection. Using it after is a TcpErr.

Components and reactivity#

Solid browser too

web/platform/Solid.roc

Solid 2.0's primitives, as Roc names them: createSignal is create_signal!, and so on. A read is an accessor (count!()), and it is tracked: a computation that reads it runs again when it changes. The browser's timers are here too (set_interval!, set_timeout!), each stopped by the clear! it answers, or when what started it goes.

import pf.Solid exposing [create_signal!, update!, create_memo!, create_selector!, create_optimistic!, create_store!, create_effect!, create_render_effect!, create_effect_with!, on_cleanup!, on_settled!, refresh!, is_pending!, latest!, untrack!, use_context!, set_interval!]

(count!, set_count!) = create_signal!(0.U64)
doubled! = create_memo!(|| count!() * 2)
create_effect!(|| room!(), |room| Api.events_room({ room }).listen!(heard!))
Solid.create_signal! : a => ((() => a), (a => {})) where [a.is_eq : a, a -> Bool]

A value that changes: its accessor and its setter (a tuple: Roc's list patterns may not match). Writes apply when the handler making them is done, as in Solid 2.0, so a read in that handler still gives the value before them: set_count!(count!() + 1) twice in one handler adds one. update! writes from the value the handler's writes leave, and composes.

Given a value == the one it has, the setter writes nothing and tells no one (Solid's createSignal, which compares by default; a memo does the same, D-109): set_open!(Bool.True) on an open panel runs nothing. It compares with the value the handler's writes so far leave, as update! reads it. So its value compares: it is data (records, tags, lists, text, numbers; a type of one's own needs its is_eq). For a value that doesn't (a timer's clear!), see create_signal_with!.

Solid.create_signal_with! : a, { equals : a, a -> Bool } => ((() => a), (a => {}))

A signal with its options (Solid's createSignal(value, { equals })): equals says whether the value given to the setter is the one it has (the handler's writes so far applied), and then the setter writes nothing. |_, _| Bool.False writes whatever it is given, as Solid's equals: false does: for a value that doesn't compare, a function in it (a timer's clear!) or a type of one's own without is_eq.

(timer!, set_timer!) = create_signal_with!(Stopped, { equals: |_, _| Bool.False })
start! = || set_timer!(Running(set_interval!(1000, tick!)))
Solid.update! : (() => a), (a => {}), (a -> a) => {}

Writes what change makes of the value (Solid 2.0's function form of a setter, setCount((c) => c + 1)), from a handler, given the accessor and its setter: a signal's (create_signal!) or an optimistic value's (create_optimistic!). change is given the value as the handler's writes so far leave it, not yet applied, so two updates in one handler compose: the second is given what the first made. Only update! sees a write before it applies, as only Solid's function form does: a plain read in the handler (count!()) still gives the value before the handler's writes.

(count!, set_count!) = create_signal!(0)
add! = |n| update!(count!, set_count!, |c| c + n)
<button on:click={|| {
    add!(1)
    add!(1)
}}>Two more</button>

Anything else read! reads is as it is: a memo isn't computed again from the handler's writes. Anywhere but in a handler, the setter fails, as it does on its own.

Solid.create_store! : s => (Store(s), ((s -> s) => {}))

A store (Solid 2.0's createStore): state of many parts in one value, read by parts (store.get!(|s| s.filter), tracked by the part it selects), and its setter, which takes a function of the state, Solid's draft setter: set_todos!(|s| { ..s, filter: Done }). Writes apply when the handler making them is done, as a signal's do, and two in one handler compose: the second is given what the first made. See Store.

Solid.create_memo! : (() => a) => (() => a) where [a.is_eq : a, a -> Bool]

A value computed from others, computed again when they change: its accessor. It is async when it calls the server: until the answer is in, reading it makes the reader wait (it runs again once the answer is in); a failure shows the nearest <Errored>.

Computed again to a value == the one it had, it tells no one (Solid's createMemo, D-109): what reads it runs again only when it changed. So a memo of a part of what changes often (a page's answer read again, a clock) is where a part of the page that shows only that part is kept. Its value compares, so it is data (records, tags, lists, text, numbers; a type of one's own needs its is_eq); what doesn't (a function, markup) is computed in a function instead.

Solid.create_selector! : (() => a) => (a => Bool)

Whether a key is the source's value now (Solid's createSelector), for many readers at once: a list's rows. Each reader is told only when the answer for its own key changes, so a selection moving from one row to another runs those two rows' readers again, not every row's. Keys are compared as Str.inspect writes them (the source's value, and each key asked about).

(selected!, set_selected!) = create_signal!(0.U64)
is_selected! = create_selector!(selected!)

{...rows!().map(|row| <tr key={row.id} class:danger={is_selected!(row.id)}>…</tr>)}
Solid.create_optimistic! : (() => a) => ((() => a), (a => {})) where [a.is_eq : a, a -> Bool]

A value the page shows ahead of the server (Solid 2.0's createOptimistic): its accessor and its setter. It is compute's, a memo (the server's data, say: || board.read!()), until a handler writes it: the write shows once the handler is done, and is held until the submissions that handler sent are done (an action's, Router.use_action!; or the form its submit sends), the page's reads read again by then, so the server's data takes its place with no frame of the old. A refusal ends it too: the value is the server's again, the refusal the submission's error. With nothing sent, the write is undone at once, as Solid 2.0 undoes one outside a transition. Several held at once: the latest still held shows.

(cards!, set_cards!) = create_optimistic!(|| board.read!())
move! = use_action!(Api.post_move({}))
on_drop! = |day| {
    set_cards!(moved(cards!(), dragged!(), day))
    move!({ card: dragged!(), day })
}

Two writes in one handler compose through update!: update!(cards!, set_cards!, |cards| …) is given what the first wrote. On the server there are no handlers: it is compute's. Where several submissions may be on their way and each should apply to the server's latest data, derive it instead from what they sent (Submissions.pending_inputs!, D-030).

Solid.refresh! : (() => a) => {}

Computes again, asking the server again, every memo the accessor reads: refresh!(user!). Functions can't be compared, so the runtime finds them by running it once, noting what it reads.

Solid.is_pending! : (() => a) => Bool

Whether what the accessor reads is being computed again while it shows its last value (Solid 2.0's isPending): true while a memo it reads (or a memo that one reads, all the way up) has a value and waits for a new one, after a refresh! or after what it reads changed. False while there is no value yet, the first load, which <Loading> covers; and false for a memo that failed, which <Errored> covers. Calling it never waits or fails, and doesn't make the caller depend on the values the accessor reads: a hole, a memo or an effect that calls it runs again when the answer changes. On the server it is false: the server renders final values.

<p class:stale={is_pending!(user!)}>{user!().name}</p>
{if is_pending!(|| (user!(), posts!())) { <p>Refreshing…</p> }}
Solid.latest! : (() => a) => a

The last value of what the accessor reads (Solid 2.0's latest): a memo being computed again (a refresh!, or a change of what it reads) gives the value it last settled at, and doesn't make the caller wait. Every read here does that already: a memo shows its last value while it is read again (is_pending! says it is), since nothing holds a write back until a change is done, as Solid 2.0's transitions do. So latest!(read!) is read!(), written as Solid code writes it; it would differ only if writes were held back. A handler's own writes, not yet applied, it doesn't give, as Solid 2.0's doesn't: update! is given those. A memo with no value yet still makes the caller wait (<Loading>'s), and one that failed still fails (<Errored>'s).

<input value={latest!(query!)} />
Solid.untrack! : (() => a) => a

Runs read! without tracking what it reads (Solid's untrack): its answer, and what it read doesn't make the hole, memo or effect running it run again. A computation made inside it (create_memo!) tracks its own reads. A read that waits still waits.

create_effect!(|| room!(), |room| log!(room, untrack!(|| user!().name)))

In a component's body, a read is made once, as the component runs, so what shows doesn't follow it; a dev build (rocx dev, rocx generate --dev) says so in the browser's console, once for each place (Solid 2.0's dev warning). untrack! says the one read is meant, a start value:

(drawn!, set_drawn!) = create_signal!(untrack!(|| goal))
Solid.use_context! : Context(a) => a

The value of a context (useContext): what the nearest provider above gives, or its default. In a component, or a computation; a handler is above nothing.

Solid.create_effect! : (() => a), (a => {}) => {}

An effect, Solid 2.0's split one (createEffect(compute, apply)): compute runs now, its reads tracked; apply runs once the markup is on the page (after the flush), untracked, given what compute answered, as a handler does (it may write signals, applied when it is done). When what compute read changes, it runs again, then the last apply's cleanups (on_cleanup!), then apply; values aren't compared. It belongs to the component or computation that made it, and goes with it, its cleanups run. On the server neither half runs.

create_effect!(|| room!(), |room| Api.events_room({ room }).listen!(heard!))

Solid's apply returns its cleanup: here it calls on_cleanup!, since Roc has no "nothing" a function may return. Neither half is given the previous value. A listen or a timer started in apply stops before the next apply, and when the effect goes.

Solid.create_render_effect! : (() => a), (a => {}) => {}

A render effect (Solid 2.0's createRenderEffect): as create_effect!, but its apply runs at once, as soon as compute has: during the render, before the page is settled, where an effect's waits until the flush is done and the markup is on the page. Made in a component, it runs before the component's markup is built (nothing of it is on the page yet); run again in a flush, its apply comes before the effects' and before what the flush moves glides. As Solid's, it is for what must be in step with the render (a value derived into a signal the same flush reads, with no frame between); what reads the page wants create_effect!. On the server neither half runs (Solid's server runs both), so what its first apply writes is patched in as the page hydrates: keep what a page shows from the server's render.

create_render_effect!(|| query!(), |_| set_page!(1))
Solid.create_effect_with! : (() => a), { apply : a => {}, error : Str => Try({}, Str) } => {}

An effect whose compute may fail (Solid 2.0's createEffect(compute, { effect, error })): as create_effect!, with apply and error in a record. A compute that fails (a read that failed, a context nothing provides) calls error with why, instead of showing the nearest <Errored>: after the flush, as apply runs (a handler: it may write signals; its on_cleanup!s run before the next apply or error), and only if it is still failed then. When compute answers again, apply runs as before. error answers Ok({}) when it has dealt with it, or Err(why) to pass it on to the nearest <Errored> after all (Solid's rethrow: a handler that logs, or notes, and still shows the boundary); what else fails in it is passed on too. What fails in apply is its own, as a handler's is.

create_effect_with!(|| Api.get_room({ room: room!() }).read!(), { apply: |room| set_topic!(room.topic), error: |why| { set_problem!(why); Ok({}) } })
Solid.on_cleanup! : (() => {}) => {}

Runs cleanup when what is running now is done with (Solid's onCleanup): a component, when it goes; a computation (a hole, a memo, an effect's compute), before it runs again and when it goes; an effect's apply, before the next and when the effect goes. What it owns goes first, then its cleanups, the last first. As a handler: it may write signals. In an event handler it fails: nothing would ever run it. On the server it never runs.

Solid.on_settled! : (() => {}) => {}

Runs settled once, in the browser, once the markup of what is running now (a component, say) is on the page: Solid 2.0's onSettled (onMount, before it). It is an effect whose compute reads nothing, so it never runs again. It runs as a handler (it may write signals, call the browser, start a timer), and an on_cleanup! in it runs when the component goes. The server never runs it, so it is where what only makes sense in a browser goes: reading what the page kept, focusing a field, measuring.

on_settled!(|| set_awake!(Bool.True))
Solid.set_interval! : U64, (() => {}) => (() => {})

Runs tick! every ms milliseconds, as a handler runs (its writes applied together when it is done): its clear!, which stops it. Solid leaves timers to the browser, with onCleanup(() => clearInterval(id)) to stop one; here that is built in: an interval stops with the cleanups of what started it. Started in a component, it stops when the component goes (the part an if hides); in a computation (an effect's compute too), before it runs again; in an effect's apply, before the next apply; in an event handler, when the element whose handler started it goes. Only the browser runs one: while the server renders, it never ticks.

(seconds!, set_seconds!) = create_signal!(0)
stop! = set_interval!(1000, || set_seconds!(seconds!() + 1))

An interval while a signal says so, stopped by the effect's cleanup when it says otherwise:

create_effect!(
    || running!(),
    |running|
        if running {
            _ = set_interval!(1000, tick!)
            {}
        } else {
            {}
        },
)
Solid.set_timeout! : U64, (() => {}) => (() => {})

Runs done! once, ms milliseconds from now, as a handler runs: its clear!, which calls it off if it hasn't run yet. Like an interval, it is called off with the cleanups of what started it, and only the browser runs one.

cancel! = set_timeout!(400, || set_query!(draft!()))

Store browser too

web/platform/Store.roc

A store, Solid 2.0's (createStore): state of many parts in one value, each part read on its own. Roc has no proxies, so a read can't see which field it touched: a read *selects*, and is tracked by what it selected.

(todos, set_todos!) = create_store!({ items: [], filter: All })

<p>{Filter.name(todos.get!(|s| s.filter))}</p>
<ul>{...todos.get!(|s| s.items).map(|todo| <li key={todo.id}>{todo.title}</li>)}</ul>
<button on:click={|| set_todos!(|s| { ..s, filter: Done })}>Done</button>

A click on Done runs the filter's hole again, and nothing else: the list's selection is computed again, finds the same items, and keeps quiet. A write is a function of the state (Roc's record update is Solid's draft), and two in one handler compose. Store.of reads any accessor so: an endpoint's answer, a memo, a prop.

Store.get! : Store(s), (s -> a) => a where [a.is_eq : a, a -> Bool]

A part of the store, selected: todos.get!(|s| s.filter). Where it is read by what runs again (a hole, an attribute, a memo, an effect's compute), the reader runs again only when that part changes, compared by Roc's ==: a write to the store computes each part read again (a pure function, cheap), and one equal to what it was tells nobody. Anywhere else (a handler, a component's body, inside untrack!, the server) it is select of the store's value, once.

A part compares with ==, so it is data: records, tags, lists, text and numbers do, a type of one's own needs its is_eq; a function or markup can't be selected.

1 pure function
of : (() => s) -> Store(s)

Html browser too

web/platform/Html.roc

Markup in which holes are computations. A component builds it once; the runtime runs each hole (text_of, html_of, list_of, attr_of…) and runs it again when what it read changes, patching only its own node. Handlers are effects (on), not messages. A hole that reads nothing that changes is static (text, attr, class_if…): written once, with nothing to run.

Html.unmatched! : Str => a

What a name a match arm binds reads (D-070: rocx makes it a getter, so the arm stays while its value changes) once its arm no longer holds: never, as the arm is made again first; if it ever is, a failure, the nearest <Errored>'s.

Html.rows! : (() => List(a)), (a => k), ((() => a), (() => U64) => Html) => Html where [a.is_eq : a, a -> Bool]

What rocx writes for a hole's .map whose list reads what changes (D-071):

{...todos!().map(|todo| <li key={todo.id}>{todo.text}</li>)}

is a row per key (the row's root's key), made once, moved as the list changes, and dropped with its key, as Solid 2.0's <For> keeps them. Roc's values have no identity, so the row says its key. The row's name reads its item now (rocx makes it a getter, as a match arm's names), and .map_with_index(|todo, i| …)'s index, which changes as rows move, too. keyed may read what changes. Each time the list is read again, a row is told its item changed only when it isn't == the one it had, and then its holes that read it run again (a value a node has already is no patch).

Html.rows_at! : (() => List(a)), ((() => a), U64 => Html) => Html where [a.is_eq : a, a -> Bool]

A .map_with_index whose row's key is its index (key={i}, D-071): a row per position (Solid's old <Index>), its name reading the item there now; its index, the position's, a value.

Html.row! : U64, Str, a, ((() => a) => Html) => { key : Str, row : () => Html, known : Bool } where [a.is_eq : a, a -> Bool]

A row: its item kept by the host under its key (so the row's name reads the item there now), how to make the row, and whether the page shows it already (known: the runtime keeps it).

Html.read_at! : Str, (() => a) => a

Reads, saying where (Ui/Chart.rocx:44:39): a dev build (rocx dev, rocx generate --dev) writes each accessor a component's body calls (goal!()) as Html.read_at!("…", goal!), so the browser's runtime can say where a read made once, as the component runs, is (Solid 2.0's dev warning: what shows won't follow it). rocx writes this; any other build has none.

Html.serialize! : Html => Str

The markup as JSON for the runtime, each computation, handler and fallback kept by it (its id in the JSON). Static parts are plain: {"t":"e","tag":…,"a":[…],"c":[…]}, {"t":"s","v":…}, {"t":"raw","v":…} (a <script>'s or <style>'s text, as written), {"t":"doctype"}; holes name what they run: {"t":"x","r":id} text, {"t":"h","r":id} markup, {"t":"hx","r":id} either (Html.hole_of: its run answers a JSON string while it shows text alone, else markup), {"t":"l","r":id} a list; boundaries hold their parts, and so does {"t":"nh","c":[…]}, a <NoHydration>.

63 pure functions
text : Str -> Html
text_of : (() => Str) -> Html
source_text : Str -> Html
doctype : {} -> Html
html_of : (() => Html) -> Html
hole : a -> Html where [a.encode : a, Html.Hole -> Try(Html, [])]
hole_of : (() => Html) -> Html
shown : a -> Html where [a.encode : a, Html.Hole -> Try(Html, [])]
template : Str, Html -> Html
encode : Html, Html.Hole -> Try(Html, [])
list_of : (() => List(Html)) -> Html
join : List(Html) -> Html
empty : {} -> Html
element : Str, List(Attr), List(Html) -> Html
void : Str, List(Attr) -> Html
attr : Str, Str -> Attr
attr_literal : Str, Str -> Attr
attr_of : Str, (() => Str) -> Attr
enhanced : Attr
optional : Str, Str -> Attr
optional_of : Str, (() => Str) -> Attr
style_var : Str, Str -> Attr
style_of : Str, (() => Str) -> Attr
flag : Str, Bool -> Attr
flag_of : Str, (() => Bool) -> Attr
class_if : Str, Bool -> Attr
class_of : Str, (() => Bool) -> Attr
on : Str, (() => {}) -> Attr
on_value : Str, (Str => {}) -> Attr
on_checked : Str, (Bool => {}) -> Attr
on_key : Str, (Str => {}) -> Attr
on_keys : Str, (Html.Keys => {}) -> Attr
on_named_key : Str, Str, (() => {}) -> Attr
on_prevent : Str, (() => {}) -> Attr
on_frame : (F64 => {}) -> Attr
on_viewport : (Html.Viewport => {}) -> Attr
on_point : Str, (Html.Point => {}) -> Attr
on_visible : Str, (Bool => {}) -> Attr
on_data : Str, (List(Html.DragItem) => {}) -> Attr
on_files : Str, (List(Html.File) => {}) -> Attr
drag_data : List((Str, Str)) -> Attr
drag_data_of : (() => List((Str, Str))) -> Attr
drag_image : Str -> Attr
drag_image_of : (() => Str) -> Attr
key : a -> Attr
key_of : (() => a) -> Attr
key_text : a -> Str
transition : [In, Out, Both, Move], Transition -> Attr
transition_of : [In, Out, Both, Move], (() => Transition) -> Attr
loading : Html, List(Html) -> Html
errored : (Str, (() => {}) -> Html), List(Html) -> Html
switched : (() => Try(Str, [None])), (() => Html), Html -> Html
branched : (() => Try(Str, [None])), (() => Html) -> Html
each : (U64 => List({ key : Str, row : () => Html, known : Bool })), Html -> Html
row_keys : List(Str) -> List(Str)
component : (() => Html) -> Html
document_title : List(Html) -> Html
document_head : Html -> Html
on_document : List(Attr) -> Html
on_window : List(Attr) -> Html
provided : Str, U64, List(Html) -> Html
no_hydration : List(Html) -> Html
to_str : Html -> Str

Repeat browser too

web/platform/Repeat.roc

<Repeat>, as Solid 2.0 has it: a row for each index from from! (0 unless it says) up to, not including, from! + count!, with no list behind them:

<Repeat count!={stars!()}>{|index| <span class="star" />}</Repeat>

A row is kept as long as its index is in the range, so when the range moves (from! grows as a list scrolls) only the rows that come into it are made, and only those that leave it go: what a virtual list renders the rows that show with.

<Repeat count!={shown!()} from!={first!()}>{|index| <Row index={index} />}</Repeat>

The child is effectful (=>): it runs when its row is made, given the row's index, which doesn't change, and may do what a component does there. The fallback while the count is 0.

Repeat.view_with! : Props => Html

What <Repeat count!={…}>{|index| …}</Repeat> is: a row per index in the range, made once and kept while its index is in it.

Loading browser too

web/platform/Loading.roc

<Loading fallback={…}>…</Loading>: the fallback, until everything inside has its first values. Later, a change that waits keeps what is shown.

Loading.view! : { fallback : Html, children : List(Html) } => Html

What <Loading> is: the fallback until everything inside has its first values, then the children.

Errored browser too

web/platform/Errored.roc

<Errored fallback={|problem, retry| …}>…</Errored>: when something inside fails, the fallback, given why and a handler that tries again.

Errored.view! : { fallback : Str, (() => {}) -> Html, children : List(Html) } => Html

What <Errored> is: its children, or, once something inside fails, the fallback, given why and a handler that renders the children again.

1 pure function
status_of : Str -> U16

Context browser too

web/platform/Context.roc

Solid 2.0's context: a value given to everything under its provider, however deep, without passing it down.

picks_context : Context(Store)
picks_context = create_context()        # or create_context(default)

<PicksContext value={store!({})}>…</PicksContext>
store = use_context!(picks_context)     # import pf.Solid exposing [use_context!]

rocx names a context after its module and definition (Picks.picks_context): Roc's values have no identity to tell two contexts apart. It writes create_context(…) as Context.define or Context.required, and a provider's tag as Context.provide!. A context with no default fails, when nothing above provides it, and the nearest <Errored> shows why.

Context.provide! : Context(a), a, List(Html) => Html

What is inside, given value for the context.

Context.use! : Context(a) => a

The value the nearest provider above gives; with none, the default.

2 pure functions
define : Str, a -> Context(a)
required : Str -> Context(a)

Transition browser too

web/platform/Transition.roc

An animation an element plays as it comes and as it goes, as Svelte's transitions are: written on the element (transition={…} both ways, transition:in={…}, transition:out={…}), played when a .map's row or an if's or match's part that has it comes or goes. One that goes stays on the page, its holes no longer run, until its animations are over; then the runtime takes it away.

<li transition={Transition.fade}>{todo!().text}</li>
<rect transition:out={Transition.grow(Bottom).plus(Transition.fade).ms(150)} … />

transition:move={Transition.glide} is how it moves: when a change of the page moves it (a row put in another order, pushed by one that comes or goes; or, with a key, taken out of one list as an element with the same key comes into another), it glides from where it was to where it is (FLIP: its new place, played backwards from its old one). Only the pace of the transition counts there (ms, delay, easing).

<li key={card.id} transition:move={Transition.glide}>{card.title}</li>

A transition is the element's style while it is hidden (opacity: 0, scale: 1 0): it comes from that to its own style, and goes from its own to that, the same way back. The browser plays it (element.animate), so it costs Roc nothing per frame. For someone who asked their system for less motion, none plays.

No effects: pure functions alone.

12 pure functions
fade : Transition
fly : { x : Dec, y : Dec } -> Transition
scale : Dec -> Transition
glide : Transition
grow : [Top, Bottom, Left, Right] -> Transition
style : List((Str, Str)) -> Transition
ms : Transition, U64 -> Transition
delay : Transition, U64 -> Transition
easing : Transition, Str -> Transition
origin : Transition, Str -> Transition
plus : Transition, Transition -> Transition
json : Transition -> Str

Title browser too

web/platform/Title.roc

<Title>, as @solidjs/meta has it: the document's title, from anywhere in the page.

<Title>{post!().title} · Notes</Title>

The last <Title> rendered that is still there is the title: a page's, rendered after its layouts', over theirs; one inside an if's part, while it shows. Its holes are computations, so the title follows what they read. With none, the root layout's own <title> stands. The server puts the title in the page's <head>, first (<title data-rocx>), and the browser keeps document.title to it, from hydration on; hydrating, nothing in the layout's <head> changes.

Title.view! : { children : List(Html) } => Html

What <Title> is: its children are the document's title, while it is rendered.

HttpStatusCode browser too

web/platform/HttpStatusCode.roc

<HttpStatusCode code={404} />, as SolidStart has it: the status the server answers the page with, rendered nowhere. In the browser it does nothing: the page has its status already.

HttpStatusCode.view! : { code : U16 } => Html

What <HttpStatusCode code={…} /> is: on the server, sets the status the page is answered with; in the browser, nothing. It renders nothing.

Browser browser too

web/platform/Browser.roc

The page's own JavaScript, from a handler, for what the platform has no module for: a vibration, the clipboard, an analytics event (a sound file is packages/audio's Audio.play!, a call of its plugin's effect audio.play). Browser.call!("vibrate", { ms: 50 }) calls the function the page gave the runtime as vibrate, with the argument as JSON, parsed, as Elm's ports do:

Runtime.load(wasm, { effects: { vibrate: ({ ms }) => navigator.vibrate(ms) } })

(or window.rocxEffects = { vibrate… }, for a page start.js wakes up). A plugin's script (Plugin.scripts, which every page loads before start.js) registers its effects on window.rocxEffects too, named with the plugin's name first (audio.play). Every effect is given a second argument, { under }: under(url) is a URL that begins with / under the site's base, as the runtime asks for an endpoint's. A call runs once the handler is done, after the page is patched with what it wrote, so the function sees the page as the handler left it; a handler that waits for the server, and runs again, calls it once. It answers nothing. Only a handler calls: while computing (a hole, a memo, a component's body), and on the server, it fails. Names beginning with rocx: are the runtime's own (rocx:focus is Browser.focus!).

Browser.ask! is the call that answers (D-159): the page's function runs at once, where it is asked, and what it returns comes back as a value. A page registers it on window.rocxAsks (or Engine.load(wasm, { asks })): window.rocxAsks = { "local.get": ({ key }) => …stored value… }. On a phone the shell answers it (Android's Calls.answer, iOS's shell), by the same name and JSON. packages/local keeps signals on the device with it.

Browser.call! : Str, arg => {} where [arg.Json.Encodable(e)]

Calls the page's function name with arg, as JSON, once the handler is done. It fails outside a handler, on the server, and for an argument JSON can't write.

Browser.focus! : Str => {}

Moves the keyboard's focus to the element whose id this is, once the handler is done and the page is patched, so a field the handler's writes show is there by then; nothing if there is none. From a handler, or an effect's apply: on_settled!(|| Browser.focus!("card-title")) focuses a field as its part shows. While computing, and on the server, it fails, as Browser.call! does.

Browser.ask! : Str, arg => Try(answer, [Unanswered, BadAnswer(Str)]) where [arg.Json.Encodable(e), answer.Json.Parseable([InvalidJson(Str)])]

Asks the page's function name (on a phone, the shell's answer by that name), given arg as JSON, at once, and reads what it returned as JSON: a value kept in localStorage, a setting the system has. Anywhere: a handler, an effect's apply, a component's body, a memo; nothing tracks it, so a computation that asks runs again only when a signal it read changes. Err(Unanswered) when nothing answers name (no function by that name, or one that returned nothing), and always on the server, whose render has no page; Err(BadAnswer(why)) when the answer isn't the type asked for. It fails for an argument JSON can't write.

stored : Try(Str, _)
stored = Browser.ask!("local.get", { key: "theme" })

Reading what the device keeps while a page hydrates would make the browser's first render differ from the server's, so ask after it, in an effect's apply (on_settled!), as packages/local does.

Browser.languages! : {} => List(Str)

The languages the person prefers, most wanted first, as BCP 47 tags (["pl-PL", "en"]): the browser's (navigator.languages), a phone's system's (D-164). An app with no server (a static copy, a phone app) picks its language by them, as a server reads Accept-Language (packages/intl's Locale.best). None in the server's render, which reads the request's instead; like any question for the device, ask once the page is drawn (on_settled!), so hydration finds what the server wrote.

Other#

Blobs

server/platform/Blobs.roc

Bytes kept by key, in a directory beside the server or in its memory, for packages/storage's file: and memory: buckets (D-047): what the host keeps for them, under a root, file:<dir> (made when missing; an object's bytes at <dir>/<key>, written whole or not at all) or memory:<name> (gone when the server stops). A key is segments between /s, none empty, . or ..; anything else is refused (BlobErr), so a key never reaches outside its root. An object has its content type and its ETag (its MD5) beside it. Server.stored(root, key, headers) answers a request with one, sent by the host as it is.

Blobs.put! : Str, Str, List(U8), Str => Try({}, [BlobErr(Str), ..others])

Keeps bytes at key, with their content type, in place of what was there.

Blobs.get! : Str, Str => Try(List(U8), [NotFound, BlobErr(Str), ..others])

The bytes at key, whole.

Blobs.range! : Str, Str, { offset : U64, length : U64 } => Try({ bytes : List(U8), size : U64 }, [NotFound, BlobErr(Str), ..others])

length bytes at key from offset (fewer at its end; none past it), and its size.

Blobs.head! : Str, Str => Try(Info, [NotFound, BlobErr(Str), ..others])

key's size, content type and ETag.

Blobs.delete! : Str, Str => Try({}, [BlobErr(Str), ..others])

The bytes at key gone; none there is no problem.

Blobs.compose! : Str, List(Str), Str, Str => Try({}, [NotFound, BlobErr(Str), ..others])

The bytes at parts, joined in order, kept at key with a content type (the parts stay).

Blobs.keys! : Str, Str => Try(List(Str), [BlobErr(Str), ..others])

The keys that start with prefix, in order (all of them, for "").

Blobs.check! : Str => Try({}, [BlobErr(Str), ..others])

Whether the root can be written: a directory made, written to and cleaned when missing.

Blobs.secret! : Str => Str

The secret a root's signed URLs are made with when its URL gives none: drawn when first asked for, and kept while the server runs (its URLs end with it).

Channel browser too

web/platform/Channel.roc

A channel: what the server publishes to the pages subscribed to it, as it happens, and what pages say to the server, over one stream per browser tab (/rocx/live).

A route's +server.roc defines one at its path, as it defines an endpoint: channel!, its check, is given the request, the path's params and what the route's middleware handed on, and answers who the subscriber is (Channel.allow(who)), or a refusal. Its type says what is published on it (message) and what pages may say on it (said, [] for nothing):

channel! : { request : Server.Request, params : { org : Str }, context : Member } => Try(Channel(Str, News, []), Endpoint.Refusal)
channel! = |{ params, context, .. }| if context.org == params.org Ok(Channel.allow(context.name)) else Err(Forbidden)

Generated/Api has it as a function of its params (Api.channel_org_org_news({ org })): a component subscribes to it (Endpoint.subscribe!) and says things on it (Endpoint.say!); the server publishes on it (Endpoint.publish!). The route may define hooks beside it: receive!, what pages say; on_open!, what a subscriber is sent first, each time it subscribes; on_close!, told when a subscription ends.

No effects: pure functions alone.

2 pure functions
allow : who -> Channel(who, message, said)
who_of : Channel(who, message, said) -> who

Leave browser too

web/platform/Leave.roc

A navigation about to leave the page, as Solid Router's useBeforeLeave gives it (BeforeLeaveEventArgs, D-040): a Router.use_before_leave! listener is given one before each navigation in place (a link, Router.navigate!, <Navigate>, a GET form, a submission's redirect, a change of the query alone, back and forward), and may stop it (prevent!), then let it go later (retry!), from another handler: an app's own "Discard your changes?" dialog.

(leaving!, set_leaving!) = create_signal_with!(Err(Staying), { equals: |_, _| Bool.False })
use_before_leave!(|leave|
    if dirty!() {
        leave.prevent!()
        set_leaving!(Ok(leave))
    }
)
<button on:click={|| match leaving!() { Ok(leave) => leave.retry!(Bool.True), Err(_) => {} }}>Discard</button>
  • to: where it goes, a path and its query as Router.location! writes them (/lists/3?tab=done, the site's base left out); "" for a load (leaving the site, reloading, closing the tab), which the browser doesn't say where.
  • from: where the page is, as Router.location! says it.
  • options: a link's or navigate_with!'s replace and scroll; back and forward, neither replaces, and both scroll to where the entry was.
  • delta: back and forward, how far in history (-1: back one entry), Solid Router's numeric to; 0 for the others.
  • default_prevented: a listener asked before this one stopped it.
  • id: the runtime's, for prevent! and retry!.
Leave.prevent! : Leave => {}

Stops the navigation (Solid Router's preventDefault): the page stays, and its address (back and forward's, already changed, is put back). Only while its listeners are being asked: the navigation is decided once they have all run, so a listener decides from what the page has (a signal, a memo already in), not from the server.

Leave.retry! : Leave, Bool => {}

Navigates where it was going after all (Solid Router's retry), from a handler, once it is done: a dialog's "Discard" button, long after the listener stopped it. With force, the listeners aren't asked again; without, they are, so one whose reason has gone (the form saved since) lets it go. Back and forward go there again in history, while the page is still on the entry it was left from (else to its URL). Anywhere but a handler it fails; on the server, no handler runs.

1 pure function
of : Str -> Leave

Submissions browser too

web/platform/Submissions.roc

Every submission to an endpoint, each its own, as Solid Router's useSubmissions gives them (Router.use_submissions!(endpoint)): several may be on their way at once (two cards dragged quickly), and each is answered, refused or forgotten on its own.

An optimistic value is the server's, with what the submissions on their way sent applied to it: shown at once, kept while they are on their way, and gone with them. One the endpoint answers with its result stays on its way until the page's reads have been read again, so the server's data takes its place all at once; one it refuses goes at once, and the value is the server's again, the refusal in its error.

moves = use_submissions!(Api.post_api_planner_move({}))
cards! = create_memo!(|| moves.pending_inputs!().fold(Api.get_api_planner({}).read!(), moved))

Submissions are kept by the endpoint's URL: an endpoint with params in its path has a list for each URL, so what varies goes in its body. Their types are the endpoint's, from the app's contract (Generated/Api, D-037), in the browser's copy as on the server.

Submissions.all! : Submissions(arg, result) => List(Sent(arg, result)) where [arg.Json.Parseable([InvalidJson(Str)]), result.Json.Parseable([InvalidJson(Str)])]

Each one, oldest first, as it is now: those on their way, and those answered, until forgotten (clear!). A computation that reads them runs again when one changes. Without the runtime, the flash of a plain form's post, when it is the endpoint's (its id 0); on the server, that flash, or none.

Submissions.pending! : Submissions(arg, result) => Bool

Whether any is on its way (Solid's submissions.pending).

Submissions.pending_inputs! : Submissions(arg, result) => List(arg) where [arg.Json.Parseable([InvalidJson(Str)])]

What the submissions on their way sent, oldest first, as the endpoint reads it: what an optimistic value applies to the server's. None on the server.

Submissions.clear! : Submissions(arg, result), U64 => {}

Forgets one, by its id (Solid's submission.clear()), from a handler: it leaves the list. Its answer, should it come later, is dropped. Id 0, the flash, forgets the latest too (Submission.clear!).

Submissions.retry! : Submissions(arg, result), U64 => {}

Sends one again, by its id (Solid's submission.retry()), from a handler, with what it sent before: pending again, its answer to come. One still on its way, or forgotten, isn't sent.

2 pure functions
of : Str, (List({ name : Str, value : Str }) -> Try(arg, Str)) -> Submissions(arg, result)
url_of : Submissions(arg, result) -> Str