@dim24/servin 0.0.0-stage → 0.0.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/LICENSE +21 -0
- package/README.md +1655 -3
- package/example/index.js +43 -0
- package/example/router.js +11 -0
- package/index.js +3 -0
- package/package.json +38 -4
- package/src/server.js +793 -0
- package/src/servin.test.js +292 -0
- package/src/session.js +311 -0
- package/src/tree.js +504 -0
- package/src/utils.js +436 -0
- package/src/websocket.js +311 -0
- package/src/wire.js +254 -0
- package/test.js +45 -0
package/README.md
CHANGED
|
@@ -1,3 +1,1655 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# servin
|
|
2
|
+
|
|
3
|
+
**A modern, zero-dependency Node.js web server built around _Domain-Tree Projection_ and _Ambient Wire_.**
|
|
4
|
+
|
|
5
|
+
`servin` lets you build HTTP APIs, 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.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Table of Contents
|
|
10
|
+
|
|
11
|
+
1. [Why servin?](#1-why-servin)
|
|
12
|
+
2. [Requirements & Installation](#2-requirements--installation)
|
|
13
|
+
3. [Step-by-Step 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)
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## 1. Why servin?
|
|
69
|
+
|
|
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.
|
|
71
|
+
|
|
72
|
+
`servin` replaces string routing and middleware chains with two cohesive primitives:
|
|
73
|
+
|
|
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. |
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## 2. Requirements & Installation
|
|
90
|
+
|
|
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`).
|
|
94
|
+
|
|
95
|
+
Install `servin`:
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
npm install servin
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## 3. Step-by-Step Walkthrough
|
|
104
|
+
|
|
105
|
+
### Step 1: Booting the Server (`serve`)
|
|
106
|
+
|
|
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:
|
|
108
|
+
|
|
109
|
+
```javascript
|
|
110
|
+
import { serve } from "servin";
|
|
111
|
+
|
|
112
|
+
await serve({
|
|
113
|
+
port: 3000,
|
|
114
|
+
message: ({ port, url }) => `Server is running on port ${port} (${url})`,
|
|
115
|
+
api: {},
|
|
116
|
+
});
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Run `node server.js` and your server is live on `http://127.0.0.1:3000`.
|
|
120
|
+
|
|
121
|
+
---
|
|
122
|
+
|
|
123
|
+
### Step 2: Understanding the URL Routing Paradigm & Adding `GET`
|
|
124
|
+
|
|
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:
|
|
126
|
+
|
|
127
|
+
```text
|
|
128
|
+
JavaScript Object Tree Projected HTTP Endpoint
|
|
129
|
+
─────────────────────────────────────────────────────────────────
|
|
130
|
+
api: {
|
|
131
|
+
health: {
|
|
132
|
+
get() { ... } ──────► GET /health
|
|
133
|
+
},
|
|
134
|
+
tasks: {
|
|
135
|
+
get(query) { ... } ──────► GET /tasks (and GET /tasks?done=false)
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Any plain object or array returned from `get()` is automatically serialized as `application/json` with status `200 OK`:
|
|
141
|
+
|
|
142
|
+
```javascript
|
|
143
|
+
import { serve } from "servin";
|
|
144
|
+
|
|
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
|
+
]);
|
|
157
|
+
|
|
158
|
+
await serve({
|
|
159
|
+
port: 3000,
|
|
160
|
+
api: {
|
|
161
|
+
// GET /health
|
|
162
|
+
health: {
|
|
163
|
+
get: () => ({ status: "ok" }),
|
|
164
|
+
},
|
|
165
|
+
|
|
166
|
+
// GET /tasks?done=false
|
|
167
|
+
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
|
+
},
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
---
|
|
180
|
+
|
|
181
|
+
### Step 3: Dynamic & Typed URL Parameters (`$id` + `param`)
|
|
182
|
+
|
|
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:
|
|
184
|
+
|
|
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"`).
|
|
187
|
+
|
|
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
|
+
}
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
Use `wire.abort(status, message)` whenever you need to halt execution and send an HTTP error response:
|
|
199
|
+
|
|
200
|
+
```javascript
|
|
201
|
+
import { serve, wire, param } from "servin";
|
|
202
|
+
|
|
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
|
+
});
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
---
|
|
215
|
+
|
|
216
|
+
### Step 4: Creating Resources with `POST`, Validation & Rollbacks
|
|
217
|
+
|
|
218
|
+
Add a `post(payload)` handler to `tasks` to handle `POST /tasks`. You can layer declarative safeguards directly onto the same object:
|
|
219
|
+
|
|
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`.
|
|
224
|
+
|
|
225
|
+
```javascript
|
|
226
|
+
import { wire } from "servin";
|
|
227
|
+
|
|
228
|
+
let nextId = 3;
|
|
229
|
+
|
|
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",
|
|
238
|
+
post(payload) {
|
|
239
|
+
const id = nextId++;
|
|
240
|
+
const record = {
|
|
241
|
+
id,
|
|
242
|
+
title: payload.title,
|
|
243
|
+
priority: payload.priority,
|
|
244
|
+
done: payload.done ?? false,
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
tasksDb.set(id, record);
|
|
248
|
+
wire.undo(() => tasksDb.delete(id));
|
|
249
|
+
wire.status(201);
|
|
250
|
+
return record;
|
|
251
|
+
},
|
|
252
|
+
};
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
---
|
|
256
|
+
|
|
257
|
+
### Step 5: Updating (`put|patch`), Deleting (`delete`) & Auto-Invalidating `cache`
|
|
258
|
+
|
|
259
|
+
Now let's complete the CRUD lifecycle inside `$id` and add `cache: '5m'` to both `tasks` and `$id`:
|
|
260
|
+
|
|
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.
|
|
263
|
+
|
|
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!
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
```javascript
|
|
273
|
+
import { wire, param } from "servin";
|
|
274
|
+
|
|
275
|
+
const taskItemNode = param("int", {
|
|
276
|
+
cache: "5m",
|
|
277
|
+
|
|
278
|
+
// GET /tasks/:id
|
|
279
|
+
get(id) {
|
|
280
|
+
const task = tasksDb.get(id);
|
|
281
|
+
if (!task) wire.abort(404, `Task #${id} not found`);
|
|
282
|
+
return task;
|
|
283
|
+
},
|
|
284
|
+
|
|
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;
|
|
302
|
+
},
|
|
303
|
+
|
|
304
|
+
// DELETE /tasks/:id
|
|
305
|
+
delete(id) {
|
|
306
|
+
if (!tasksDb.has(id)) wire.abort(404, `Task #${id} not found`);
|
|
307
|
+
tasksDb.delete(id);
|
|
308
|
+
wire.status(204);
|
|
309
|
+
return null;
|
|
310
|
+
},
|
|
311
|
+
});
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
---
|
|
315
|
+
|
|
316
|
+
### Step 6: Decoupled Side Effects (`reactTo`) & Serving HTML (`wire.html`)
|
|
317
|
+
|
|
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:
|
|
319
|
+
|
|
320
|
+
```javascript
|
|
321
|
+
import { wire, reactTo } from "servin";
|
|
322
|
+
|
|
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
|
+
});
|
|
327
|
+
|
|
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
|
+
`;
|
|
351
|
+
},
|
|
352
|
+
};
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
---
|
|
356
|
+
|
|
357
|
+
### Step 7: Complete Assembled Application
|
|
358
|
+
|
|
359
|
+
Putting Steps 1 through 6 together produces a clean, self-contained application:
|
|
360
|
+
|
|
361
|
+
```javascript
|
|
362
|
+
import { serve, wire, param, reactTo } from "servin";
|
|
363
|
+
|
|
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
|
+
]);
|
|
376
|
+
let nextId = 3;
|
|
377
|
+
|
|
378
|
+
const tasks = {
|
|
379
|
+
cache: "5m",
|
|
380
|
+
|
|
381
|
+
// GET /tasks?done=false
|
|
382
|
+
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;
|
|
387
|
+
},
|
|
388
|
+
|
|
389
|
+
// POST /tasks
|
|
390
|
+
expect: {
|
|
391
|
+
title: "string",
|
|
392
|
+
priority: ["low", "medium", "high"],
|
|
393
|
+
done: "boolean?",
|
|
394
|
+
},
|
|
395
|
+
idempotent: "10m",
|
|
396
|
+
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));
|
|
406
|
+
wire.status(201);
|
|
407
|
+
return record;
|
|
408
|
+
},
|
|
409
|
+
|
|
410
|
+
// /tasks/:id (integer-only)
|
|
411
|
+
$id: param("int", {
|
|
412
|
+
cache: "5m",
|
|
413
|
+
|
|
414
|
+
get(id) {
|
|
415
|
+
const task = tasksDb.get(id);
|
|
416
|
+
if (!task) wire.abort(404, `Task #${id} not found`);
|
|
417
|
+
return task;
|
|
418
|
+
},
|
|
419
|
+
|
|
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;
|
|
436
|
+
},
|
|
437
|
+
|
|
438
|
+
delete(id) {
|
|
439
|
+
if (!tasksDb.has(id)) wire.abort(404, `Task #${id} not found`);
|
|
440
|
+
tasksDb.delete(id);
|
|
441
|
+
wire.status(204);
|
|
442
|
+
return null;
|
|
443
|
+
},
|
|
444
|
+
}),
|
|
445
|
+
};
|
|
446
|
+
|
|
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
|
+
await serve({
|
|
477
|
+
port: 3000,
|
|
478
|
+
message: ({ port, url }) => `Server is running on port ${port} (${url})`,
|
|
479
|
+
api: {
|
|
480
|
+
home,
|
|
481
|
+
tasks,
|
|
482
|
+
},
|
|
483
|
+
});
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
---
|
|
487
|
+
|
|
488
|
+
## 4. Server Configuration (`serve`)
|
|
489
|
+
|
|
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.
|
|
491
|
+
|
|
492
|
+
### 4.1 Configuration Options Reference
|
|
493
|
+
|
|
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`. |
|
|
511
|
+
|
|
512
|
+
### 4.2 Server Instance API
|
|
513
|
+
|
|
514
|
+
`await serve(config)` returns a control object:
|
|
515
|
+
|
|
516
|
+
```javascript
|
|
517
|
+
const app = await serve({
|
|
518
|
+
port: 0,
|
|
519
|
+
api: { health: { get: () => ({ ok: true }) } },
|
|
520
|
+
});
|
|
521
|
+
|
|
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"
|
|
524
|
+
|
|
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 }
|
|
528
|
+
|
|
529
|
+
// Gracefully close the HTTP server and await all pending wire.defer() background tasks:
|
|
530
|
+
await app.close();
|
|
531
|
+
```
|
|
532
|
+
|
|
533
|
+
---
|
|
534
|
+
|
|
535
|
+
## 5. Domain-Tree Projection & Routing
|
|
536
|
+
|
|
537
|
+
### 5.1 Static, Dynamic, Typed, and Wildcard Segments
|
|
538
|
+
|
|
539
|
+
Every property key inside `api` corresponds to a URL path segment:
|
|
540
|
+
|
|
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"`).
|
|
545
|
+
|
|
546
|
+
```javascript
|
|
547
|
+
import { serve, param } from "servin";
|
|
548
|
+
|
|
549
|
+
await serve({
|
|
550
|
+
port: 3000,
|
|
551
|
+
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
|
+
},
|
|
570
|
+
}),
|
|
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
|
+
},
|
|
577
|
+
},
|
|
578
|
+
},
|
|
579
|
+
});
|
|
580
|
+
```
|
|
581
|
+
|
|
582
|
+
### 5.2 Automatic Route Matching Priority
|
|
583
|
+
|
|
584
|
+
Regardless of property definition order in your JavaScript objects, `servin` sorts compiled routes deterministically per segment from highest to lowest specificity:
|
|
585
|
+
|
|
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`)
|
|
590
|
+
|
|
591
|
+
### 5.3 HTTP Methods, Method Unions & Shorthand Leaf Functions
|
|
592
|
+
|
|
593
|
+
Inside any route object, define handlers using lowercase HTTP verb keys:
|
|
594
|
+
|
|
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:
|
|
598
|
+
|
|
599
|
+
```javascript
|
|
600
|
+
const articles = {
|
|
601
|
+
$id: param("int", {
|
|
602
|
+
async "put|patch"(id, payload) {
|
|
603
|
+
const isPartial = wire.method === "PATCH";
|
|
604
|
+
return { id, isPartial, payload };
|
|
605
|
+
},
|
|
606
|
+
}),
|
|
607
|
+
};
|
|
608
|
+
```
|
|
609
|
+
|
|
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`).
|
|
613
|
+
|
|
614
|
+
```javascript
|
|
615
|
+
const system = {
|
|
616
|
+
// Maps directly to POST /system/reboot
|
|
617
|
+
reboot(payload) {
|
|
618
|
+
return { rebooting: true, reason: payload.reason };
|
|
619
|
+
},
|
|
620
|
+
|
|
621
|
+
// Maps directly to GET /system/metrics (SSE stream)
|
|
622
|
+
async *metrics() {
|
|
623
|
+
yield { cpu: 12 };
|
|
624
|
+
yield { cpu: 18 };
|
|
625
|
+
},
|
|
626
|
+
};
|
|
627
|
+
```
|
|
628
|
+
|
|
629
|
+
### 5.4 Predictable Handler Argument Mapping
|
|
630
|
+
|
|
631
|
+
`servin` passes arguments to your handler functions in a strict, predictable order:
|
|
632
|
+
|
|
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)`.
|
|
637
|
+
|
|
638
|
+
```javascript
|
|
639
|
+
const orgs = {
|
|
640
|
+
$orgId: param("int", {
|
|
641
|
+
members: {
|
|
642
|
+
$memberId: param("uuid", {
|
|
643
|
+
// 1. orgId (number), 2. memberId (string), 3. payload (object), 4. query (object)
|
|
644
|
+
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" };
|
|
651
|
+
},
|
|
652
|
+
}),
|
|
653
|
+
},
|
|
654
|
+
}),
|
|
655
|
+
};
|
|
656
|
+
```
|
|
657
|
+
|
|
658
|
+
### 5.5 Typed Route Parameters (`param`) — Complete Type Guide
|
|
659
|
+
|
|
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**:
|
|
661
|
+
|
|
662
|
+
#### A. Built-in String Type Names
|
|
663
|
+
|
|
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`) |
|
|
677
|
+
|
|
678
|
+
#### B. Native JavaScript Constructors
|
|
679
|
+
|
|
680
|
+
You can pass JavaScript built-in constructors directly:
|
|
681
|
+
|
|
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`)
|
|
686
|
+
|
|
687
|
+
#### C. Inline `RegExp` Literals
|
|
688
|
+
|
|
689
|
+
Pass any regular expression directly without string escaping:
|
|
690
|
+
|
|
691
|
+
```javascript
|
|
692
|
+
const catalog = {
|
|
693
|
+
// Matches /catalog/PRD-1042, rejects /catalog/prd-1042
|
|
694
|
+
$sku: param(/^[A-Z]{3}-\d{4}$/, {
|
|
695
|
+
get(sku) {
|
|
696
|
+
return { sku };
|
|
697
|
+
},
|
|
698
|
+
}),
|
|
699
|
+
};
|
|
700
|
+
```
|
|
701
|
+
|
|
702
|
+
#### D. Inline Validator & Transformer Functions
|
|
703
|
+
|
|
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:
|
|
705
|
+
|
|
706
|
+
```javascript
|
|
707
|
+
const events = {
|
|
708
|
+
// Parses YYYY-MM-DD directly into a JavaScript Date instance
|
|
709
|
+
$date: param(
|
|
710
|
+
(raw) => {
|
|
711
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(raw)) return null;
|
|
712
|
+
const d = new Date(`${raw}T00:00:00Z`);
|
|
713
|
+
return Number.isNaN(d.getTime()) ? null : d;
|
|
714
|
+
},
|
|
715
|
+
{
|
|
716
|
+
get(date) {
|
|
717
|
+
// `date` is already a valid Date object
|
|
718
|
+
return { iso: date.toISOString() };
|
|
719
|
+
},
|
|
720
|
+
},
|
|
721
|
+
),
|
|
722
|
+
};
|
|
723
|
+
```
|
|
724
|
+
|
|
725
|
+
#### E. Global Reusable Custom Types (`serve({ types })`)
|
|
726
|
+
|
|
727
|
+
Register custom types once in `serve()` and reference them by name anywhere in your domain tree:
|
|
728
|
+
|
|
729
|
+
```javascript
|
|
730
|
+
await serve({
|
|
731
|
+
port: 3000,
|
|
732
|
+
types: {
|
|
733
|
+
invoiceId: /^INV-\d{6}$/,
|
|
734
|
+
positiveInt: (raw) => {
|
|
735
|
+
const n = Number(raw);
|
|
736
|
+
return Number.isInteger(n) && n > 0 ? n : null;
|
|
737
|
+
},
|
|
738
|
+
},
|
|
739
|
+
api: {
|
|
740
|
+
invoices: {
|
|
741
|
+
$id: param("invoiceId", {
|
|
742
|
+
get: (id) => ({ invoice: id }),
|
|
743
|
+
}),
|
|
744
|
+
},
|
|
745
|
+
pages: {
|
|
746
|
+
$page: param("positiveInt", {
|
|
747
|
+
get: (page) => ({ page }),
|
|
748
|
+
}),
|
|
749
|
+
},
|
|
750
|
+
},
|
|
751
|
+
});
|
|
752
|
+
```
|
|
753
|
+
|
|
754
|
+
---
|
|
755
|
+
|
|
756
|
+
## 6. Automatic Response Formatting & HTML Rendering
|
|
757
|
+
|
|
758
|
+
### 6.1 Content-Type Resolution Matrix
|
|
759
|
+
|
|
760
|
+
`servin` inspects the return value of your handler and constructs the HTTP response automatically:
|
|
761
|
+
|
|
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. |
|
|
772
|
+
|
|
773
|
+
### 6.2 XSS-Safe HTML Templates & Raw HTML (`wire.html`)
|
|
774
|
+
|
|
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`.
|
|
779
|
+
|
|
780
|
+
```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 <script>...
|
|
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
|
+
},
|
|
808
|
+
|
|
809
|
+
// 2. Direct string call
|
|
810
|
+
banner: {
|
|
811
|
+
get: () => wire.html('<div class="banner">System Operational</div>'),
|
|
812
|
+
},
|
|
813
|
+
|
|
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
|
+
},
|
|
820
|
+
},
|
|
821
|
+
},
|
|
822
|
+
});
|
|
823
|
+
```
|
|
824
|
+
|
|
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.
|
|
832
|
+
|
|
833
|
+
```javascript
|
|
834
|
+
import path from "node:path";
|
|
835
|
+
import { serve, wire } from "servin";
|
|
836
|
+
|
|
837
|
+
const PAGES_DIR = path.resolve("./pages");
|
|
838
|
+
|
|
839
|
+
await serve({
|
|
840
|
+
port: 3000,
|
|
841
|
+
api: {
|
|
842
|
+
// GET /home -> ./pages/home.html
|
|
843
|
+
home: {
|
|
844
|
+
get: () => wire.file("./pages/home.html"),
|
|
845
|
+
},
|
|
846
|
+
|
|
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
|
+
});
|
|
861
|
+
```
|
|
862
|
+
|
|
863
|
+
### 6.4 Server-Sent Events (SSE) with Async Generators
|
|
864
|
+
|
|
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:
|
|
866
|
+
|
|
867
|
+
```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
|
+
},
|
|
890
|
+
},
|
|
891
|
+
});
|
|
892
|
+
```
|
|
893
|
+
|
|
894
|
+
### 6.5 Sparse Fieldsets (`?fields=`) & Automatic Redaction (`redact`)
|
|
895
|
+
|
|
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.
|
|
898
|
+
|
|
899
|
+
```javascript
|
|
900
|
+
await serve({
|
|
901
|
+
port: 3000,
|
|
902
|
+
redact: ["password*", "*.secret", "internalNotes"],
|
|
903
|
+
api: {
|
|
904
|
+
users: {
|
|
905
|
+
get: () => [
|
|
906
|
+
{
|
|
907
|
+
id: 1,
|
|
908
|
+
name: "Nadia",
|
|
909
|
+
passwordHash: "$2b$10$...", // Automatically stripped by `redact`
|
|
910
|
+
profile: { email: "nadia@example.com", secret: "xyz" }, // `secret` stripped
|
|
911
|
+
},
|
|
912
|
+
],
|
|
913
|
+
},
|
|
914
|
+
},
|
|
915
|
+
});
|
|
916
|
+
// GET /users?fields=id,profile.email -> [{ "id": 1, "profile": { "email": "nadia@example.com" } }]
|
|
917
|
+
```
|
|
918
|
+
|
|
919
|
+
---
|
|
920
|
+
|
|
921
|
+
## 7. Security, Sessions & Traffic Control
|
|
922
|
+
|
|
923
|
+
### 7.1 Branch & Leaf Protection (`guard`)
|
|
924
|
+
|
|
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.
|
|
926
|
+
|
|
927
|
+
```javascript
|
|
928
|
+
import { serve, wire, guard, param } from "servin";
|
|
929
|
+
|
|
930
|
+
function requireAuth() {
|
|
931
|
+
if (!wire.session.userId) {
|
|
932
|
+
wire.abort(401, "Authentication required");
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
function requireAdmin() {
|
|
937
|
+
if (wire.session.role !== "admin") {
|
|
938
|
+
wire.abort(403, "Administrator privileges required");
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
await serve({
|
|
943
|
+
port: 3000,
|
|
944
|
+
session: {
|
|
945
|
+
secret: process.env.SESSION_SECRET || "dev-secret-change-in-production",
|
|
946
|
+
},
|
|
947
|
+
api: {
|
|
948
|
+
// Public route: `wire.session` is never touched, incurring zero cookie/store overhead
|
|
949
|
+
status: {
|
|
950
|
+
get: () => ({ status: "healthy" }),
|
|
951
|
+
},
|
|
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
|
+
},
|
|
967
|
+
});
|
|
968
|
+
```
|
|
969
|
+
|
|
970
|
+
### 7.2 Lazy Reactive Sessions (`wire.session`) & Multi-Device Control (`wire.sessions`)
|
|
971
|
+
|
|
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**:
|
|
973
|
+
|
|
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`).
|
|
978
|
+
|
|
979
|
+
```javascript
|
|
980
|
+
import { serve, wire, guard } from "servin";
|
|
981
|
+
|
|
982
|
+
await serve({
|
|
983
|
+
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
|
+
},
|
|
992
|
+
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
|
+
},
|
|
1006
|
+
},
|
|
1007
|
+
|
|
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
|
+
},
|
|
1015
|
+
|
|
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
|
+
),
|
|
1035
|
+
},
|
|
1036
|
+
},
|
|
1037
|
+
});
|
|
1038
|
+
```
|
|
1039
|
+
|
|
1040
|
+
### 7.3 Custom Session Store Interface (Redis / Database)
|
|
1041
|
+
|
|
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`:
|
|
1043
|
+
|
|
1044
|
+
```javascript
|
|
1045
|
+
const redisSessionStore = {
|
|
1046
|
+
async get(sid) {
|
|
1047
|
+
const raw = await redis.get(`sess:${sid}`);
|
|
1048
|
+
return raw ? JSON.parse(raw) : null; // { userId, data, createdAt, updatedAt, expiresAt }
|
|
1049
|
+
},
|
|
1050
|
+
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
|
+
}
|
|
1059
|
+
},
|
|
1060
|
+
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}`);
|
|
1066
|
+
},
|
|
1067
|
+
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;
|
|
1082
|
+
},
|
|
1083
|
+
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;
|
|
1093
|
+
},
|
|
1094
|
+
};
|
|
1095
|
+
|
|
1096
|
+
await serve({
|
|
1097
|
+
port: 3000,
|
|
1098
|
+
session: { secret: process.env.SESSION_SECRET, store: redisSessionStore },
|
|
1099
|
+
api: {
|
|
1100
|
+
/* ... */
|
|
1101
|
+
},
|
|
1102
|
+
});
|
|
1103
|
+
```
|
|
1104
|
+
|
|
1105
|
+
### 7.4 Timing-Safe Webhook Verification (`webhook`)
|
|
1106
|
+
|
|
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=...`):
|
|
1108
|
+
|
|
1109
|
+
```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
|
+
},
|
|
1121
|
+
},
|
|
1122
|
+
};
|
|
1123
|
+
```
|
|
1124
|
+
|
|
1125
|
+
### 7.5 Context-Aware Smart Rate Limiting (`limit` & `wire.cost`)
|
|
1126
|
+
|
|
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:
|
|
1128
|
+
|
|
1129
|
+
```javascript
|
|
1130
|
+
import { wire } from "servin";
|
|
1131
|
+
|
|
1132
|
+
export const login = {
|
|
1133
|
+
limit: {
|
|
1134
|
+
max: 15,
|
|
1135
|
+
window: "10m",
|
|
1136
|
+
key: (payload) => `login:${payload?.email || "anon"}`,
|
|
1137
|
+
},
|
|
1138
|
+
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");
|
|
1143
|
+
}
|
|
1144
|
+
wire.cost(0); // Successful logins consume 0 quota
|
|
1145
|
+
return { id: user.id };
|
|
1146
|
+
},
|
|
1147
|
+
};
|
|
1148
|
+
```
|
|
1149
|
+
|
|
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:
|
|
1153
|
+
|
|
1154
|
+
```javascript
|
|
1155
|
+
await serve({
|
|
1156
|
+
port: 3000,
|
|
1157
|
+
origins: ["https://app.example.com", "http://localhost:5173"],
|
|
1158
|
+
api: {
|
|
1159
|
+
/* ... */
|
|
1160
|
+
},
|
|
1161
|
+
});
|
|
1162
|
+
```
|
|
1163
|
+
|
|
1164
|
+
---
|
|
1165
|
+
|
|
1166
|
+
## 8. Data Integrity, Caching & Resilience
|
|
1167
|
+
|
|
1168
|
+
### 8.1 Self-Invalidating Response Cache (`cache`)
|
|
1169
|
+
|
|
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:
|
|
1171
|
+
|
|
1172
|
+
```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
|
|
1177
|
+
|
|
1178
|
+
$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
|
|
1183
|
+
}),
|
|
1184
|
+
};
|
|
1185
|
+
```
|
|
1186
|
+
|
|
1187
|
+
### 8.2 Request Coalescing (`coalesce`)
|
|
1188
|
+
|
|
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:
|
|
1190
|
+
|
|
1191
|
+
```javascript
|
|
1192
|
+
export const analytics = {
|
|
1193
|
+
dashboard: {
|
|
1194
|
+
coalesce: true,
|
|
1195
|
+
cache: "1m",
|
|
1196
|
+
async get() {
|
|
1197
|
+
return await db.runHeavyAggregationQuery();
|
|
1198
|
+
},
|
|
1199
|
+
},
|
|
1200
|
+
};
|
|
1201
|
+
```
|
|
1202
|
+
|
|
1203
|
+
### 8.3 Idempotent Mutations (`idempotent`)
|
|
1204
|
+
|
|
1205
|
+
Set `idempotent: '<duration>'` on mutating endpoints to deduplicate retries carrying the same `Idempotency-Key` HTTP header:
|
|
1206
|
+
|
|
1207
|
+
```javascript
|
|
1208
|
+
export const transfers = {
|
|
1209
|
+
idempotent: "24h",
|
|
1210
|
+
async post(payload) {
|
|
1211
|
+
// Retries with the same Idempotency-Key return the original response without re-running
|
|
1212
|
+
return await ledger.transfer(payload);
|
|
1213
|
+
},
|
|
1214
|
+
};
|
|
1215
|
+
```
|
|
1216
|
+
|
|
1217
|
+
### 8.4 Declarative Shape-by-Example Validation (`expect`)
|
|
1218
|
+
|
|
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:
|
|
1220
|
+
|
|
1221
|
+
Supported field rules:
|
|
1222
|
+
|
|
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
|
|
1228
|
+
|
|
1229
|
+
```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 };
|
|
1244
|
+
},
|
|
1245
|
+
},
|
|
1246
|
+
};
|
|
1247
|
+
```
|
|
1248
|
+
|
|
1249
|
+
### 8.5 Automatic Rollbacks (`wire.undo`) & Speculative Dry-Runs (`X-Simulate`)
|
|
1250
|
+
|
|
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**).
|
|
1252
|
+
|
|
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:
|
|
1254
|
+
|
|
1255
|
+
```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));
|
|
1265
|
+
|
|
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 };
|
|
1272
|
+
},
|
|
1273
|
+
};
|
|
1274
|
+
```
|
|
1275
|
+
|
|
1276
|
+
### 8.6 Graceful Background Tasks (`wire.defer`)
|
|
1277
|
+
|
|
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";
|
|
1282
|
+
|
|
1283
|
+
export const orders = {
|
|
1284
|
+
async post(payload) {
|
|
1285
|
+
const order = await db.orders.insert(payload);
|
|
1286
|
+
|
|
1287
|
+
wire.defer(async () => {
|
|
1288
|
+
await mailer.sendReceipt(order.email, order.id);
|
|
1289
|
+
});
|
|
1290
|
+
|
|
1291
|
+
wire.status(201);
|
|
1292
|
+
return order;
|
|
1293
|
+
},
|
|
1294
|
+
};
|
|
1295
|
+
```
|
|
1296
|
+
|
|
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.
|
|
1301
|
+
|
|
1302
|
+
```javascript
|
|
1303
|
+
export const legacy = {
|
|
1304
|
+
sunset: "2027-06-01T00:00:00Z",
|
|
1305
|
+
exportCsv: {
|
|
1306
|
+
priority: "low",
|
|
1307
|
+
get: () => generateLargeCsvReport(),
|
|
1308
|
+
},
|
|
1309
|
+
};
|
|
1310
|
+
```
|
|
1311
|
+
|
|
1312
|
+
---
|
|
1313
|
+
|
|
1314
|
+
## 9. Unified Linear WebSockets
|
|
1315
|
+
|
|
1316
|
+
### 9.1 Linear WebSocket Streams (`ws` & `for await`)
|
|
1317
|
+
|
|
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)`:
|
|
1319
|
+
|
|
1320
|
+
```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
|
+
};
|
|
1326
|
+
|
|
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
|
+
}),
|
|
1367
|
+
},
|
|
1368
|
+
});
|
|
1369
|
+
```
|
|
1370
|
+
|
|
1371
|
+
### 9.2 Pub/Sub Topics & Cross-Protocol Messaging (`wire.publish`)
|
|
1372
|
+
|
|
1373
|
+
Any HTTP handler can broadcast real-time messages to subscribed WebSocket clients using `wire.publish(topic, data)`:
|
|
1374
|
+
|
|
1375
|
+
```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
|
+
},
|
|
1385
|
+
},
|
|
1386
|
+
}),
|
|
1387
|
+
};
|
|
1388
|
+
```
|
|
1389
|
+
|
|
1390
|
+
**Linear Socket Methods & Properties:**
|
|
1391
|
+
|
|
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`:
|
|
1403
|
+
|
|
1404
|
+
```javascript
|
|
1405
|
+
export const telemetry = {
|
|
1406
|
+
wsConfig: {
|
|
1407
|
+
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
|
+
}
|
|
1415
|
+
},
|
|
1416
|
+
};
|
|
1417
|
+
```
|
|
1418
|
+
|
|
1419
|
+
---
|
|
1420
|
+
|
|
1421
|
+
## 10. Streaming Uploads (`wire.multipart` & `rawBody`)
|
|
1422
|
+
|
|
1423
|
+
### Streaming `multipart/form-data` (`wire.multipart`)
|
|
1424
|
+
|
|
1425
|
+
`wire.multipart(opts)` parses incoming multipart streams sequentially without buffering entire file uploads into RAM:
|
|
1426
|
+
|
|
1427
|
+
```javascript
|
|
1428
|
+
import fs from "node:fs";
|
|
1429
|
+
import { pipeline } from "node:stream/promises";
|
|
1430
|
+
import { Readable } from "node:stream";
|
|
1431
|
+
import { wire } from "servin";
|
|
1432
|
+
|
|
1433
|
+
export const uploads = {
|
|
1434
|
+
async post() {
|
|
1435
|
+
const metadata = {};
|
|
1436
|
+
const uploadedFiles = [];
|
|
1437
|
+
|
|
1438
|
+
for await (const part of wire.multipart({ maxFileSize: "50mb" })) {
|
|
1439
|
+
if (part.isField) {
|
|
1440
|
+
metadata[part.name] = await part.text();
|
|
1441
|
+
} else if (part.isFile) {
|
|
1442
|
+
const dest = `./uploads/${Date.now()}-${part.filename}`;
|
|
1443
|
+
await pipeline(
|
|
1444
|
+
Readable.fromWeb(part.stream),
|
|
1445
|
+
fs.createWriteStream(dest),
|
|
1446
|
+
);
|
|
1447
|
+
uploadedFiles.push({
|
|
1448
|
+
field: part.name,
|
|
1449
|
+
filename: part.filename,
|
|
1450
|
+
savedTo: dest,
|
|
1451
|
+
});
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
wire.status(201);
|
|
1456
|
+
return { metadata, uploadedFiles };
|
|
1457
|
+
},
|
|
1458
|
+
};
|
|
1459
|
+
```
|
|
1460
|
+
|
|
1461
|
+
### Raw Unbuffered Binary Uploads (`rawBody: true`)
|
|
1462
|
+
|
|
1463
|
+
Set `rawBody: true` on a route to skip body parsing and pipe `wire.stream` directly:
|
|
1464
|
+
|
|
1465
|
+
```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: {
|
|
1473
|
+
rawBody: true,
|
|
1474
|
+
async put(name) {
|
|
1475
|
+
await pipeline(
|
|
1476
|
+
Readable.fromWeb(wire.stream),
|
|
1477
|
+
fs.createWriteStream(`./storage/${name}`),
|
|
1478
|
+
);
|
|
1479
|
+
wire.status(201);
|
|
1480
|
+
return { stored: name };
|
|
1481
|
+
},
|
|
1482
|
+
},
|
|
1483
|
+
};
|
|
1484
|
+
```
|
|
1485
|
+
|
|
1486
|
+
---
|
|
1487
|
+
|
|
1488
|
+
## 11. Decoupled Side Effects (`reactTo`)
|
|
1489
|
+
|
|
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:
|
|
1491
|
+
|
|
1492
|
+
```javascript
|
|
1493
|
+
import { reactTo } from "servin";
|
|
1494
|
+
import { orders } from "./modules/orders.js";
|
|
1495
|
+
|
|
1496
|
+
const unsubscribe = reactTo(orders.post, async ({ input, output, wire }) => {
|
|
1497
|
+
if (output.total >= 100) {
|
|
1498
|
+
await db.loyalty.addPoints(output.userId, 50);
|
|
1499
|
+
}
|
|
1500
|
+
});
|
|
1501
|
+
```
|
|
1502
|
+
|
|
1503
|
+
---
|
|
1504
|
+
|
|
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);
|
|
1527
|
+
|
|
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
|
+
|
|
1533
|
+
// 7. WebSocket connection (ws endpoint)
|
|
1534
|
+
const room = api.rooms.$id.ws("general");
|
|
1535
|
+
room.send({ text: "Hello from the browser!" });
|
|
1536
|
+
|
|
1537
|
+
for await (const msg of room) {
|
|
1538
|
+
console.log("WS message:", msg);
|
|
1539
|
+
}
|
|
1540
|
+
```
|
|
1541
|
+
|
|
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:
|
|
1549
|
+
|
|
1550
|
+
```javascript
|
|
1551
|
+
import { serve } from "servin";
|
|
1552
|
+
|
|
1553
|
+
await serve({
|
|
1554
|
+
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
|
+
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" }) },
|
|
1573
|
+
},
|
|
1574
|
+
});
|
|
1575
|
+
```
|
|
1576
|
+
|
|
1577
|
+
### 13.2 Error-Triggered Debug Trace (`wire.log.debug`) & `Server-Timing` (`wire.mark`)
|
|
1578
|
+
|
|
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.
|
|
1581
|
+
|
|
1582
|
+
```javascript
|
|
1583
|
+
import { wire } from "servin";
|
|
1584
|
+
|
|
1585
|
+
export const reports = {
|
|
1586
|
+
async get() {
|
|
1587
|
+
wire.log.debug("Starting report generation", {
|
|
1588
|
+
userId: wire.session.userId,
|
|
1589
|
+
});
|
|
1590
|
+
|
|
1591
|
+
const endDb = wire.mark("db");
|
|
1592
|
+
const rows = await db.reports.fetch();
|
|
1593
|
+
endDb();
|
|
1594
|
+
|
|
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;
|
|
1601
|
+
},
|
|
1602
|
+
};
|
|
1603
|
+
```
|
|
1604
|
+
|
|
1605
|
+
### 13.3 Automated Test Synthesis (`synthesizeTests`)
|
|
1606
|
+
|
|
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.
|
|
1608
|
+
|
|
1609
|
+
### 13.4 Production Error Snapshots & Local Replay (`snapshotOnError` & `replay`)
|
|
1610
|
+
|
|
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`:
|
|
1612
|
+
|
|
1613
|
+
```javascript
|
|
1614
|
+
import { replay } from "servin/test";
|
|
1615
|
+
import { users } from "./modules/users.js";
|
|
1616
|
+
|
|
1617
|
+
// Re-executes the failing handler locally with captured URL, headers, and extracted parameters
|
|
1618
|
+
await replay(
|
|
1619
|
+
users.$id.get,
|
|
1620
|
+
"./snapshots/err-2026-11-25T12-00-00-000Z-a1b2c3d4.json",
|
|
1621
|
+
);
|
|
1622
|
+
```
|
|
1623
|
+
|
|
1624
|
+
---
|
|
1625
|
+
|
|
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`. |
|
|
1650
|
+
|
|
1651
|
+
---
|
|
1652
|
+
|
|
1653
|
+
## 15. License
|
|
1654
|
+
|
|
1655
|
+
MIT
|