Skip to content

The app framework ​

From the spec

This page is spec/app.md, the specification the compiler and the backends are written from. It is rebuilt from the spec with every deploy (how).

Weft's built-in framework for apps: where a file sits says what it is, as in SvelteKit or Next. It is optional. A project with a routes/ directory is an app; a project without one is plain Weft (language.md, Projects), such as a backend that defines its API in code. An app can do both: file routes, and a router of its own (below).

The tree ​

app.weft                     the app: its name, permissions, globals it declares (optional)
routes/                      pages, by URL path
  layout.weft                wraps every page below it; the page is its `children` snippet
  page.weft                  /
  error.weft                 shown when a page below it fails
  todos/page.weft            /todos
  todos/[id]/page.weft       /todos/:id
  todos/[id]/page.phone.weft the same page's phone UI (`env.md`, form factors)
  (account)/settings/page.weft   /settings: a group adds no segment, but can have its own layout
  docs/[...path]/page.weft   /docs/a/b/c
  api/todos/server.weft      an HTTP endpoint: `export async fn GET(req: Request): Response`, `POST`…
components/                  components
lib/                         modules
lib/server/                  modules only the server runs (the client imports their server functions and types)
static/                      files served as they are
user/migrations/             migrations of users' trees, by id (`user-files.md`); user/api.json: the API as deployed
  • Pages are the page.weft files under routes/; their path comes from the folders. [name] is a parameter, [...name] takes the rest, (name) groups without a segment. A page reads its parameters with prop params: { id: string }, typed by the compiler from the path (a mismatch is an error). A [...name] parameter is a string[] of the remaining segments, possibly empty (/docs matches docs/[...path] with path: []). page({…}) holds only what the path can't say (label, transitions, forms…; no path).
  • Layouts nest: a page is rendered inside every layout.weft above it, outermost first. The compiler gives each layout prop children: Snippet (it needn't declare it) and it shows the page with @render children(). A layout's state lives as long as navigation stays below it.
  • Errors: a page or layout can't fail with an error (a component handles its errors where they occur: language.md, Errors); when one below it panics while loading or rendering (language.md, Panics), the nearest error.weft above it is shown in its place, inside the layouts above that error.weft, with prop error: Panic ({ name, message }), as an @try around the page would. Navigating to another page leaves it.
  • Components are the files under components/ (subfolders are only for order). Besides imports, a tag names one by its file name, with no import: <SeriesPanel> is components/**/SeriesPanel.weft. Two components with one name are an error. A component shadows a primitive of its name (language.md, Markup); weft component puts the registry's in components/ui/. A component in a route folder is private to that folder and the ones below it, and wins over components/.
  • Dialogs are components whose code calls dialog({…}); dialogs.open(Confirm, props) opens one, with its props type-checked.
  • Modules are imported as in any project (import { x } from "lib/dates"). Client code may import only the query fns, mutation fns, action fns and types of a lib/server/ module (or a server.weft): its server functions are the way across (language.md, The server), compiled for the client to calls of the server. Importing anything else of it is an error (server-import).
  • Server code is lib/server/, the server.weft endpoints, the program's entry (the module weft run runs, weft.toml's main: examples/sites' main.weft serves the app itself) and app.weft, unless it declares a global or context (those are shared with the client, so such an app.weft is client code). Server code may import anything of a lib/server/ module; like it, it gives client code only its server functions and types.
  • Sources. The compiler and the runtime read a tree through a source: a directory, a built bundle, or a user tree kept in a database or S3 (below).
  • What user code may use of the app is what each run of it imports, in the run's options (std/sandbox's run, app.serve's sandbox; std/sandbox.md, Imports): { money: cash } gives user code the name money for the app's cash, so the app's own renames and moves never reach users' files. All the labels are the app's API for user code, with the migrations and deprecations that keep users' trees working when it changes (User trees, below; user-files.md).

Routes in code ​

app.weft may export a router (export let api = router()…, std/http); the framework serves it beside the file routes, and a path both define is an error. This is also how an app grows endpoints that are easier to write as code than as files.

Running an app ​

weft run and weft dev on an app's project run the framework: it serves the pages, endpoints and the exported router over HTTP (std/app.md, beside std.md: what a request reaches, the client, caching). --window opens the app's pages in the desktop app instead (desktop.md). The same is available as code, for a program that wants to set the framework up itself:

weft
import { app } from "std/app"
try await app.serve("./routes", { port: 8080 })

User trees: front ends users define ​

An app can let its users define their own pages and components, completely or in part, with the app's own routes as the fallback. app.serve takes the trees to serve, first one first:

weft
import { app } from "std/app"
import { s3 } from "std/s3"
import { session } from "std/http"

let sites = s3.bucket("sites")

try await app.serve(async req => {
  let user = try await session(req).user()
  return [user != null ? sites.tree(`users/${user.id}`) : null, "./routes"]
}, { port: 8080, sandbox: req => ({ /* what user code may reach */ }) })
  • Which trees apply is the app's choice per request: app.serve takes the trees themselves (app.serve(s3.tree(…), "./routes")) or a function of the request returning them. The usual key is the signed-in user (std/http's sessions); a subdomain or a path segment works the same way. null entries are skipped.

  • A user tree is a manifest and its files, stored by std/sandbox in memory, a folder, the app's database or an S3 prefix; it has no folders:

    json
    { "version": "…", "kind": "copies",
      "files": [{ "id": "home", "source": "…" }, { "id": "Card", "source": "…", "base": { "file": "components/ui/Card", "rev": "…" } }],
      "routes": [{ "path": "/", "file": "home" }, { "path": "/test", "deleted": true }] }

    A route in the manifest serves its file at that path ([id] parameters as in routes/). deleted hides the routes below it at that path (a 404). Every other path falls through to the next tree, and finally to the app's routes/.

  • Two ways users' files live (user-files.md): a tree of copies (kind: "copies", the default) is layered over the app: editing one of the app's files copies only that file into the tree, with its base (the app's file and its revision then); everything else stays the app's and keeps its new features. A tree that is the source itself (kind: "source") is a user's own project, its files edited in place. Either way every save is a version of the file (its history), drafts are kept apart until published, and when the app's file changes after a copy was taken, the editor shows the change and offers keep, take or bring over.

  • Resolution inside a user tree: its components (files named like components) come first, then what its run imports under their labels (sandbox: req => ({ imports: { Card: FancyCard, money: cash } }): <Card>, import { money } from "app", a module given whole from "app/<label>"); nothing else of the app is visible, neither its files nor its own names, and a file using what this request's run doesn't import falls back to the app's. A component of the tree replaces the app's of that name, for the app's own files too.

  • When the app changes: only a change of an exported signature can break a tree. The checker classifies each change of the exported API as compatible or breaking, an index kept on every save finds the trees using what broke, and the app's migrations (user/migrations/) bring them over, in the background after a deploy and otherwise when they are next served or opened; an export kept @deprecated(until:, use:) keeps working until its date, then the files still using it fall back to the app's (user-files.md).

  • User code is sandboxed: every file of a user tree runs through std/sandbox, with only what sandbox returns for the request, a plain record as run takes it: what it may use of the app (imports), its caps (data: the user's name, a scoped query's results) and its limits (fuel, memory, deadline; language.md, Projects). It imports no I/O module.

  • Where a user tree lives is the app developer's choice: on the server (database, S3), on the user's device (a desktop or mobile app's local storage), or both, kept in step (the device works offline and syncs with the server). app.serve takes a device tree like any other. A folder (std/sandbox's dir) and an S3 prefix (std/s3's bucket.trees) keep a tree in one layout, so the same tree can be in both; keeping them in step is std/sync's, later.

  • Compiling: a tree is checked and compiled when it is saved (std/sandbox), and cached by its version and the version of what it uses of the app's API; a tree that doesn't check can't be published, so serving never checks, and a deploy that changes nothing a tree uses compiles nothing new for it.

Built with std/app and std/sandbox (std/app.md, std/sandbox.md, user-files.md), with trees kept in memory, in folders, in a SQL database or in S3 (std/s3.md; examples/sites, which shows a migration).

The framework gives an app a routes value built from its tree: every page is a function of its parameters returning a Route, so a link to a page that doesn't exist, or one missing a parameter, is a compile error.

weft
<Link to={routes.todos.id({ id: todo.id })}>{todo.title}</Link>          // /todos/a1
lib.nav.go(routes.docs.path({ path: ["guide", "values"] }))               // /docs/guide/values
<Link to={routes.search({ q: query, page: 2 })}>Next</Link>             // /search?q=…&page=2
let todos = try await routes.api.todos.get()                             // a typed call to an endpoint
  • A page's function takes its path parameters ([id] a string, [...path] a string[]) and the query parameters its page declares with prop query: { q?: string, page?: number }; groups don't appear. routes.home() is /.
  • A Route is data: { path: string, params: json, query: json, href: string }: path the concrete pathname (segments UTF-8 percent-encoded), params the path parameters, query the query parameters (null ones left out), href the path plus the query in the page's declared order. route.isActive is true when the current path is it or below it by whole segments (/todos is active on /todos/a1, not on /todos2; / only on /). Link, lib.nav.go and redirects take a Route; a string isn't one. Link is the framework's component in every app (no import, no file): <Link to={route} class="…" replace>…</Link>, to required.
  • A folder that is both a page and the parent of others is a function with fields: routes.todos() is /todos, routes.todos.id({ id }) is /todos/:id. A page's function takes one record of its parameters; with only optional ones the record may be left out (routes.home()).
  • An endpoint appears typed when its server.weft exports lowercase methods with typed signatures (export async fn get(args: { q: string? }): Todo[], post(body: NewTodo): Todo): routes.api.todos.get({ q }) calls it (a get's arguments travel as query parameters, the others' as a JSON body) and returns its result type, checked on arrival as server functions are: Task<R ! E | NetworkError>, E the method's error type. Raw GET(req: Request): Response handlers serve HTTP as they are and don't appear typed.
  • Renaming or moving a page's folder makes every link to it an error until it's updated; the editor's rename does that in one edit.
  • Route.url("https://…") is a Route to another site, and Route.path("/u/anna/x") one into a user tree (User trees), unchecked by necessity (std.md, Routes).

Weft is in development. The reference is the spec as it stands today.