@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
mdx 484 lines 16 KB
Raw
1 ---
2 title: "Part 6: Build the UI with foldkit"
3 description: A browser app that signs in with a cookie, opens an account, deposits, and watches its balance live.
4 sidebar:
5 order: 6
6 ---
7
8 Build a browser app with [foldkit](https://foldkit.dev): sign in, open your account, deposit, and see the balance change as it happens.
9
10 ## Install
11
12 ```sh
13 bun add foldkit @effect/platform-browser
14 bun add -d vite @foldkit/vite-plugin
15 ```
16
17 ## Add the browser's types
18
19 The app runs in a browser. Add `"DOM"` to `lib` in your `tsconfig.json`, so `document` and `location` type-check:
20
21 ```json
22 {
23 "compilerOptions": {
24 "lib": ["ESNext", "DOM"]
25 }
26 }
27 ```
28
29 ## Configure Vite
30
31 ```typescript
32 // vite.config.ts
33 import { foldkit } from "@foldkit/vite-plugin";
34 import { defineConfig } from "vite";
35
36 export default defineConfig({
37 plugins: [foldkit()],
38 optimizeDeps: {
39 entries: ["src/web/entry.ts"],
40 include: ["effect", "effect/Function", "effect/http", "@effect/platform-browser"],
41 },
42 });
43 ```
44
45 The foldkit plugin builds the app. `include` pre-bundles the Effect modules foldkit imports, so the browser loads one copy of Effect.
46
47 ## Add the page
48
49 ```html
50 <!-- index.html -->
51 <!doctype html>
52 <html lang="en">
53 <head>
54 <meta charset="UTF-8" />
55 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
56 <title>Bank</title>
57 </head>
58 <body>
59 <div id="root"></div>
60 <script type="module" src="/src/web/entry.ts"></script>
61 </body>
62 </html>
63 ```
64
65 ## Read the session cookie
66
67 ```diff lang="typescript"
68 // src/Session.middleware.ts
69 import * as Effect from "effect/Effect";
70 +import * as Cookies from "effect/http/Cookies";
71 import * as Headers from "effect/http/Headers";
72 import * as Layer from "effect/Layer";
73 // ...
74 ) {}
75
76 -// Demo only: trusts `Authorization: Bearer <customer id>`. Verify a real session in production.
77 +export const SESSION_COOKIE = "bank_session";
78 +
79 +// The customer from the session cookie (browsers), or the Authorization header (scripts).
80 +const signedIn = (headers: Headers.Headers): Option.Option<string> =>
81 + Option.orElse(
82 + Option.flatMap(Headers.get(headers, "cookie"), (cookie) =>
83 + Option.fromNullishOr(Cookies.parseHeader(cookie)[SESSION_COOKIE]),
84 + ),
85 + () =>
86 + Option.flatMap(Headers.get(headers, "authorization"), (value) =>
87 + value.startsWith("Bearer ") ? Option.some(value.slice("Bearer ".length)) : Option.none(),
88 + ),
89 + );
90 +
91 +// Demo only: trusts the cookie or header as given. Verify a real session in production.
92 export const SessionLive = Layer.succeed(Session, (effect, { headers }) =>
93 - Option.match(Headers.get(headers, "authorization"), {
94 + Option.match(signedIn(headers), {
95 onNone: () => Effect.fail(new Unauthorized()),
96 - onSome: (value) =>
97 - value.startsWith("Bearer ")
98 - ? Effect.provideService(effect, CurrentActor, {
99 - customerId: CustomerId.make(value.slice("Bearer ".length)),
100 - })
101 - : Effect.fail(new Unauthorized()),
102 + onSome: (customerId) =>
103 + Effect.provideService(effect, CurrentActor, { customerId: CustomerId.make(customerId) }),
104 }),
105 );
106 ```
107
108 A browser can't set headers on a WebSocket, but it always sends its cookies. `Session` now reads the customer from the `bank_session` cookie, and falls back to the header for scripts.
109
110 ## Sign in
111
112 ```diff lang="typescript"
113 // src/Session.middleware.ts
114 import * as Cookies from "effect/http/Cookies";
115 import * as Headers from "effect/http/Headers";
116 +import { HttpServerRequest } from "effect/http/HttpServerRequest";
117 +import * as HttpServerResponse from "effect/http/HttpServerResponse";
118 import * as Layer from "effect/Layer";
119 import * as Option from "effect/Option";
120 // ...
121 );
122
123 +// POST /api/session signs a customer in. Demo only: anyone may sign in as anyone.
124 +export const sessionRoute = Effect.gen(function* () {
125 + const request = yield* HttpServerRequest;
126 + const body = yield* request.json.pipe(
127 + Effect.flatMap(Schema.decodeUnknownEffect(Schema.Struct({ customerId: CustomerId }))),
128 + Effect.option,
129 + );
130 + if (Option.isNone(body)) return HttpServerResponse.text("Expected { customerId }", { status: 400 });
131 + return HttpServerResponse.empty({ status: 204 }).pipe(
132 + HttpServerResponse.setCookieUnsafe(SESSION_COOKIE, body.value.customerId, {
133 + httpOnly: true,
134 + secure: true,
135 + sameSite: "strict",
136 + path: "/",
137 + }),
138 + );
139 +});
140 +
141 export const sessionClient = (customerId: string) =>
142 RpcMiddleware.layerClient(Session, ({ request, next }) =>
143 ```
144
145 `sessionRoute` sets the cookie. `HttpOnly` keeps it out of reach of scripts, and `SameSite=Strict` keeps it off requests from other sites.
146
147 ## Route sign-in
148
149 ```diff lang="typescript"
150 // src/BankWorker.ts
151 import * as DomainCloudflare from "@alchemy.run/cloudflare/Domain";
152 import * as Effect from "effect/Effect";
153 +import { HttpServerRequest } from "effect/http/HttpServerRequest";
154 import * as Layer from "effect/Layer";
155 import { Bank, BankHandlers } from "./Bank.model.ts";
156 import { BankApi } from "./BankApi.api.ts";
157 -import { SessionLive } from "./Session.middleware.ts";
158 +import { SessionLive, sessionRoute } from "./Session.middleware.ts";
159
160 const BankLive = SessionLive.pipe(
161 // ...
162 Effect.gen(function* () {
163 const api = yield* BankApi;
164 - return { fetch: api.fetch };
165 + return {
166 + fetch: Effect.gen(function* () {
167 + const request = yield* HttpServerRequest;
168 + const path = new URL(request.url, "http://localhost").pathname;
169 + return path === "/api/session" ? yield* sessionRoute : yield* api.fetch;
170 + }),
171 + };
172 }).pipe(Effect.provide(BankLive)),
173 ) {}
174 ```
175
176 `/api/session` signs in, and everything else goes to the Api.
177
178 ## Describe the app's state
179
180 ```typescript
181 // src/web/Bank.ts
182 import type * as Domain from "@alchemy.run/domain";
183 import * as Schema from "effect/Schema";
184 import { defineMessageUnion } from "foldkit/message";
185 import { AccountId } from "../Account.id.ts";
186 import { CustomerId } from "../Customer.id.ts";
187
188 // The bank client this app runs on, provided when the app starts.
189 type Bank = Domain.Api.ClientKey<"BankApi">;
190
191 export const Flags = Schema.Struct({ customerId: CustomerId });
192 export type Flags = typeof Flags.Type;
193
194 export const Model = Schema.Struct({
195 customerId: CustomerId,
196 accountId: AccountId,
197 // `null` until the account is open.
198 balance: Schema.NullOr(Schema.Number),
199 error: Schema.NullOr(Schema.String),
200 });
201 export type Model = typeof Model.Type;
202
203 export const Message = defineMessageUnion({
204 ClickedOpen: {},
205 ClickedDeposit: {},
206 Succeeded: {},
207 Failed: { reason: Schema.String },
208 GotBalance: { balance: Schema.NullOr(Schema.Number) },
209 });
210 export type Message = typeof Message.Type;
211 ```
212
213 `Flags` is what the app starts with, `Model` is what it shows, and `Message` is everything that can happen. The balance is `null` until the account is open.
214
215 ## Send domain commands
216
217 ```diff lang="typescript"
218 // src/web/Bank.ts
219 import type * as Domain from "@alchemy.run/domain";
220 +import * as Effect from "effect/Effect";
221 import * as Schema from "effect/Schema";
222 +import { Command } from "foldkit";
223 import { defineMessageUnion } from "foldkit/message";
224 import { AccountId } from "../Account.id.ts";
225 +import { BankApi } from "../BankApi.api.ts";
226 import { CustomerId } from "../Customer.id.ts";
227 // ...
228 });
229 export type Message = typeof Message.Type;
230 +
231 +export const Register = Command.define("Register", {
232 + args: { customerId: CustomerId },
233 + messages: [Message.Succeeded, Message.Failed],
234 + execute: ({ customerId }) =>
235 + Effect.gen(function* () {
236 + const bank = yield* BankApi.Client;
237 + yield* bank.RegisterCustomer(customerId, { name: customerId });
238 + return Message.Succeeded();
239 + }).pipe(Effect.catch((error) => Effect.succeed(Message.Failed({ reason: error._tag })))),
240 +});
241 +
242 +export const Deposit = Command.define("Deposit", {
243 + args: { accountId: AccountId, amount: Schema.Number },
244 + messages: [Message.Succeeded, Message.Failed],
245 + execute: ({ accountId, amount }) =>
246 + Effect.gen(function* () {
247 + const bank = yield* BankApi.Client;
248 + yield* bank.DepositMoney(accountId, { amount });
249 + return Message.Succeeded();
250 + }).pipe(Effect.catch((error) => Effect.succeed(Message.Failed({ reason: error._tag })))),
251 +});
252 ```
253
254 A foldkit command runs a domain command through the bank client and turns the outcome into a message. A rejection becomes `Failed` with its tag.
255
256 ## Update the model
257
258 ```diff lang="typescript"
259 // src/web/Bank.ts
260 import * as Effect from "effect/Effect";
261 import * as Schema from "effect/Schema";
262 -import { Command } from "foldkit";
263 +import { Command, type Update } from "foldkit";
264 import { defineMessageUnion } from "foldkit/message";
265 import { AccountId } from "../Account.id.ts";
266 // ...
267 yield* bank.DepositMoney(accountId, { amount });
268 return Message.Succeeded();
269 }).pipe(Effect.catch((error) => Effect.succeed(Message.Failed({ reason: error._tag })))),
270 });
271 +
272 +export const update = (model: Model, message: Message): Update.Return<Model, Message, Bank> =>
273 + Message.match<Update.Return<Model, Message, Bank>>(message, {
274 + ClickedOpen: () => ({ model, commands: [Register({ customerId: model.customerId })] }),
275 + ClickedDeposit: () => ({
276 + model,
277 + commands: [Deposit({ accountId: model.accountId, amount: 1_000 })],
278 + }),
279 + // The balance arrives through the subscription; success only clears an error.
280 + Succeeded: () => ({ model: { ...model, error: null } }),
281 + Failed: ({ reason }) => ({ model: { ...model, error: reason } }),
282 + GotBalance: ({ balance }) => ({ model: { ...model, balance } }),
283 + });
284 +
285 +export const init = (flags: Flags): Update.Return<Model, Message, Bank> => ({
286 + model: {
287 + customerId: flags.customerId,
288 + accountId: AccountId.make(`${flags.customerId}-main`),
289 + balance: null,
290 + error: null,
291 + },
292 +});
293 ```
294
295 Clicks send commands. The balance never changes on success: it arrives from the bank, through the next step.
296
297 ## Watch the balance
298
299 ```diff lang="typescript"
300 // src/web/Bank.ts
301 import * as Effect from "effect/Effect";
302 import * as Schema from "effect/Schema";
303 -import { Command, type Update } from "foldkit";
304 +import * as Stream from "effect/Stream";
305 +import { Command, Subscription, type Update } from "foldkit";
306 import { defineMessageUnion } from "foldkit/message";
307 import { AccountId } from "../Account.id.ts";
308 // ...
309 },
310 });
311 +
312 +export const subscriptions = Subscription.make<Model, Message, Bank>()((entry) => ({
313 + balance: entry(
314 + { accountId: AccountId },
315 + {
316 + modelToDependencies: (model) => ({ accountId: model.accountId }),
317 + dependenciesToStream: ({ accountId }) =>
318 + Stream.unwrap(
319 + Effect.gen(function* () {
320 + const bank = yield* BankApi.Client;
321 + return bank.AccountSummary.watch(accountId);
322 + }),
323 + ).pipe(
324 + Stream.map(({ state: summary }) =>
325 + Message.GotBalance({ balance: summary?.owner ? summary.balance : null }),
326 + ),
327 + Stream.catch((error) => Stream.succeed(Message.Failed({ reason: error._tag }))),
328 + ),
329 + },
330 + ),
331 +}));
332 ```
333
334 The subscription watches the account's summary. The bank pushes every change over a WebSocket, so a deposit from any device shows up here.
335
336 ## Draw the page
337
338 ```diff lang="typescript"
339 // src/web/Bank.ts
340 import * as Stream from "effect/Stream";
341 import { Command, Subscription, type Update } from "foldkit";
342 +import type { Document, HtmlBuilder } from "foldkit/html";
343 import { defineMessageUnion } from "foldkit/message";
344 import { AccountId } from "../Account.id.ts";
345 // ...
346 ),
347 }));
348 +
349 +const cents = (amount: number) => (amount / 100).toFixed(2);
350 +
351 +export const view = (model: Model, h: HtmlBuilder<Message>): Document => ({
352 + title: "Bank",
353 + body: h.div(
354 + [],
355 + [
356 + h.p([], [`Signed in as ${model.customerId}`]),
357 + model.balance === null
358 + ? h.button([h.OnClick(Message.ClickedOpen())], ["Open my account"])
359 + : h.div(
360 + [],
361 + [
362 + h.p([], [`Balance: ${cents(model.balance)}`]),
363 + h.button([h.OnClick(Message.ClickedDeposit())], ["Deposit 10.00"]),
364 + ],
365 + ),
366 + h.p([], [model.error ?? ""]),
367 + ],
368 + ),
369 +});
370 ```
371
372 Before the account opens, the page offers to open it. After, it shows the balance and a deposit button.
373
374 ## Start the app
375
376 ```typescript
377 // src/web/entry.ts
378 import * as Domain from "@alchemy.run/domain";
379 import * as Effect from "effect/Effect";
380 import * as FetchHttpClient from "effect/http/FetchHttpClient";
381 import * as HttpClient from "effect/http/HttpClient";
382 import * as HttpClientRequest from "effect/http/HttpClientRequest";
383 import * as Layer from "effect/Layer";
384 import * as Socket from "effect/socket/Socket";
385 import { Runtime } from "foldkit";
386 import { BankApi } from "../BankApi.api.ts";
387 import { CustomerId } from "../Customer.id.ts";
388 import { Flags, init, Model, subscriptions, update, view } from "./Bank.ts";
389
390 // A stand-in for a login page: `?customer=c-2` picks who you are.
391 const customerId = CustomerId.make(new URLSearchParams(location.search).get("customer") ?? "c-1");
392
393 // Sign in, so the browser holds the session cookie for every call and watch.
394 const signIn = Effect.gen(function* () {
395 const client = HttpClient.filterStatusOk(yield* HttpClient.HttpClient);
396 yield* client.execute(
397 HttpClientRequest.post("/api/session").pipe(HttpClientRequest.bodyJsonUnsafe({ customerId })),
398 );
399 });
400
401 const BankConnection = Layer.unwrap(
402 signIn.pipe(
403 Effect.orDie,
404 Effect.as(
405 BankApi.layerClient.pipe(
406 Layer.provide(Domain.protocolWebSocket(`${location.origin}/api`)),
407 Layer.provide(Socket.layerWebSocketConstructorGlobal),
408 ),
409 ),
410 ),
411 ).pipe(Layer.provide(FetchHttpClient.layer));
412
413 Runtime.run(
414 Runtime.makeApplication({
415 Model,
416 Flags,
417 init,
418 update,
419 view,
420 subscriptions,
421 resources: BankConnection,
422 container: document.getElementById("root"),
423 }),
424 { flags: Effect.succeed({ customerId }) },
425 );
426 ```
427
428 The app signs in first, then connects to the Api on its own origin. `Domain.protocolWebSocket` sends commands over HTTP and opens a WebSocket for each watch.
429
430 ## Serve the app and the Api from one origin
431
432 ```typescript
433 // src/web/worker.ts
434 interface Fetcher {
435 fetch(request: Request): Promise<Response>;
436 }
437
438 // Serve the app, and forward /api to the bank: one origin, so the session cookie is first-party.
439 export default {
440 fetch(request: Request, env: { readonly ASSETS: Fetcher; readonly BANK: Fetcher }) {
441 const { pathname } = new URL(request.url);
442 return pathname.startsWith("/api") ? env.BANK.fetch(request) : env.ASSETS.fetch(request);
443 },
444 };
445 ```
446
447 The app's Worker serves the built page and forwards `/api` to the bank. Sharing one origin keeps the session cookie first-party, so browsers send it.
448
449 ## Deploy the app
450
451 ```diff lang="typescript"
452 // alchemy.run.ts
453 Effect.gen(function* () {
454 const bank = yield* BankWorker;
455 - return { url: bank.url.as<string>() };
456 + const app = yield* Cloudflare.Website.Foldkit("BankApp", {
457 + main: "src/web/worker.ts",
458 + env: { BANK: bank },
459 + assets: { runWorkerFirst: ["/api", "/api/*"] },
460 + });
461 + return { url: bank.url.as<string>(), app: app.url.as<string>() };
462 }),
463 );
464 ```
465
466 `Cloudflare.Website.Foldkit` builds the app with Vite. `env: { BANK: bank }` gives the app's Worker a binding to the bank, and `runWorkerFirst` sends `/api` through it.
467
468 ## Run it
469
470 ```sh
471 bun alchemy dev
472 ```
473
474 Open the `app` URL it prints, with `?customer=c-2`: Part 5's script already gave `c-1` an account. Open your account, deposit, and the balance updates as the bank records it. Open a second tab with the same customer: both update together.
475
476 ```sh
477 bun alchemy deploy
478 ```
479
480 You've built a bank: an account that keeps its own rules, views that answer questions, a policy that reacts, an Api that checks who's asking, and an app that watches it live.
481
482 :::note
483 Next, [trace a click through the whole bank](/domain/tutorial/part-7). Show changes before the server confirms them with [optimistic updates](/domain/optimistic-updates), and keep working offline with [local first](/domain/local-first). The [bank example](https://github.com/alchemy-run/alchemy/tree/main/examples/cloudflare-domain) adds transfers, fraud checks and support agents.
484 :::