xanout 0.0.0-stage → 1.0.0
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 +379 -3
- package/dist/context/context.d.ts +31 -0
- package/dist/context/context.js +71 -0
- package/dist/context/finalize.d.ts +5 -0
- package/dist/context/finalize.js +38 -0
- package/dist/context/store.d.ts +5 -0
- package/dist/context/store.js +19 -0
- package/dist/cookies/index.d.ts +11 -0
- package/dist/cookies/index.js +10 -0
- package/dist/cookies/jar.d.ts +6 -0
- package/dist/cookies/jar.js +33 -0
- package/dist/cookies/parse.d.ts +7 -0
- package/dist/cookies/parse.js +29 -0
- package/dist/cookies/serialize.d.ts +6 -0
- package/dist/cookies/serialize.js +30 -0
- package/dist/http/index.d.ts +2 -0
- package/dist/http/index.js +2 -0
- package/dist/http/toRequest.d.ts +11 -0
- package/dist/http/toRequest.js +218 -0
- package/dist/http/toResponse.d.ts +2 -0
- package/dist/http/toResponse.js +148 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/router/dispatch.d.ts +2 -0
- package/dist/router/dispatch.js +68 -0
- package/dist/router/index.d.ts +4 -0
- package/dist/router/index.js +115 -0
- package/dist/router/types.d.ts +41 -0
- package/dist/router/types.js +2 -0
- package/dist/shared/types.d.ts +90 -0
- package/dist/shared/types.js +1 -0
- package/dist/shared/utils.d.ts +1 -0
- package/dist/shared/utils.js +5 -0
- package/dist/static/cache-control.d.ts +2 -0
- package/dist/static/cache-control.js +20 -0
- package/dist/static/index.d.ts +6 -0
- package/dist/static/index.js +15 -0
- package/dist/static/mime.d.ts +1 -0
- package/dist/static/mime.js +30 -0
- package/dist/static/serve-file.d.ts +9 -0
- package/dist/static/serve-file.js +69 -0
- package/package.json +72 -6
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Naxrul Ahmed
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,379 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# xanout
|
|
2
|
+
|
|
3
|
+
Tiny router for the web-standard `Request` / `Response` API. Middleware, params, cookies, response headers, static files and a request-scoped context, in one small package. Server-only: runs on Node 18+, Bun and Deno (Cloudflare Workers with `nodejs_compat`).
|
|
4
|
+
|
|
5
|
+
- One dependency: [`regexparam`](https://github.com/lukeed/regexparam)
|
|
6
|
+
- Handlers take a single argument: `next`
|
|
7
|
+
- Request context from anywhere with `route.context()`
|
|
8
|
+
- `route.fetch(request)` takes a web `Request`; `toRequest` / `toResponse` convert to and from Node-style servers (Express, Fastify, Koa, ...)
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm i xanout
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Quick start
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { Router } from "xanout";
|
|
20
|
+
|
|
21
|
+
const route = Router();
|
|
22
|
+
|
|
23
|
+
route.use((next) => {
|
|
24
|
+
// runs for every request
|
|
25
|
+
return next();
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
route.use("/api", (next) => {
|
|
29
|
+
// runs for /api and everything under it
|
|
30
|
+
return next();
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
route.get("/", () => new Response("Hello World"));
|
|
34
|
+
|
|
35
|
+
route.get("/users/:id", () => {
|
|
36
|
+
const { params } = route.context();
|
|
37
|
+
return Response.json({ id: params.id });
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const res = await route.fetch(new Request("http://localhost/users/42"));
|
|
41
|
+
// res is a Response, or undefined when nothing handled the request
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### Use as a server
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
const notFound = () => new Response("Not Found", { status: 404 });
|
|
48
|
+
|
|
49
|
+
export default { fetch: async (req: Request) => (await route.fetch(req)) ?? notFound() }; // Bun, Workers, `deno serve`
|
|
50
|
+
Bun.serve({ fetch: async (req) => (await route.fetch(req)) ?? notFound() }); // Bun
|
|
51
|
+
Deno.serve(async (req) => (await route.fetch(req)) ?? notFound()); // Deno
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`route.fetch()` resolves to `undefined` when nothing handled the request. There is no built-in 404: you decide what happens next.
|
|
55
|
+
|
|
56
|
+
## Routes
|
|
57
|
+
|
|
58
|
+
`get`, `post`, `put`, `patch`, `delete`, `head`, `options`, `all`.
|
|
59
|
+
`HEAD` requests fall through to `get` routes. If no route answers, `route.fetch()` resolves to `undefined`.
|
|
60
|
+
|
|
61
|
+
Patterns come from `regexparam`:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
route.get("/posts/:id?", ...) // optional param
|
|
65
|
+
route.get("/files/*", ...) // wildcard -> route.context().params["*"]
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Params are URL-decoded.
|
|
69
|
+
If a captured parameter contains invalid percent-encoding, the request receives `400 Bad Request`.
|
|
70
|
+
|
|
71
|
+
## Middleware
|
|
72
|
+
|
|
73
|
+
A handler either returns a `Response` (stops the chain) or calls `next()`.
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
// run code before and after the route
|
|
77
|
+
route.use(async (next) => {
|
|
78
|
+
const t = Date.now();
|
|
79
|
+
const res = await next(); // Response, or undefined if no route matched
|
|
80
|
+
res?.headers.set("x-time", String(Date.now() - t));
|
|
81
|
+
return res;
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
// auth on a prefix
|
|
85
|
+
route.use("/admin", (next) => {
|
|
86
|
+
if (route.context().request.headers.get("authorization") !== "Bearer secret")
|
|
87
|
+
return new Response("Unauthorized", { status: 401 });
|
|
88
|
+
return next();
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
// error handling (uncaught errors otherwise become a plain 500)
|
|
92
|
+
route.use(async (next) => {
|
|
93
|
+
try { return await next(); }
|
|
94
|
+
catch (e) { return Response.json({ error: (e as Error).message }, { status: 500 }); }
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
If a middleware calls `next()` without returning it, the downstream response is still used.
|
|
99
|
+
|
|
100
|
+
**Call order is fixed, wherever you declare things.** For every request:
|
|
101
|
+
|
|
102
|
+
1. static: `static(...)`, served before any middleware
|
|
103
|
+
2. middleware: `use(handler)` and `use(path, handler)`
|
|
104
|
+
3. mounted routers: `use(router)` and `use(path, router)`
|
|
105
|
+
4. routes: `get`, `post`, ..., `all`, and routers passed to a verb such as `post(path, router)`
|
|
106
|
+
|
|
107
|
+
Each group keeps the order you declared it in. Static comes first so asset requests (a page load fetches many) don't run your middleware; a static miss continues to middleware and routes. Each request runs each middleware once. So `route.use("/admin", auth)` declared after `route.get("/admin/stats", ...)` still protects that route, and a mounted router wins over a route with the same path. If the mounted router has no match, routing continues to your routes.
|
|
108
|
+
|
|
109
|
+
## Sub-routers
|
|
110
|
+
|
|
111
|
+
Pass another `Router` to `use`, or to any method, to mount it. The sub-router sees paths with the mount prefix removed.
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
const api = Router();
|
|
115
|
+
api.use((next) => next()); // only runs for /api/...
|
|
116
|
+
api.get("/users/:id", () => Response.json({ id: route.context().params.id }));
|
|
117
|
+
|
|
118
|
+
const route = Router();
|
|
119
|
+
route.use("/api", api); // GET /api/users/42
|
|
120
|
+
route.use("/orgs/:org", membersRouter); // params from the prefix are available in the sub-router
|
|
121
|
+
route.post("/users", usersRouter); // only POST requests reach usersRouter
|
|
122
|
+
route.use(otherRouter); // mount at the root
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
- If the sub-router doesn't handle the request, or its middleware calls `next()` past its last layer, routing continues with the parent's next routes.
|
|
126
|
+
- Sub-routers share the request's context, cookies and headers, so `route.context()` works in any of them.
|
|
127
|
+
- Inside a sub-router, `ctx.pathname` is relative to it and `ctx.basePath` is the prefix removed so far (full path = `basePath + pathname`; `ctx.request.url` is the original).
|
|
128
|
+
- `static()` inside a sub-router is relative to its mount: `sub.static("/assets", { dir: "./public" })` mounted at `/v1` serves `/v1/assets/...`. It runs first inside that sub-router, after the parent's middleware.
|
|
129
|
+
- A router can't be mounted on itself.
|
|
130
|
+
|
|
131
|
+
## Context
|
|
132
|
+
|
|
133
|
+
`route.context()` returns the `Context` of the request being handled, from anywhere: handlers, middleware, or code they call. It is stored with `AsyncLocalStorage`, so it stays correct across `await` and overlapping requests. Calling it outside a request throws.
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
const ctx = route.context();
|
|
137
|
+
|
|
138
|
+
ctx.request; // the original Request
|
|
139
|
+
ctx.method; // "GET"
|
|
140
|
+
ctx.url; // URL
|
|
141
|
+
ctx.query; // URLSearchParams
|
|
142
|
+
ctx.params; // { id: "42" }
|
|
143
|
+
ctx.pathname; // "/users/42" (relative to the router handling it)
|
|
144
|
+
ctx.basePath; // mount prefix removed so far, "" at the top level
|
|
145
|
+
ctx.headers; // response Headers
|
|
146
|
+
ctx.cookies; // request cookies + queued response cookies
|
|
147
|
+
ctx.states; // Map<string, unknown> for request-scoped state
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Use `ctx.states.set(key, value)`, `ctx.states.get(key)`, `ctx.states.delete(key)`, and `ctx.states.clear()` to manage state for the current request.
|
|
151
|
+
|
|
152
|
+
### Responses
|
|
153
|
+
|
|
154
|
+
These return a standard `Response`. The second argument is a status code or a full `ResponseInit` (`status`, `statusText`, `headers`).
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
ctx.json({ message: "Hello, world!" }); // application/json
|
|
158
|
+
ctx.json(data, 201);
|
|
159
|
+
ctx.text("Hello, world!"); // text/plain
|
|
160
|
+
ctx.html("<h1>Hello</h1>"); // text/html
|
|
161
|
+
ctx.redirect("/new-url"); // 302; also 301, 303, 307, 308
|
|
162
|
+
ctx.redirect("https://example.com", 301);
|
|
163
|
+
|
|
164
|
+
ctx.success(); // { "success": true }
|
|
165
|
+
ctx.success({ id: 1 }, 201); // { "success": true, "data": { "id": 1 } }
|
|
166
|
+
ctx.error(); // 500 { "success": false, "error": "Internal Server Error" }
|
|
167
|
+
ctx.error("Not allowed", 403); // 403 { "success": false, "error": "Not allowed" }
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
```ts
|
|
171
|
+
route.get("/hello", () => {
|
|
172
|
+
const ctx = route.context();
|
|
173
|
+
ctx.headers.set("X-Request-Id", crypto.randomUUID());
|
|
174
|
+
ctx.cookies.set("session", "abc123");
|
|
175
|
+
return ctx.json({ message: "Hello, world!" });
|
|
176
|
+
});
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
A status of 204, 205 or 304 sends no body. `redirect` throws for any other status, and for a URL that isn't a valid header value (for example one containing a line break).
|
|
180
|
+
|
|
181
|
+
### Response headers
|
|
182
|
+
|
|
183
|
+
`ctx.headers` is a standard `Headers` object for the **response**. It is merged into whatever `Response` your handler returns, and wins over a header with the same name on that response, including `ctx.json()`'s own `Content-Type`. (Request headers: `ctx.request.headers`.)
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
route.use((next) => {
|
|
187
|
+
route.context().headers.set("x-request-id", crypto.randomUUID());
|
|
188
|
+
return next();
|
|
189
|
+
});
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
### Cookies
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
const cookies = route.context().cookies;
|
|
196
|
+
|
|
197
|
+
cookies.get("theme"); // from the request Cookie header
|
|
198
|
+
cookies.has("sid");
|
|
199
|
+
cookies.all(); // { theme: "dark", ... }
|
|
200
|
+
|
|
201
|
+
cookies.set("sid", "abc123", {
|
|
202
|
+
httpOnly: true,
|
|
203
|
+
secure: true,
|
|
204
|
+
sameSite: "lax", // "lax" | "strict" | "none"
|
|
205
|
+
maxAge: 3600, // seconds
|
|
206
|
+
// path (default "/"), domain, expires, partitioned
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
cookies.delete("old"); // sends an expired cookie (pass the same path/domain it was set with)
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
`get` / `has` / `all` reflect changes made earlier in the same request. Setting the same cookie twice sends only the last one. Invalid cookie names, or paths/domains containing `;` or line breaks, throw. `sameSite: "none"` is not checked for `secure`: browsers require it.
|
|
213
|
+
|
|
214
|
+
Headers and cookies are applied to your handler's response, static and custom handler responses, and immutable responses such as `Response.redirect()`. A request that ends in an uncaught error gets a plain 500 without them.
|
|
215
|
+
|
|
216
|
+
### Cookie helpers
|
|
217
|
+
|
|
218
|
+
`Cookie.parse` and `Cookie.serialize` work on their own, with or without a router.
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
import { Cookie } from "xanout";
|
|
222
|
+
|
|
223
|
+
Cookie.parse("theme=dark; sid=abc%20123");
|
|
224
|
+
// { theme: "dark", sid: "abc 123" }
|
|
225
|
+
|
|
226
|
+
Cookie.serialize("sid", "abc 123", { httpOnly: true, sameSite: "lax", maxAge: 3600 });
|
|
227
|
+
// "sid=abc%20123; Path=/; Max-Age=3600; HttpOnly; SameSite=Lax"
|
|
228
|
+
|
|
229
|
+
// e.g. in your own response
|
|
230
|
+
new Response("ok", { headers: { "Set-Cookie": Cookie.serialize("a", "1") } });
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
- `parse(header)` accepts `null` or `undefined` (returns `{}`). Values are URL-decoded, and the first occurrence of a name wins.
|
|
234
|
+
- `serialize(name, value, options?)` takes the same options as `cookies.set()` and throws on an invalid name.
|
|
235
|
+
|
|
236
|
+
## Static files
|
|
237
|
+
|
|
238
|
+
`static` serves files only. It has no `next`: a static handler returns a `Response`, or `undefined` when it has nothing, and routing continues. It handles `GET` (and `HEAD`) requests.
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
route.static("/", { dir: "./public" }); // ./public at /
|
|
242
|
+
route.static("/assets", { dir: "./dist", maxAge: 31536000, immutable: true });
|
|
243
|
+
|
|
244
|
+
route.static("/files", () => { // your own handler for a path
|
|
245
|
+
const { pathname } = route.context(); // "/a.txt" for GET /files/a.txt
|
|
246
|
+
return pathname === "/a.txt" ? new Response("custom") : undefined;
|
|
247
|
+
});
|
|
248
|
+
route.static(() => { /* handler for every path */ return undefined; });
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
- `static(path, config)`: `path` is the URL it is served under, `config.dir` the folder.
|
|
252
|
+
- `static(path, handler)` and `static(handler)`: a handler with no arguments. Read the request with `route.context()`; `ctx.pathname` is relative to `path`, and `ctx.basePath` is `path`.
|
|
253
|
+
- Anything else throws a `TypeError`.
|
|
254
|
+
|
|
255
|
+
Directories serve `index.html`. Supports `ETag` / `If-None-Match` (304), `Range` requests, `HEAD`, and about 30 common content types. Path traversal is blocked, and dotfiles are hidden.
|
|
256
|
+
|
|
257
|
+
| Config | Meaning | Default |
|
|
258
|
+
| ---------------------- | ------------------------------------- | -------------- |
|
|
259
|
+
| `dir` | Folder to serve (required) | |
|
|
260
|
+
| `index` | Directory index file, or `false` | `"index.html"` |
|
|
261
|
+
| `dotfiles` | Serve files/folders starting with `.` | `false` |
|
|
262
|
+
| `maxAge` | `Cache-Control: max-age` (seconds) | `0` |
|
|
263
|
+
| `sMaxAge` | `s-maxage` (CDNs) | none |
|
|
264
|
+
| `immutable` | add `immutable` | `false` |
|
|
265
|
+
| `visibility` | `"public"` or `"private"` | `"public"` |
|
|
266
|
+
| `noCache` | add `no-cache` | `false` |
|
|
267
|
+
| `noStore` | send only `no-store` | `false` |
|
|
268
|
+
| `mustRevalidate` | add `must-revalidate` | `false` |
|
|
269
|
+
| `staleWhileRevalidate` | `stale-while-revalidate` (seconds) | none |
|
|
270
|
+
|
|
271
|
+
`static` with `dir` reads from the file system (Node, Bun, Deno). It is not available on Cloudflare Workers. Symlinks inside the served folder are followed.
|
|
272
|
+
|
|
273
|
+
Coming from Express:
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
// app.use(`/${outdirs.client}`, express.static(outdirs.client, { maxAge: "1y", immutable: true, etag: true }))
|
|
277
|
+
route.static(`/${outdirs.client}`, { dir: outdirs.client, maxAge: 31536000, immutable: true }); // ETag is always on
|
|
278
|
+
|
|
279
|
+
// app.use("/__xmod", express.static(outdirs.module_cache))
|
|
280
|
+
route.static("/__xmod", { dir: outdirs.module_cache });
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
## Frameworks and runtimes
|
|
284
|
+
|
|
285
|
+
`route.fetch(request)` takes a web `Request` only (anything else throws a `TypeError`) and resolves to a web `Response`, or `undefined` when nothing handled it. For Node-style servers, convert in with `toRequest` and out with `toResponse`.
|
|
286
|
+
|
|
287
|
+
**Runtimes and frameworks that already use `Request` / `Response`**:
|
|
288
|
+
|
|
289
|
+
```ts
|
|
290
|
+
const notFound = () => new Response("Not Found", { status: 404 });
|
|
291
|
+
|
|
292
|
+
export default { fetch: async (req: Request) => (await route.fetch(req)) ?? notFound() }; // Bun, Workers, `deno serve`
|
|
293
|
+
Bun.serve({ fetch: async (req) => (await route.fetch(req)) ?? notFound() }); // Bun
|
|
294
|
+
|
|
295
|
+
// Hono: fall through to the next handler
|
|
296
|
+
app.all("*", async (c, next) => (await route.fetch(c.req.raw)) ?? next());
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
**Node-style servers** (Node `http`, Express, Fastify, Koa, ...) need the request converted and the response written back: `toRequest(req)` and `toResponse(res, response)`. `toResponse` returns `false` (touching nothing) when `route.fetch` gave `undefined`, so you can fall through:
|
|
300
|
+
|
|
301
|
+
```ts
|
|
302
|
+
import { toRequest, toResponse } from "xanout";
|
|
303
|
+
|
|
304
|
+
// Node http
|
|
305
|
+
http.createServer(async (req, res) => {
|
|
306
|
+
if (!(await toResponse(res, await route.fetch(toRequest(req))))) { res.statusCode = 404; res.end("Not Found"); }
|
|
307
|
+
}).listen(3000);
|
|
308
|
+
|
|
309
|
+
// Express
|
|
310
|
+
app.use(async (req, res, next) => { if (!(await toResponse(res, await route.fetch(toRequest(req))))) next(); });
|
|
311
|
+
|
|
312
|
+
// Fastify
|
|
313
|
+
app.all("/*", async (req, reply) => { if (!(await toResponse(reply, await route.fetch(toRequest(req))))) return reply.callNotFound(); });
|
|
314
|
+
|
|
315
|
+
// Koa
|
|
316
|
+
app.use(async (ctx) => { if (!(await toResponse(ctx, await route.fetch(toRequest(ctx))))) { ctx.status = 404; ctx.body = "Not Found"; } });
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
`toResponse(target, response)` accepts a Node `ServerResponse` (http, Express, Connect), a Fastify reply or a Koa context. It streams the body with backpressure, stops if the client disconnects, and sends multiple `Set-Cookie` headers correctly. It returns `false` without touching the target when `response` is `undefined`, and `true` after handling a response. Stream/write errors are rethrown after destroying the response. For Fastify it takes over the raw response and keeps headers already set on the reply (for example by `@fastify/cors`). For Koa it sets `ctx.respond = false`.
|
|
320
|
+
|
|
321
|
+
### toRequest
|
|
322
|
+
|
|
323
|
+
`toRequest(input, options?)` converts a Node-style request into a web `Request`. Pass options when you need them:
|
|
324
|
+
|
|
325
|
+
```ts
|
|
326
|
+
import { toRequest } from "xanout";
|
|
327
|
+
|
|
328
|
+
const request = toRequest(req, { baseUrl: "https://api.example.com" });
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
It accepts:
|
|
332
|
+
|
|
333
|
+
| Input | Result |
|
|
334
|
+
| ---------------------------------------------------------------------------------------------------------------- | -------------------------------------- |
|
|
335
|
+
| Web `Request` (Bun, Deno, Workers, Next.js app router, ...) | returned as is |
|
|
336
|
+
| Context wrapping one: Hono `c`, `{ request }` (SvelteKit, Astro, Remix, Elysia, Cloudflare Pages), h3 v2 `event` | the wrapped `Request` |
|
|
337
|
+
| Node request: `http`, Express, Connect, Polka, Next.js pages API, Nest | converted |
|
|
338
|
+
| Fastify `request`, Koa `ctx`, h3 v1 `event` | converted from the Node request inside |
|
|
339
|
+
| anything else (for example an AWS Lambda event) | throws `TypeError` |
|
|
340
|
+
|
|
341
|
+
Tested here: Node `http`, Express 5, Fastify 5, Koa 3, Hono 4 and Bun. The others use the same shapes but are not tested.
|
|
342
|
+
|
|
343
|
+
- **Body:** streamed. If a body parser has consumed the Node request, the body is rebuilt from `rawBody` when present, otherwise from the framework's parsed `body`. JSON-compatible objects are serialized as JSON; URL-encoded bodies become form data. Nested form fields can't be restored exactly: use `rawBody` or leave the stream unread. A consumed body is included only when the request declares a body using `content-length` or `transfer-encoding`.
|
|
344
|
+
- **URL:** an absolute HTTP(S) URL is kept as-is; otherwise the origin is built from the request protocol and `Host`/`:authority` headers, and the path comes from `originalUrl` or `url`. A `Host` that isn't a valid host name, IP, or `host:port` is replaced with `localhost`, and a path like `//evil.com` can't change the host. Normal Node request targets start with `/`.
|
|
345
|
+
- **Proxies:** `X-Forwarded-Proto` / `X-Forwarded-Host` are ignored unless you pass `trustProxy: true`. `baseUrl` overrides the origin completely.
|
|
346
|
+
- **HTTP/2:** pseudo-headers (`:path`, `:authority`, ...) are not copied into the headers.
|
|
347
|
+
- **Fastify** rejects content types it has no parser for (for example form posts) with a 415 before your code runs. To pass every body through untouched:
|
|
348
|
+
|
|
349
|
+
```ts
|
|
350
|
+
app.removeAllContentTypeParsers();
|
|
351
|
+
app.addContentTypeParser("*", (_req, _payload, done) => done(null));
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
## API
|
|
355
|
+
|
|
356
|
+
```ts
|
|
357
|
+
Router(): Router
|
|
358
|
+
|
|
359
|
+
route.use(handlerOrRouter)
|
|
360
|
+
route.use(path, handlerOrRouter) // prefix match; a Router is mounted under the prefix
|
|
361
|
+
route.get | post | put | patch | delete | head | options | all (path, handlerOrRouter)
|
|
362
|
+
route.static(path, { dir, ...cacheOptions })
|
|
363
|
+
route.static(path, handler)
|
|
364
|
+
route.static(handler)
|
|
365
|
+
route.context(): Context
|
|
366
|
+
route.fetch(request: Request): Promise<Response | undefined>
|
|
367
|
+
|
|
368
|
+
toRequest(nodeRequest, { baseUrl?, trustProxy? }?): Request
|
|
369
|
+
toResponse(nodeResponse, response: Response | undefined): Promise<boolean> // false = nothing written
|
|
370
|
+
|
|
371
|
+
type StaticHandler = () => Response | undefined | Promise<Response | undefined>
|
|
372
|
+
type Handler = (next: () => Promise<Response | undefined>) => Response | void | Promise<Response | void>
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
All registration methods return the router, so calls can be chained.
|
|
376
|
+
|
|
377
|
+
## License
|
|
378
|
+
|
|
379
|
+
MIT
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Cookies, ReplyInit } from "../shared/types.js";
|
|
2
|
+
/** Everything about the request being handled. Get it anywhere with `route.context()`. */
|
|
3
|
+
export declare class Context {
|
|
4
|
+
#private;
|
|
5
|
+
readonly request: Request;
|
|
6
|
+
readonly method: string;
|
|
7
|
+
readonly url: URL;
|
|
8
|
+
readonly query: URLSearchParams;
|
|
9
|
+
readonly states: Map<string, unknown>;
|
|
10
|
+
readonly headers: Headers;
|
|
11
|
+
readonly cookies: Cookies;
|
|
12
|
+
isWebRequest: boolean;
|
|
13
|
+
pathname: string;
|
|
14
|
+
basePath: string;
|
|
15
|
+
params: Record<string, string>;
|
|
16
|
+
constructor(request: Request);
|
|
17
|
+
/** JSON response. `init` is a status code or a ResponseInit. Default status 200. */
|
|
18
|
+
json(data: unknown, init?: ReplyInit): Response;
|
|
19
|
+
/** Plain text response. */
|
|
20
|
+
text(body: string, init?: ReplyInit): Response;
|
|
21
|
+
/** HTML response. */
|
|
22
|
+
html(body: string, init?: ReplyInit): Response;
|
|
23
|
+
/** Redirect to a path or URL. Status 301, 302 (default), 303, 307 or 308. */
|
|
24
|
+
redirect(url: string | URL, status?: number): Response;
|
|
25
|
+
/** JSON `{ success: true, data }` (`data` is left out when undefined). Default status 200. */
|
|
26
|
+
success(data?: unknown, init?: ReplyInit): Response;
|
|
27
|
+
/** JSON `{ success: false, error: message }`. Default status 500. */
|
|
28
|
+
error(message?: string, init?: ReplyInit): Response;
|
|
29
|
+
/** @internal Merge `headers` and queued cookies into the final response. */
|
|
30
|
+
finalize(res: Response): Response;
|
|
31
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { createCookies } from "../cookies/index.js";
|
|
2
|
+
import { mergeIntoResponse } from "./finalize.js";
|
|
3
|
+
const JSON_TYPE = "application/json; charset=utf-8";
|
|
4
|
+
const NO_BODY = new Set([204, 205, 304]);
|
|
5
|
+
const REDIRECTS = new Set([301, 302, 303, 307, 308]);
|
|
6
|
+
/** Everything about the request being handled. Get it anywhere with `route.context()`. */
|
|
7
|
+
export class Context {
|
|
8
|
+
request;
|
|
9
|
+
method;
|
|
10
|
+
url;
|
|
11
|
+
query;
|
|
12
|
+
states = new Map();
|
|
13
|
+
headers = new Headers();
|
|
14
|
+
cookies;
|
|
15
|
+
#jar;
|
|
16
|
+
isWebRequest = true;
|
|
17
|
+
pathname;
|
|
18
|
+
basePath = "";
|
|
19
|
+
params = {};
|
|
20
|
+
constructor(request) {
|
|
21
|
+
this.request = request;
|
|
22
|
+
this.method = request.method.toUpperCase();
|
|
23
|
+
this.url = new URL(request.url);
|
|
24
|
+
this.query = this.url.searchParams;
|
|
25
|
+
this.pathname = this.url.pathname;
|
|
26
|
+
this.#jar = createCookies(request.headers.get("cookie"));
|
|
27
|
+
this.cookies = this.#jar;
|
|
28
|
+
}
|
|
29
|
+
/** JSON response. `init` is a status code or a ResponseInit. Default status 200. */
|
|
30
|
+
json(data, init) {
|
|
31
|
+
return this.#reply(JSON.stringify(data) ?? "null", JSON_TYPE, init);
|
|
32
|
+
}
|
|
33
|
+
/** Plain text response. */
|
|
34
|
+
text(body, init) {
|
|
35
|
+
return this.#reply(body, "text/plain; charset=utf-8", init);
|
|
36
|
+
}
|
|
37
|
+
/** HTML response. */
|
|
38
|
+
html(body, init) {
|
|
39
|
+
return this.#reply(body, "text/html; charset=utf-8", init);
|
|
40
|
+
}
|
|
41
|
+
/** Redirect to a path or URL. Status 301, 302 (default), 303, 307 or 308. */
|
|
42
|
+
redirect(url, status = 302) {
|
|
43
|
+
if (!REDIRECTS.has(status))
|
|
44
|
+
throw new RangeError(`Invalid redirect status: ${status}`);
|
|
45
|
+
return new Response(null, {
|
|
46
|
+
status,
|
|
47
|
+
headers: { Location: String(url) },
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
/** JSON `{ success: true, data }` (`data` is left out when undefined). Default status 200. */
|
|
51
|
+
success(data, init) {
|
|
52
|
+
return this.json({ success: true, data }, init);
|
|
53
|
+
}
|
|
54
|
+
/** JSON `{ success: false, error: message }`. Default status 500. */
|
|
55
|
+
error(message = "Internal Server Error", init) {
|
|
56
|
+
return this.#reply(JSON.stringify({ success: false, error: message }), JSON_TYPE, init, 500);
|
|
57
|
+
}
|
|
58
|
+
/** @internal Merge `headers` and queued cookies into the final response. */
|
|
59
|
+
finalize(res) {
|
|
60
|
+
return mergeIntoResponse(res, this.headers, this.#jar._out());
|
|
61
|
+
}
|
|
62
|
+
#reply(body, type, init, defaultStatus = 200) {
|
|
63
|
+
const o = typeof init === "number" ? { status: init } : { ...init };
|
|
64
|
+
o.status ??= defaultStatus;
|
|
65
|
+
const headers = new Headers(o.headers);
|
|
66
|
+
if (!headers.has("content-type"))
|
|
67
|
+
headers.set("content-type", type);
|
|
68
|
+
o.headers = headers;
|
|
69
|
+
return new Response(NO_BODY.has(o.status) ? null : body, o);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Merge ctx.headers() and the cookies queued by ctx.cookies() into the final Response.
|
|
3
|
+
* Context headers win over same-named headers on the response.
|
|
4
|
+
*/
|
|
5
|
+
export declare function mergeIntoResponse(res: Response, resHeaders: Headers, cookies: string[]): Response;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Merge ctx.headers() and the cookies queued by ctx.cookies() into the final Response.
|
|
3
|
+
* Context headers win over same-named headers on the response.
|
|
4
|
+
*/
|
|
5
|
+
export function mergeIntoResponse(res, resHeaders, cookies) {
|
|
6
|
+
const extraCookies = resHeaders.getSetCookie();
|
|
7
|
+
let has = cookies.length > 0 || extraCookies.length > 0;
|
|
8
|
+
resHeaders.forEach((_v, k) => {
|
|
9
|
+
if (k !== "set-cookie")
|
|
10
|
+
has = true;
|
|
11
|
+
});
|
|
12
|
+
if (!has)
|
|
13
|
+
return res;
|
|
14
|
+
const apply = (h) => {
|
|
15
|
+
resHeaders.forEach((v, k) => {
|
|
16
|
+
if (k !== "set-cookie")
|
|
17
|
+
h.set(k, v);
|
|
18
|
+
});
|
|
19
|
+
for (const c of extraCookies)
|
|
20
|
+
h.append("set-cookie", c);
|
|
21
|
+
for (const c of cookies)
|
|
22
|
+
h.append("set-cookie", c);
|
|
23
|
+
};
|
|
24
|
+
try {
|
|
25
|
+
apply(res.headers);
|
|
26
|
+
return res;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
// immutable headers (Response.redirect(), fetch() results): rebuild
|
|
30
|
+
const h = new Headers(res.headers);
|
|
31
|
+
apply(h);
|
|
32
|
+
return new Response(res.body, {
|
|
33
|
+
status: res.status,
|
|
34
|
+
statusText: res.statusText,
|
|
35
|
+
headers: h,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Context } from "./context.js";
|
|
2
|
+
/** Run `fn` with `ctx` as the current request context. */
|
|
3
|
+
export declare function runInContext<R>(ctx: Context, fn: () => R): R;
|
|
4
|
+
/** The context of the request currently being handled. Throws outside a request. */
|
|
5
|
+
export declare function currentContext(): Context;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
// Request-scoped context. xanout is server-only: it relies on AsyncLocalStorage
|
|
3
|
+
// (Node, Bun, Deno, Cloudflare Workers with nodejs_compat).
|
|
4
|
+
// const store = new AsyncLocalStorage<Context>();
|
|
5
|
+
const KEY = Symbol.for("xanix.server-context");
|
|
6
|
+
const stores = globalThis;
|
|
7
|
+
const contextStorage = stores[KEY] ??
|
|
8
|
+
(stores[KEY] = new AsyncLocalStorage());
|
|
9
|
+
/** Run `fn` with `ctx` as the current request context. */
|
|
10
|
+
export function runInContext(ctx, fn) {
|
|
11
|
+
return contextStorage.run(ctx, fn);
|
|
12
|
+
}
|
|
13
|
+
/** The context of the request currently being handled. Throws outside a request. */
|
|
14
|
+
export function currentContext() {
|
|
15
|
+
const c = contextStorage.getStore();
|
|
16
|
+
if (!c)
|
|
17
|
+
throw new Error("route.context() called outside of a request");
|
|
18
|
+
return c;
|
|
19
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { parseCookie } from "./parse.js";
|
|
2
|
+
import { serializeCookie } from "./serialize.js";
|
|
3
|
+
/** Cookie helpers usable on their own, outside a router. */
|
|
4
|
+
export declare const Cookie: {
|
|
5
|
+
parse: typeof parseCookie;
|
|
6
|
+
serialize: typeof serializeCookie;
|
|
7
|
+
};
|
|
8
|
+
export { createCookies } from "./jar.js";
|
|
9
|
+
export type { CookieJar } from "./jar.js";
|
|
10
|
+
export { parseCookie } from "./parse.js";
|
|
11
|
+
export { serializeCookie } from "./serialize.js";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { parseCookie } from "./parse.js";
|
|
2
|
+
import { serializeCookie } from "./serialize.js";
|
|
3
|
+
/** Cookie helpers usable on their own, outside a router. */
|
|
4
|
+
export const Cookie = {
|
|
5
|
+
parse: parseCookie,
|
|
6
|
+
serialize: serializeCookie,
|
|
7
|
+
};
|
|
8
|
+
export { createCookies } from "./jar.js";
|
|
9
|
+
export { parseCookie } from "./parse.js";
|
|
10
|
+
export { serializeCookie } from "./serialize.js";
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { parseCookie } from "./parse.js";
|
|
2
|
+
import { serializeCookie } from "./serialize.js";
|
|
3
|
+
export function createCookies(header) {
|
|
4
|
+
let base;
|
|
5
|
+
const read = () => (base ??= parseCookie(header));
|
|
6
|
+
const view = new Map();
|
|
7
|
+
const out = new Map();
|
|
8
|
+
const key = (name, options) => `${name};${options.domain ?? ""};${options.path ?? "/"}`;
|
|
9
|
+
const jar = {
|
|
10
|
+
get: (name) => (view.has(name) ? view.get(name) : read()[name]),
|
|
11
|
+
has: (name) => jar.get(name) !== undefined,
|
|
12
|
+
all: () => {
|
|
13
|
+
const cookies = { ...read() };
|
|
14
|
+
for (const [name, value] of view)
|
|
15
|
+
value === undefined
|
|
16
|
+
? delete cookies[name]
|
|
17
|
+
: (cookies[name] = value);
|
|
18
|
+
return cookies;
|
|
19
|
+
},
|
|
20
|
+
set: (name, value, options = {}) => (out.set(key(name, options), serializeCookie(name, value, options)),
|
|
21
|
+
view.set(name, value),
|
|
22
|
+
jar),
|
|
23
|
+
delete: (name, options = {}) => (out.set(key(name, options), serializeCookie(name, "", {
|
|
24
|
+
...options,
|
|
25
|
+
maxAge: 0,
|
|
26
|
+
expires: new Date(0),
|
|
27
|
+
})),
|
|
28
|
+
view.set(name, undefined),
|
|
29
|
+
jar),
|
|
30
|
+
_out: () => [...out.values()],
|
|
31
|
+
};
|
|
32
|
+
return jar;
|
|
33
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parse a `Cookie` request header (`"a=1; b=x%20y"`) into a name -> value object.
|
|
3
|
+
* Values are URL-decoded; if decoding fails the raw value is kept. When a name appears
|
|
4
|
+
* twice, the first one wins. Accepts null/undefined and returns `{}`.
|
|
5
|
+
* (The result has no prototype, so a cookie named `__proto__` is harmless.)
|
|
6
|
+
*/
|
|
7
|
+
export declare function parseCookie(header: string | null | undefined): Record<string, string>;
|