Duolith docs

data

The data layer against a mock server (data/server/server.ts): state that loads, optimistic actions, retries, the offline queue, a live stream, a paged list and form validation.

Run it

cargo run -p duolith-cli -- dev examples/data     # live, reloads on save
cargo run -p duolith-cli -- build examples/data   # static output in examples/data/dist

The folder on the web: examples/data.

Features it shows

FeatureWhereScreenshot
<match> and <case>, exhaustive at build timedata pages/typed.duo (over feed.state.status)data-typed.png
on:inputdata pages/signup.duodata-signup-errors.png
Offline queue, networkgallery pages/data.duo (Offline queue); data pages/offline.duogallery-data-offline.png, data-offline-queued.png
pagedList()gallery pages/data.duo; data pages/catalogue.duogallery-data-paging.png, data-catalogue-more.png
duolith.env, duolith.<mode>.env, typed environment()data duolith.env, pages/typed.duodata-typed.png
typedApi() from an OpenAPI description (api/*.openapi.yaml)data api/posts.openapi.yaml, pages/typed.duodata-typed.png
state.load().state, one uniondata pages/typed.duodata-typed.png
autocomplete on fields, TextField's autocompletedata pages/signup.duo; effects pages/sign-in.duodata-signup-errors.png
api(), the typed clientdata pages/posts.duodata-posts.png, data-posts-liked.png
Retries, ApiErrordata pages/retry.duodata-retry.png
stream()data pages/live.duodata-live.png

Source

api/posts.openapi.yaml
# The mock API in server/server.ts, described for the typed client (decision
# 0104). Every build writes api/posts.ts from this file; pages/typed.duo
# imports its PostsApi type and calls the server through typedApi, so a path
# or a parameter this file does not have fails the build.
openapi: 3.0.3
info:
  title: Data example API
  version: "1"
paths:
  /posts:
    get:
      summary: Every post, newest first.
      responses:
        "200":
          description: The posts.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/Post" } }
  /posts/{id}/like:
    parameters:
      - { name: id, in: path, required: true, schema: { type: integer } }
    post:
      summary: Likes a post; refused with 503 when its author closed likes.
      responses:
        "200":
          description: The post, liked.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Post" }
  /products:
    get:
      summary: One page of the catalogue.
      parameters:
        - { name: page, in: query, schema: { type: integer, minimum: 1 } }
        - { name: size, in: query, schema: { type: integer, minimum: 1 } }
      responses:
        "200":
          description: The page, and the next page's number while there is one.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ProductPage" }
  /signup:
    post:
      summary: Makes an account; refused with 409 when the email is taken.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, email]
              properties:
                name: { type: string }
                email: { type: string, format: email }
      responses:
        "201":
          description: Welcomed.
          content:
            application/json:
              schema: { type: object, required: [message], properties: { message: { type: string } } }
components:
  schemas:
    Post:
      type: object
      required: [id, author, caption, likes, likesClosed]
      properties:
        id: { type: integer }
        author: { type: string }
        caption: { type: string }
        likes: { type: integer }
        likesClosed: { type: boolean, description: Whether the author closed likes. }
    Product:
      type: object
      required: [id, name, category, price]
      properties:
        id: { type: integer }
        name: { type: string }
        category: { type: string, enum: [kitchen, office, home] }
        price: { type: number }
    ProductPage:
      type: object
      required: [items, next, total]
      properties:
        items: { type: array, items: { $ref: "#/components/schemas/Product" } }
        next: { type: integer, nullable: true }
        total: { type: integer }
api/posts.ts
// Generated by duolith from posts.openapi.yaml (decision 0104). Do not edit: change the
// description and build, or run duolith api generate api/posts.openapi.yaml.
// Import it with `import type`, and call the server with typedApi<PostsApi>(url).

export type Post = {
  author: string;
  caption: string;
  id: number;
  likes: number;
  /** Whether the author closed likes. */
  likesClosed: boolean;
};

export type Product = {
  category: "kitchen" | "office" | "home";
  id: number;
  name: string;
  price: number;
};

export type ProductPage = {
  items: (Product)[];
  next: number | null;
  total: number;
};

export interface PostsApi {
  "/posts": {
    /** Every post, newest first. */
    get: { response: (Post)[] };
  };
  "/posts/{id}/like": {
    /** Likes a post; refused with 503 when its author closed likes. */
    post: { params: { id: number }; response: Post };
  };
  "/products": {
    /** One page of the catalogue. */
    get: { query?: { page?: number; size?: number }; response: ProductPage };
  };
  "/signup": {
    /** Makes an account; refused with 409 when the email is taken. */
    post: { body: {
      email: string;
      name: string;
    }; response: {
      message: string;
    } };
  };
}
duolith.yaml
# The mock server (server/server.ts) answers on another origin, so the
# Content-Security-Policy lets the pages reach it (docs/guide/security.md).
security:
  content-security-policy:
    connect-src: [http://localhost:4480]
pages/catalogue.duo
---
import { api, byNumber, byText, containsText, environment, listView, pagedList } from "@duolith/client";
import type { Page } from "@duolith/client";

type Product = { id: number; name: string; category: string; price: number };

const settings = environment({ apiUrl: "http://localhost:4480", pageSize: 8 });
const server = api(settings.apiUrl);

// Pages are numbered: each answer names the next page, or null after the last.
const products = pagedList((page) =>
  server.get<Page<Product, number>>("/products", { query: { page: page ?? 1, size: settings.pageSize } }),
);

// Search and sort what has loaded so far, without asking the server again.
const shown = listView(() => products.items, {
  search: (product, query) => containsText(`${product.name} ${product.category}`, query),
  sorts: { name: byText((product: Product) => product.name), price: byNumber((product: Product) => product.price) },
});

function sortBy(name: "name" | "price") {
  if (shown.sortBy === name) shown.descending = !shown.descending;
  else shown.sortBy = name;
}

const arrow = (name: string) => (shown.sortBy !== name ? "" : shown.descending ? " ↓" : " ↑");
---

<screen title="Catalogue" class="p-4 gap-4 bg-canvas">
  <text class="text-label text-primary" href="/">‹ Data</text>
  <text class="text-title text-ink">Catalogue</text>

  <input
    class="px-3 py-2 rounded-md bg-surface text-body text-ink border"
    type="search"
    label="Search loaded products"
    placeholder="Search loaded products"
    value={shown.query}
    on:input={(event) => (shown.query = event.value)}
  />

  <view class="row items-center gap-2">
    <text class="text-caption text-muted grow">
      {shown.count} of {products.items.length} loaded
    </text>
    <button
      class="px-3 py-2 rounded-md bg-raised text-label text-ink"
      on:press={() => sortBy("name")}
    >
      Name{arrow("name")}
    </button>
    <button
      class="px-3 py-2 rounded-md bg-raised text-label text-ink"
      on:press={() => sortBy("price")}
    >
      Price{arrow("price")}
    </button>
  </view>

  <list each={shown.items} as="product" key={product.id} class="gap-2">
    <view class="row items-center justify-between p-3 rounded-md bg-surface border">
      <view class="gap-1">
        <text class="text-body text-ink">{product.name}</text>
        <text class="text-caption text-muted">{product.category}</text>
      </view>
      <text class="text-label text-ink">£{product.price}</text>
    </view>
  </list>

  <list each={products.errorMessage ? [products.errorMessage] : []} as="message">
    <text class="text-caption text-danger">{message}</text>
  </list>

  <list each={products.hasMore ? [true] : []} as="more">
    <button
      class="px-4 py-2 rounded-md bg-primary text-on-primary text-label pressed:bg-ink"
      on:press={() => products.loadMore()}
    >
      {products.loading ? "Loading…" : "Load more"}
    </button>
  </list>
  <list each={products.hasMore ? [] : [true]} as="end">
    <text class="text-caption text-muted">That is everything.</text>
  </list>
</screen>
pages/index.duo
---
import { network } from "@duolith/client";
---

<screen title="Data" class="p-4 gap-4 bg-canvas">
  <view class="gap-1">
    <text class="text-title text-ink">Data</text>
    <text class="text-body text-muted">
      Every way a duolith page loads, writes and streams data. Start the mock API first: node
      examples/data/server/server.ts
    </text>
    <text class="text-caption text-muted">Network: {network.online ? "online" : "offline"}</text>
  </view>

  <view class="gap-2">
    <view class="p-4 rounded-lg bg-surface border gap-1" href="/posts">
      <text class="text-label text-primary">Posts</text>
      <text class="text-caption text-muted">
        A loading state, a fetched list, refresh, and an optimistic like that rolls back.
      </text>
    </view>
    <view class="p-4 rounded-lg bg-surface border gap-1" href="/retry">
      <text class="text-label text-primary">Retry</text>
      <text class="text-caption text-muted">
        A server that fails the first two times, retried with backoff.
      </text>
    </view>
    <view class="p-4 rounded-lg bg-surface border gap-1" href="/offline">
      <text class="text-label text-primary">Offline queue</text>
      <text class="text-caption text-muted">
        Writes made offline wait, survive a reload, and are sent in order.
      </text>
    </view>
    <view class="p-4 rounded-lg bg-surface border gap-1" href="/live">
      <text class="text-label text-primary">Live updates</text>
      <text class="text-caption text-muted">
        A stream over server-sent events that reconnects on its own.
      </text>
    </view>
    <view class="p-4 rounded-lg bg-surface border gap-1" href="/catalogue">
      <text class="text-label text-primary">Catalogue</text>
      <text class="text-caption text-muted">
        Load more, page by page, with search and sorting over what has loaded.
      </text>
    </view>
    <view class="p-4 rounded-lg bg-surface border gap-1" href="/signup">
      <text class="text-label text-primary">Sign up</text>
      <text class="text-caption text-muted">
        A validated form, and the server's typed error when an email is taken.
      </text>
    </view>
    <view class="p-4 rounded-lg bg-surface border gap-1" href="/typed">
      <text class="text-label text-primary">Typed API</text>
      <text class="text-caption text-muted">
        A client made from the server's OpenAPI description, and a match over the feed's state.
      </text>
    </view>
  </view>
</screen>
pages/live.duo
---
import { environment, stream } from "@duolith/client";

type Update = { id: number; text: string; at: string };

const settings = environment({ apiUrl: "http://localhost:4480" });

// Server-sent events; an address starting with ws: or wss: would use a WebSocket.
// If the connection drops, the stream reconnects after 1 s, then 2 s, 4 s...
const updates = stream<Update>(`${settings.apiUrl}/events`, { keep: 8 });
---

<screen title="Live updates" class="p-4 gap-4 bg-canvas">
  <text class="text-label text-primary" href="/">‹ Data</text>
  <text class="text-title text-ink">Live updates</text>

  <view class="row items-center gap-2 p-3 rounded-lg bg-surface border">
    <view class="dot" />
    <text class="text-label text-ink">{updates.connected ? "Connected" : "Connecting…"}</text>
    <text class="text-caption text-muted">
      {updates.reconnects === 0 ? "" : `reconnected ${updates.reconnects} times`}
    </text>
  </view>

  <text class="text-caption text-muted">
    Latest: {updates.latest?.text ?? "waiting for the first update"}
  </text>

  <list each={updates.messages} as="update" key={update.id} class="gap-2">
    <view class="row justify-between p-3 rounded-md bg-surface border">
      <text class="text-body text-ink">{update.text}</text>
      <text class="text-caption text-muted">{update.at}</text>
    </view>
  </list>
</screen>

<style>
  .dot {
    width: 10px;
    height: 10px;
    border-radius: 5px;
    background: var(--color-primary);
  }
</style>
pages/offline.duo
---
import { action, api, environment, network, state } from "@duolith/client";

type Note = { id: number; text: string; at: string };
// A note waiting to be sent, with an id of its own so the queue's rows keep
// their place even when two notes say the same thing.
type Draft = { id: string; text: string };

const settings = environment({ apiUrl: "http://localhost:4480" });
const server = api(settings.apiUrl);

const notes = state.load("notes", () => server.get<Note[]>("/notes"));

// Queued-write mode: offline, a note waits in local storage (it survives a
// reload) and is sent, in order, when the network is back. The optimistic
// update shows it in the list straight away.
const addNote = action(
  (note: Draft, { idempotencyKey }) => server.post<Note>("/notes", { text: note.text }, { idempotencyKey }),
  {
    queue: "notes",
    optimistic: {
      key: "notes",
      update: (current: Note[] | undefined, note) => [
        ...(current ?? []),
        { id: -Date.now(), text: note.text, at: "waiting to send" },
      ],
    },
    invalidates: ["notes"],
  },
);

let draft = state("");

function save() {
  const text = draft.trim();
  if (text === "") return;
  addNote.run({ id: `${Date.now()}-${Math.random().toString(36).slice(2)}`, text });
  draft = "";
}

const toggleOffline = () => network.pretendOffline(!network.pretendingOffline);
---

<screen title="Offline queue" class="p-4 gap-4 bg-canvas">
  <text class="text-label text-primary" href="/">‹ Data</text>
  <text class="text-title text-ink">Offline queue</text>

  <view class="row items-center justify-between p-3 rounded-lg bg-surface border">
    <view class="gap-1">
      <text class="text-label text-ink">{network.online ? "Online" : "Offline"}</text>
      <text class="text-caption text-muted">
        {addNote.queued.length === 0 ? "Nothing waiting" : `${addNote.queued.length} waiting to send`}
      </text>
    </view>
    <button
      class="px-4 py-2 rounded-md bg-primary text-on-primary text-label pressed:bg-ink"
      on:press={toggleOffline}
    >
      {network.pretendingOffline ? "Go back online" : "Go offline"}
    </button>
  </view>

  <view class="row gap-2 p-3 rounded-lg bg-surface border">
    <input
      class="grow px-3 py-2 rounded-md bg-raised text-body text-ink border"
      label="Note"
      placeholder="Write a note"
      value={draft}
      on:input={(event) => (draft = event.value)}
    />
    <button
      class="px-4 py-2 rounded-md bg-primary text-on-primary text-label pressed:bg-ink"
      on:press={save}
    >
      Save
    </button>
  </view>

  <list each={addNote.queued} as="queued" key={queued.id} class="gap-1">
    <text class="text-caption text-muted">Queued: {queued.text}</text>
  </list>

  <list each={addNote.errorMessage ? [addNote.errorMessage] : []} as="message">
    <text class="text-caption text-danger">{message}</text>
  </list>

  <text class="text-label text-muted">
    {notes.loading ? "Loading notes…" : "Notes on the server"}
  </text>
  <list each={notes.data ?? []} as="note" key={note.id} class="gap-2">
    <view class="p-3 rounded-md bg-surface border gap-1">
      <text class="text-body text-ink">{note.text}</text>
      <text class="text-caption text-muted">{note.at}</text>
    </view>
  </list>
</screen>
pages/posts.duo
---
import { action, api, environment, state } from "@duolith/client";

type Post = { id: number; author: string; caption: string; likes: number };

const settings = environment({ apiUrl: "http://localhost:4480" });
const server = api(settings.apiUrl);

// Cached under "posts": every part of the app that asks for "posts" shares it.
const feed = state.load("posts", () => server.get<Post[]>("/posts"), { staleTime: 10_000 });

// The like shows at once. If the server refuses (it does for Grace's post),
// the count goes back and the error explains why.
const like = action(
  (post: Post, { idempotencyKey }) => server.post<Post>(`/posts/${post.id}/like`, undefined, { idempotencyKey }),
  {
    optimistic: {
      key: "posts",
      update: (posts: Post[], liked) => posts.map((each) => (each.id === liked.id ? { ...each, likes: each.likes + 1 } : each)),
    },
    invalidates: ["posts"],
    retry: false,
  },
);

/** Lists of zero or one item show a part of the screen only when there is something to show; the one item is its own key. */
const when = (shown: boolean) => (shown ? ["shown"] : []);
---

<screen title="Posts" class="p-4 gap-4 bg-canvas">
  <view class="row items-center justify-between">
    <text class="text-label text-primary" href="/">‹ Data</text>
    <button
      class="px-4 py-2 rounded-md bg-primary text-on-primary text-label pressed:bg-ink"
      on:press={() => feed.refresh()}
    >
      {feed.refreshing ? "Refreshing…" : "Refresh"}
    </button>
  </view>
  <text class="text-title text-ink">Posts</text>

  <list each={when(feed.loading)} as="shown" key={shown} class="gap-3">
    <view class="p-4 rounded-lg bg-surface border gap-2">
      <text class="text-label text-muted">Loading posts…</text>
      <view class="skeleton-bar" />
      <view class="skeleton-bar short" />
    </view>
  </list>

  <list each={feed.error && !feed.data ? [feed.errorMessage] : []} as="message">
    <view class="p-4 rounded-lg bg-surface border gap-2">
      <text class="text-label text-danger">Could not load the posts</text>
      <text class="text-caption text-muted">{message} Is the mock API running?</text>
    </view>
  </list>

  <list each={like.errorMessage ? [like.errorMessage] : []} as="message">
    <view class="p-3 rounded-md bg-raised border">
      <text class="text-caption text-danger">Like rolled back: {message}</text>
    </view>
  </list>

  <list each={feed.data ?? []} as="post" key={post.id} class="gap-3">
    <view class="card gap-2 p-4 rounded-lg bg-surface border">
      <text class="text-label text-muted">{post.author}</text>
      <text class="text-body text-ink">{post.caption}</text>
      <view class="row">
        <button
          class="row gap-2 text-label text-primary"
          label="Like"
          on:press={() => like.run(post)}
        >
          ♥ {post.likes}
        </button>
      </view>
    </view>
  </list>
</screen>

<style>
  .card {
    box-shadow: 0 1px 2px rgb(0 0 0 / 0.06);
  }
  .skeleton-bar {
    height: 14px;
    border-radius: 7px;
    background: var(--color-raised, #eeece7);
  }
  .short {
    width: 60%;
  }
</style>
pages/posts.test.ts
// Tests for the posts screen, with the server mocked: run with
// duolith test examples/data (no mock API needed).
import { expect, fail, pending, render, test } from "@duolith/testing";

const posts = [
  { id: 1, author: "Ada", caption: "First light over the harbour.", likes: 12 },
  { id: 2, author: "Grace", caption: "Found the moth.", likes: 31 },
];

test("the posts that load are shown", async () => {
  const screen = await render("/posts", { loads: { posts } });

  await expect(screen.byText("First light over the harbour.")).toBeShown();
  await expect(screen.byRole("button", { name: "Like" })).toHaveCount(2);
});

test("a mock written as a function runs in the page, under the build's Content-Security-Policy", async () => {
  const screen = await render("/posts", {
    loads: { posts: () => [{ id: 3, author: "Lin", caption: "Made by a function.", likes: 0 }] },
  });

  await expect(screen.byText("Made by a function.")).toBeShown();
});

test("while the posts load, the skeleton is shown", async () => {
  const screen = await render("/posts", { loads: { posts: pending() } });

  await expect(screen.byText("Loading posts…")).toBeShown();
});

test("a failed load explains itself", async () => {
  const screen = await render("/posts", { loads: { posts: fail("The server is down.") } });

  await expect(screen.byText("Could not load the posts")).toBeShown();
});

test("a like counts at once and is sent with its post", async () => {
  const screen = await render("/posts", {
    loads: { posts },
    // The write never finishes, so the optimistic count stays on screen.
    actions: { like: pending() },
  });

  await screen.byRole("button", { name: "Like" }).nth(0).press();

  await expect(screen.byRole("button", { name: "Like" }).nth(0)).toHaveText("♥ 13");
  const runs = (await screen.runs("like")) as { id: number }[];
  expect(runs.map((post) => post.id)).toEqual([1]);
});

test("a refused like is rolled back and says why", async () => {
  const screen = await render("/posts", {
    loads: { posts },
    actions: { like: fail("Likes are closed on this post.", 403) },
  });

  await screen.byRole("button", { name: "Like" }).nth(1).press();

  await expect(screen.byText("Like rolled back: Likes are closed on this post.")).toBeShown();
  await expect(screen.byRole("button", { name: "Like" }).nth(1)).toHaveText("♥ 31");
});
pages/retry.duo
---
import { api, environment, state } from "@duolith/client";

type Reply = { message: string; attempts: number };

const settings = environment({ apiUrl: "http://localhost:4480" });
const server = api(settings.apiUrl);

let attempts = state<{ number: number; at: string }[]>([]);
let caller = state(`page-${Date.now()}`);

// /flaky refuses each new caller twice with 503 before it answers. The
// state.load retries after 800 ms, then 1600 ms, so the third attempt succeeds.
// The key includes the caller, so "Try with a new caller" loads afresh.
const reply = state.load(
  () => ["flaky", caller],
  (key) => {
    attempts = [...attempts, { number: attempts.length + 1, at: new Date().toLocaleTimeString("en-GB") }];
    return server.get<Reply>("/flaky", { query: { caller: String(key[1]), failures: 2, delay: 300 } });
  },
  { retry: { times: 3, delay: 800 } },
);

function startOver() {
  attempts = [];
  caller = `page-${Date.now()}`;
}
---

<screen title="Retry" class="p-4 gap-4 bg-canvas">
  <text class="text-label text-primary" href="/">‹ Data</text>
  <text class="text-title text-ink">Retry with backoff</text>
  <text class="text-body text-muted">
    The server refuses the first two requests. Each retry waits twice as long as the last.
  </text>

  <view class="p-4 rounded-lg bg-surface border gap-2">
    <text class="text-label text-ink">
      {reply.loading ? "Waiting for the server…" : reply.data?.message ?? reply.errorMessage}
    </text>
    <list each={attempts} as="attempt" key={attempt.number} class="gap-1">
      <text class="text-caption text-muted">Attempt {attempt.number} at {attempt.at}</text>
    </list>
  </view>

  <button
    class="px-4 py-2 rounded-md bg-primary text-on-primary text-label pressed:bg-ink"
    on:press={startOver}
  >
    Try with a new caller
  </button>
</screen>
pages/signup.duo
---
import { action, api, custom, email, environment, field, form, maxLength, minLength, required } from "@duolith/client";

const settings = environment({ apiUrl: "http://localhost:4480" });
const server = api(settings.apiUrl);

const password = field("", required("Choose a password."), minLength(8));
const signUp = form({
  name: field("", required("Tell us your name."), maxLength(40)),
  email: field("", required("We need an email address."), email()),
  password,
  confirmation: field("", custom((value) => value === password.value, "The passwords do not match.")),
});

// The server answers 409 for taken@example.com: the action's error carries its message.
const register = action((values: { name: string; email: string; password: string }) =>
  server.post<{ message: string }>("/signup", values),
);

function send() {
  signUp.submit(({ name, email, password }) => register.run({ name, email, password }));
}
---

<screen title="Sign up" class="p-4 gap-4 bg-canvas">
  <text class="text-label text-primary" href="/">‹ Data</text>
  <text class="text-title text-ink">Sign up</text>

  <view class="gap-3 p-4 rounded-lg bg-surface border">
    <view class="gap-1">
      <text class="text-label text-ink">Name</text>
      <input
        class="px-3 py-2 rounded-md bg-raised text-body text-ink border"
        label="Name"
        autocomplete="name"
        value={signUp.fields.name.value}
        on:input={(event) => (signUp.fields.name.value = event.value)}
      />
      <text class="text-caption text-danger">{signUp.fields.name.error}</text>
    </view>
    <view class="gap-1">
      <text class="text-label text-ink">Email</text>
      <input
        class="px-3 py-2 rounded-md bg-raised text-body text-ink border"
        label="Email"
        autocomplete="email"
        type="email"
        value={signUp.fields.email.value}
        on:input={(event) => (signUp.fields.email.value = event.value)}
      />
      <text class="text-caption text-danger">{signUp.fields.email.error}</text>
    </view>
    <view class="gap-1">
      <text class="text-label text-ink">Password</text>
      <input
        class="px-3 py-2 rounded-md bg-raised text-body text-ink border"
        label="Password"
        autocomplete="new-password"
        type="password"
        value={password.value}
        on:input={(event) => (password.value = event.value)}
      />
      <text class="text-caption text-danger">{password.error}</text>
    </view>
    <view class="gap-1">
      <text class="text-label text-ink">Confirm password</text>
      <input
        class="px-3 py-2 rounded-md bg-raised text-body text-ink border"
        label="Confirm password"
        autocomplete="new-password"
        type="password"
        value={signUp.fields.confirmation.value}
        on:input={(event) => (signUp.fields.confirmation.value = event.value)}
      />
      <text class="text-caption text-danger">{signUp.fields.confirmation.error}</text>
    </view>

    <button
      class="px-4 py-2 rounded-md bg-primary text-on-primary text-label pressed:bg-ink"
      on:press={send}
    >
      {register.pending ? "Signing up…" : "Sign up"}
    </button>
    <text class="text-caption text-danger">{register.errorMessage}</text>
    <text class="text-label text-primary">{register.data?.message ?? ""}</text>
  </view>

  <text class="text-caption text-muted">Try taken@example.com to see the server refuse.</text>
</screen>
pages/typed.duo
---
import { action, environment, state, typedApi } from "@duolith/client";
import type { PostsApi } from "../api/posts.ts";

// apiUrl is DUOLITH_PUBLIC_API_URL from duolith.env, typed as a string: a name no
// environment file defines fails the build (E0514).
const settings = environment();

// The paths, parameters and answers come from api/posts.openapi.yaml: a path
// the server does not have, or an id that is not a number, fails the build.
const server = typedApi<PostsApi>(settings.apiUrl);

const feed = state.load("typed-posts", () => server.get("/posts"));

const like = action(
  (id: number, { idempotencyKey }) => server.post("/posts/{id}/like", { params: { id }, idempotencyKey }),
  { invalidates: ["typed-posts"], retry: false },
);
---

<screen title="Typed API" class="p-4 gap-4 bg-canvas">
  <text class="text-label text-primary" href="/">‹ Data</text>
  <text class="text-title text-ink">Typed API</text>
  <text class="text-body text-muted">
    The client is made from the server's OpenAPI description, and the feed's state is one union: the
    match below must show every status, or the page does not build.
  </text>

  <match value={feed.state.status}>
    <case is="loading">
      <text class="text-label text-muted">Loading posts…</text>
    </case>
    <case is="failed">
      <text class="text-label text-danger">Could not load the posts. Is the mock API running?</text>
    </case>
    <case is="ready">
      <list each={feed.data ?? []} as="post" key={post.id} class="gap-3">
        <view class="p-4 rounded-lg bg-surface border gap-2">
          <text class="text-label text-muted">{post.author}</text>
          <text class="text-body text-ink">{post.caption}</text>
          <button class="text-label text-primary" label="Like" on:press={() => like.run(post.id)}>
            ♥ {post.likes}
          </button>
        </view>
      </list>
    </case>
  </match>

  <list each={like.errorMessage ? [like.errorMessage] : []} as="message">
    <text class="text-caption text-danger">{message}</text>
  </list>
</screen>
server/server.ts
// A mock API for the `data` example: JSON endpoints with artificial latency,
// one that fails the first few times, a like that the server refuses for one
// post, pages of a catalogue and a server-sent event stream. No dependencies:
//
//   node examples/data/server/server.ts            (port 4480)
//   PORT=4490 node examples/data/server/server.ts
//
// Every answer carries CORS headers, so a page served by `duolith dev` on
// another port can call it. State lives in memory and resets on restart.

import { createServer, type IncomingMessage, type ServerResponse } from "node:http";

type Post = { id: number; author: string; caption: string; likes: number; likesClosed: boolean };
type Note = { id: number; text: string; at: string };
type Product = { id: number; name: string; category: string; price: number };

const port = Number(process.env.PORT ?? 4480);
const latency = Number(process.env.LATENCY ?? 700);

const posts: Post[] = [
  { id: 1, author: "Ada", caption: "First light over the harbour.", likes: 12, likesClosed: false },
  { id: 2, author: "Linus", caption: "New desk, same bugs.", likes: 4, likesClosed: false },
  { id: 3, author: "Grace", caption: "Found the moth. Likes are closed on this one.", likes: 31, likesClosed: true },
];
const notes: Note[] = [{ id: 1, text: "Buy more coffee", at: new Date().toISOString() }];
const products: Product[] = makeProducts(42);
const takenEmails = new Set(["taken@example.com"]);
/** Answers already given, by idempotency key, so a resent write is applied once. */
const answered = new Map<string, { status: number; body: unknown }>();
/** How many times each caller of /flaky has been refused. */
const flakyRefusals = new Map<string, number>();

type Route = (request: IncomingMessage, url: URL, body: any) => Promise<Answer> | Answer;
type Answer = { status: number; body?: unknown };

const routes: Record<string, Route> = {
  "GET /posts": () => ({ status: 200, body: posts }),
  "POST /posts/:id/like": (_request, url) => likePost(Number(url.pathname.split("/")[2])),
  "GET /flaky": (_request, url) => flaky(url),
  "GET /notes": () => ({ status: 200, body: notes }),
  "POST /notes": (_request, _url, body) => addNote(body),
  "GET /products": (_request, url) => productPage(url),
  "POST /signup": (_request, _url, body) => signUp(body),
};

createServer((request, response) => void handle(request, response)).listen(port, () => {
  console.log(`data-server: http://localhost:${port}/ (latency ${latency} ms)`);
});

async function handle(request: IncomingMessage, response: ServerResponse): Promise<void> {
  const url = new URL(request.url ?? "/", `http://localhost:${port}`);
  allowOtherOrigins(response);
  if (request.method === "OPTIONS") return void response.writeHead(204).end();
  if (url.pathname === "/events") return streamEvents(request, response);
  const route = findRoute(request.method ?? "GET", url.pathname);
  if (!route) return send(response, { status: 404, body: { message: `No route for ${url.pathname}.` } });
  const body = await readJson(request);
  await wait(Number(url.searchParams.get("delay") ?? latency));
  send(response, await answerOnce(request, () => route(request, url, body)));
}

function allowOtherOrigins(response: ServerResponse): void {
  response.setHeader("access-control-allow-origin", "*");
  response.setHeader("access-control-allow-methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
  response.setHeader("access-control-allow-headers", "content-type, accept, authorization, idempotency-key");
}

function findRoute(method: string, path: string): Route | undefined {
  const pattern = path.replace(/^\/posts\/\d+\/like$/, "/posts/:id/like");
  return routes[`${method} ${pattern}`];
}

/** Writes carrying an idempotency key get the first answer again instead of being applied twice. */
async function answerOnce(request: IncomingMessage, work: () => Promise<Answer> | Answer): Promise<Answer> {
  const key = request.headers["idempotency-key"];
  if (typeof key !== "string") return work();
  const earlier = answered.get(key);
  if (earlier) return earlier;
  const answer = await work();
  answered.set(key, answer);
  return answer;
}

function likePost(id: number): Answer {
  const post = posts.find((each) => each.id === id);
  if (!post) return { status: 404, body: { message: "No such post." } };
  if (post.likesClosed) return { status: 503, body: { message: `${post.author} closed likes on this post.` } };
  post.likes += 1;
  return { status: 200, body: post };
}

/** Refuses the first `failures` requests from each `caller`, then answers. */
function flaky(url: URL): Answer {
  const caller = url.searchParams.get("caller") ?? "anyone";
  const failures = Number(url.searchParams.get("failures") ?? 2);
  const refused = flakyRefusals.get(caller) ?? 0;
  if (refused < failures) {
    flakyRefusals.set(caller, refused + 1);
    return { status: 503, body: { message: `Refused attempt ${refused + 1} of ${failures}.` } };
  }
  return { status: 200, body: { message: `Answered after ${refused} refusals.`, attempts: refused + 1 } };
}

function addNote(body: { text?: unknown }): Answer {
  const text = typeof body?.text === "string" ? body.text.trim() : "";
  if (text === "") return { status: 400, body: { message: "A note needs some text." } };
  const note = { id: notes.length + 1, text, at: new Date().toISOString() };
  notes.push(note);
  return { status: 201, body: note };
}

/** `?page=1&size=10`: one page, and the next page's number while there is one. */
function productPage(url: URL): Answer {
  const page = Math.max(1, Number(url.searchParams.get("page") ?? 1));
  const size = Math.max(1, Number(url.searchParams.get("size") ?? 10));
  const items = products.slice((page - 1) * size, page * size);
  const next = page * size < products.length ? page + 1 : null;
  return { status: 200, body: { items, next, total: products.length } };
}

function signUp(body: { name?: string; email?: string }): Answer {
  const email = (body?.email ?? "").toLowerCase();
  if (takenEmails.has(email)) return { status: 409, body: { message: "That email already has an account." } };
  takenEmails.add(email);
  return { status: 201, body: { message: `Welcome, ${body?.name ?? "friend"}!` } };
}

/** Server-sent events: one update every 1.5 seconds until the page closes the connection. */
function streamEvents(request: IncomingMessage, response: ServerResponse): void {
  response.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" });
  let count = 0;
  const sendUpdate = () => {
    count += 1;
    const update = { id: count, text: updateText(count), at: new Date().toLocaleTimeString("en-GB") };
    response.write(`id: ${count}\ndata: ${JSON.stringify(update)}\n\n`);
  };
  sendUpdate();
  const timer = setInterval(sendUpdate, 1500);
  request.on("close", () => clearInterval(timer));
}

function updateText(count: number): string {
  const authors = ["Ada", "Linus", "Grace", "Margaret", "Alan"];
  const verbs = ["liked a post", "shared a photo", "started following you", "commented: nice!", "joined"];
  return `${authors[count % authors.length]} ${verbs[(count * 3) % verbs.length]}`;
}

function makeProducts(count: number): Product[] {
  const names = ["Kettle", "Lamp", "Notebook", "Mug", "Chair", "Plant", "Clock", "Rug", "Pen", "Shelf"];
  const categories = ["kitchen", "office", "home"];
  return Array.from({ length: count }, (_, index) => ({
    id: index + 1,
    name: `${names[index % names.length]} ${Math.floor(index / names.length) + 1}`,
    category: categories[index % categories.length]!,
    price: 5 + ((index * 37) % 120),
  }));
}

async function readJson(request: IncomingMessage): Promise<unknown> {
  let text = "";
  for await (const chunk of request) text += chunk;
  try {
    return text === "" ? undefined : JSON.parse(text);
  } catch {
    return undefined;
  }
}

function send(response: ServerResponse, answer: Answer): void {
  response.writeHead(answer.status, { "content-type": "application/json" });
  response.end(answer.body === undefined ? "" : JSON.stringify(answer.body));
}

function wait(milliseconds: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
}