@dim24/servin 0.0.1 → 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
@@ -2,7 +2,7 @@
2
2
 
3
3
  **A modern, zero-dependency Node.js web server built around _Domain-Tree Projection_ and _Ambient Wire_.**
4
4
 
5
- `servin` lets you build HTTP APIs, 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 protocol translation automatically.
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
6
 
7
7
  ---
8
8
 
@@ -10,87 +10,86 @@
10
10
 
11
11
  1. [Why servin?](#1-why-servin)
12
12
  2. [Requirements & Installation](#2-requirements--installation)
13
- 3. [Step-by-Step Walkthrough](#3-step-by-step-walkthrough)
14
- - [Step 1: Booting the Server (`serve`)](#step-1-booting-the-server-serve)
15
- - [Step 2: Understanding the URL Routing Paradigm & Adding `GET`](#step-2-understanding-the-url-routing-paradigm--adding-get)
16
- - [Step 3: Dynamic & Typed URL Parameters (`$id` + `param`)](#step-3-dynamic--typed-url-parameters-id--param)
17
- - [Step 4: Creating Resources with `POST`, Validation & Rollbacks](#step-4-creating-resources-with-post-validation--rollbacks)
18
- - [Step 5: Updating (`put|patch`), Deleting (`delete`) & Auto-Invalidating `cache`](#step-5-updating-putpatch-deleting-delete--auto-invalidating-cache)
19
- - [Step 6: Decoupled Side Effects (`reactTo`) & Serving HTML (`wire.html`)](#step-6-decoupled-side-effects-reactto--serving-html-wirehtml)
20
- - [Step 7: Complete Assembled Application](#step-7-complete-assembled-application)
21
- 4. [Server Configuration (`serve`)](#4-server-configuration-serve)
22
- - [4.1 Configuration Options Reference](#41-configuration-options-reference)
23
- - [4.2 Server Instance API](#42-server-instance-api)
24
- 5. [Domain-Tree Projection & Routing](#5-domain-tree-projection--routing)
25
- - [5.1 Static, Dynamic, Typed, and Wildcard Segments](#51-static-dynamic-typed-and-wildcard-segments)
26
- - [5.2 Automatic Route Matching Priority](#52-automatic-route-matching-priority)
27
- - [5.3 HTTP Methods, Method Unions & Shorthand Leaf Functions](#53-http-methods-method-unions--shorthand-leaf-functions)
28
- - [5.4 Predictable Handler Argument Mapping](#54-predictable-handler-argument-mapping)
29
- - [5.5 Typed Route Parameters (`param`) — Complete Type Guide](#55-typed-route-parameters-param--complete-type-guide)
30
- 6. [Automatic Response Formatting & HTML Rendering](#6-automatic-response-formatting--html-rendering)
31
- - [6.1 Content-Type Resolution Matrix](#61-content-type-resolution-matrix)
32
- - [6.2 XSS-Safe HTML Templates & Raw HTML (`wire.html`)](#62-xss-safe-html-templates--raw-html-wirehtml)
33
- - [6.3 Streaming Files with ETag & Byte-Range (`wire.file`)](#63-streaming-files-with-etag--byte-range-wirefile)
34
- - [6.4 Server-Sent Events (SSE) with Async Generators](#64-server-sent-events-sse-with-async-generators)
35
- - [6.5 Sparse Fieldsets (`?fields=`) & Automatic Redaction (`redact`)](#65-sparse-fieldsets-fields--automatic-redaction-redact)
36
- 7. [Security, Sessions & Traffic Control](#7-security-sessions--traffic-control)
37
- - [7.1 Branch & Leaf Protection (`guard`)](#71-branch--leaf-protection-guard)
38
- - [7.2 Lazy Reactive Sessions (`wire.session`) & Multi-Device Control (`wire.sessions`)](#72-lazy-reactive-sessions-wiresession--multi-device-control-wiresessions)
39
- - [7.3 Custom Session Store Interface (Redis / Database)](#73-custom-session-store-interface-redis--database)
40
- - [7.4 Timing-Safe Webhook Verification (`webhook`)](#74-timing-safe-webhook-verification-webhook)
41
- - [7.5 Context-Aware Smart Rate Limiting (`limit` & `wire.cost`)](#75-context-aware-smart-rate-limiting-limit--wirecost)
42
- - [7.6 CORS & Preflight Handling (`origins`)](#76-cors--preflight-handling-origins)
43
- 8. [Data Integrity, Caching & Resilience](#8-data-integrity-caching--resilience)
44
- - [8.1 Self-Invalidating Response Cache (`cache`)](#81-self-invalidating-response-cache-cache)
45
- - [8.2 Request Coalescing (`coalesce`)](#82-request-coalescing-coalesce)
46
- - [8.3 Idempotent Mutations (`idempotent`)](#83-idempotent-mutations-idempotent)
47
- - [8.4 Declarative Shape-by-Example Validation (`expect`)](#84-declarative-shape-by-example-validation-expect)
48
- - [8.5 Automatic Rollbacks (`wire.undo`) & Speculative Dry-Runs (`X-Simulate`)](#85-automatic-rollbacks-wireundo--speculative-dry-runs-x-simulate)
49
- - [8.6 Graceful Background Tasks (`wire.defer`)](#86-graceful-background-tasks-wiredefer)
50
- - [8.7 Adaptive Load Shedding (`priority: 'low'`) & API Deprecation (`sunset`)](#87-adaptive-load-shedding-priority-low--api-deprecation-sunset)
51
- 9. [Unified Linear WebSockets](#9-unified-linear-websockets)
52
- - [9.1 Linear WebSocket Streams (`ws` & `for await`)](#91-linear-websocket-streams-ws--for-await)
53
- - [9.2 Pub/Sub Topics & Cross-Protocol Messaging (`wire.publish`)](#92-pubsub-topics--cross-protocol-messaging-wirepublish)
54
- - [9.3 WebSocket Options (`wsConfig`) & Session Auto-Kick](#93-websocket-options-wsconfig--session-auto-kick)
55
- 10. [Streaming Uploads (`wire.multipart` & `rawBody`)](#10-streaming-uploads-wiremultipart--rawbody)
56
- 11. [Decoupled Side Effects (`reactTo`)](#11-decoupled-side-effects-reactto)
57
- 12. [Zero-Build Virtual ESM Client (`/@client.js`)](#12-zero-build-virtual-esm-client-clientjs)
58
- 13. [Observability, Logging & Automated Testing](#13-observability-logging--automated-testing)
59
- - [13.1 Custom Startup Messages & Access Logs (`message`, `onListen`, `accessLog`)](#131-custom-startup-messages--access-logs-message-onlisten-accesslog)
60
- - [13.2 Error-Triggered Debug Trace (`wire.log.debug`) & `Server-Timing` (`wire.mark`)](#132-error-triggered-debug-trace-wirelogdebug--server-timing-wiremark)
61
- - [13.3 Automated Test Synthesis (`synthesizeTests`)](#133-automated-test-synthesis-synthesizetests)
62
- - [13.4 Production Error Snapshots & Local Replay (`snapshotOnError` & `replay`)](#134-production-error-snapshots--local-replay-snapshotonerror--replay)
63
- 14. [Complete Ambient `wire` API Reference](#14-complete-ambient-wire-api-reference)
64
- 15. [License](#15-license)
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)
65
74
 
66
75
  ---
67
76
 
68
77
  ## 1. Why servin?
69
78
 
70
- Traditional Node.js web frameworks (Express, Fastify, Hono, Koa) rely on sequential middleware pipelines that mutate shared `req` or `ctx` objects and bind handlers to string URL patterns. As codebases expand, this architecture introduces hidden state mutations, manual cache-invalidation plumbing, and separate event-driven subsystems for WebSockets.
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.
71
80
 
72
- `servin` replaces string routing and middleware chains with two cohesive primitives:
81
+ `servin` replaces that boilerplate with two core concepts:
73
82
 
74
- 1. **Domain-Tree Projection:** You define your backend as a standard nested JavaScript object. `servin` projects that object structure directly onto HTTP endpoints, SSE streams, WebSocket channels, and a zero-build frontend ES module (`/@client.js`).
75
- 2. **Ambient `wire`:** Backed by Node.js `AsyncLocalStorage`, `wire` gives any function in your call stack direct access to headers, status codes, sessions, rollbacks, background tasks, and pub/sub broadcasts without passing `req` or `res` arguments around.
76
-
77
- | Capability | Conventional Frameworks | `servin` |
78
- | :----------------------- | :--------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------- |
79
- | **Route Definition** | String paths (`app.get('/users/:id', ...)`). | Plain JS object tree (`users: { $id: param('int', { get(id) { ... } }) }`). |
80
- | **Parameter Validation** | Manual `Number(req.params.id)` + `Number.isNaN()` checks in every handler. | Declarative `param('int', branch)` validates before dispatch and passes typed values (`number`, `boolean`, `bigint`). |
81
- | **Cache Invalidation** | Manual cache key tracking and deletion across update/delete routes. | `cache: '5m'` caches `GET` responses and automatically purges node and parent caches on `POST`, `PUT`, `PATCH`, or `DELETE`. |
82
- | **Traffic Spikes** | Concurrent requests execute redundant database queries unless custom locks are built. | `coalesce: true` merges simultaneous identical `GET` requests into a single execution. |
83
- | **Session Overhead** | Global middleware parses cookies and queries stores on every request, including public routes. | **Lazy Proxy:** zero cookie decryption or store lookups unless `wire.session` is actually read or written. |
84
- | **WebSockets** | Separate callback registration (`open`, `message`, `close`) detached from HTTP routes. | Co-located `ws` method in the same domain tree using a linear `for await (const msg of socket)` loop. |
85
- | **Frontend Integration** | Hand-written `fetch()` wrappers or build-time OpenAPI code generators. | Native browser/ESM import from `/@client.js` with zero build step. |
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.
86
85
 
87
86
  ---
88
87
 
89
88
  ## 2. Requirements & Installation
90
89
 
91
- - **Runtime:** Node.js `v20.0.0` or higher (uses native Web `Request`/`Response`, `WebSocket`, `AsyncLocalStorage`, and `node:test`).
92
- - **Dependencies:** Zero external runtime dependencies.
93
- - **Module System:** ES Modules (`"type": "module"` in `package.json`).
90
+ - **Runtime:** Node.js `v20.0.0` or higher.
91
+ - **Dependencies:** Zero external dependencies.
92
+ - **Module Format:** ES Modules (`"type": "module"` in `package.json`).
94
93
 
95
94
  Install `servin`:
96
95
 
@@ -98,386 +97,336 @@ Install `servin`:
98
97
  npm install servin
99
98
  ```
100
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
+
101
112
  ---
102
113
 
103
- ## 3. Step-by-Step Walkthrough
114
+ ## 3. Step-by-Step Core Walkthrough
104
115
 
105
- ### Step 1: Booting the Server (`serve`)
116
+ ### Step 1: Starting the Server (`serve`)
106
117
 
107
- Create a `server.js` file and call `serve()`. At its simplest, `serve()` binds an HTTP/WebSocket server to a port and prints a startup message:
118
+ Create `server.js` and call `serve()`. By default, it listens on `127.0.0.1:3000`:
108
119
 
109
120
  ```javascript
110
121
  import { serve } from "servin";
111
122
 
112
123
  await serve({
113
124
  port: 3000,
114
- message: ({ port, url }) => `Server is running on port ${port} (${url})`,
115
125
  api: {},
116
126
  });
117
127
  ```
118
128
 
119
- Run `node server.js` and your server is live on `http://127.0.0.1:3000`.
129
+ You can customize the startup log message using `message`:
120
130
 
121
- ---
131
+ ```javascript
132
+ import { serve } from "servin";
122
133
 
123
- ### Step 2: Understanding the URL Routing Paradigm & Adding `GET`
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`
124
142
 
125
- In `servin`, **you never write URL strings**. Instead, nested keys inside the `api` object automatically project into URL path segments, while lowercase HTTP verb names (`get`, `post`, `put`, `patch`, `delete`) act as the endpoint handlers:
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:
126
144
 
127
145
  ```text
128
- JavaScript Object Tree Projected HTTP Endpoint
129
- ─────────────────────────────────────────────────────────────────
146
+ Object Tree HTTP Endpoint
147
+ ───────────────────────────────────────────────────────────────
130
148
  api: {
131
- health: {
132
- get() { ... } ──────► GET /health
149
+ hello: {
150
+ get() { ... } ──────► GET /hello
133
151
  },
134
152
  tasks: {
135
- get(query) { ... } ──────► GET /tasks (and GET /tasks?done=false)
153
+ get() { ... } ──────► GET /tasks
136
154
  }
137
155
  }
138
156
  ```
139
157
 
140
- Any plain object or array returned from `get()` is automatically serialized as `application/json` with status `200 OK`:
158
+ Any plain object or array you `return` is automatically serialized as `application/json` (`200 OK`):
141
159
 
142
160
  ```javascript
143
161
  import { serve } from "servin";
144
162
 
145
- const tasksDb = new Map([
146
- [1, { id: 1, title: "Design domain tree", priority: "high", done: true }],
147
- [
148
- 2,
149
- {
150
- id: 2,
151
- title: "Write integration tests",
152
- priority: "medium",
153
- done: false,
154
- },
155
- ],
156
- ]);
163
+ const tasksDb = [
164
+ { id: 1, title: "Learn servin", done: true },
165
+ { id: 2, title: "Build an API", done: false },
166
+ ];
157
167
 
158
168
  await serve({
159
169
  port: 3000,
160
170
  api: {
161
- // GET /health
162
- health: {
163
- get: () => ({ status: "ok" }),
171
+ // GET /hello
172
+ hello: {
173
+ get: () => ({ message: "Hello from servin!" }),
164
174
  },
165
175
 
166
- // GET /tasks?done=false
176
+ // GET /tasks
167
177
  tasks: {
168
- get(query) {
169
- let list = [...tasksDb.values()];
170
- if (query.done === "true") list = list.filter((t) => t.done);
171
- if (query.done === "false") list = list.filter((t) => !t.done);
172
- return list;
173
- },
178
+ get: () => tasksDb,
174
179
  },
175
180
  },
176
181
  });
177
182
  ```
178
183
 
179
- ---
184
+ ### Step 3: Reading URL Query Parameters (`?done=true`)
185
+
186
+ Every `get()` handler automatically receives a `query` object containing the URL search parameters:
180
187
 
181
- ### Step 3: Dynamic & Typed URL Parameters (`$id` + `param`)
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
+ ```
182
202
 
183
- To capture a dynamic segment in the URL, prefix a key with `$` (such as `$id`). Wrapping that branch with `param('int', ...)` guarantees two things before your handler even runs:
203
+ ### Step 4: Dynamic URL Segments (`$id`) & Type Rules (`param`)
184
204
 
185
- 1. **Automatic Filtering:** Non-integer URLs like `GET /tasks/abc` are rejected automatically (`404 Not Found`).
186
- 2. **Automatic Type Coercion:** The `id` argument passed to `get(id)` is already a JavaScript `number` (`1`), not a string (`"1"`).
205
+ Prefix a key with `$` to capture a dynamic URL segment:
187
206
 
188
- ```text
189
- JavaScript Object Tree Projected HTTP Endpoint
190
- ─────────────────────────────────────────────────────────────────
191
- tasks: {
192
- $id: param('int', {
193
- get(id) { ... } ──────► GET /tasks/1 (id === 1 as number)
194
- }) GET /tasks/abc (auto-rejected: 404)
195
- }
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
+ };
196
216
  ```
197
217
 
198
- Use `wire.abort(status, message)` whenever you need to halt execution and send an HTTP error response:
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 })`.
199
219
 
200
220
  ```javascript
201
- import { serve, wire, param } from "servin";
221
+ import { param } from "servin";
202
222
 
203
- // Inside api.tasks:
204
- $id: param("int", {
205
- // GET /tasks/:id
206
- get(id) {
207
- const task = tasksDb.get(id);
208
- if (!task) wire.abort(404, `Task #${id} not found`);
209
- return task;
210
- },
211
- });
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
+ };
212
232
  ```
213
233
 
214
- ---
234
+ See [Section 7.5](#75-typed-route-parameters-param--all-supported-types--custom-formats) for every supported type and custom format option.
215
235
 
216
- ### Step 4: Creating Resources with `POST`, Validation & Rollbacks
236
+ ### Direct Path Parameters on Route Nodes (`wire.params` & `wire.param(name)`)
217
237
 
218
- Add a `post(payload)` handler to `tasks` to handle `POST /tasks`. You can layer declarative safeguards directly onto the same object:
238
+ Read trailing path segments directly inside a route handler without creating a separate `$id` child branch.
219
239
 
220
- - `expect`: Validates the incoming JSON body shape before execution and returns `422 Unprocessable Entity` on invalid input.
221
- - `idempotent: '10m'`: Prevents duplicate creation if a client retries a request with the same `Idempotency-Key` header.
222
- - `wire.undo(fn)`: Registers a rollback action that automatically undoes the database write if a later step throws an error—or if the client sends `X-Simulate: true` for a dry-run.
223
- - `wire.status(201)`: Sets the HTTP response status to `201 Created`.
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')`.
224
242
 
225
- ```javascript
226
- import { wire } from "servin";
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`
227
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
228
264
  let nextId = 3;
229
265
 
230
- // Added directly inside api.tasks:
231
- const createTaskRules = {
232
- expect: {
233
- title: "string",
234
- priority: ["low", "medium", "high"],
235
- done: "boolean?",
236
- },
237
- idempotent: "10m",
266
+ const tasks = {
267
+ get: () => tasksDb,
268
+
269
+ // POST /tasks
238
270
  post(payload) {
239
- const id = nextId++;
240
- const record = {
241
- id,
271
+ const newTask = {
272
+ id: nextId++,
242
273
  title: payload.title,
243
- priority: payload.priority,
244
- done: payload.done ?? false,
274
+ done: false,
245
275
  };
246
-
247
- tasksDb.set(id, record);
248
- wire.undo(() => tasksDb.delete(id));
249
- wire.status(201);
250
- return record;
276
+ tasksDb.push(newTask);
277
+ return newTask;
251
278
  },
252
279
  };
253
- ```
280
+ ````
254
281
 
255
- ---
282
+ ### Step 6: Setting HTTP Status Codes & Errors (`wire.status` & `wire.abort`)
256
283
 
257
- ### Step 5: Updating (`put|patch`), Deleting (`delete`) & Auto-Invalidating `cache`
284
+ Import `wire` when you need to change the HTTP status code or stop a request with an error:
258
285
 
259
- Now let's complete the CRUD lifecycle inside `$id` and add `cache: '5m'` to both `tasks` and `$id`:
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";
260
291
 
261
- - **Method Union (`'put|patch'`):** Handles both `PUT /tasks/:id` and `PATCH /tasks/:id` in one clean function, inspecting `wire.method` to distinguish full replacement from partial updates.
262
- - **Self-Invalidating Cache:** When `GET /tasks` or `GET /tasks/1` is called, responses are served from cache. As soon as `POST`, `PUT`, `PATCH`, or `DELETE` succeeds, `servin` automatically purges both the item cache and the parent list cache.
292
+ const tasks = {
293
+ post(payload) {
294
+ const newTask = { id: nextId++, title: payload.title, done: false };
295
+ tasksDb.push(newTask);
263
296
 
264
- ```text
265
- Cache Invalidation Flow
266
- ─────────────────────────────────────────────────────────────────
267
- GET /tasks ──► Cached for 5m
268
- GET /tasks/1 ──► Cached for 5m
269
- PATCH /tasks/1 ──► Succeeds ──► Automatically purges BOTH caches!
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
+ };
270
309
  ```
271
310
 
272
- ```javascript
273
- import { wire, param } from "servin";
311
+ ### Step 7: Updating (`patch` / `'put|patch'`) & Deleting (`delete`)
274
312
 
275
- const taskItemNode = param("int", {
276
- cache: "5m",
313
+ Add `patch` (or `'put|patch'` to handle both verbs in one function) and `delete` inside `$id`:
277
314
 
278
- // GET /tasks/:id
315
+ ```javascript
316
+ const taskById = param("int", {
279
317
  get(id) {
280
- const task = tasksDb.get(id);
318
+ const task = tasksDb.find((t) => t.id === id);
281
319
  if (!task) wire.abort(404, `Task #${id} not found`);
282
320
  return task;
283
321
  },
284
322
 
285
- // PUT /tasks/:id & PATCH /tasks/:id
286
- "put|patch"(id, payload) {
287
- const existing = tasksDb.get(id);
288
- if (!existing) wire.abort(404, `Task #${id} not found`);
289
-
290
- const updated =
291
- wire.method === "PATCH"
292
- ? { ...existing, ...payload, id }
293
- : {
294
- id,
295
- title: payload.title,
296
- priority: payload.priority || "medium",
297
- done: Boolean(payload.done),
298
- };
299
-
300
- tasksDb.set(id, updated);
301
- return updated;
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;
302
329
  },
303
330
 
304
331
  // DELETE /tasks/:id
305
332
  delete(id) {
306
- if (!tasksDb.has(id)) wire.abort(404, `Task #${id} not found`);
307
- tasksDb.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);
308
336
  wire.status(204);
309
- return null;
337
+ return null; // Sends empty 204 No Content
310
338
  },
311
339
  });
312
340
  ```
313
341
 
314
- ---
342
+ ### Step 8: Returning HTML (`wire.html` & `wire.file`)
315
343
 
316
- ### Step 6: Decoupled Side Effects (`reactTo`) & Serving HTML (`wire.html`)
344
+ By default, returning a plain `string` sends `text/plain` so user text cannot accidentally execute scripts. To serve HTML:
317
345
 
318
- Finally, you can attach decoupled observers via `reactTo()` and serve an HTML frontend via `wire.html` that imports your backend tree directly from `/@client.js` with zero `fetch()` boilerplate:
346
+ **Option A — Inline HTML string with `wire.html`:**
319
347
 
320
348
  ```javascript
321
- import { wire, reactTo } from "servin";
349
+ const home = {
350
+ get: () => wire.html("<h1>Welcome to Task Manager</h1>"),
351
+ };
352
+ ```
322
353
 
323
- // Runs automatically after tasks.post succeeds (skipped during X-Simulate dry-runs)
324
- reactTo(tasks.post, ({ output }) => {
325
- wire.log.info(`Created task #${output.id}: ${output.title}`);
326
- });
354
+ **Option B — Tagged template ``wire.html`...` `` (auto-escapes variables against XSS):**
327
355
 
328
- // GET /home -> serves an HTML page with auto-escaped variables
329
- const home = {
330
- get() {
331
- return wire.html`
332
- <!doctype html>
333
- <html lang="en">
334
- <head>
335
- <meta charset="utf-8">
336
- <title>servin Tasks</title>
337
- </head>
338
- <body>
339
- <h1>Tasks (${tasksDb.size})</h1>
340
- <ul id="list"></ul>
341
- <script type="module">
342
- import { api } from '/@client.js';
343
- const items = await api.tasks.get();
344
- document.getElementById('list').innerHTML = items
345
- .map((t) => \`<li>[\${t.priority}] \${t.title}</li>\`)
346
- .join('');
347
- </script>
348
- </body>
349
- </html>
350
- `;
356
+ ```javascript
357
+ const greet = {
358
+ $name: {
359
+ get(name) {
360
+ return wire.html`<h1>Hello, ${name}!</h1>`;
361
+ },
351
362
  },
352
363
  };
353
364
  ```
354
365
 
355
- ---
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
+ ```
356
373
 
357
- ### Step 7: Complete Assembled Application
374
+ ### Step 9: Assembled CRUD Server
358
375
 
359
- Putting Steps 1 through 6 together produces a clean, self-contained application:
376
+ Combining Steps 1–8 gives you a complete, readable CRUD server:
360
377
 
361
378
  ```javascript
362
- import { serve, wire, param, reactTo } from "servin";
379
+ import { serve, wire, param } from "servin";
363
380
 
364
- const tasksDb = new Map([
365
- [1, { id: 1, title: "Design domain tree", priority: "high", done: true }],
366
- [
367
- 2,
368
- {
369
- id: 2,
370
- title: "Write integration tests",
371
- priority: "medium",
372
- done: false,
373
- },
374
- ],
375
- ]);
381
+ const tasksDb = [
382
+ { id: 1, title: "Learn servin", done: true },
383
+ { id: 2, title: "Build an API", done: false },
384
+ ];
376
385
  let nextId = 3;
377
386
 
378
387
  const tasks = {
379
- cache: "5m",
380
-
381
- // GET /tasks?done=false
382
388
  get(query) {
383
- let list = [...tasksDb.values()];
384
- if (query.done === "true") list = list.filter((t) => t.done);
385
- if (query.done === "false") list = list.filter((t) => !t.done);
386
- return list;
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;
387
392
  },
388
393
 
389
- // POST /tasks
390
- expect: {
391
- title: "string",
392
- priority: ["low", "medium", "high"],
393
- done: "boolean?",
394
- },
395
- idempotent: "10m",
396
394
  post(payload) {
397
- const id = nextId++;
398
- const record = {
399
- id,
400
- title: payload.title,
401
- priority: payload.priority,
402
- done: payload.done ?? false,
403
- };
404
- tasksDb.set(id, record);
405
- wire.undo(() => tasksDb.delete(id));
395
+ const newTask = { id: nextId++, title: payload.title, done: false };
396
+ tasksDb.push(newTask);
406
397
  wire.status(201);
407
- return record;
398
+ return newTask;
408
399
  },
409
400
 
410
- // /tasks/:id (integer-only)
411
401
  $id: param("int", {
412
- cache: "5m",
413
-
414
402
  get(id) {
415
- const task = tasksDb.get(id);
403
+ const task = tasksDb.find((t) => t.id === id);
416
404
  if (!task) wire.abort(404, `Task #${id} not found`);
417
405
  return task;
418
406
  },
419
407
 
420
- "put|patch"(id, payload) {
421
- const existing = tasksDb.get(id);
422
- if (!existing) wire.abort(404, `Task #${id} not found`);
423
-
424
- const updated =
425
- wire.method === "PATCH"
426
- ? { ...existing, ...payload, id }
427
- : {
428
- id,
429
- title: payload.title,
430
- priority: payload.priority || "medium",
431
- done: Boolean(payload.done),
432
- };
433
-
434
- tasksDb.set(id, updated);
435
- return updated;
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;
436
413
  },
437
414
 
438
415
  delete(id) {
439
- if (!tasksDb.has(id)) wire.abort(404, `Task #${id} not found`);
440
- tasksDb.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);
441
419
  wire.status(204);
442
420
  return null;
443
421
  },
444
422
  }),
445
423
  };
446
424
 
447
- reactTo(tasks.post, ({ output }) => {
448
- wire.log.info(`Created task #${output.id}: ${output.title}`);
449
- });
450
-
451
- const home = {
452
- get() {
453
- return wire.html`
454
- <!doctype html>
455
- <html lang="en">
456
- <head>
457
- <meta charset="utf-8">
458
- <title>servin Tasks</title>
459
- </head>
460
- <body>
461
- <h1>Tasks (${tasksDb.size})</h1>
462
- <ul id="list"></ul>
463
- <script type="module">
464
- import { api } from '/@client.js';
465
- const items = await api.tasks.get();
466
- document.getElementById('list').innerHTML = items
467
- .map((t) => \`<li>[\${t.priority}] \${t.title}</li>\`)
468
- .join('');
469
- </script>
470
- </body>
471
- </html>
472
- `;
473
- },
474
- };
475
-
476
425
  await serve({
477
426
  port: 3000,
478
- message: ({ port, url }) => `Server is running on port ${port} (${url})`,
427
+ message: ({ port }) => `Server is running on port ${port}`,
479
428
  api: {
480
- home,
429
+ home: { get: () => wire.html("<h1>Task Manager</h1>") },
481
430
  tasks,
482
431
  },
483
432
  });
@@ -485,169 +434,411 @@ await serve({
485
434
 
486
435
  ---
487
436
 
488
- ## 4. Server Configuration (`serve`)
437
+ ## 4. Zero-Build Virtual ESM Client (`/@client.js`)
489
438
 
490
- `serve(config)` compiles your domain tree, binds the HTTP and WebSocket servers, registers graceful shutdown hooks (`SIGINT` and `SIGTERM`), and resolves once the server is listening.
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.
491
440
 
492
- ### 4.1 Configuration Options Reference
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**.
493
442
 
494
- | Option | Type | Default | Description |
495
- | :---------------- | :---------------------------- | :------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------ |
496
- | `port` | `number` | `3000` | TCP port to listen on. Pass `0` to let the OS assign an available ephemeral port. |
497
- | `host` | `string` | `'127.0.0.1'` | Network interface to bind (use `'0.0.0.0'` for containers/external access). |
498
- | `api` | `object` | `{}` | The root domain tree defining all HTTP routes, SSE streams, and WebSocket endpoints. |
499
- | `types` | `object` | `{}` | Dictionary of named custom parameter rules (`RegExp` or validator functions) usable via `param('typeName', branch)`. |
500
- | `session` | `object \| null` | `null` | Enables encrypted lazy sessions. Requires `{ secret: string }`. See [Section 7.2](#72-lazy-reactive-sessions-wiresession--multi-device-control-wiresessions). |
501
- | `origins` | `string[]` | `undefined` | Allowed CORS origins (e.g., `['https://app.example.com']` or `['*']`). Automatically handles `OPTIONS` preflight requests and credentials. |
502
- | `redact` | `string[]` | `undefined` | Wildcard key patterns (e.g., `['password*', '*.secret', 'token']`) stripped recursively from all JSON responses. |
503
- | `message` | `string \| function \| false` | `'[servin] listening on <url>'` | Custom startup log message. Accepts a string, `({ port, host, url }) => string`, or `false` to suppress. |
504
- | `onListen` | `function` | `undefined` | Sync or async callback `({ port, host, url }) => void` executed right after the port opens. |
505
- | `accessLog` | `boolean \| function` | `true` | Logs every HTTP and WebSocket request. Pass `false` to disable, or `(info) => string \| null` to customize/filter output. |
506
- | `silent` | `boolean` | `false` | Suppresses both the startup message and access logs. |
507
- | `lagThresholdMs` | `number` | `60` | Event-loop p95 latency threshold (in milliseconds) before `priority: 'low'` routes shed load with `503`. |
508
- | `synthesizeTests` | `string` | `undefined` | File path (e.g., `'./tests/api.test.js'`) where verified request/response pairs are automatically written as `node:test` suites. |
509
- | `snapshotOnError` | `string` | `undefined` | Directory path (e.g., `'./snapshots'`) where failing `500` request snapshots are saved for local `replay()`. |
510
- | `onError` | `function` | `undefined` | Custom unhandled error formatter `(err, { req }) => Response \| object`. |
443
+ ### 4.1 Step 1: Importing `api` in Browser or Frontend Apps
511
444
 
512
- ### 4.2 Server Instance API
445
+ **Same-origin HTML page served by `servin`:**
513
446
 
514
- `await serve(config)` returns a control object:
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`):**
515
466
 
516
467
  ```javascript
517
- const app = await serve({
518
- port: 0,
519
- api: { health: { get: () => ({ ok: true }) } },
520
- });
468
+ import { api } from "http://localhost:3000/@client.js";
521
469
 
522
- console.log(app.port); // Actual bound port (useful when port: 0 is used)
523
- console.log(app.url); // e.g. "http://127.0.0.1:54321"
470
+ const tasks = await api.tasks.get();
524
471
 
525
- // Invoke the HTTP router directly in-memory without opening a network socket:
526
- const res = await app.fetch(new Request("http://localhost/health"));
527
- console.log(await res.json()); // { ok: true }
472
+ // GET with custom header
473
+ const profile = await api.profile.get(authHeaders);
528
474
 
529
- // Gracefully close the HTTP server and await all pending wire.defer() background tasks:
530
- await app.close();
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
+ }
531
527
  ```
532
528
 
533
529
  ---
534
530
 
535
- ## 5. Domain-Tree Projection & Routing
531
+ ## 5. Static Routing, Redirects & Custom Error Pages
536
532
 
537
- ### 5.1 Static, Dynamic, Typed, and Wildcard Segments
533
+ ### 5.1 Static File & Folder Routing (`serveStatic` & `static`)
538
534
 
539
- Every property key inside `api` corresponds to a URL path segment:
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.
540
536
 
541
- - **Static segment (`users`, `summary`):** Matches the exact path segment (`/users/summary`).
542
- - **Untyped dynamic parameter (`$slug`, `$username`):** Matches any single non-empty URL segment and decodes URI components (`/posts/:slug`).
543
- - **Typed dynamic parameter (`$id: param(...)`):** Validates and coerces the URL segment according to the specified rule. If validation fails, the route is skipped (resulting in `404 Not Found` or falling back to a lower-priority sibling route).
544
- - **Wildcard catch-all (`$path`):** Matches all remaining trailing path segments joined with `/` (`/files/docs/2026/report.pdf` -> `path = "docs/2026/report.pdf"`).
537
+ **Step 1 — Mount static folders or single files via `serve({ static })`:**
545
538
 
546
539
  ```javascript
547
- import { serve, param } from "servin";
540
+ import { serve } from "servin";
548
541
 
549
542
  await serve({
550
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
+ },
551
548
  api: {
552
- files: {
553
- // GET /files/a/b/c.txt -> path = "a/b/c.txt"
554
- $path: {
555
- get(path) {
556
- return { requestedPath: path };
557
- },
558
- },
559
- },
560
- users: {
561
- // 1. Static route: GET /users/me
562
- me: {
563
- get: () => ({ id: 0, username: "current_user" }),
564
- },
565
- // 2. Typed int route: GET /users/42
566
- $id: param("int", {
567
- get(id) {
568
- return { id, type: typeof id }; // { id: 42, type: "number" }
569
- },
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.
570
573
  }),
571
- // 3. Fallback untyped route: GET /users/nadia
572
- $username: {
573
- get(username) {
574
- return { username, type: typeof username }; // { username: "nadia", type: "string" }
575
- },
576
- },
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>`;
577
691
  },
578
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 }) } },
579
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();
580
757
  ```
581
758
 
582
- ### 5.2 Automatic Route Matching Priority
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 `/`.
583
769
 
584
- Regardless of property definition order in your JavaScript objects, `servin` sorts compiled routes deterministically per segment from highest to lowest specificity:
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
585
784
 
586
- 1. **Priority 0 — Static segments** (`me`, `add`, `summary`)
587
- 2. **Priority 1 — Typed dynamic parameters** (`$id: param(...)`)
588
- 3. **Priority 2 — Untyped dynamic parameters** (`$username`)
589
- 4. **Priority 3 — Wildcard catch-all segments** (`$path`)
785
+ Regardless of object key order, `servin` always matches segments from most specific to least specific:
590
786
 
591
- ### 5.3 HTTP Methods, Method Unions & Shorthand Leaf Functions
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)
592
791
 
593
- Inside any route object, define handlers using lowercase HTTP verb keys:
792
+ ### 7.3 Method Unions (`'put|patch'`) & Shorthand Leaf Functions
594
793
 
595
- - Standard HTTP verbs: `get`, `post`, `put`, `patch`, `delete`, `head`, `options`
596
- - WebSocket upgrade handler: `ws`
597
- - **Method Unions:** Combine multiple verbs with `|` to share a single handler cleanly:
794
+ **1. Method Unions:** Share one handler across multiple HTTP verbs using `|`:
598
795
 
599
796
  ```javascript
600
- const articles = {
797
+ const items = {
601
798
  $id: param("int", {
602
- async "put|patch"(id, payload) {
603
- const isPartial = wire.method === "PATCH";
604
- return { id, isPartial, payload };
799
+ "put|patch"(id, payload) {
800
+ return { methodUsed: wire.method, id, payload };
605
801
  },
606
802
  }),
607
803
  };
608
804
  ```
609
805
 
610
- - **Shorthand Leaf Functions:** Assigning a function directly to a non-verb key creates a leaf route automatically:
611
- - A standard function (`fn`) maps to **`POST`** on that path.
612
- - An async generator function (`async *fn()`) maps to **`GET`** streaming Server-Sent Events (`text/event-stream`).
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)
613
810
 
614
811
  ```javascript
615
- const system = {
616
- // Maps directly to POST /system/reboot
617
- reboot(payload) {
618
- return { rebooting: true, reason: payload.reason };
812
+ const actions = {
813
+ // POST /actions/sync
814
+ sync(payload) {
815
+ return { synced: true, payload };
619
816
  },
620
817
 
621
- // Maps directly to GET /system/metrics (SSE stream)
622
- async *metrics() {
623
- yield { cpu: 12 };
624
- yield { cpu: 18 };
818
+ // GET /actions/events (SSE stream)
819
+ async *events() {
820
+ yield { status: "started" };
821
+ yield { status: "finished" };
625
822
  },
626
823
  };
627
824
  ```
628
825
 
629
- ### 5.4 Predictable Handler Argument Mapping
826
+ ### 7.4 Handler Argument Order
630
827
 
631
- `servin` passes arguments to your handler functions in a strict, predictable order:
828
+ Arguments are always passed in this order:
632
829
 
633
- 1. **Extracted URL parameters** (`$...` and `$path`) from left to right, already decoded and type-coerced.
634
- 2. **Parsed `payload`** (for body-bearing methods `POST`, `PUT`, `PATCH`, unless `rawBody: true` or streaming `multipart/form-data` is used).
635
- 3. **`query` object** (`Record<string, string>`) parsed from `url.searchParams` as the final argument.
636
- 4. For **`ws`** handlers: `(...extractedParams, socket)`.
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.
637
833
 
638
834
  ```javascript
835
+ // PATCH /orgs/10/members/550e8400-e29b-41d4-a716-446655440000?notify=true
639
836
  const orgs = {
640
837
  $orgId: param("int", {
641
838
  members: {
642
839
  $memberId: param("uuid", {
643
- // 1. orgId (number), 2. memberId (string), 3. payload (object), 4. query (object)
644
840
  patch(orgId, memberId, payload, query) {
645
- return { orgId, memberId, payload, notify: query.notify === "true" };
646
- },
647
-
648
- // 1. orgId (number), 2. memberId (string), 3. query (object)
649
- get(orgId, memberId, query) {
650
- return { orgId, memberId, includeRoles: query.roles === "1" };
841
+ return { orgId, memberId, payload, notify: query.notify };
651
842
  },
652
843
  }),
653
844
  },
@@ -655,57 +846,74 @@ const orgs = {
655
846
  };
656
847
  ```
657
848
 
658
- ### 5.5 Typed Route Parameters (`param`) — Complete Type Guide
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.
659
852
 
660
- Use `param(rule, branch)` on any `$`-prefixed key so your object keys remain clean JavaScript identifiers without string quotes. `param()` accepts **five kinds of rules**:
853
+ You can supply `rule` in **five ways**:
661
854
 
662
855
  #### A. Built-in String Type Names
663
856
 
664
- | Rule String | Validation Rule | Coerced JS Type | Matches Example | Rejects (`404`) Example |
665
- | :---------- | :---------------------------------------------------- | :------------------- | :------------------------------------- | :------------------------------------ |
666
- | `'int'` | Non-negative safe integer (`/^\d+$/`) | `number` | `0`, `42`, `1005` | `-1`, `3.14`, `42abc`, `abc` |
667
- | `'number'` | Signed integer or decimal (`/^-?\d+(?:\.\d+)?$/`) | `number` | `-10`, `42`, `19.99` | `10px`, `NaN`, `abc` |
668
- | `'float'` | Alias for `'number'` | `number` | `-0.5`, `12.34` | `abc` |
669
- | `'bigint'` | Arbitrary-precision signed integer (`/^-?\d+$/`) | `bigint` | `9007199254740993` | `12.5`, `abc` |
670
- | `'uuid'` | Standard UUID v1–v5 (case-insensitive) | `string` (lowercase) | `550e8400-e29b-41d4-a716-446655440000` | `not-a-uuid`, `12345` |
671
- | `'alpha'` | ASCII letters only (`/^[a-zA-Z]+$/`) | `string` | `en`, `Indonesia` | `en2`, `en-US` |
672
- | `'alnum'` | ASCII letters and digits (`/^[a-zA-Z0-9]+$/`) | `string` | `v2026`, `user99` | `user-99`, `v2.0` |
673
- | `'slug'` | Lowercase kebab-case (`/^[a-z0-9]+(?:-[a-z0-9]+)*$/`) | `string` | `hello-world-2026` | `Hello_World`, `-leading` |
674
- | `'bool'` | `'true'`, `'1'`, `'false'`, `'0'` (case-insensitive) | `boolean` | `true`, `1`, `FALSE`, `0` | `yes`, `no`, `2` |
675
- | `'boolean'` | Alias for `'bool'` | `boolean` | `true`, `false` | `maybe` |
676
- | `'string'` | Any valid URI-decoded string | `string` | `anything` | Invalid percent-encoding (`%E0%A4%A`) |
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
+ ```
677
881
 
678
882
  #### B. Native JavaScript Constructors
679
883
 
680
- You can pass JavaScript built-in constructors directly:
884
+ Pass `Number`, `Boolean`, `BigInt`, or `String` directly:
681
885
 
682
- - `param(Number, branch)` — equivalent to `'number'` (coerces to `number`)
683
- - `param(Boolean, branch)` — equivalent to `'bool'` (coerces to `boolean`)
684
- - `param(BigInt, branch)` — equivalent to `'bigint'` (coerces to `bigint`)
685
- - `param(String, branch)` — equivalent to `'string'` (passes `string`)
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
+ ```
686
893
 
687
- #### C. Inline `RegExp` Literals
894
+ #### C. Inline `RegExp` Literals (Custom Formats)
688
895
 
689
- Pass any regular expression directly without string escaping:
896
+ Pass any `RegExp` literal directly for custom code formats, SKUs, or structured identifiers:
690
897
 
691
898
  ```javascript
692
- const catalog = {
693
- // Matches /catalog/PRD-1042, rejects /catalog/prd-1042
899
+ const products = {
900
+ // Matches /products/SKU-1024, rejects /products/sku-1024 or /products/1024
694
901
  $sku: param(/^[A-Z]{3}-\d{4}$/, {
695
- get(sku) {
696
- return { sku };
697
- },
902
+ get: (sku) => ({ sku }),
698
903
  }),
699
904
  };
700
905
  ```
701
906
 
702
- #### D. Inline Validator & Transformer Functions
907
+ #### D. Custom Validator / Transformer Function
908
+
909
+ Pass a function `(rawSegment) => parsedValue | null | undefined | false`:
703
910
 
704
- Pass a function `(raw: string) => parsedValue`. Returning `null`, `undefined`, `false`, or throwing an error rejects the route (`404`). Returning any other value passes that transformed value directly to your handler:
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`).
705
913
 
706
914
  ```javascript
707
915
  const events = {
708
- // Parses YYYY-MM-DD directly into a JavaScript Date instance
916
+ // Parses "YYYY-MM-DD" into a real Date instance
709
917
  $date: param(
710
918
  (raw) => {
711
919
  if (!/^\d{4}-\d{2}-\d{2}$/.test(raw)) return null;
@@ -713,10 +921,7 @@ const events = {
713
921
  return Number.isNaN(d.getTime()) ? null : d;
714
922
  },
715
923
  {
716
- get(date) {
717
- // `date` is already a valid Date object
718
- return { iso: date.toISOString() };
719
- },
924
+ get: (date) => ({ iso: date.toISOString() }),
720
925
  },
721
926
  ),
722
927
  };
@@ -724,13 +929,13 @@ const events = {
724
929
 
725
930
  #### E. Global Reusable Custom Types (`serve({ types })`)
726
931
 
727
- Register custom types once in `serve()` and reference them by name anywhere in your domain tree:
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:
728
933
 
729
934
  ```javascript
730
935
  await serve({
731
936
  port: 3000,
732
937
  types: {
733
- invoiceId: /^INV-\d{6}$/,
938
+ invoiceCode: /^INV-\d{6}$/,
734
939
  positiveInt: (raw) => {
735
940
  const n = Number(raw);
736
941
  return Number.isInteger(n) && n > 0 ? n : null;
@@ -738,14 +943,10 @@ await serve({
738
943
  },
739
944
  api: {
740
945
  invoices: {
741
- $id: param("invoiceId", {
742
- get: (id) => ({ invoice: id }),
743
- }),
946
+ $code: param("invoiceCode", { get: (code) => ({ code }) }),
744
947
  },
745
948
  pages: {
746
- $page: param("positiveInt", {
747
- get: (page) => ({ page }),
748
- }),
949
+ $page: param("positiveInt", { get: (page) => ({ page }) }),
749
950
  },
750
951
  },
751
952
  });
@@ -753,676 +954,515 @@ await serve({
753
954
 
754
955
  ---
755
956
 
756
- ## 6. Automatic Response Formatting & HTML Rendering
757
-
758
- ### 6.1 Content-Type Resolution Matrix
957
+ ## 8. Response Formatting, HTML & Streaming
759
958
 
760
- `servin` inspects the return value of your handler and constructs the HTTP response automatically:
959
+ ### 8.1 Automatic `Content-Type` Matrix
761
960
 
762
- | Handler Return Value | Default HTTP Status | `Content-Type` Header | Behavior |
763
- | :------------------------------ | :-------------------- | :--------------------------------- | :---------------------------------------------------------------------------------- |
764
- | Plain `Object` or `Array` | `200` | `application/json; charset=utf-8` | Applies `redact` rules and `?fields=` masks, then serializes to JSON. |
765
- | `wire.html(...)` | `200` | `text/html; charset=utf-8` | Sends rendered HTML string. |
766
- | `wire.file(path)` | `200` / `206` / `304` | Auto-detected from file extension | Streams file from disk with `ETag` and `Accept-Ranges: bytes`. |
767
- | `string` | `200` | `text/plain; charset=utf-8` | Sends plain text (unless `Content-Type` was explicitly set via `wire.headers.set`). |
768
- | `null` or `undefined` | `204` | _(none)_ | Sends an empty body (`204 No Content`, or explicit `wire.status(code)`). |
769
- | `async *generator()` | `200` | `text/event-stream; charset=utf-8` | Streams yielded values as Server-Sent Events (`data: <json>\n\n`). |
770
- | `ReadableStream` / `Uint8Array` | `200` | _(user-defined or default)_ | Streams raw binary bytes directly to the response. |
771
- | Web `Response` | `Response.status` | `Response.headers` | Returned verbatim as-is. |
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. |
772
971
 
773
- ### 6.2 XSS-Safe HTML Templates & Raw HTML (`wire.html`)
972
+ ### 8.2 HTML Responses & XSS Protection (`wire.html`)
774
973
 
775
- Returning a plain `string` always defaults to `text/plain` to prevent accidental Cross-Site Scripting (XSS). To send HTML responses, use **`wire.html`**:
776
-
777
- 1. **Tagged Template Literal (Recommended):** Automatically HTML-escapes all interpolated variables (`&`, `<`, `>`, `"`, `'`), while preserving nested `wire.html` fragments and arrays of fragments unescaped.
778
- 2. **Direct Function Call:** `wire.html(rawHtmlString)` sends an already-trusted HTML string with `Content-Type: text/html; charset=utf-8`.
974
+ **1. Raw HTML string:**
779
975
 
780
976
  ```javascript
781
- import { serve, wire } from "servin";
782
-
783
- await serve({
784
- port: 3000,
785
- api: {
786
- // 1. Tagged template with automatic XSS escaping and nested components
787
- greet: {
788
- $name: {
789
- get(name) {
790
- const badges = ["Admin", "Verified"].map(
791
- (b) => wire.html`<span class="badge">${b}</span>`,
792
- );
793
-
794
- // If `name` is "<script>alert(1)</script>", it is safely escaped to &lt;script&gt;...
795
- // Meanwhile `badges` (already HtmlResponse instances) render as real <span> tags.
796
- return wire.html`
797
- <!doctype html>
798
- <html>
799
- <body>
800
- <h1>Welcome, ${name}!</h1>
801
- <div class="badges">${badges}</div>
802
- </body>
803
- </html>
804
- `;
805
- },
806
- },
807
- },
977
+ const page = {
978
+ get: () => wire.html("<h1>Hello World</h1>"),
979
+ };
980
+ ```
808
981
 
809
- // 2. Direct string call
810
- banner: {
811
- get: () => wire.html('<div class="banner">System Operational</div>'),
812
- },
982
+ **2. Tagged template literal (auto-escapes untrusted variables against XSS):**
813
983
 
814
- // 3. Manual Content-Type header override on a plain string
815
- custom: {
816
- get() {
817
- wire.headers.set("content-type", "text/html; charset=utf-8");
818
- return "<p>Sent with explicit header</p>";
819
- },
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>`;
820
990
  },
821
991
  },
822
- });
992
+ };
823
993
  ```
824
994
 
825
- ### 6.3 Streaming Files with ETag & Byte-Range (`wire.file`)
826
-
827
- `wire.file(filePath)` streams files directly from the filesystem without loading them into memory. It automatically:
828
-
829
- - Resolves MIME types (`.html`, `.css`, `.js`, `.json`, `.svg`, `.png`, `.jpg`, `.webp`, `.pdf`, `.mp4`, `.mp3`, `.zip`, etc.).
830
- - Computes weak `ETag` headers (`W/"<size>-<mtimeMs>"`) and responds with `304 Not Modified` when `If-None-Match` matches.
831
- - Supports HTTP `Range: bytes=start-end` headers (`206 Partial Content` and `416 Range Not Satisfiable`) for audio/video scrubbing and resumable downloads.
995
+ **3. Composing nested `wire.html` fragments safely:**
832
996
 
833
997
  ```javascript
834
- import path from "node:path";
835
- import { serve, wire } from "servin";
836
-
837
- const PAGES_DIR = path.resolve("./pages");
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
+ ```
838
1008
 
839
- await serve({
840
- port: 3000,
841
- api: {
842
- // GET /home -> ./pages/home.html
843
- home: {
844
- get: () => wire.file("./pages/home.html"),
845
- },
1009
+ ### 8.3 File Streaming with `ETag` & Byte-Range (`wire.file`)
846
1010
 
847
- // GET /docs/guide -> ./pages/guide.html (with path-traversal protection)
848
- docs: {
849
- $slug: {
850
- get(slug) {
851
- const resolved = path.resolve(PAGES_DIR, `${slug}.html`);
852
- if (!resolved.startsWith(PAGES_DIR + path.sep)) {
853
- wire.abort(403, "Access denied");
854
- }
855
- return wire.file(resolved);
856
- },
857
- },
858
- },
859
- },
860
- });
1011
+ ```javascript
1012
+ const landing = {
1013
+ get: () => wire.file("./public/index.html"),
1014
+ };
861
1015
  ```
862
1016
 
863
- ### 6.4 Server-Sent Events (SSE) with Async Generators
1017
+ ### 8.4 Server-Sent Events (SSE) with Async Generators
864
1018
 
865
- Define an `async *get()` method (or a leaf `async *name()`) to stream real-time events over HTTP. If the client closes the connection early, `servin` automatically invokes `iterator.return()` and runs any registered `wire.undo()` cleanup handlers:
1019
+ Use `async *get()` to stream live updates. If the client disconnects early, `servin` automatically stops the generator and runs any `wire.undo()` cleanup:
866
1020
 
867
1021
  ```javascript
868
- import { serve, wire } from "servin";
869
-
870
- await serve({
871
- port: 3000,
872
- api: {
873
- notifications: {
874
- async *stream(query) {
875
- let count = 0;
876
- const interval = setInterval(() => {}, 1000);
877
- wire.undo(() => clearInterval(interval));
878
-
879
- while (!wire.signal.aborted && count < 5) {
880
- count++;
881
- yield {
882
- id: count,
883
- channel: query.channel || "general",
884
- ts: Date.now(),
885
- };
886
- await new Promise((r) => setTimeout(r, 1000));
887
- }
888
- },
889
- },
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
+ }
890
1028
  },
891
- });
1029
+ };
892
1030
  ```
893
1031
 
894
- ### 6.5 Sparse Fieldsets (`?fields=`) & Automatic Redaction (`redact`)
1032
+ ### 8.5 Sparse Fieldsets (`?fields=`) & Automatic Redaction (`redact`)
895
1033
 
896
- - **Global Field Redaction (`redact`):** Any matching key names or dot-paths configured in `serve({ redact: [...] })` are stripped recursively from all JSON responses before serialization and caching.
897
- - **Client-Driven Sparse Fieldsets (`?fields=`):** Every `GET` endpoint returning a JSON object or array automatically supports `?fields=id,title,author.name` to trim unused properties before serialization.
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.
898
1036
 
899
1037
  ```javascript
900
1038
  await serve({
901
1039
  port: 3000,
902
- redact: ["password*", "*.secret", "internalNotes"],
1040
+ redact: ["password*", "*.secret"],
903
1041
  api: {
904
1042
  users: {
905
1043
  get: () => [
906
1044
  {
907
1045
  id: 1,
908
1046
  name: "Nadia",
909
- passwordHash: "$2b$10$...", // Automatically stripped by `redact`
910
- profile: { email: "nadia@example.com", secret: "xyz" }, // `secret` stripped
1047
+ email: "nadia@example.com",
1048
+ passwordHash: "xyz",
911
1049
  },
912
1050
  ],
913
1051
  },
914
1052
  },
915
1053
  });
916
- // GET /users?fields=id,profile.email -> [{ "id": 1, "profile": { "email": "nadia@example.com" } }]
1054
+ // GET /users?fields=id,name -> [{ "id": 1, "name": "Nadia" }]
917
1055
  ```
918
1056
 
919
1057
  ---
920
1058
 
921
- ## 7. Security, Sessions & Traffic Control
1059
+ ## 9. Security, Sessions & Traffic Control
922
1060
 
923
- ### 7.1 Branch & Leaf Protection (`guard`)
1061
+ ### 9.1 Protecting Routes & Branches (`guard`)
924
1062
 
925
- `guard(policyFn, branch)` attaches an authorization or precondition policy to an entire domain subtree or a single leaf route. Guards execute **before** request body parsing, **before** rate-limit accounting, and **before** WebSocket `101 Switching Protocols` handshakes. Multiple `guard()` wrappers compose cleanly from outer to inner branches.
1063
+ **Step 1 — Guard a single endpoint:**
926
1064
 
927
1065
  ```javascript
928
- import { serve, wire, guard, param } from "servin";
1066
+ import { wire, guard } from "servin";
929
1067
 
930
1068
  function requireAuth() {
931
- if (!wire.session.userId) {
932
- wire.abort(401, "Authentication required");
933
- }
1069
+ if (!wire.session.userId) wire.abort(401, "Please sign in");
934
1070
  }
935
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
936
1080
  function requireAdmin() {
937
- if (wire.session.role !== "admin") {
938
- wire.abort(403, "Administrator privileges required");
939
- }
1081
+ if (wire.session.role !== "admin") wire.abort(403, "Admins only");
940
1082
  }
941
1083
 
942
- await serve({
943
- port: 3000,
944
- session: {
945
- secret: process.env.SESSION_SECRET || "dev-secret-change-in-production",
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 }),
946
1089
  },
947
- api: {
948
- // Public route: `wire.session` is never touched, incurring zero cookie/store overhead
949
- status: {
950
- get: () => ({ status: "healthy" }),
1090
+ admin: guard(requireAdmin, {
1091
+ settings: {
1092
+ get: () => ({ maintenanceMode: false }),
951
1093
  },
952
-
953
- // Protected branch: requires authenticated user, and nested `admin` requires admin role
954
- account: guard(requireAuth, {
955
- profile: {
956
- get: () => ({ userId: wire.session.userId, role: wire.session.role }),
957
- },
958
- admin: guard(requireAdmin, {
959
- users: {
960
- $id: param("int", {
961
- delete: (id) => ({ deletedUserId: id }),
962
- }),
963
- },
964
- }),
965
- }),
966
- },
1094
+ }),
967
1095
  });
968
1096
  ```
969
1097
 
970
- ### 7.2 Lazy Reactive Sessions (`wire.session`) & Multi-Device Control (`wire.sessions`)
1098
+ ### 9.2 Lazy Encrypted Sessions (`wire.session` & `wire.sessions`)
971
1099
 
972
- When `session: { secret }` is configured in `serve()`, `wire.session` provides an AES-256-GCM encrypted, HttpOnly cookie-backed session managed through a **Lazy Proxy**:
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.
973
1101
 
974
- - **Zero Overhead on Public Routes:** If a handler never reads or writes `wire.session`, cookies are never decrypted and the session store is never queried.
975
- - **Plain Object Semantics:** Assign or delete properties directly (`wire.session.userId = 42`, `delete wire.session.tempFlag`). Changes are persisted and `Set-Cookie` is emitted automatically before headers are sent.
976
- - **Session Fixation Protection:** Call `await wire.session.rotate()` on login to issue a fresh session ID and invalidate the previous one.
977
- - **Multi-Device Tracking & Cross-Protocol Auto-Kick:** Call `wire.session.bind(userId)` to associate the session with a user account. Setting `wire.session = null` on logout deletes the store record, clears the cookie, and **immediately closes all active WebSockets** bound to that session (`4001 Session revoked`).
1102
+ **Step 1 — Enable sessions in `serve()` and read/write properties:**
978
1103
 
979
1104
  ```javascript
980
- import { serve, wire, guard } from "servin";
981
-
982
1105
  await serve({
983
1106
  port: 3000,
984
- session: {
985
- secret: "super-secret-key-at-least-32-chars",
986
- cookieName: "app_sid",
987
- ttl: "7d",
988
- rolling: true,
989
- secure: process.env.NODE_ENV === "production",
990
- sameSite: "Lax",
991
- },
1107
+ session: { secret: "replace-with-32-char-secret-key!!" },
992
1108
  api: {
993
- auth: {
994
- login: {
995
- async post({ email, password }) {
996
- const user = { id: 42, name: "Nadia", role: "admin" };
997
-
998
- await wire.session.rotate();
999
- wire.session.bind(user.id);
1000
- wire.session.userId = user.id;
1001
- wire.session.role = user.role;
1002
- wire.session.device = wire.headers.get("user-agent") || "Unknown";
1003
-
1004
- return { id: user.id, name: user.name };
1005
- },
1109
+ counter: {
1110
+ get() {
1111
+ wire.session.views = (wire.session.views || 0) + 1;
1112
+ return { views: wire.session.views };
1006
1113
  },
1114
+ },
1115
+ },
1116
+ });
1117
+ ```
1007
1118
 
1008
- logout: {
1009
- post() {
1010
- // Destroys store record, clears cookie, and kicks active WebSockets for this session
1011
- wire.session = null;
1012
- return { signedOut: true };
1013
- },
1014
- },
1119
+ **Step 2 — Rotate session ID on login & destroy on logout:**
1015
1120
 
1016
- devices: guard(
1017
- () => {
1018
- if (!wire.session.userId) wire.abort(401);
1019
- },
1020
- {
1021
- // List all active sessions bound to the current user
1022
- get: () => wire.sessions.list(wire.session.userId),
1023
-
1024
- // Revoke all other devices and close their active WebSockets
1025
- revokeOthers: {
1026
- async post() {
1027
- const revokedCount = await wire.sessions.revokeOthers(
1028
- wire.session.userId,
1029
- );
1030
- return { revokedCount };
1031
- },
1032
- },
1033
- },
1034
- ),
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 };
1035
1129
  },
1036
1130
  },
1037
- });
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
+ };
1038
1154
  ```
1039
1155
 
1040
- ### 7.3 Custom Session Store Interface (Redis / Database)
1156
+ ### 9.3 Custom Session Store Interface (Redis / Database)
1041
1157
 
1042
- By default, `servin` uses an in-memory store (`MemorySessionStore`). For multi-instance deployments, pass any custom store implementing `get`, `set`, `delete`, `listByUser`, and `revokeOthers`:
1158
+ Pass a custom `store` object to `session` for multi-server deployments:
1043
1159
 
1044
1160
  ```javascript
1045
- const redisSessionStore = {
1161
+ const customStore = {
1046
1162
  async get(sid) {
1047
- const raw = await redis.get(`sess:${sid}`);
1048
- return raw ? JSON.parse(raw) : null; // { userId, data, createdAt, updatedAt, expiresAt }
1163
+ /* return { userId, data, createdAt, updatedAt, expiresAt } | null */
1049
1164
  },
1050
1165
  async set(sid, record) {
1051
- const ttlSec = Math.max(
1052
- 1,
1053
- Math.ceil((record.expiresAt - Date.now()) / 1000),
1054
- );
1055
- await redis.set(`sess:${sid}`, JSON.stringify(record), "EX", ttlSec);
1056
- if (record.userId != null) {
1057
- await redis.sadd(`user_sess:${record.userId}`, sid);
1058
- }
1166
+ /* persist record */
1059
1167
  },
1060
1168
  async delete(sid) {
1061
- const existing = await this.get(sid);
1062
- if (existing?.userId != null) {
1063
- await redis.srem(`user_sess:${existing.userId}`, sid);
1064
- }
1065
- await redis.del(`sess:${sid}`);
1169
+ /* delete sid */
1066
1170
  },
1067
1171
  async listByUser(userId) {
1068
- const sids = await redis.smembers(`user_sess:${userId}`);
1069
- const out = [];
1070
- for (const sid of sids) {
1071
- const rec = await this.get(sid);
1072
- if (rec) {
1073
- out.push({
1074
- id: sid.slice(0, 8),
1075
- createdAt: rec.createdAt,
1076
- updatedAt: rec.updatedAt,
1077
- device: rec.data?.device,
1078
- });
1079
- }
1080
- }
1081
- return out;
1172
+ /* return array of active session summaries */
1082
1173
  },
1083
1174
  async revokeOthers(userId, currentSid) {
1084
- const sids = await redis.smembers(`user_sess:${userId}`);
1085
- const revoked = [];
1086
- for (const sid of sids) {
1087
- if (sid !== currentSid) {
1088
- await this.delete(sid);
1089
- revoked.push(sid);
1090
- }
1091
- }
1092
- return revoked;
1175
+ /* delete all user sessions except currentSid; return revoked sids */
1093
1176
  },
1094
1177
  };
1095
1178
 
1096
1179
  await serve({
1097
1180
  port: 3000,
1098
- session: { secret: process.env.SESSION_SECRET, store: redisSessionStore },
1099
- api: {
1100
- /* ... */
1101
- },
1181
+ session: { secret: process.env.SESSION_SECRET, store: customStore },
1182
+ api: {},
1102
1183
  });
1103
1184
  ```
1104
1185
 
1105
- ### 7.4 Timing-Safe Webhook Verification (`webhook`)
1186
+ ### 9.4 Timing-Safe Webhook Verification (`webhook`)
1106
1187
 
1107
- Add `webhook: { secret, header, algo }` to any endpoint to verify HMAC signatures over the raw request body using `crypto.timingSafeEqual` before JSON parsing occurs. Supports raw hex digests as well as prefixed signatures (`sha256=...`):
1188
+ Verify HMAC signatures automatically over the raw body before JSON parsing:
1108
1189
 
1109
1190
  ```javascript
1110
- export const webhooks = {
1111
- stripe: {
1112
- webhook: {
1113
- secret: process.env.STRIPE_WEBHOOK_SECRET,
1114
- header: "stripe-signature",
1115
- algo: "sha256",
1116
- },
1117
- async post(event) {
1118
- // Only reached if HMAC signature is valid
1119
- return { received: true, type: event.type };
1120
- },
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 };
1121
1199
  },
1122
1200
  };
1123
1201
  ```
1124
1202
 
1125
- ### 7.5 Context-Aware Smart Rate Limiting (`limit` & `wire.cost`)
1203
+ ### 9.5 Rate Limiting (`limit` & `wire.cost`)
1126
1204
 
1127
- Configure `limit: { max, window, key }` on any node to enforce sliding point-bucket rate limits. By default, each request deducts `1` point. Inside your handler, call `wire.cost(points)` to dynamically adjust the cost—for example, charging `5` points on a failed password attempt and `0` points on a valid login:
1205
+ **Step 1 — Basic rate limit per window:**
1128
1206
 
1129
1207
  ```javascript
1130
- import { wire } from "servin";
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()`:**
1131
1215
 
1132
- export const login = {
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 = {
1133
1220
  limit: {
1134
- max: 15,
1221
+ max: 10,
1135
1222
  window: "10m",
1136
- key: (payload) => `login:${payload?.email || "anon"}`,
1223
+ key: (payload) => `login:${payload?.email || "unknown"}`,
1137
1224
  },
1138
1225
  async post(payload) {
1139
- const user = await verifyUser(payload.email, payload.password);
1140
- if (!user) {
1141
- wire.cost(5); // Penalize failed login attempts heavily
1142
- wire.abort(401, "Invalid email or password");
1226
+ const valid = payload.password === "secret123";
1227
+ if (!valid) {
1228
+ wire.cost(5); // Failed attempts consume 5x quota
1229
+ wire.abort(401, "Invalid credentials");
1143
1230
  }
1144
- wire.cost(0); // Successful logins consume 0 quota
1145
- return { id: user.id };
1231
+ wire.cost(0); // Successful login costs 0 points
1232
+ return { ok: true };
1146
1233
  },
1147
1234
  };
1148
1235
  ```
1149
1236
 
1150
- ### 7.6 CORS & Preflight Handling (`origins`)
1151
-
1152
- Pass `origins` to `serve()` to enable Cross-Origin Resource Sharing with credentials and automatic `OPTIONS` preflight responses:
1237
+ ### 9.6 CORS & Preflight Handling (`origins`)
1153
1238
 
1154
1239
  ```javascript
1155
1240
  await serve({
1156
1241
  port: 3000,
1157
1242
  origins: ["https://app.example.com", "http://localhost:5173"],
1158
- api: {
1159
- /* ... */
1160
- },
1243
+ api: {},
1161
1244
  });
1162
1245
  ```
1163
1246
 
1164
1247
  ---
1165
1248
 
1166
- ## 8. Data Integrity, Caching & Resilience
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
+ ```
1167
1261
 
1168
- ### 8.1 Self-Invalidating Response Cache (`cache`)
1262
+ **Step 2 — Automatic invalidation on mutations:**
1169
1263
 
1170
- Setting `cache: '<duration>'` (e.g., `'30s'`, `'5m'`, `'1h'`) on a domain node caches `GET` responses keyed by route parameters and query string. Whenever a mutating method (`POST`, `PUT`, `PATCH`, `DELETE`) succeeds on that node—or on any child branch beneath it—`servin` automatically invalidates both the node's cache entries and any ancestor caches:
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:
1171
1265
 
1172
1266
  ```javascript
1173
- export const posts = {
1174
- cache: "10m", // Caches GET /posts
1175
- get: () => db.posts.findAll(),
1176
- post: (data) => db.posts.create(data), // Automatically purges GET /posts cache
1267
+ const articles = {
1268
+ cache: "5m",
1269
+ get: () => db.articles.all(),
1270
+ post: (data) => db.articles.create(data), // Automatically clears GET /articles cache
1177
1271
 
1178
1272
  $id: param("int", {
1179
- cache: "10m", // Caches GET /posts/:id
1180
- get: (id) => db.posts.findById(id),
1181
- patch: (id, data) => db.posts.update(id, data), // Purges BOTH GET /posts/:id AND GET /posts
1182
- delete: (id) => db.posts.delete(id), // Purges BOTH GET /posts/:id AND GET /posts
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
1183
1276
  }),
1184
1277
  };
1185
1278
  ```
1186
1279
 
1187
- ### 8.2 Request Coalescing (`coalesce`)
1280
+ ### 10.2 Request Coalescing (`coalesce`)
1188
1281
 
1189
- Set `coalesce: true` on expensive `GET` endpoints to deduplicate concurrent identical requests. If 500 clients hit the same URL at the exact same millisecond on a cold cache, the handler executes **once** and all 500 callers receive the resolved result together:
1282
+ Deduplicate simultaneous identical `GET` requests during traffic spikes so your database runs the query only once:
1190
1283
 
1191
1284
  ```javascript
1192
- export const analytics = {
1193
- dashboard: {
1194
- coalesce: true,
1195
- cache: "1m",
1196
- async get() {
1197
- return await db.runHeavyAggregationQuery();
1198
- },
1285
+ const report = {
1286
+ coalesce: true,
1287
+ cache: "30s",
1288
+ async get() {
1289
+ return await db.runExpensiveQuery();
1199
1290
  },
1200
1291
  };
1201
1292
  ```
1202
1293
 
1203
- ### 8.3 Idempotent Mutations (`idempotent`)
1294
+ ### 10.3 Idempotent Mutations (`idempotent`)
1204
1295
 
1205
- Set `idempotent: '<duration>'` on mutating endpoints to deduplicate retries carrying the same `Idempotency-Key` HTTP header:
1296
+ Prevent duplicate writes when clients retry requests with the same `Idempotency-Key` header:
1206
1297
 
1207
1298
  ```javascript
1208
- export const transfers = {
1299
+ const payments = {
1209
1300
  idempotent: "24h",
1210
1301
  async post(payload) {
1211
- // Retries with the same Idempotency-Key return the original response without re-running
1212
- return await ledger.transfer(payload);
1302
+ return await chargeCustomer(payload);
1213
1303
  },
1214
1304
  };
1215
1305
  ```
1216
1306
 
1217
- ### 8.4 Declarative Shape-by-Example Validation (`expect`)
1307
+ ### 10.4 Declarative Input Validation (`expect`)
1218
1308
 
1219
- Define `expect` on any node with `POST`, `PUT`, or `PATCH` handlers to validate request payloads before execution. Invalid payloads automatically return `422 Unprocessable Entity` with structured field-level error details:
1309
+ **Step 1 — Validate basic required fields (returns `422` if invalid):**
1220
1310
 
1221
- Supported field rules:
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
+ ```
1222
1323
 
1223
- - Primitive types: `'string'`, `'number'`, `'boolean'`, `'array'`
1224
- - Built-in format: `'email'`
1225
- - Optional fields: append `?` (e.g., `'string?'`, `'number?'`, `'email?'`)
1226
- - Enum values: pass an array of allowed literals (e.g., `['free', 'pro', 'enterprise']`)
1227
- - Nested objects: nest another schema object
1324
+ **Step 2 — Optional fields (`?`), enums, arrays, and nested objects:**
1228
1325
 
1229
1326
  ```javascript
1230
- export const users = {
1231
- register: {
1232
- expect: {
1233
- email: "email",
1234
- age: "number",
1235
- plan: ["free", "pro"],
1236
- bio: "string?",
1237
- tags: "array?",
1238
- preferences: {
1239
- newsletter: "boolean",
1240
- },
1241
- },
1242
- post(payload) {
1243
- return { created: true, user: payload };
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",
1244
1336
  },
1245
1337
  },
1338
+ post: (payload) => payload,
1246
1339
  };
1247
1340
  ```
1248
1341
 
1249
- ### 8.5 Automatic Rollbacks (`wire.undo`) & Speculative Dry-Runs (`X-Simulate`)
1342
+ ### 10.5 Automatic Rollbacks (`wire.undo`) & Dry-Runs (`X-Simulate`)
1250
1343
 
1251
- Register compensating actions via `wire.undo(fn)` right after each side-effecting step. If any subsequent step throws an error or calls `wire.abort()`, `servin` executes all registered undo callbacks in reverse order (**LIFO**).
1344
+ **Step 1 — Register undo actions after each side effect:**
1252
1345
 
1253
- Additionally, sending **`X-Simulate: true`** in the request headers executes your real handler logic to compute the exact response and status code, then automatically triggers the `wire.undo()` stack before returning—enabling zero-duplication dry-runs and transaction previews:
1346
+ If a later step throws an error or calls `wire.abort()`, `servin` runs all `wire.undo()` functions in reverse order (LIFO):
1254
1347
 
1255
1348
  ```javascript
1256
- import { wire } from "servin";
1257
-
1258
- export const checkout = {
1259
- async post(order) {
1260
- const hold = await inventory.reserve(order.items);
1261
- wire.undo(() => inventory.release(hold.id));
1262
-
1263
- const payment = await billing.charge(order.userId, order.total);
1264
- wire.undo(() => billing.refund(payment.id));
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
1265
1353
 
1266
- // If dispatch fails—or if the client sent `X-Simulate: true`—both
1267
- // `billing.refund` and `inventory.release` run automatically in reverse order.
1268
- const shipment = await shipping.dispatch(hold.id, order.address);
1269
-
1270
- wire.status(201);
1271
- return { trackingId: shipment.id, totalCharged: order.total };
1354
+ await db.credit(to, amount);
1355
+ return { transferred: amount };
1272
1356
  },
1273
1357
  };
1274
1358
  ```
1275
1359
 
1276
- ### 8.6 Graceful Background Tasks (`wire.defer`)
1360
+ **Step 2 — Speculative dry-runs via `X-Simulate: true`:**
1277
1361
 
1278
- Use `wire.defer(fn)` to schedule non-blocking tasks (such as sending emails, webhooks, or audit logs) after the HTTP response is sent. `servin` tracks all active deferred promises and awaits their completion during `SIGTERM` / `SIGINT` / `app.close()` shutdowns:
1279
-
1280
- ```javascript
1281
- import { wire } from "servin";
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.
1282
1363
 
1283
- export const orders = {
1284
- async post(payload) {
1285
- const order = await db.orders.insert(payload);
1364
+ ### 10.6 Graceful Background Tasks (`wire.defer`)
1286
1365
 
1287
- wire.defer(async () => {
1288
- await mailer.sendReceipt(order.email, order.id);
1289
- });
1366
+ Run non-blocking work after sending the HTTP response. `servin` waits for all deferred tasks to finish during server shutdown:
1290
1367
 
1368
+ ```javascript
1369
+ const register = {
1370
+ async post(user) {
1371
+ const saved = await db.users.insert(user);
1372
+ wire.defer(() => sendWelcomeEmail(saved.email));
1291
1373
  wire.status(201);
1292
- return order;
1374
+ return saved;
1293
1375
  },
1294
1376
  };
1295
1377
  ```
1296
1378
 
1297
- ### 8.7 Adaptive Load Shedding (`priority: 'low'`) & API Deprecation (`sunset`)
1298
-
1299
- - **Adaptive Load Shedding:** Mark non-critical endpoints (like exports or recommendations) with `priority: 'low'`. When the Node.js event-loop p95 delay exceeds `lagThresholdMs` (default `60ms`), `servin` automatically sheds those requests with `503 Service Unavailable` and `Retry-After: 2` to protect critical traffic.
1300
- - **API Sunset Headers:** Set `sunset: '2027-01-01'` on legacy endpoints to automatically attach standard `Deprecation: true` and `Sunset` HTTP headers.
1379
+ ### 10.7 Load Shedding (`priority: 'low'`) & Deprecation (`sunset`)
1301
1380
 
1302
1381
  ```javascript
1303
- export const legacy = {
1304
- sunset: "2027-06-01T00:00:00Z",
1305
- exportCsv: {
1306
- priority: "low",
1307
- get: () => generateLargeCsvReport(),
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(),
1308
1387
  },
1309
1388
  };
1310
1389
  ```
1311
1390
 
1312
1391
  ---
1313
1392
 
1314
- ## 9. Unified Linear WebSockets
1393
+ ## 11. Linear WebSockets & Pub/Sub
1315
1394
 
1316
- ### 9.1 Linear WebSocket Streams (`ws` & `for await`)
1395
+ ### 11.1 Step 1: Minimal Echo WebSocket (`ws` & `for await`)
1317
1396
 
1318
- WebSocket endpoints live directly inside your domain tree as a `ws` method. Guards, typed parameters (`param()`), and lazy sessions (`wire.session`) all execute prior to the `101 Switching Protocols` handshake. Inside `ws`, you write the entire connection lifecycle linearly using `for await (const msg of socket)`:
1397
+ Add a `ws(socket)` method anywhere in your tree and iterate over incoming messages linearly with `for await`:
1319
1398
 
1320
1399
  ```javascript
1321
- import { serve, wire, guard, param } from "servin";
1322
-
1323
- const requireUser = () => {
1324
- if (!wire.session.userId) wire.abort(401, "Sign in required");
1325
- };
1400
+ const echo = {
1401
+ // WS /echo
1402
+ async ws(socket) {
1403
+ socket.send({ status: "connected" });
1326
1404
 
1327
- await serve({
1328
- port: 3000,
1329
- session: { secret: "super-secret-key-at-least-32-chars" },
1330
- api: {
1331
- rooms: guard(requireUser, {
1332
- $id: param("slug", {
1333
- // HTTP GET /rooms/general
1334
- get: (id) => ({ room: id, active: true }),
1335
-
1336
- // WS /rooms/general
1337
- async ws(id, socket) {
1338
- const topic = `room:${id}`;
1339
- const joinedAt = Date.now();
1340
-
1341
- socket.join(topic);
1342
- socket.send({ type: "welcome", room: id, user: wire.session.userId });
1343
- socket.broadcast(topic, {
1344
- type: "user_joined",
1345
- user: wire.session.userId,
1346
- });
1347
-
1348
- // Runs automatically when the client disconnects or session is revoked
1349
- wire.undo(() => {
1350
- socket.broadcast(topic, {
1351
- type: "user_left",
1352
- user: wire.session.userId,
1353
- connectedMs: Date.now() - joinedAt,
1354
- });
1355
- });
1356
-
1357
- for await (const message of socket) {
1358
- wire.publish(topic, {
1359
- type: "chat",
1360
- from: wire.session.userId,
1361
- text: message.text,
1362
- });
1363
- }
1364
- },
1365
- }),
1366
- }),
1405
+ for await (const msg of socket) {
1406
+ socket.send({ echoed: msg });
1407
+ }
1367
1408
  },
1368
- });
1409
+ };
1369
1410
  ```
1370
1411
 
1371
- ### 9.2 Pub/Sub Topics & Cross-Protocol Messaging (`wire.publish`)
1412
+ ### 11.2 Step 2: Rooms & Pub/Sub Broadcasting (`socket.join`, `wire.publish`)
1372
1413
 
1373
- Any HTTP handler can broadcast real-time messages to subscribed WebSocket clients using `wire.publish(topic, data)`:
1414
+ Subscribe sockets to named topics and broadcast messages from either WebSocket handlers or HTTP routes:
1374
1415
 
1375
1416
  ```javascript
1376
- export const orders = {
1377
- $id: param("int", {
1378
- approve: {
1379
- async post(id) {
1380
- const updated = await db.orders.markApproved(id);
1381
- // Pushes live update to all WebSocket clients subscribed to `order:42`
1382
- wire.publish(`order:${id}`, { event: "approved", order: updated });
1383
- return updated;
1384
- },
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
+ }
1385
1427
  },
1386
- }),
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
+ },
1387
1437
  };
1388
1438
  ```
1389
1439
 
1390
- **Linear Socket Methods & Properties:**
1440
+ ### 11.3 Step 3: Guarded WebSockets & `wsConfig`
1391
1441
 
1392
- - `for await (const msg of socket)` — Yields parsed JSON objects (or `Uint8Array` for binary frames).
1393
- - `socket.send(data)` — Sends JSON-serialized data or raw `Uint8Array` binary frames to this client.
1394
- - `socket.join(topic)` / `socket.leave(topic)` — Subscribes or unsubscribes the socket from a topic (automatically cleaned up on disconnect).
1395
- - `socket.broadcast(topic, data)` — Sends `data` to all subscribers of `topic` _except_ the sender.
1396
- - `socket.close(code, reason)` — Closes the WebSocket connection cleanly.
1397
- - `socket.isOpen` — Boolean indicating whether the underlying TCP socket is open.
1398
- - `socket.bufferedAmount` — Bytes currently queued in the socket write buffer.
1399
-
1400
- ### 9.3 WebSocket Options (`wsConfig`) & Session Auto-Kick
1401
-
1402
- Customize frame limits, ping/pong heartbeats, and binary mode per branch using `wsConfig`:
1442
+ Combine `guard()`, `param()`, and `wsConfig` (`heartbeat`, `maxPayload`, `binary`) on the same branch:
1403
1443
 
1404
1444
  ```javascript
1405
- export const telemetry = {
1445
+ const liveStream = guard(requireAuth, {
1406
1446
  wsConfig: {
1407
1447
  maxPayload: "256kb",
1408
- heartbeat: "30s", // Automatically sends WebSocket Ping frames and closes unresponsive clients
1409
- binary: true, // Delivers incoming frames as Uint8Array
1410
- },
1411
- async ws(socket) {
1412
- for await (const chunk of socket) {
1413
- socket.send(chunk); // Echo binary Uint8Array
1414
- }
1448
+ heartbeat: "30s",
1415
1449
  },
1416
- };
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
+ });
1417
1459
  ```
1418
1460
 
1419
1461
  ---
1420
1462
 
1421
- ## 10. Streaming Uploads (`wire.multipart` & `rawBody`)
1463
+ ## 12. Streaming File Uploads (`wire.multipart` & `rawBody`)
1422
1464
 
1423
- ### Streaming `multipart/form-data` (`wire.multipart`)
1424
-
1425
- `wire.multipart(opts)` parses incoming multipart streams sequentially without buffering entire file uploads into RAM:
1465
+ **1. Streaming `multipart/form-data` without buffering in RAM:**
1426
1466
 
1427
1467
  ```javascript
1428
1468
  import fs from "node:fs";
@@ -1430,54 +1470,42 @@ import { pipeline } from "node:stream/promises";
1430
1470
  import { Readable } from "node:stream";
1431
1471
  import { wire } from "servin";
1432
1472
 
1433
- export const uploads = {
1473
+ const upload = {
1434
1474
  async post() {
1435
- const metadata = {};
1436
- const uploadedFiles = [];
1475
+ const fields = {};
1476
+ const files = [];
1437
1477
 
1438
- for await (const part of wire.multipart({ maxFileSize: "50mb" })) {
1478
+ for await (const part of wire.multipart({ maxFileSize: "20mb" })) {
1439
1479
  if (part.isField) {
1440
- metadata[part.name] = await part.text();
1480
+ fields[part.name] = await part.text();
1441
1481
  } else if (part.isFile) {
1442
- const dest = `./uploads/${Date.now()}-${part.filename}`;
1482
+ const dest = `./uploads/${part.filename}`;
1443
1483
  await pipeline(
1444
1484
  Readable.fromWeb(part.stream),
1445
1485
  fs.createWriteStream(dest),
1446
1486
  );
1447
- uploadedFiles.push({
1448
- field: part.name,
1449
- filename: part.filename,
1450
- savedTo: dest,
1451
- });
1487
+ files.push(part.filename);
1452
1488
  }
1453
1489
  }
1454
1490
 
1455
- wire.status(201);
1456
- return { metadata, uploadedFiles };
1491
+ return { fields, files };
1457
1492
  },
1458
1493
  };
1459
1494
  ```
1460
1495
 
1461
- ### Raw Unbuffered Binary Uploads (`rawBody: true`)
1462
-
1463
- Set `rawBody: true` on a route to skip body parsing and pipe `wire.stream` directly:
1496
+ **2. Raw unbuffered binary upload (`rawBody: true`):**
1464
1497
 
1465
1498
  ```javascript
1466
- import fs from "node:fs";
1467
- import { pipeline } from "node:stream/promises";
1468
- import { Readable } from "node:stream";
1469
- import { wire } from "servin";
1470
-
1471
- export const blobs = {
1472
- $name: {
1499
+ const rawUpload = {
1500
+ $filename: {
1473
1501
  rawBody: true,
1474
- async put(name) {
1502
+ async put(filename) {
1475
1503
  await pipeline(
1476
1504
  Readable.fromWeb(wire.stream),
1477
- fs.createWriteStream(`./storage/${name}`),
1505
+ fs.createWriteStream(`./uploads/${filename}`),
1478
1506
  );
1479
1507
  wire.status(201);
1480
- return { stored: name };
1508
+ return { saved: filename };
1481
1509
  },
1482
1510
  },
1483
1511
  };
@@ -1485,171 +1513,113 @@ export const blobs = {
1485
1513
 
1486
1514
  ---
1487
1515
 
1488
- ## 11. Decoupled Side Effects (`reactTo`)
1516
+ ## 13. Decoupled Side Effects (`reactTo`)
1489
1517
 
1490
- Use `reactTo(targetHandlerFn, observerFn)` to attach cross-cutting side effects (loyalty points, analytics, audit logs) from separate modules without cluttering core domain handlers. `reactTo` returns an unsubscribe function and never runs when `X-Simulate: true` is active:
1518
+ Attach secondary side effects (analytics, loyalty points, audit logs) from outside your main handler without coupling modules together:
1491
1519
 
1492
1520
  ```javascript
1493
1521
  import { reactTo } from "servin";
1494
- import { orders } from "./modules/orders.js";
1495
1522
 
1496
- const unsubscribe = reactTo(orders.post, async ({ input, output, wire }) => {
1497
- if (output.total >= 100) {
1498
- await db.loyalty.addPoints(output.userId, 50);
1499
- }
1523
+ reactTo(tasks.post, ({ output }) => {
1524
+ console.log(`Audit: task #${output.id} created`);
1500
1525
  });
1501
1526
  ```
1502
1527
 
1503
1528
  ---
1504
1529
 
1505
- ## 12. Zero-Build Virtual ESM Client (`/@client.js`)
1506
-
1507
- `servin` automatically serves a dynamic ES module at **`GET /@client.js`** mirroring your exact domain tree. Frontend apps can import `api` directly in the browser without `fetch()` boilerplate, URL string interpolation, or build steps:
1508
-
1509
- ```javascript
1510
- // In your frontend application (Browser / React / Vue / Svelte / Vanilla JS)
1511
- import { api } from "http://localhost:3000/@client.js";
1512
-
1513
- // 1. GET /tasks?done=false
1514
- const pendingTasks = await api.tasks.get({ done: "false" });
1515
-
1516
- // 2. GET /tasks/1 (typed parameter)
1517
- const task = await api.tasks.$id.get(1);
1518
-
1519
- // 3. POST /tasks
1520
- const created = await api.tasks.post({ title: "Ship v1.0", priority: "high" });
1521
-
1522
- // 4. Method union PUT|PATCH /tasks/1
1523
- const updated = await api.tasks.$id["put|patch"](1, { done: true });
1524
-
1525
- // 5. DELETE /tasks/1 -> returns null on 204
1526
- await api.tasks.$id.delete(1);
1530
+ ## 14. Logging, Debugging & Automated Testing
1527
1531
 
1528
- // 6. Server-Sent Events (async generator endpoint)
1529
- for await (const event of api.notifications.stream({ channel: "alerts" })) {
1530
- console.log("SSE event:", event);
1531
- }
1532
+ ### 14.1 Startup Messages & Access Logs (`message`, `onListen`, `accessLog`)
1532
1533
 
1533
- // 7. WebSocket connection (ws endpoint)
1534
- const room = api.rooms.$id.ws("general");
1535
- room.send({ text: "Hello from the browser!" });
1534
+ **1. Custom startup message:**
1536
1535
 
1537
- for await (const msg of room) {
1538
- console.log("WS message:", msg);
1539
- }
1536
+ ```javascript
1537
+ await serve({
1538
+ port: 3000,
1539
+ message: ({ port, url }) => `Server running on port ${port} (${url})`,
1540
+ api: {},
1541
+ });
1540
1542
  ```
1541
1543
 
1542
- ---
1543
-
1544
- ## 13. Observability, Logging & Automated Testing
1545
-
1546
- ### 13.1 Custom Startup Messages & Access Logs (`message`, `onListen`, `accessLog`)
1547
-
1548
- `servin` logs incoming HTTP and WebSocket traffic automatically (`[servin] GET /tasks 200 1.2ms [CACHE]`) and prints a startup message when ready. Both can be customized or disabled:
1544
+ **2. Custom access log formatter (or `accessLog: false` to disable):**
1549
1545
 
1550
1546
  ```javascript
1551
- import { serve } from "servin";
1552
-
1553
1547
  await serve({
1554
1548
  port: 3000,
1555
-
1556
- // Custom startup message (string, function, or false)
1557
- message: ({ port, url }) => `Server is running on port ${port} -> ${url}`,
1558
-
1559
- // Optional async hook once listening
1560
- async onListen({ port }) {
1561
- console.log(`Health check ready at http://127.0.0.1:${port}/health`);
1562
- },
1563
-
1564
- // Custom access log formatter & filter (or pass `accessLog: false` to disable)
1565
1549
  accessLog(info) {
1566
- if (info.url.pathname === "/health") return null; // Skip noisy healthchecks
1567
- const cacheTag = info.cached ? " [CACHE]" : "";
1568
- return `[${info.status}] ${info.method} ${info.url.pathname} (${info.durationMs.toFixed(1)}ms)${cacheTag}`;
1569
- },
1570
-
1571
- api: {
1572
- health: { get: () => ({ status: "ok" }) },
1550
+ if (info.url.pathname === "/health") return null; // Hide healthchecks
1551
+ return `[${info.status}] ${info.method} ${info.url.pathname} (${info.durationMs.toFixed(1)}ms)`;
1573
1552
  },
1553
+ api: {},
1574
1554
  });
1575
1555
  ```
1576
1556
 
1577
- ### 13.2 Error-Triggered Debug Trace (`wire.log.debug`) & `Server-Timing` (`wire.mark`)
1557
+ ### 14.2 Error-Triggered Debug Trace (`wire.log.debug`) & `Server-Timing` (`wire.mark`)
1578
1558
 
1579
- - **`wire.log.debug(msg, meta)`:** Buffers diagnostic logs per request in memory and **only prints them to stderr if the request fails with an unhandled error**, keeping production logs clean during normal traffic while providing full execution traces on failures.
1580
- - **`wire.mark(label)`:** Measures sub-operation durations and emits them in the standard HTTP `Server-Timing` response header.
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.
1581
1561
 
1582
1562
  ```javascript
1583
- import { wire } from "servin";
1584
-
1585
- export const reports = {
1563
+ const report = {
1586
1564
  async get() {
1587
- wire.log.debug("Starting report generation", {
1588
- userId: wire.session.userId,
1589
- });
1565
+ wire.log.debug("Querying analytics table");
1590
1566
 
1591
1567
  const endDb = wire.mark("db");
1592
- const rows = await db.reports.fetch();
1568
+ const rows = await db.query("SELECT * FROM metrics");
1593
1569
  endDb();
1594
1570
 
1595
- const endFormat = wire.mark("format");
1596
- const summary = formatSummary(rows);
1597
- endFormat();
1598
-
1599
- // Emits header: Server-Timing: db;dur=14.20, format;dur=1.85
1600
- return summary;
1571
+ return rows; // Emits header: Server-Timing: db;dur=12.40
1601
1572
  },
1602
1573
  };
1603
1574
  ```
1604
1575
 
1605
- ### 13.3 Automated Test Synthesis (`synthesizeTests`)
1576
+ ### 14.3 Automated Test Synthesis (`synthesizeTests`)
1606
1577
 
1607
- During local development, set `synthesizeTests: './tests/generated.test.js'`. As you exercise endpoints manually or via your frontend, `servin` records verified inputs, status codes, and response shapes and writes a standalone `node:test` file automatically.
1578
+ Set `synthesizeTests: './tests/api.test.js'` in `serve()` during development to automatically record verified endpoints into a runnable `node:test` file.
1608
1579
 
1609
- ### 13.4 Production Error Snapshots & Local Replay (`snapshotOnError` & `replay`)
1580
+ ### 14.4 Error Snapshots & Local Replay (`snapshotOnError` & `replay`)
1610
1581
 
1611
- Set `snapshotOnError: './snapshots'` to capture full request metadata whenever an unhandled `500` error occurs. You can replay the exact failing request locally against your handler function using `replay()` from `servin/test`:
1582
+ Set `snapshotOnError: './snapshots'` to save failing `500` requests, then replay them locally against your handler:
1612
1583
 
1613
1584
  ```javascript
1614
1585
  import { replay } from "servin/test";
1615
- import { users } from "./modules/users.js";
1586
+ import { tasks } from "./tasks.js";
1616
1587
 
1617
- // Re-executes the failing handler locally with captured URL, headers, and extracted parameters
1618
1588
  await replay(
1619
- users.$id.get,
1589
+ tasks.$id.get,
1620
1590
  "./snapshots/err-2026-11-25T12-00-00-000Z-a1b2c3d4.json",
1621
1591
  );
1622
1592
  ```
1623
1593
 
1624
1594
  ---
1625
1595
 
1626
- ## 14. Complete Ambient `wire` API Reference
1627
-
1628
- | Property / Method | Type / Signature | Description |
1629
- | :-------------------------- | :------------------------------------ | :--------------------------------------------------------------------------------------------------------------------------------------- |
1630
- | `wire.req` | `Request` | Underlying Web Fetch `Request` object. |
1631
- | `wire.method` | `string` | Uppercase HTTP method (`'GET'`, `'POST'`, etc.) or `'WS'`. |
1632
- | `wire.url` | `URL` | Parsed `URL` instance for the active request. |
1633
- | `wire.headers` | `Headers` (Proxy) | `.get()` / `.has()` reads outgoing headers then incoming request headers; `.set()` / `.append()` / `.delete()` mutates response headers. |
1634
- | `wire.stream` | `ReadableStream \| null` | Unbuffered request body byte stream. |
1635
- | `wire.signal` | `AbortSignal` | Triggered when the client disconnects or aborts the request. |
1636
- | `wire.status(code)` | `(number) => void` | Sets the HTTP response status code. |
1637
- | `wire.abort(status, msg)` | `(number, string) => never` | Immediately halts execution, runs `wire.undo()`, and sends `{ error: msg }`. |
1638
- | `wire.undo(fn)` | `(() => any) => void` | Registers a LIFO rollback callback run on errors, aborts, SSE cancel, or `X-Simulate: true`. |
1639
- | `wire.defer(fn)` | `(() => any) => void` | Queues post-response background tasks tracked during graceful shutdown. |
1640
- | `wire.html` | `tag \| (string) => HtmlResponse` | Tagged template literal (auto-escaping XSS) or raw HTML response helper. |
1641
- | `wire.file(path)` | `(string) => FileStreamResponse` | Streams a file with automatic MIME, `ETag` (`304`), and `Range` (`206`). |
1642
- | `wire.multipart(opts)` | `({ maxFileSize }) => AsyncGenerator` | Streams `multipart/form-data` fields and files sequentially without buffering in RAM. |
1643
- | `wire.session` | `Proxy` | Lazy encrypted session object (`rotate()`, `bind(uid)`, `id`, `= null` to destroy). |
1644
- | `wire.sessions` | `{ list, revokeOthers }` | Multi-device session listing and remote WebSocket revocation per `userId`. |
1645
- | `wire.publish(topic, data)` | `(string, any) => void` | Broadcasts data to all WebSocket clients subscribed to `topic`. |
1646
- | `wire.cost(points)` | `(number) => void` | Sets the dynamic rate-limit point cost for the current request. |
1647
- | `wire.log.debug(msg, meta)` | `(string, any) => void` | Request-scoped debug log printed only if an unhandled error occurs. |
1648
- | `wire.log.info(msg, meta)` | `(string, any) => void` | Structured request-tagged console log. |
1649
- | `wire.mark(label)` | `(string) => () => void` | Starts a performance timer and returns a stop function recorded in `Server-Timing`. |
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`. |
1650
1620
 
1651
1621
  ---
1652
1622
 
1653
- ## 15. License
1623
+ ## 16. License
1654
1624
 
1655
1625
  MIT