@dim24/servin 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,1625 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # servin
2
+
3
+ **A modern, zero-dependency Node.js web server built around _Domain-Tree Projection_ and _Ambient Wire_.**
4
+
5
+ `servin` lets you build HTTP APIs, static websites, HTML pages, Server-Sent Events (SSE), and WebSockets using plain JavaScript functions and nested object trees. Instead of manually wiring string paths, `(req, res)` handlers, and `next()` middleware chains, you express your backend as a clean JavaScript object hierarchy while `servin` handles routing, parameter type coercion, self-invalidating caching, session persistence, rate limiting, and zero-build frontend client generation automatically.
6
+
7
+ ---
8
+
9
+ ## Table of Contents
10
+
11
+ 1. [Why servin?](#1-why-servin)
12
+ 2. [Requirements & Installation](#2-requirements--installation)
13
+ 3. [Step-by-Step Core Walkthrough](#3-step-by-step-core-walkthrough)
14
+ - [Step 1: Starting the Server (`serve`)](#step-1-starting-the-server-serve)
15
+ - [Step 2: How URL Routing Works & Your First `GET`](#step-2-how-url-routing-works--your-first-get)
16
+ - [Step 3: Reading URL Query Parameters (`?done=true`)](#step-3-reading-url-query-parameters-donetrue)
17
+ - [Step 4: Dynamic URL Segments (`$id`) & Type Rules (`param`)](#step-4-dynamic-url-segments-id--type-rules-param)
18
+ - [Step 5: Creating Data with a Simple `POST`](#step-5-creating-data-with-a-simple-post)
19
+ - [Step 6: Setting HTTP Status Codes & Errors (`wire.status` & `wire.abort`)](#step-6-setting-http-status-codes--errors-wirestatus--wireabort)
20
+ - [Step 7: Updating (`patch` / `'put|patch'`) & Deleting (`delete`)](#step-7-updating-patch--putpatch--deleting-delete)
21
+ - [Step 8: Returning HTML (`wire.html` & `wire.file`)](#step-8-returning-html-wirehtml--wirefile)
22
+ - [Step 9: Assembled CRUD Server](#step-9-assembled-crud-server)
23
+ 4. [Zero-Build Virtual ESM Client (`/@client.js`)](#4-zero-build-virtual-esm-client-clientjs)
24
+ - [4.1 Step 1: Importing `api` in Browser or Frontend Apps](#41-step-1-importing-api-in-browser-or-frontend-apps)
25
+ - [4.2 Step 2: Calling `GET`, `POST`, `PATCH`, `DELETE` & Typed Params](#42-step-2-calling-get-post-patch-delete--typed-params)
26
+ - [4.3 Step 3: Consuming SSE Streams & WebSockets on the Client](#43-step-3-consuming-sse-streams--websockets-on-the-client)
27
+ 5. [Static Routing, Redirects & Custom Error Pages](#5-static-routing-redirects--custom-error-pages)
28
+ - [5.1 Static File & Folder Routing (`serveStatic` & `static`)](#51-static-file--folder-routing-servestatic--static)
29
+ - [5.2 HTTP Redirects (`wire.redirect` & `redirect`)](#52-http-redirects-wireredirect--redirect)
30
+ - [5.3 Custom Error Pages (`404`, `401`, `403`, `500`, etc.)](#53-custom-error-pages-404-401-403-500-etc)
31
+ 6. [Server Configuration (`serve`)](#6-server-configuration-serve)
32
+ - [6.1 All `serve()` Options](#61-all-serve-options)
33
+ - [6.2 Server Instance Control (`port`, `url`, `fetch`, `close`)](#62-server-instance-control-port-url-fetch-close)
34
+ 7. [Domain-Tree Projection & Routing](#7-domain-tree-projection--routing)
35
+ - [7.1 Static, Dynamic, Typed, and Wildcard Segments](#71-static-dynamic-typed-and-wildcard-segments)
36
+ - [7.2 Automatic Route Matching Priority](#72-automatic-route-matching-priority)
37
+ - [7.3 Method Unions (`'put|patch'`) & Shorthand Leaf Functions](#73-method-unions-putpatch--shorthand-leaf-functions)
38
+ - [7.4 Handler Argument Order](#74-handler-argument-order)
39
+ - [7.5 Typed Route Parameters (`param`) — All Supported Types & Custom Formats](#75-typed-route-parameters-param--all-supported-types--custom-formats)
40
+ 8. [Response Formatting, HTML & Streaming](#8-response-formatting-html--streaming)
41
+ - [8.1 Automatic `Content-Type` Matrix](#81-automatic-content-type-matrix)
42
+ - [8.2 HTML Responses & XSS Protection (`wire.html`)](#82-html-responses--xss-protection-wirehtml)
43
+ - [8.3 File Streaming with `ETag` & Byte-Range (`wire.file`)](#83-file-streaming-with-etag--byte-range-wirefile)
44
+ - [8.4 Server-Sent Events (SSE) with Async Generators](#84-server-sent-events-sse-with-async-generators)
45
+ - [8.5 Sparse Fieldsets (`?fields=`) & Automatic Redaction (`redact`)](#85-sparse-fieldsets-fields--automatic-redaction-redact)
46
+ 9. [Security, Sessions & Traffic Control](#9-security-sessions--traffic-control)
47
+ - [9.1 Protecting Routes & Branches (`guard`)](#91-protecting-routes--branches-guard)
48
+ - [9.2 Lazy Encrypted Sessions (`wire.session` & `wire.sessions`)](#92-lazy-encrypted-sessions-wiresession--wiresessions)
49
+ - [9.3 Custom Session Store Interface (Redis / Database)](#93-custom-session-store-interface-redis--database)
50
+ - [9.4 Timing-Safe Webhook Verification (`webhook`)](#94-timing-safe-webhook-verification-webhook)
51
+ - [9.5 Rate Limiting (`limit` & `wire.cost`)](#95-rate-limiting-limit--wirecost)
52
+ - [9.6 CORS & Preflight Handling (`origins`)](#96-cors--preflight-handling-origins)
53
+ 10. [Caching, Validation & Resilience](#10-caching-validation--resilience)
54
+ - [10.1 Self-Invalidating Response Cache (`cache`)](#101-self-invalidating-response-cache-cache)
55
+ - [10.2 Request Coalescing (`coalesce`)](#102-request-coalescing-coalesce)
56
+ - [10.3 Idempotent Mutations (`idempotent`)](#103-idempotent-mutations-idempotent)
57
+ - [10.4 Declarative Input Validation (`expect`)](#104-declarative-input-validation-expect)
58
+ - [10.5 Automatic Rollbacks (`wire.undo`) & Dry-Runs (`X-Simulate`)](#105-automatic-rollbacks-wireundo--dry-runs-x-simulate)
59
+ - [10.6 Graceful Background Tasks (`wire.defer`)](#106-graceful-background-tasks-wiredefer)
60
+ - [10.7 Load Shedding (`priority: 'low'`) & Deprecation (`sunset`)](#107-load-shedding-priority-low--deprecation-sunset)
61
+ 11. [Linear WebSockets & Pub/Sub](#11-linear-websockets--pubsub)
62
+ - [11.1 Step 1: Minimal Echo WebSocket (`ws` & `for await`)](#111-step-1-minimal-echo-websocket-ws--for-await)
63
+ - [11.2 Step 2: Rooms & Pub/Sub Broadcasting (`socket.join`, `wire.publish`)](#112-step-2-rooms--pubsub-broadcasting-socketjoin-wirepublish)
64
+ - [11.3 Step 3: Guarded WebSockets & `wsConfig`](#113-step-3-guarded-websockets--wsconfig)
65
+ 12. [Streaming File Uploads (`wire.multipart` & `rawBody`)](#12-streaming-file-uploads-wiremultipart--rawbody)
66
+ 13. [Decoupled Side Effects (`reactTo`)](#13-decoupled-side-effects-reactto)
67
+ 14. [Logging, Debugging & Automated Testing](#14-logging-debugging--automated-testing)
68
+ - [14.1 Startup Messages & Access Logs (`message`, `onListen`, `accessLog`)](#141-startup-messages--access-logs-message-onlisten-accesslog)
69
+ - [14.2 Error-Triggered Debug Trace (`wire.log.debug`) & `Server-Timing` (`wire.mark`)](#142-error-triggered-debug-trace-wirelogdebug--server-timing-wiremark)
70
+ - [14.3 Automated Test Synthesis (`synthesizeTests`)](#143-automated-test-synthesis-synthesizetests)
71
+ - [14.4 Error Snapshots & Local Replay (`snapshotOnError` & `replay`)](#144-error-snapshots--local-replay-snapshotonerror--replay)
72
+ 15. [Complete Ambient `wire` API Reference](#15-complete-ambient-wire-api-reference)
73
+ 16. [License](#16-license)
74
+
75
+ ---
76
+
77
+ ## 1. Why servin?
78
+
79
+ Conventional Node.js frameworks require you to bind handlers to string URLs, chain `(req, res, next)` middleware, manually parse and validate route parameters, and maintain separate client-side `fetch()` wrappers alongside separate WebSocket and cache-invalidation systems.
80
+
81
+ `servin` replaces that boilerplate with two core concepts:
82
+
83
+ 1. **Domain-Tree Projection:** You structure your backend as a plain nested JavaScript object. `servin` projects that tree directly onto HTTP endpoints, static assets, SSE streams, WebSockets, and a browser-ready ES module (`/@client.js`).
84
+ 2. **Ambient `wire`:** Powered by Node.js `AsyncLocalStorage`, `wire` lets any function read headers, set status codes, issue redirects, manage sessions, register rollbacks, or publish WebSocket messages without passing `req` or `res` arguments down the call stack.
85
+
86
+ ---
87
+
88
+ ## 2. Requirements & Installation
89
+
90
+ - **Runtime:** Node.js `v20.0.0` or higher.
91
+ - **Dependencies:** Zero external dependencies.
92
+ - **Module Format:** ES Modules (`"type": "module"` in `package.json`).
93
+
94
+ Install `servin`:
95
+
96
+ ```bash
97
+ npm install servin
98
+ ```
99
+
100
+ Verify your `package.json` includes `"type": "module"`:
101
+
102
+ ```json
103
+ {
104
+ "name": "my-servin-app",
105
+ "type": "module",
106
+ "scripts": {
107
+ "start": "node server.js"
108
+ }
109
+ }
110
+ ```
111
+
112
+ ---
113
+
114
+ ## 3. Step-by-Step Core Walkthrough
115
+
116
+ ### Step 1: Starting the Server (`serve`)
117
+
118
+ Create `server.js` and call `serve()`. By default, it listens on `127.0.0.1:3000`:
119
+
120
+ ```javascript
121
+ import { serve } from "servin";
122
+
123
+ await serve({
124
+ port: 3000,
125
+ api: {},
126
+ });
127
+ ```
128
+
129
+ You can customize the startup log message using `message`:
130
+
131
+ ```javascript
132
+ import { serve } from "servin";
133
+
134
+ await serve({
135
+ port: 3000,
136
+ message: ({ port }) => `Server is running on port ${port}`,
137
+ api: {},
138
+ });
139
+ ```
140
+
141
+ ### Step 2: How URL Routing Works & Your First `GET`
142
+
143
+ In `servin`, **you never write URL path strings**. Every object key inside `api` becomes a URL segment, and a lowercase HTTP verb (`get`, `post`, `put`, `patch`, `delete`) defines the handler:
144
+
145
+ ```text
146
+ Object Tree HTTP Endpoint
147
+ ───────────────────────────────────────────────────────────────
148
+ api: {
149
+ hello: {
150
+ get() { ... } ──────► GET /hello
151
+ },
152
+ tasks: {
153
+ get() { ... } ──────► GET /tasks
154
+ }
155
+ }
156
+ ```
157
+
158
+ Any plain object or array you `return` is automatically serialized as `application/json` (`200 OK`):
159
+
160
+ ```javascript
161
+ import { serve } from "servin";
162
+
163
+ const tasksDb = [
164
+ { id: 1, title: "Learn servin", done: true },
165
+ { id: 2, title: "Build an API", done: false },
166
+ ];
167
+
168
+ await serve({
169
+ port: 3000,
170
+ api: {
171
+ // GET /hello
172
+ hello: {
173
+ get: () => ({ message: "Hello from servin!" }),
174
+ },
175
+
176
+ // GET /tasks
177
+ tasks: {
178
+ get: () => tasksDb,
179
+ },
180
+ },
181
+ });
182
+ ```
183
+
184
+ ### Step 3: Reading URL Query Parameters (`?done=true`)
185
+
186
+ Every `get()` handler automatically receives a `query` object containing the URL search parameters:
187
+
188
+ ```javascript
189
+ const tasks = {
190
+ // GET /tasks?done=false
191
+ get(query) {
192
+ if (query.done === "true") {
193
+ return tasksDb.filter((t) => t.done);
194
+ }
195
+ if (query.done === "false") {
196
+ return tasksDb.filter((t) => !t.done);
197
+ }
198
+ return tasksDb;
199
+ },
200
+ };
201
+ ```
202
+
203
+ ### Step 4: Dynamic URL Segments (`$id`) & Type Rules (`param`)
204
+
205
+ Prefix a key with `$` to capture a dynamic URL segment:
206
+
207
+ ```javascript
208
+ // Matches ANY string: /tasks/1, /tasks/abc, /tasks/hello
209
+ const tasks = {
210
+ $id: {
211
+ get(id) {
212
+ return { rawId: id }; // `id` is always a string when untyped
213
+ },
214
+ },
215
+ };
216
+ ```
217
+
218
+ To restrict a parameter to a specific type or pattern while keeping object keys as clean JavaScript identifiers, wrap the branch in **`param(rule, branch)`**. `param()` supports built-in types (`'int'`, `'number'`, `'float'`, `'bigint'`, `'uuid'`, `'alpha'`, `'alnum'`, `'slug'`, `'bool'`, `'boolean'`, `'string'`), native constructors (`Number`, `Boolean`, `BigInt`, `String`), regular expressions (`/^[A-Z]{3}-\d+$/`), custom functions, and named custom types from `serve({ types })`.
219
+
220
+ ```javascript
221
+ import { param } from "servin";
222
+
223
+ const tasks = {
224
+ // GET /tasks/1 -> matches! `id` is coerced to number `1`
225
+ // GET /tasks/abc -> automatically rejected with 404 Not Found
226
+ $id: param("int", {
227
+ get(id) {
228
+ return tasksDb.find((t) => t.id === id);
229
+ },
230
+ }),
231
+ };
232
+ ```
233
+
234
+ See [Section 7.5](#75-typed-route-parameters-param--all-supported-types--custom-formats) for every supported type and custom format option.
235
+
236
+ ### Direct Path Parameters on Route Nodes (`wire.params` & `wire.param(name)`)
237
+
238
+ Read trailing path segments directly inside a route handler without creating a separate `$id` child branch.
239
+
240
+ - `GET /profile?id=234` reads query parameters via `wire.url.searchParams.get('id')`.
241
+ - `GET /profile/234` reads the trailing path segment directly via `wire.params.id` or `wire.param('id')`.
242
+
243
+ ````javascript
244
+ import { serve, wire } from './index.js';
245
+
246
+ await serve({
247
+ port: 3000,
248
+ api: {
249
+ profile: {
250
+ get() {
251
+ const id = wire.param('id'); // or wire.params.id
252
+ const queryId = wire.url.searchParams.get('id');
253
+ return { id, queryId };
254
+ }
255
+ }
256
+ }
257
+ });
258
+
259
+ ### Step 5: Creating Data with a Simple `POST`
260
+
261
+ Add a `post(payload)` method to handle `POST /tasks`. `servin` automatically parses the incoming JSON body and passes it as `payload`:
262
+
263
+ ```javascript
264
+ let nextId = 3;
265
+
266
+ const tasks = {
267
+ get: () => tasksDb,
268
+
269
+ // POST /tasks
270
+ post(payload) {
271
+ const newTask = {
272
+ id: nextId++,
273
+ title: payload.title,
274
+ done: false,
275
+ };
276
+ tasksDb.push(newTask);
277
+ return newTask;
278
+ },
279
+ };
280
+ ````
281
+
282
+ ### Step 6: Setting HTTP Status Codes & Errors (`wire.status` & `wire.abort`)
283
+
284
+ Import `wire` when you need to change the HTTP status code or stop a request with an error:
285
+
286
+ - `wire.status(201)` sets the response status to `201 Created`.
287
+ - `wire.abort(404, 'Message')` immediately stops execution and returns `{ "error": "Message" }` with status `404`.
288
+
289
+ ```javascript
290
+ import { wire, param } from "servin";
291
+
292
+ const tasks = {
293
+ post(payload) {
294
+ const newTask = { id: nextId++, title: payload.title, done: false };
295
+ tasksDb.push(newTask);
296
+
297
+ wire.status(201); // Return 201 Created instead of 200
298
+ return newTask;
299
+ },
300
+
301
+ $id: param("int", {
302
+ get(id) {
303
+ const task = tasksDb.find((t) => t.id === id);
304
+ if (!task) wire.abort(404, `Task #${id} not found`);
305
+ return task;
306
+ },
307
+ }),
308
+ };
309
+ ```
310
+
311
+ ### Step 7: Updating (`patch` / `'put|patch'`) & Deleting (`delete`)
312
+
313
+ Add `patch` (or `'put|patch'` to handle both verbs in one function) and `delete` inside `$id`:
314
+
315
+ ```javascript
316
+ const taskById = param("int", {
317
+ get(id) {
318
+ const task = tasksDb.find((t) => t.id === id);
319
+ if (!task) wire.abort(404, `Task #${id} not found`);
320
+ return task;
321
+ },
322
+
323
+ // PATCH /tasks/:id
324
+ patch(id, payload) {
325
+ const task = tasksDb.find((t) => t.id === id);
326
+ if (!task) wire.abort(404, `Task #${id} not found`);
327
+ Object.assign(task, payload);
328
+ return task;
329
+ },
330
+
331
+ // DELETE /tasks/:id
332
+ delete(id) {
333
+ const idx = tasksDb.findIndex((t) => t.id === id);
334
+ if (idx === -1) wire.abort(404, `Task #${id} not found`);
335
+ tasksDb.splice(idx, 1);
336
+ wire.status(204);
337
+ return null; // Sends empty 204 No Content
338
+ },
339
+ });
340
+ ```
341
+
342
+ ### Step 8: Returning HTML (`wire.html` & `wire.file`)
343
+
344
+ By default, returning a plain `string` sends `text/plain` so user text cannot accidentally execute scripts. To serve HTML:
345
+
346
+ **Option A — Inline HTML string with `wire.html`:**
347
+
348
+ ```javascript
349
+ const home = {
350
+ get: () => wire.html("<h1>Welcome to Task Manager</h1>"),
351
+ };
352
+ ```
353
+
354
+ **Option B — Tagged template ``wire.html`...` `` (auto-escapes variables against XSS):**
355
+
356
+ ```javascript
357
+ const greet = {
358
+ $name: {
359
+ get(name) {
360
+ return wire.html`<h1>Hello, ${name}!</h1>`;
361
+ },
362
+ },
363
+ };
364
+ ```
365
+
366
+ **Option C — Streaming an HTML file from disk with `wire.file`:**
367
+
368
+ ```javascript
369
+ const about = {
370
+ get: () => wire.file("./pages/about.html"),
371
+ };
372
+ ```
373
+
374
+ ### Step 9: Assembled CRUD Server
375
+
376
+ Combining Steps 1–8 gives you a complete, readable CRUD server:
377
+
378
+ ```javascript
379
+ import { serve, wire, param } from "servin";
380
+
381
+ const tasksDb = [
382
+ { id: 1, title: "Learn servin", done: true },
383
+ { id: 2, title: "Build an API", done: false },
384
+ ];
385
+ let nextId = 3;
386
+
387
+ const tasks = {
388
+ get(query) {
389
+ if (query.done === "true") return tasksDb.filter((t) => t.done);
390
+ if (query.done === "false") return tasksDb.filter((t) => !t.done);
391
+ return tasksDb;
392
+ },
393
+
394
+ post(payload) {
395
+ const newTask = { id: nextId++, title: payload.title, done: false };
396
+ tasksDb.push(newTask);
397
+ wire.status(201);
398
+ return newTask;
399
+ },
400
+
401
+ $id: param("int", {
402
+ get(id) {
403
+ const task = tasksDb.find((t) => t.id === id);
404
+ if (!task) wire.abort(404, `Task #${id} not found`);
405
+ return task;
406
+ },
407
+
408
+ patch(id, payload) {
409
+ const task = tasksDb.find((t) => t.id === id);
410
+ if (!task) wire.abort(404, `Task #${id} not found`);
411
+ Object.assign(task, payload);
412
+ return task;
413
+ },
414
+
415
+ delete(id) {
416
+ const idx = tasksDb.findIndex((t) => t.id === id);
417
+ if (idx === -1) wire.abort(404, `Task #${id} not found`);
418
+ tasksDb.splice(idx, 1);
419
+ wire.status(204);
420
+ return null;
421
+ },
422
+ }),
423
+ };
424
+
425
+ await serve({
426
+ port: 3000,
427
+ message: ({ port }) => `Server is running on port ${port}`,
428
+ api: {
429
+ home: { get: () => wire.html("<h1>Task Manager</h1>") },
430
+ tasks,
431
+ },
432
+ });
433
+ ```
434
+
435
+ ---
436
+
437
+ ## 4. Zero-Build Virtual ESM Client (`/@client.js`)
438
+
439
+ Because `servin` compiles your `api` tree at startup, it automatically serves **`GET /@client.js`**—a lightweight, zero-dependency ES module that mirrors your exact backend domain structure.
440
+
441
+ Frontend code (vanilla HTML `<script type="module">`, React, Vue, Svelte, or Vite) can import `api` directly from `/@client.js` **without writing `fetch()`, URL strings, JSON serialization, or build-step code generators**.
442
+
443
+ ### 4.1 Step 1: Importing `api` in Browser or Frontend Apps
444
+
445
+ **Same-origin HTML page served by `servin`:**
446
+
447
+ ```html
448
+ <!doctype html>
449
+ <html>
450
+ <body>
451
+ <ul id="list"></ul>
452
+
453
+ <script type="module">
454
+ import { api } from "/@client.js";
455
+
456
+ const tasks = await api.tasks.get();
457
+ document.getElementById("list").innerHTML = tasks
458
+ .map((t) => `<li>${t.title}</li>`)
459
+ .join("");
460
+ </script>
461
+ </body>
462
+ </html>
463
+ ```
464
+
465
+ **Separate frontend dev server (e.g., Vite on `:5173` calling `servin` on `:3000`):**
466
+
467
+ ```javascript
468
+ import { api } from "http://localhost:3000/@client.js";
469
+
470
+ const tasks = await api.tasks.get();
471
+
472
+ // GET with custom header
473
+ const profile = await api.profile.get(authHeaders);
474
+
475
+ // GET with query + header
476
+ const orders = await api.v1.orders.get({ page: 1 }, authHeaders);
477
+
478
+ // POST with body + header
479
+ const created = await api.v1.orders.post(
480
+ { item: "Keyboard", qty: 2 },
481
+ authHeaders,
482
+ );
483
+ ```
484
+
485
+ ### 4.2 Step 2: Calling `GET`, `POST`, `PATCH`, `DELETE` & Typed Params
486
+
487
+ Every method call on `api` matches the exact shape of your server's `api` tree and automatically includes credentials (`HttpOnly` session cookies) and JSON headers:
488
+
489
+ ```javascript
490
+ import { api } from "/@client.js";
491
+
492
+ // 1. GET /tasks?done=false
493
+ const pending = await api.tasks.get({ done: "false" });
494
+
495
+ // 2. POST /tasks
496
+ const created = await api.tasks.post({ title: "Ship v1.0" });
497
+
498
+ // 3. GET /tasks/1 (passes `1` into `$id`)
499
+ const single = await api.tasks.$id.get(1);
500
+
501
+ // 4. PATCH /tasks/1 (first arg is `$id`, second arg is JSON body)
502
+ const updated = await api.tasks.$id.patch(1, { done: true });
503
+
504
+ // 5. DELETE /tasks/1 (returns `null` on 204 No Content)
505
+ await api.tasks.$id.delete(1);
506
+ ```
507
+
508
+ ### 4.3 Step 3: Consuming SSE Streams & WebSockets on the Client
509
+
510
+ `/@client.js` also translates Server-Sent Events and WebSockets into standard JavaScript `for await...of` async iterators:
511
+
512
+ ```javascript
513
+ import { api } from "/@client.js";
514
+
515
+ // 1. Consuming an SSE endpoint (async *get())
516
+ for await (const tick of api.clock.get()) {
517
+ console.log("Server tick:", tick);
518
+ }
519
+
520
+ // 2. Consuming a WebSocket endpoint (async ws(room, socket))
521
+ const room = api.chat.$room.ws("general");
522
+ room.send({ text: "Hello everyone!" });
523
+
524
+ for await (const message of room) {
525
+ console.log("Chat message:", message);
526
+ }
527
+ ```
528
+
529
+ ---
530
+
531
+ ## 5. Static Routing, Redirects & Custom Error Pages
532
+
533
+ ### 5.1 Static File & Folder Routing (`serveStatic` & `static`)
534
+
535
+ `servin` serves static files and entire directories with automatic MIME detection, `ETag` (`304 Not Modified`), `Byte-Range` streaming (`206 Partial Content`), directory `index.html` resolution, and built-in path-traversal protection.
536
+
537
+ **Step 1 — Mount static folders or single files via `serve({ static })`:**
538
+
539
+ ```javascript
540
+ import { serve } from "servin";
541
+
542
+ await serve({
543
+ port: 3000,
544
+ static: {
545
+ "/assets": "./public/assets", // Serves entire directory at /assets/*
546
+ "/favicon.ico": "./public/favicon.ico", // Serves a single file at /favicon.ico
547
+ },
548
+ api: {
549
+ health: { get: () => ({ ok: true }) },
550
+ },
551
+ });
552
+ ```
553
+
554
+ **Step 2 — Mount static directories inside the `api` tree with `serveStatic()` (and combine with `guard()`):**
555
+
556
+ ```javascript
557
+ import { serve, guard, serveStatic } from "servin";
558
+
559
+ await serve({
560
+ port: 3000,
561
+ api: {
562
+ // Public documentation folder with Cache-Control header
563
+ docs: serveStatic("./public/docs", {
564
+ index: "index.html",
565
+ cacheControl: "public, max-age=3600",
566
+ }),
567
+
568
+ // Protected downloads folder requiring login
569
+ downloads: guard(
570
+ requireAuth,
571
+ serveStatic("./storage/private", {
572
+ dotfiles: "deny", // Returns 403 Forbidden for .env, .git, etc.
573
+ }),
574
+ ),
575
+ },
576
+ });
577
+ ```
578
+
579
+ **Step 3 — Single-Page Application (SPA) fallback mode:**
580
+
581
+ Set `spa: true` so client-side routes (like `/app/settings/profile`) automatically fall back to `index.html` when no matching asset file exists:
582
+
583
+ ```javascript
584
+ const api = {
585
+ app: serveStatic("./dist", {
586
+ spa: true,
587
+ index: "index.html",
588
+ }),
589
+ };
590
+ ```
591
+
592
+ **All `serveStatic(targetPath, options)` options:**
593
+
594
+ | Option | Type | Default | Description |
595
+ | :------------- | :------------------------------ | :------------- | :---------------------------------------------------------------------------------------- |
596
+ | `index` | `string \| false` | `'index.html'` | Default file served when a directory URL is requested. Set `false` to disable. |
597
+ | `dotfiles` | `'ignore' \| 'deny' \| 'allow'` | `'ignore'` | How files/folders starting with `.` (e.g., `.env`) are handled (`404`, `403`, or served). |
598
+ | `cacheControl` | `string \| null` | `null` | Optional `Cache-Control` response header (e.g., `'public, max-age=86400'`). |
599
+ | `spa` | `boolean` | `false` | Falls back to `index` (or `fallback`) when a requested sub-path is not found. |
600
+ | `fallback` | `string \| null` | `null` | Custom fallback HTML file path when `spa: true` is enabled. |
601
+
602
+ ### 5.2 HTTP Redirects (`wire.redirect` & `redirect`)
603
+
604
+ **1. Declarative redirects in the `api` tree (`redirect(target, status = 301)`):**
605
+
606
+ ```javascript
607
+ import { serve, param, redirect } from "servin";
608
+
609
+ await serve({
610
+ port: 3000,
611
+ api: {
612
+ // Static permanent redirect: GET /old-blog -> 301 Location: /articles
613
+ "old-blog": redirect("/articles", 301),
614
+
615
+ // Dynamic redirect using extracted route parameters & query:
616
+ promo: {
617
+ $code: param(
618
+ "alnum",
619
+ redirect((code, query) => {
620
+ const ref = query.ref ? `&ref=${encodeURIComponent(query.ref)}` : "";
621
+ return `/checkout?voucher=${code}${ref}`;
622
+ }, 302),
623
+ ),
624
+ },
625
+ },
626
+ });
627
+ ```
628
+
629
+ **2. Imperative redirects inside handlers (`wire.redirect(location, status = 302)`):**
630
+
631
+ Calling `wire.redirect()` immediately halts handler execution, **commits any newly created/updated `wire.session` cookies**, and sends the redirect response:
632
+
633
+ ```javascript
634
+ const auth = {
635
+ login: {
636
+ async post({ email }) {
637
+ await wire.session.rotate();
638
+ wire.session.user = email;
639
+
640
+ // Session cookie is automatically attached to this 302 redirect response
641
+ wire.redirect("/dashboard");
642
+ },
643
+ },
644
+ };
645
+ ```
646
+
647
+ ### 5.3 Custom Error Pages (`404`, `401`, `403`, `500`, etc.)
648
+
649
+ Configure `errors` in `serve()` to customize responses for specific HTTP status codes (`404`, `401`, `403`, `405`, `422`, `429`, `500`), status ranges (`'4xx'`, `'5xx'`), or `default`.
650
+
651
+ An error handler can return **`wire.html`**, **`wire.file()`**, a **JSON object**, a **plain string**, or trigger **`wire.redirect()`**:
652
+
653
+ ```javascript
654
+ import { serve, wire, guard } from "servin";
655
+
656
+ const requireAdmin = () => {
657
+ if (!wire.session.user) wire.abort(401, "Authentication required");
658
+ if (wire.session.role !== "admin")
659
+ wire.abort(403, "Administrator access required");
660
+ };
661
+
662
+ await serve({
663
+ port: 3000,
664
+ session: { secret: "replace-with-32-char-secret-key!!" },
665
+
666
+ errors: {
667
+ // 1. Custom 404 Not Found HTML page
668
+ 404({ path }) {
669
+ return wire.html`
670
+ <h1>404 — Page Not Found</h1>
671
+ <p>No route matches <code>${path}</code>.</p>
672
+ <a href="/">Back to Home</a>
673
+ `;
674
+ },
675
+
676
+ // 2. Custom 401 Unauthorized: redirect browsers to /login, return JSON for API clients
677
+ 401({ message }) {
678
+ const accept = wire.headers.get("accept") || "";
679
+ if (accept.includes("text/html")) {
680
+ return wire.redirect("/login");
681
+ }
682
+ return { error: "Unauthorized", reason: message };
683
+ },
684
+
685
+ // 3. Custom 403 Forbidden: stream a static HTML file while keeping status 403
686
+ 403: wire.file("./pages/403.html"),
687
+
688
+ // 4. Custom 500 Internal Server Error
689
+ 500() {
690
+ return wire.html`<h1>500 — Something went wrong on our end</h1>`;
691
+ },
692
+ },
693
+
694
+ api: {
695
+ admin: guard(requireAdmin, {
696
+ get: () => wire.html`<h1>Welcome, Admin ${wire.session.user}</h1>`,
697
+ }),
698
+ },
699
+ });
700
+ ```
701
+
702
+ **Context passed to custom error functions `errors[code](ctx)`:**
703
+
704
+ | Property | Type | Description |
705
+ | :-------- | :-------------- | :-------------------------------------------------------------------------- |
706
+ | `status` | `number` | HTTP status code being returned (e.g., `404`, `401`, `403`, `500`). |
707
+ | `message` | `string` | Default error message (e.g., the message passed to `wire.abort(401, msg)`). |
708
+ | `details` | `any` | Validation field details when `status === 422`. |
709
+ | `path` | `string` | Request URL pathname (e.g., `'/admin'`). |
710
+ | `method` | `string` | Uppercase HTTP method (e.g., `'GET'`). |
711
+ | `error` | `Error \| null` | Original thrown error instance if available. |
712
+ | `wire` | `object` | Active `wire` ambient context handle. |
713
+
714
+ ---
715
+
716
+ ## 6. Server Configuration (`serve`)
717
+
718
+ ### 6.1 All `serve()` Options
719
+
720
+ | Option | Type | Default | Description |
721
+ | :---------------- | :------------------------------------- | :---------------------------- | :---------------------------------------------------------------------------------------- |
722
+ | `port` | `number` | `3000` | TCP port to listen on. Pass `0` for a random OS-assigned port. |
723
+ | `host` | `string` | `'127.0.0.1'` | Host interface to bind (use `'0.0.0.0'` inside Docker/containers). |
724
+ | `api` | `object` | `{}` | Root domain object defining all routes. |
725
+ | `static` | `string \| StaticDescriptor \| object` | `null` | Root or prefix-mapped static files/directories (e.g., `{ '/assets': './public' }`). |
726
+ | `errors` | `object` | `undefined` | Custom status handlers (`404`, `401`, `403`, `500`, `'4xx'`, `'5xx'`, `default`). |
727
+ | `types` | `object` | `{}` | Named custom parameter types usable via `param('typeName', branch)`. |
728
+ | `session` | `object \| null` | `null` | Session config `{ secret, ttl, cookieName, rolling, secure, sameSite, store }`. |
729
+ | `origins` | `string[]` | `undefined` | Allowed CORS origins (e.g., `['https://app.example.com']` or `['*']`). |
730
+ | `redact` | `string[]` | `undefined` | Wildcard keys (e.g., `['password*', '*.secret']`) stripped from all JSON responses. |
731
+ | `message` | `string \| function \| false` | `"[servin] listening on ..."` | Custom startup log message or `false` to silence startup output. |
732
+ | `onListen` | `function` | `undefined` | Sync/async callback `({ port, host, url }) => void` run when listening starts. |
733
+ | `accessLog` | `boolean \| function` | `true` | Enables per-request access logs or accepts a custom formatter `(info) => string \| null`. |
734
+ | `silent` | `boolean` | `false` | Disables both startup and access logs. |
735
+ | `lagThresholdMs` | `number` | `60` | Event-loop p95 delay threshold (ms) before `priority: 'low'` routes return `503`. |
736
+ | `synthesizeTests` | `string` | `undefined` | File path where verified requests are recorded as `node:test` test cases. |
737
+ | `snapshotOnError` | `string` | `undefined` | Directory where `500` error snapshots are saved for local `replay()`. |
738
+ | `onError` | `function` | `undefined` | Custom unhandled error formatter `(err, { req }) => Response \| object`. |
739
+
740
+ ### 6.2 Server Instance Control (`port`, `url`, `fetch`, `close`)
741
+
742
+ ```javascript
743
+ const app = await serve({
744
+ port: 0,
745
+ api: { ping: { get: () => ({ pong: true }) } },
746
+ });
747
+
748
+ console.log(app.port); // Actual assigned port
749
+ console.log(app.url); // e.g. "http://127.0.0.1:51234"
750
+
751
+ // Call routes directly in-memory without network overhead:
752
+ const res = await app.fetch(new Request("http://localhost/ping"));
753
+ console.log(await res.json()); // { pong: true }
754
+
755
+ // Shut down server and wait for pending wire.defer() tasks:
756
+ await app.close();
757
+ ```
758
+
759
+ ---
760
+
761
+ ## 7. Domain-Tree Projection & Routing
762
+
763
+ ### 7.1 Static, Dynamic, Typed, and Wildcard Segments
764
+
765
+ - **Static (`users`):** Matches `/users` literally.
766
+ - **Dynamic (`$username`):** Matches any single URL segment as a string.
767
+ - **Typed Dynamic (`$id: param(...)`):** Validates and converts the segment type before matching.
768
+ - **Wildcard (`$path`):** Captures all remaining trailing path segments joined by `/`.
769
+
770
+ ```javascript
771
+ const api = {
772
+ users: {
773
+ me: { get: () => "static" }, // GET /users/me
774
+ $id: param("int", { get: (id) => ({ id }) }), // GET /users/42
775
+ $username: { get: (u) => ({ username: u }) }, // GET /users/nadia
776
+ },
777
+ files: {
778
+ $path: { get: (path) => ({ path }) }, // GET /files/docs/2026/a.pdf
779
+ },
780
+ };
781
+ ```
782
+
783
+ ### 7.2 Automatic Route Matching Priority
784
+
785
+ Regardless of object key order, `servin` always matches segments from most specific to least specific:
786
+
787
+ 1. **Static segments** (`me`)
788
+ 2. **Typed parameters** (`$id: param(...)`)
789
+ 3. **Untyped parameters** (`$username`)
790
+ 4. **Wildcard catch-all** (`$path` or `serveStatic` mount)
791
+
792
+ ### 7.3 Method Unions (`'put|patch'`) & Shorthand Leaf Functions
793
+
794
+ **1. Method Unions:** Share one handler across multiple HTTP verbs using `|`:
795
+
796
+ ```javascript
797
+ const items = {
798
+ $id: param("int", {
799
+ "put|patch"(id, payload) {
800
+ return { methodUsed: wire.method, id, payload };
801
+ },
802
+ }),
803
+ };
804
+ ```
805
+
806
+ **2. Shorthand Leaf Functions:** Assigning a function directly to a non-verb key creates a route automatically:
807
+
808
+ - Normal function $\rightarrow$ **`POST`**
809
+ - Async generator (`async *`) $\rightarrow$ **`GET`** (SSE stream)
810
+
811
+ ```javascript
812
+ const actions = {
813
+ // POST /actions/sync
814
+ sync(payload) {
815
+ return { synced: true, payload };
816
+ },
817
+
818
+ // GET /actions/events (SSE stream)
819
+ async *events() {
820
+ yield { status: "started" };
821
+ yield { status: "finished" };
822
+ },
823
+ };
824
+ ```
825
+
826
+ ### 7.4 Handler Argument Order
827
+
828
+ Arguments are always passed in this order:
829
+
830
+ 1. URL parameters (`$...`) from left to right.
831
+ 2. Parsed `payload` (only for `POST`, `PUT`, `PATCH`).
832
+ 3. `query` object (`url.searchParams`) as the final argument.
833
+
834
+ ```javascript
835
+ // PATCH /orgs/10/members/550e8400-e29b-41d4-a716-446655440000?notify=true
836
+ const orgs = {
837
+ $orgId: param("int", {
838
+ members: {
839
+ $memberId: param("uuid", {
840
+ patch(orgId, memberId, payload, query) {
841
+ return { orgId, memberId, payload, notify: query.notify };
842
+ },
843
+ }),
844
+ },
845
+ }),
846
+ };
847
+ ```
848
+
849
+ ### 7.5 Typed Route Parameters (`param`) — All Supported Types & Custom Formats
850
+
851
+ `param(rule, branch)` keeps object keys as clean JavaScript identifiers without string quotes. When a URL segment does not satisfy `rule`, `servin` treats that route branch as non-matching (falling through to other routes or returning `404 Not Found`). When it does satisfy `rule`, `servin` passes the **converted value** directly into your handler.
852
+
853
+ You can supply `rule` in **five ways**:
854
+
855
+ #### A. Built-in String Type Names
856
+
857
+ | Rule | Validation | Coerced JS Type | Example Match | Example Rejected (`404`) |
858
+ | :---------- | :--------------------------------------- | :------------------- | :------------------------------------- | :----------------------- |
859
+ | `'int'` | Non-negative safe integer (`/^\d+$/`) | `number` | `0`, `42` | `-1`, `3.14`, `42abc` |
860
+ | `'number'` | Signed integer or decimal | `number` | `-10`, `19.99` | `10px`, `abc` |
861
+ | `'float'` | Alias for `'number'` | `number` | `-0.5`, `12.34` | `abc` |
862
+ | `'bigint'` | Arbitrary-precision integer | `bigint` | `9007199254740993` | `12.5`, `abc` |
863
+ | `'uuid'` | Standard UUID v1–v5 | `string` (lowercase) | `550e8400-e29b-41d4-a716-446655440000` | `12345`, `not-uuid` |
864
+ | `'alpha'` | Letters only (`a-z`, `A-Z`) | `string` | `Indonesia` | `id2`, `en-US` |
865
+ | `'alnum'` | Letters and digits (`a-z`, `A-Z`, `0-9`) | `string` | `v2026` | `v-2026` |
866
+ | `'slug'` | Lowercase kebab-case (`a-z`, `0-9`, `-`) | `string` | `hello-world` | `Hello_World` |
867
+ | `'bool'` | `'true'`, `'1'`, `'false'`, `'0'` | `boolean` | `true`, `1`, `0` | `yes`, `2` |
868
+ | `'boolean'` | Alias for `'bool'` | `boolean` | `true`, `false` | `maybe` |
869
+ | `'string'` | Any URI-decoded string | `string` | `anything` | Invalid `%` encoding |
870
+
871
+ ```javascript
872
+ const users = {
873
+ $id: param("int", {
874
+ get: (id) => ({ id, isNumber: typeof id === "number" }),
875
+ }),
876
+ $handle: param("slug", {
877
+ get: (handle) => ({ handle }),
878
+ }),
879
+ };
880
+ ```
881
+
882
+ #### B. Native JavaScript Constructors
883
+
884
+ Pass `Number`, `Boolean`, `BigInt`, or `String` directly:
885
+
886
+ ```javascript
887
+ const posts = {
888
+ $id: param(Number, { get: (id) => ({ id }) }),
889
+ $published: param(Boolean, { get: (flag) => ({ published: flag }) }),
890
+ $ledgerId: param(BigInt, { get: (val) => ({ ledgerId: val.toString() }) }),
891
+ };
892
+ ```
893
+
894
+ #### C. Inline `RegExp` Literals (Custom Formats)
895
+
896
+ Pass any `RegExp` literal directly for custom code formats, SKUs, or structured identifiers:
897
+
898
+ ```javascript
899
+ const products = {
900
+ // Matches /products/SKU-1024, rejects /products/sku-1024 or /products/1024
901
+ $sku: param(/^[A-Z]{3}-\d{4}$/, {
902
+ get: (sku) => ({ sku }),
903
+ }),
904
+ };
905
+ ```
906
+
907
+ #### D. Custom Validator / Transformer Function
908
+
909
+ Pass a function `(rawSegment) => parsedValue | null | undefined | false`:
910
+
911
+ - Return any non-null, non-undefined value (other than `false`) to **accept** and pass that returned value to the handler.
912
+ - Return `null`, `undefined`, or `false` (or throw an error) to **reject** (`404`).
913
+
914
+ ```javascript
915
+ const events = {
916
+ // Parses "YYYY-MM-DD" into a real Date instance
917
+ $date: param(
918
+ (raw) => {
919
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(raw)) return null;
920
+ const d = new Date(`${raw}T00:00:00Z`);
921
+ return Number.isNaN(d.getTime()) ? null : d;
922
+ },
923
+ {
924
+ get: (date) => ({ iso: date.toISOString() }),
925
+ },
926
+ ),
927
+ };
928
+ ```
929
+
930
+ #### E. Global Reusable Custom Types (`serve({ types })`)
931
+
932
+ Define named types once in `serve({ types })`—using either a `RegExp` or a validator function—and reference them by string name anywhere in your tree:
933
+
934
+ ```javascript
935
+ await serve({
936
+ port: 3000,
937
+ types: {
938
+ invoiceCode: /^INV-\d{6}$/,
939
+ positiveInt: (raw) => {
940
+ const n = Number(raw);
941
+ return Number.isInteger(n) && n > 0 ? n : null;
942
+ },
943
+ },
944
+ api: {
945
+ invoices: {
946
+ $code: param("invoiceCode", { get: (code) => ({ code }) }),
947
+ },
948
+ pages: {
949
+ $page: param("positiveInt", { get: (page) => ({ page }) }),
950
+ },
951
+ },
952
+ });
953
+ ```
954
+
955
+ ---
956
+
957
+ ## 8. Response Formatting, HTML & Streaming
958
+
959
+ ### 8.1 Automatic `Content-Type` Matrix
960
+
961
+ | Return Value | Status | `Content-Type` | Notes |
962
+ | :------------------------------ | :---------------- | :--------------------------------- | :---------------------------------------------------------- |
963
+ | Object / Array | `200` | `application/json` | Applies `redact` and `?fields=` automatically. |
964
+ | `wire.html(...)` | `200` | `text/html; charset=utf-8` | Sends rendered HTML. |
965
+ | `wire.file(path)` | `200`/`206`/`304` | Auto from extension | Streams file with `ETag` and `Range` support. |
966
+ | `string` | `200` | `text/plain; charset=utf-8` | Plain text (unless `Content-Type` header was set manually). |
967
+ | `null` / `undefined` | `204` | _(none)_ | Empty response body. |
968
+ | `async *generator()` | `200` | `text/event-stream; charset=utf-8` | Streams SSE `data: <json>\n\n` frames. |
969
+ | `ReadableStream` / `Uint8Array` | `200` | _(user-defined)_ | Streams raw binary bytes. |
970
+ | Web `Response` | Custom | Custom | Sent as-is. |
971
+
972
+ ### 8.2 HTML Responses & XSS Protection (`wire.html`)
973
+
974
+ **1. Raw HTML string:**
975
+
976
+ ```javascript
977
+ const page = {
978
+ get: () => wire.html("<h1>Hello World</h1>"),
979
+ };
980
+ ```
981
+
982
+ **2. Tagged template literal (auto-escapes untrusted variables against XSS):**
983
+
984
+ ```javascript
985
+ const profile = {
986
+ $name: {
987
+ get(name) {
988
+ // If `name` is "<script>alert(1)</script>", it is safely escaped to &lt;script&gt;...
989
+ return wire.html`<h1>Profile: ${name}</h1>`;
990
+ },
991
+ },
992
+ };
993
+ ```
994
+
995
+ **3. Composing nested `wire.html` fragments safely:**
996
+
997
+ ```javascript
998
+ const dashboard = {
999
+ get() {
1000
+ const items = ["Apples", "Bananas"].map(
1001
+ (item) => wire.html`<li>${item}</li>`,
1002
+ );
1003
+ // Nested `wire.html` values and arrays are NOT double-escaped
1004
+ return wire.html`<ul>${items}</ul>`;
1005
+ },
1006
+ };
1007
+ ```
1008
+
1009
+ ### 8.3 File Streaming with `ETag` & Byte-Range (`wire.file`)
1010
+
1011
+ ```javascript
1012
+ const landing = {
1013
+ get: () => wire.file("./public/index.html"),
1014
+ };
1015
+ ```
1016
+
1017
+ ### 8.4 Server-Sent Events (SSE) with Async Generators
1018
+
1019
+ Use `async *get()` to stream live updates. If the client disconnects early, `servin` automatically stops the generator and runs any `wire.undo()` cleanup:
1020
+
1021
+ ```javascript
1022
+ const clock = {
1023
+ async *get() {
1024
+ for (let i = 0; i < 5; i++) {
1025
+ yield { tick: i, time: new Date().toISOString() };
1026
+ await new Promise((r) => setTimeout(r, 1000));
1027
+ }
1028
+ },
1029
+ };
1030
+ ```
1031
+
1032
+ ### 8.5 Sparse Fieldsets (`?fields=`) & Automatic Redaction (`redact`)
1033
+
1034
+ - **`redact`:** Strips sensitive keys globally from all JSON responses.
1035
+ - **`?fields=`:** Allows clients on any `GET` endpoint to request only the fields they need.
1036
+
1037
+ ```javascript
1038
+ await serve({
1039
+ port: 3000,
1040
+ redact: ["password*", "*.secret"],
1041
+ api: {
1042
+ users: {
1043
+ get: () => [
1044
+ {
1045
+ id: 1,
1046
+ name: "Nadia",
1047
+ email: "nadia@example.com",
1048
+ passwordHash: "xyz",
1049
+ },
1050
+ ],
1051
+ },
1052
+ },
1053
+ });
1054
+ // GET /users?fields=id,name -> [{ "id": 1, "name": "Nadia" }]
1055
+ ```
1056
+
1057
+ ---
1058
+
1059
+ ## 9. Security, Sessions & Traffic Control
1060
+
1061
+ ### 9.1 Protecting Routes & Branches (`guard`)
1062
+
1063
+ **Step 1 — Guard a single endpoint:**
1064
+
1065
+ ```javascript
1066
+ import { wire, guard } from "servin";
1067
+
1068
+ function requireAuth() {
1069
+ if (!wire.session.userId) wire.abort(401, "Please sign in");
1070
+ }
1071
+
1072
+ const secretNote = guard(requireAuth, {
1073
+ get: () => ({ secret: "Top secret data" }),
1074
+ });
1075
+ ```
1076
+
1077
+ **Step 2 — Guard an entire branch and stack multiple guards:**
1078
+
1079
+ ```javascript
1080
+ function requireAdmin() {
1081
+ if (wire.session.role !== "admin") wire.abort(403, "Admins only");
1082
+ }
1083
+
1084
+ // `requireAuth` runs first on everything inside `dashboard`,
1085
+ // and `requireAdmin` also runs on everything inside `admin`.
1086
+ const dashboard = guard(requireAuth, {
1087
+ overview: {
1088
+ get: () => ({ userId: wire.session.userId }),
1089
+ },
1090
+ admin: guard(requireAdmin, {
1091
+ settings: {
1092
+ get: () => ({ maintenanceMode: false }),
1093
+ },
1094
+ }),
1095
+ });
1096
+ ```
1097
+
1098
+ ### 9.2 Lazy Encrypted Sessions (`wire.session` & `wire.sessions`)
1099
+
1100
+ Sessions use AES-256-GCM encrypted `HttpOnly` cookies and are **completely lazy**: if a route never reads or writes `wire.session`, cookies are never decrypted and the session store is never touched.
1101
+
1102
+ **Step 1 — Enable sessions in `serve()` and read/write properties:**
1103
+
1104
+ ```javascript
1105
+ await serve({
1106
+ port: 3000,
1107
+ session: { secret: "replace-with-32-char-secret-key!!" },
1108
+ api: {
1109
+ counter: {
1110
+ get() {
1111
+ wire.session.views = (wire.session.views || 0) + 1;
1112
+ return { views: wire.session.views };
1113
+ },
1114
+ },
1115
+ },
1116
+ });
1117
+ ```
1118
+
1119
+ **Step 2 — Rotate session ID on login & destroy on logout:**
1120
+
1121
+ ```javascript
1122
+ const auth = {
1123
+ login: {
1124
+ async post({ userId, role }) {
1125
+ await wire.session.rotate(); // Prevents session fixation
1126
+ wire.session.userId = userId;
1127
+ wire.session.role = role;
1128
+ return { loggedIn: true };
1129
+ },
1130
+ },
1131
+ logout: {
1132
+ post() {
1133
+ wire.session = null; // Deletes store record, clears cookie, closes active WS
1134
+ return { loggedOut: true };
1135
+ },
1136
+ },
1137
+ };
1138
+ ```
1139
+
1140
+ **Step 3 — Multi-device session listing & remote revocation:**
1141
+
1142
+ ```javascript
1143
+ const devices = {
1144
+ // Bind session to a userId during login: `wire.session.bind(userId)`
1145
+ get: () => wire.sessions.list(wire.session.userId),
1146
+
1147
+ revokeOthers: {
1148
+ async post() {
1149
+ const count = await wire.sessions.revokeOthers(wire.session.userId);
1150
+ return { revokedDevices: count };
1151
+ },
1152
+ },
1153
+ };
1154
+ ```
1155
+
1156
+ ### 9.3 Custom Session Store Interface (Redis / Database)
1157
+
1158
+ Pass a custom `store` object to `session` for multi-server deployments:
1159
+
1160
+ ```javascript
1161
+ const customStore = {
1162
+ async get(sid) {
1163
+ /* return { userId, data, createdAt, updatedAt, expiresAt } | null */
1164
+ },
1165
+ async set(sid, record) {
1166
+ /* persist record */
1167
+ },
1168
+ async delete(sid) {
1169
+ /* delete sid */
1170
+ },
1171
+ async listByUser(userId) {
1172
+ /* return array of active session summaries */
1173
+ },
1174
+ async revokeOthers(userId, currentSid) {
1175
+ /* delete all user sessions except currentSid; return revoked sids */
1176
+ },
1177
+ };
1178
+
1179
+ await serve({
1180
+ port: 3000,
1181
+ session: { secret: process.env.SESSION_SECRET, store: customStore },
1182
+ api: {},
1183
+ });
1184
+ ```
1185
+
1186
+ ### 9.4 Timing-Safe Webhook Verification (`webhook`)
1187
+
1188
+ Verify HMAC signatures automatically over the raw body before JSON parsing:
1189
+
1190
+ ```javascript
1191
+ const stripeWebhook = {
1192
+ webhook: {
1193
+ secret: process.env.STRIPE_WEBHOOK_SECRET,
1194
+ header: "stripe-signature",
1195
+ algo: "sha256",
1196
+ },
1197
+ post(event) {
1198
+ return { received: true, type: event.type };
1199
+ },
1200
+ };
1201
+ ```
1202
+
1203
+ ### 9.5 Rate Limiting (`limit` & `wire.cost`)
1204
+
1205
+ **Step 1 — Basic rate limit per window:**
1206
+
1207
+ ```javascript
1208
+ const search = {
1209
+ limit: { max: 30, window: "1m" },
1210
+ get: (query) => ({ results: [], q: query.q }),
1211
+ };
1212
+ ```
1213
+
1214
+ **Step 2 — Dynamic point costs with `wire.cost()`:**
1215
+
1216
+ Each request costs `1` point by default. Call `wire.cost(points)` to penalize failed attempts or refund valid ones:
1217
+
1218
+ ```javascript
1219
+ const login = {
1220
+ limit: {
1221
+ max: 10,
1222
+ window: "10m",
1223
+ key: (payload) => `login:${payload?.email || "unknown"}`,
1224
+ },
1225
+ async post(payload) {
1226
+ const valid = payload.password === "secret123";
1227
+ if (!valid) {
1228
+ wire.cost(5); // Failed attempts consume 5x quota
1229
+ wire.abort(401, "Invalid credentials");
1230
+ }
1231
+ wire.cost(0); // Successful login costs 0 points
1232
+ return { ok: true };
1233
+ },
1234
+ };
1235
+ ```
1236
+
1237
+ ### 9.6 CORS & Preflight Handling (`origins`)
1238
+
1239
+ ```javascript
1240
+ await serve({
1241
+ port: 3000,
1242
+ origins: ["https://app.example.com", "http://localhost:5173"],
1243
+ api: {},
1244
+ });
1245
+ ```
1246
+
1247
+ ---
1248
+
1249
+ ## 10. Caching, Validation & Resilience
1250
+
1251
+ ### 10.1 Self-Invalidating Response Cache (`cache`)
1252
+
1253
+ **Step 1 — Cache a `GET` endpoint:**
1254
+
1255
+ ```javascript
1256
+ const stats = {
1257
+ cache: "1m", // Cached for 1 minute
1258
+ get: () => ({ generatedAt: Date.now() }),
1259
+ };
1260
+ ```
1261
+
1262
+ **Step 2 — Automatic invalidation on mutations:**
1263
+
1264
+ When `cache` is placed on a parent or item node, any successful `POST`, `PUT`, `PATCH`, or `DELETE` automatically clears both the item cache and parent list cache:
1265
+
1266
+ ```javascript
1267
+ const articles = {
1268
+ cache: "5m",
1269
+ get: () => db.articles.all(),
1270
+ post: (data) => db.articles.create(data), // Automatically clears GET /articles cache
1271
+
1272
+ $id: param("int", {
1273
+ cache: "5m",
1274
+ get: (id) => db.articles.find(id),
1275
+ patch: (id, data) => db.articles.update(id, data), // Clears GET /articles/:id AND GET /articles
1276
+ }),
1277
+ };
1278
+ ```
1279
+
1280
+ ### 10.2 Request Coalescing (`coalesce`)
1281
+
1282
+ Deduplicate simultaneous identical `GET` requests during traffic spikes so your database runs the query only once:
1283
+
1284
+ ```javascript
1285
+ const report = {
1286
+ coalesce: true,
1287
+ cache: "30s",
1288
+ async get() {
1289
+ return await db.runExpensiveQuery();
1290
+ },
1291
+ };
1292
+ ```
1293
+
1294
+ ### 10.3 Idempotent Mutations (`idempotent`)
1295
+
1296
+ Prevent duplicate writes when clients retry requests with the same `Idempotency-Key` header:
1297
+
1298
+ ```javascript
1299
+ const payments = {
1300
+ idempotent: "24h",
1301
+ async post(payload) {
1302
+ return await chargeCustomer(payload);
1303
+ },
1304
+ };
1305
+ ```
1306
+
1307
+ ### 10.4 Declarative Input Validation (`expect`)
1308
+
1309
+ **Step 1 — Validate basic required fields (returns `422` if invalid):**
1310
+
1311
+ ```javascript
1312
+ const signup = {
1313
+ expect: {
1314
+ email: "email",
1315
+ password: "string",
1316
+ age: "number",
1317
+ },
1318
+ post(payload) {
1319
+ return { created: payload.email };
1320
+ },
1321
+ };
1322
+ ```
1323
+
1324
+ **Step 2 — Optional fields (`?`), enums, arrays, and nested objects:**
1325
+
1326
+ ```javascript
1327
+ const createProject = {
1328
+ expect: {
1329
+ name: "string",
1330
+ visibility: ["private", "team", "public"], // Enum
1331
+ description: "string?", // Optional string
1332
+ tags: "array?", // Optional array
1333
+ settings: {
1334
+ // Nested object
1335
+ notifications: "boolean",
1336
+ },
1337
+ },
1338
+ post: (payload) => payload,
1339
+ };
1340
+ ```
1341
+
1342
+ ### 10.5 Automatic Rollbacks (`wire.undo`) & Dry-Runs (`X-Simulate`)
1343
+
1344
+ **Step 1 — Register undo actions after each side effect:**
1345
+
1346
+ If a later step throws an error or calls `wire.abort()`, `servin` runs all `wire.undo()` functions in reverse order (LIFO):
1347
+
1348
+ ```javascript
1349
+ const transfer = {
1350
+ async post({ from, to, amount }) {
1351
+ await db.debit(from, amount);
1352
+ wire.undo(() => db.credit(from, amount)); // Runs automatically if credit() below fails
1353
+
1354
+ await db.credit(to, amount);
1355
+ return { transferred: amount };
1356
+ },
1357
+ };
1358
+ ```
1359
+
1360
+ **Step 2 — Speculative dry-runs via `X-Simulate: true`:**
1361
+
1362
+ When a client sends header `X-Simulate: true`, `servin` executes your handler to compute the exact response, then automatically runs `wire.undo()` so no state changes persist.
1363
+
1364
+ ### 10.6 Graceful Background Tasks (`wire.defer`)
1365
+
1366
+ Run non-blocking work after sending the HTTP response. `servin` waits for all deferred tasks to finish during server shutdown:
1367
+
1368
+ ```javascript
1369
+ const register = {
1370
+ async post(user) {
1371
+ const saved = await db.users.insert(user);
1372
+ wire.defer(() => sendWelcomeEmail(saved.email));
1373
+ wire.status(201);
1374
+ return saved;
1375
+ },
1376
+ };
1377
+ ```
1378
+
1379
+ ### 10.7 Load Shedding (`priority: 'low'`) & Deprecation (`sunset`)
1380
+
1381
+ ```javascript
1382
+ const exportsApi = {
1383
+ sunset: "2027-01-01", // Emits standard Deprecation and Sunset headers
1384
+ csv: {
1385
+ priority: "low", // Returns 503 Retry-After: 2 if event loop p95 lag > lagThresholdMs
1386
+ get: () => buildHeavyCsv(),
1387
+ },
1388
+ };
1389
+ ```
1390
+
1391
+ ---
1392
+
1393
+ ## 11. Linear WebSockets & Pub/Sub
1394
+
1395
+ ### 11.1 Step 1: Minimal Echo WebSocket (`ws` & `for await`)
1396
+
1397
+ Add a `ws(socket)` method anywhere in your tree and iterate over incoming messages linearly with `for await`:
1398
+
1399
+ ```javascript
1400
+ const echo = {
1401
+ // WS /echo
1402
+ async ws(socket) {
1403
+ socket.send({ status: "connected" });
1404
+
1405
+ for await (const msg of socket) {
1406
+ socket.send({ echoed: msg });
1407
+ }
1408
+ },
1409
+ };
1410
+ ```
1411
+
1412
+ ### 11.2 Step 2: Rooms & Pub/Sub Broadcasting (`socket.join`, `wire.publish`)
1413
+
1414
+ Subscribe sockets to named topics and broadcast messages from either WebSocket handlers or HTTP routes:
1415
+
1416
+ ```javascript
1417
+ const chat = {
1418
+ $room: {
1419
+ // WS /chat/:room
1420
+ async ws(room, socket) {
1421
+ socket.join(`room:${room}`);
1422
+ socket.broadcast(`room:${room}`, { event: "joined" });
1423
+
1424
+ for await (const msg of socket) {
1425
+ wire.publish(`room:${room}`, { text: msg.text });
1426
+ }
1427
+ },
1428
+ },
1429
+
1430
+ // Any HTTP route can also publish to WebSocket subscribers!
1431
+ announce: {
1432
+ post({ room, text }) {
1433
+ wire.publish(`room:${room}`, { announcement: text });
1434
+ return { sent: true };
1435
+ },
1436
+ },
1437
+ };
1438
+ ```
1439
+
1440
+ ### 11.3 Step 3: Guarded WebSockets & `wsConfig`
1441
+
1442
+ Combine `guard()`, `param()`, and `wsConfig` (`heartbeat`, `maxPayload`, `binary`) on the same branch:
1443
+
1444
+ ```javascript
1445
+ const liveStream = guard(requireAuth, {
1446
+ wsConfig: {
1447
+ maxPayload: "256kb",
1448
+ heartbeat: "30s",
1449
+ },
1450
+ $channelId: param("int", {
1451
+ async ws(channelId, socket) {
1452
+ socket.join(`ch:${channelId}`);
1453
+ for await (const msg of socket) {
1454
+ socket.broadcast(`ch:${channelId}`, msg);
1455
+ }
1456
+ },
1457
+ }),
1458
+ });
1459
+ ```
1460
+
1461
+ ---
1462
+
1463
+ ## 12. Streaming File Uploads (`wire.multipart` & `rawBody`)
1464
+
1465
+ **1. Streaming `multipart/form-data` without buffering in RAM:**
1466
+
1467
+ ```javascript
1468
+ import fs from "node:fs";
1469
+ import { pipeline } from "node:stream/promises";
1470
+ import { Readable } from "node:stream";
1471
+ import { wire } from "servin";
1472
+
1473
+ const upload = {
1474
+ async post() {
1475
+ const fields = {};
1476
+ const files = [];
1477
+
1478
+ for await (const part of wire.multipart({ maxFileSize: "20mb" })) {
1479
+ if (part.isField) {
1480
+ fields[part.name] = await part.text();
1481
+ } else if (part.isFile) {
1482
+ const dest = `./uploads/${part.filename}`;
1483
+ await pipeline(
1484
+ Readable.fromWeb(part.stream),
1485
+ fs.createWriteStream(dest),
1486
+ );
1487
+ files.push(part.filename);
1488
+ }
1489
+ }
1490
+
1491
+ return { fields, files };
1492
+ },
1493
+ };
1494
+ ```
1495
+
1496
+ **2. Raw unbuffered binary upload (`rawBody: true`):**
1497
+
1498
+ ```javascript
1499
+ const rawUpload = {
1500
+ $filename: {
1501
+ rawBody: true,
1502
+ async put(filename) {
1503
+ await pipeline(
1504
+ Readable.fromWeb(wire.stream),
1505
+ fs.createWriteStream(`./uploads/${filename}`),
1506
+ );
1507
+ wire.status(201);
1508
+ return { saved: filename };
1509
+ },
1510
+ },
1511
+ };
1512
+ ```
1513
+
1514
+ ---
1515
+
1516
+ ## 13. Decoupled Side Effects (`reactTo`)
1517
+
1518
+ Attach secondary side effects (analytics, loyalty points, audit logs) from outside your main handler without coupling modules together:
1519
+
1520
+ ```javascript
1521
+ import { reactTo } from "servin";
1522
+
1523
+ reactTo(tasks.post, ({ output }) => {
1524
+ console.log(`Audit: task #${output.id} created`);
1525
+ });
1526
+ ```
1527
+
1528
+ ---
1529
+
1530
+ ## 14. Logging, Debugging & Automated Testing
1531
+
1532
+ ### 14.1 Startup Messages & Access Logs (`message`, `onListen`, `accessLog`)
1533
+
1534
+ **1. Custom startup message:**
1535
+
1536
+ ```javascript
1537
+ await serve({
1538
+ port: 3000,
1539
+ message: ({ port, url }) => `Server running on port ${port} (${url})`,
1540
+ api: {},
1541
+ });
1542
+ ```
1543
+
1544
+ **2. Custom access log formatter (or `accessLog: false` to disable):**
1545
+
1546
+ ```javascript
1547
+ await serve({
1548
+ port: 3000,
1549
+ accessLog(info) {
1550
+ if (info.url.pathname === "/health") return null; // Hide healthchecks
1551
+ return `[${info.status}] ${info.method} ${info.url.pathname} (${info.durationMs.toFixed(1)}ms)`;
1552
+ },
1553
+ api: {},
1554
+ });
1555
+ ```
1556
+
1557
+ ### 14.2 Error-Triggered Debug Trace (`wire.log.debug`) & `Server-Timing` (`wire.mark`)
1558
+
1559
+ - `wire.log.debug(...)` buffers logs in memory and **only prints them if the request fails with an unhandled error**.
1560
+ - `wire.mark(label)` measures step duration and emits an HTTP `Server-Timing` header.
1561
+
1562
+ ```javascript
1563
+ const report = {
1564
+ async get() {
1565
+ wire.log.debug("Querying analytics table");
1566
+
1567
+ const endDb = wire.mark("db");
1568
+ const rows = await db.query("SELECT * FROM metrics");
1569
+ endDb();
1570
+
1571
+ return rows; // Emits header: Server-Timing: db;dur=12.40
1572
+ },
1573
+ };
1574
+ ```
1575
+
1576
+ ### 14.3 Automated Test Synthesis (`synthesizeTests`)
1577
+
1578
+ Set `synthesizeTests: './tests/api.test.js'` in `serve()` during development to automatically record verified endpoints into a runnable `node:test` file.
1579
+
1580
+ ### 14.4 Error Snapshots & Local Replay (`snapshotOnError` & `replay`)
1581
+
1582
+ Set `snapshotOnError: './snapshots'` to save failing `500` requests, then replay them locally against your handler:
1583
+
1584
+ ```javascript
1585
+ import { replay } from "servin/test";
1586
+ import { tasks } from "./tasks.js";
1587
+
1588
+ await replay(
1589
+ tasks.$id.get,
1590
+ "./snapshots/err-2026-11-25T12-00-00-000Z-a1b2c3d4.json",
1591
+ );
1592
+ ```
1593
+
1594
+ ---
1595
+
1596
+ ## 15. Complete Ambient `wire` API Reference
1597
+
1598
+ | Member | Signature / Type | Description |
1599
+ | :--------------------------- | :-------------------------------- | :----------------------------------------------------------------------------------------------------------------------- |
1600
+ | `wire.req` | `Request` | Native Web `Request` instance. |
1601
+ | `wire.method` | `string` | Uppercase HTTP method (`'GET'`, `'POST'`, etc.) or `'WS'`. |
1602
+ | `wire.url` | `URL` | Parsed `URL` instance for the current request. |
1603
+ | `wire.headers` | `Headers` (Proxy) | Reads response then request headers (`.get()`, `.has()`); mutates response headers (`.set()`, `.append()`, `.delete()`). |
1604
+ | `wire.stream` | `ReadableStream \| null` | Unbuffered request body stream (used with `rawBody: true`). |
1605
+ | `wire.signal` | `AbortSignal` | Aborted if the client disconnects early. |
1606
+ | `wire.status(code)` | `(number) => void` | Sets the HTTP status code. |
1607
+ | `wire.abort(status, msg)` | `(number, string) => never` | Halts execution, triggers `wire.undo()`, and sends `{ error: msg }`. |
1608
+ | `wire.redirect(url, status)` | `(string, number?) => never` | Halts execution, commits session cookies, and sends a redirect (`302` by default). |
1609
+ | `wire.undo(fn)` | `(() => any) => void` | Registers a LIFO rollback callback run on error, abort, SSE cancel, or `X-Simulate: true`. |
1610
+ | `wire.defer(fn)` | `(() => any) => void` | Schedules a background task tracked during graceful shutdown. |
1611
+ | `wire.html` | `tag \| (string) => HtmlResponse` | Creates an HTML response; escapes interpolated variables when used as a tagged template. |
1612
+ | `wire.file(filePath)` | `(string) => FileStreamResponse` | Streams a file with `ETag` (`304`) and `Range` (`206`) support. |
1613
+ | `wire.multipart(opts)` | `(opts?) => AsyncGenerator` | Iterates streaming `multipart/form-data` fields and files sequentially. |
1614
+ | `wire.session` | `Proxy \| null` | Lazy encrypted session object (`.rotate()`, `.bind(userId)`, or `wire.session = null`). |
1615
+ | `wire.sessions` | `{ list, revokeOthers }` | Multi-device session listing and remote session revocation helpers. |
1616
+ | `wire.publish(topic, data)` | `(string, any) => void` | Broadcasts a message to all WebSocket clients subscribed to `topic`. |
1617
+ | `wire.cost(points)` | `(number) => void` | Adjusts rate-limit quota consumption for the current request. |
1618
+ | `wire.log.debug(msg, meta)` | `(string, any?) => void` | Buffers a debug log entry emitted only on unhandled errors. |
1619
+ | `wire.mark(label)` | `(string) => () => number` | Starts a performance timer; calling the returned function records `Server-Timing`. |
1620
+
1621
+ ---
1622
+
1623
+ ## 16. License
1624
+
1625
+ MIT