@thednp/rpc 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +22 -20
- package/CHANGELOG.md +47 -0
- package/README.md +5 -3
- package/dist/express/express.d.mts +1 -1
- package/dist/express/express.d.mts.map +1 -1
- package/dist/express/express.mjs +54 -12
- package/dist/express/express.mjs.map +1 -1
- package/dist/fastify/fastify.d.mts.map +1 -1
- package/dist/fastify/fastify.mjs +23 -5
- package/dist/fastify/fastify.mjs.map +1 -1
- package/dist/fastify/plugin/fastify/plugin.mjs +23 -5
- package/dist/fastify/plugin/fastify/plugin.mjs.map +1 -1
- package/dist/h3/h3.d.mts.map +1 -1
- package/dist/h3/h3.mjs +23 -1
- package/dist/h3/h3.mjs.map +1 -1
- package/dist/helpers/helpers.mjs.map +1 -1
- package/dist/hono/hono.d.mts.map +1 -1
- package/dist/hono/hono.mjs +23 -3
- package/dist/hono/hono.mjs.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/koa/koa.d.mts.map +1 -1
- package/dist/koa/koa.mjs +25 -5
- package/dist/koa/koa.mjs.map +1 -1
- package/dist/server/server.d.mts +84 -2
- package/dist/server/server.d.mts.map +1 -1
- package/dist/server/server.mjs +80 -2
- package/dist/server/server.mjs.map +1 -1
- package/package.json +1 -1
package/AGENTS.md
CHANGED
|
@@ -6,9 +6,11 @@
|
|
|
6
6
|
pnpm dev # Run examples/spa dev server
|
|
7
7
|
pnpm dev:express # Run examples/express dev server
|
|
8
8
|
pnpm dev:fastify # Run examples/fastify dev server
|
|
9
|
+
pnpm dev:h3 # Run examples/h3 dev server
|
|
9
10
|
pnpm dev:hono # Run examples/hono dev server
|
|
10
11
|
pnpm dev:koa # Run examples/koa dev server
|
|
11
12
|
pnpm dev:react-query # Run examples/react-query dev server
|
|
13
|
+
pnpm dev:solid-query # Run examples/solid-query dev server
|
|
12
14
|
pnpm dev:ssr # Run examples/ssr dev server
|
|
13
15
|
pnpm lint # Lint + typecheck (deno lint + tsc)
|
|
14
16
|
pnpm test # Run tests with coverage
|
|
@@ -33,7 +35,7 @@ pnpm release # Publish npm + jsr (scripts/release.js)
|
|
|
33
35
|
|
|
34
36
|
## Examples
|
|
35
37
|
|
|
36
|
-
The `examples/` directory contains
|
|
38
|
+
The `examples/` directory contains 9 example apps:
|
|
37
39
|
|
|
38
40
|
| Example | Adapter | Type | Run Command | Config |
|
|
39
41
|
| ----------------| -------------------------------------------------------------------| ------| -------------------------| -----------------------------------------|
|
|
@@ -45,12 +47,6 @@ The `examples/` directory contains 8 example apps:
|
|
|
45
47
|
| `koa` | Koa | SSR | `pnpm dev:koa` | `examples/koa/rpc.config.ts` |
|
|
46
48
|
| `react-query` | Express (React + @tanstack/react-query SSR) | SSR | `pnpm dev:react-query` | `examples/react-query/rpc.config.ts` |
|
|
47
49
|
| `solid-query` | Express (Solid + @tanstack/solid-query SSR) | SSR | `pnpm dev:solid-query` | `examples/solid-query/rpc.config.ts` |
|
|
48
|
-
| `ssr` | Custom `http-express.ts` (Express-compatible `node:http` server ) | SSR | `pnpm dev:ssr` | `examples/ssr/rpc.config.ts` | `examples/express/rpc.config.ts` |
|
|
49
|
-
| `fastify` | Fastify | SSR | `pnpm dev:fastify` | `examples/fastify/rpc.config.ts` |
|
|
50
|
-
| `hono` | Hono | SSR | `pnpm dev:hono` | `examples/hono/rpc.config.ts` |
|
|
51
|
-
| `koa` | Koa | SSR | `pnpm dev:koa` | `examples/koa/rpc.config.ts` |
|
|
52
|
-
| `react-query` | Express (React + @tanstack/react-query SSR) | SSR | `pnpm dev:react-query` | `examples/react-query/rpc.config.ts` |
|
|
53
|
-
| `solid-query` | Express (Solid + @tanstack/solid-query SSR) | SSR | `pnpm dev:solid-query` | `examples/solid-query/rpc.config.ts` |
|
|
54
50
|
| `ssr` | Custom `http-express.ts` (Express-compatible `node:http` server ) | SSR | `pnpm dev:ssr` | `examples/ssr/rpc.config.ts` |
|
|
55
51
|
|
|
56
52
|
Each example follows the same structure:
|
|
@@ -67,11 +63,11 @@ Each example follows the same structure:
|
|
|
67
63
|
|
|
68
64
|
## Key Directories
|
|
69
65
|
|
|
70
|
-
- `src/` — source for all packages (vite plugin, server, express, fastify, hono, koa adapters)
|
|
66
|
+
- `src/` — source for all packages (vite plugin, server, express, fastify, h3, hono, koa adapters)
|
|
71
67
|
- `dist/` — build output (not committed, generated by tsdown)
|
|
72
|
-
- `tests/` — test files (one per adapter + plugin)
|
|
68
|
+
- `tests/` — test files (one per adapter + plugin + helpers)
|
|
73
69
|
- `tests/fixtures/` — test fixtures (config files, vite-mock.ts)
|
|
74
|
-
- `examples/` — example apps (spa, express, fastify, hono, koa, react-query, solid-query, ssr)
|
|
70
|
+
- `examples/` — example apps (spa, express, fastify, h3, hono, koa, react-query, solid-query, ssr)
|
|
75
71
|
|
|
76
72
|
## Build Output (tsdown)
|
|
77
73
|
|
|
@@ -81,19 +77,24 @@ The tsdown.config.ts produces multiple entries:
|
|
|
81
77
|
- `dist/server/server.mjs` — standalone server
|
|
82
78
|
- `dist/express/express.mjs` — Express middleware
|
|
83
79
|
- `dist/fastify/fastify.mjs` — Fastify middleware
|
|
80
|
+
- `dist/h3/h3.mjs` — h3 middleware
|
|
84
81
|
- `dist/hono/hono.mjs` — Hono middleware
|
|
85
82
|
- `dist/koa/koa.mjs` — Koa middleware
|
|
86
83
|
|
|
87
84
|
## Test Files
|
|
88
85
|
|
|
89
|
-
| File
|
|
90
|
-
|
|
|
91
|
-
| `tests/plugin.test.ts`
|
|
92
|
-
| `tests/
|
|
93
|
-
| `tests/
|
|
94
|
-
| `tests/
|
|
95
|
-
| `tests/
|
|
96
|
-
| `tests/
|
|
86
|
+
| File | Tests | |
|
|
87
|
+
| ---------------------------------| --------------------------------------------------------------------| -----|
|
|
88
|
+
| `tests/plugin.test.ts` | Plugin init, loadRPCConfig, createServerFunction, getClientModules | |
|
|
89
|
+
| `tests/scan.test.ts` | scanForServerFiles (real scan, skip, devServer, error handling) | |
|
|
90
|
+
| `tests/server-helpers.test.ts` | RPCError, formatError, redirect, glob walking | |
|
|
91
|
+
| `tests/client-helpers.test.ts` | Client fetch stubs and retrieval helpers | |
|
|
92
|
+
| `tests/context.test.ts` | provideRequestContext / getRequestContext (AsyncLocalStorage) | |
|
|
93
|
+
| `tests/express.test.ts` | Express helpers, createMiddleware, createRPCMiddleware | |
|
|
94
|
+
| `tests/fastify.test.ts` | Fastify helpers, plugin, createMiddleware, createRPCMiddleware | |
|
|
95
|
+
| `tests/h3.test.ts` | h3 helpers, viteMiddleware, createMiddleware, createRPCMiddleware | |
|
|
96
|
+
| `tests/hono.test.ts` | Hono helpers, createMiddleware, createRPCMiddleware | |
|
|
97
|
+
| `tests/koa.test.ts` | Koa helpers, createMiddleware, createRPCMiddleware | |
|
|
97
98
|
|
|
98
99
|
## Important Notes
|
|
99
100
|
|
|
@@ -119,7 +120,7 @@ The tsdown.config.ts produces multiple entries:
|
|
|
119
120
|
- **Koa URL normalization**: Koa adapter parses `ctx.url` through `new URL()` to strip query strings and normalize encoding before prefix checking
|
|
120
121
|
- **Code injection prevention in client module generation**: `getClientModules.ts` validates all interpolated identifiers (`fnName`, `fnEntry`, `rpcPrefix`) against `/^[A-Za-z_$][A-Za-z0-9_$]*$/` (and a path-safe variant allowing `/`) before interpolating into the generated client bundle. This prevents code injection via malicious export names or prefixes containing template literal interpolations (`${...}`), backticks, or `</script>` sequences.
|
|
121
122
|
- **Body size limits**: Host frameworks cap parsed JSON bodies — Express (`express.json({ limit })`), Fastify (`bodyLimit`), Koa (`koa-body`), Hono (`hono/body-limit`). Rely on your framework's body parser middleware for size limits (see wiki/best-practices.md). The raw stream path in `readBody` does not impose a built-in limit — use framework middleware or a custom body limit handler for defense-in-depth.
|
|
122
|
-
- **Generic 404 responses**: Error messages
|
|
123
|
+
- **Generic 404 responses**: Error messages never echo the requested function name (no message-based function enumeration). Note the status code still distinguishes unknown (`404`) from known functions (`405`/`415`/`403`); function names ship in the client bundle so they are not secret — see `wiki/security.md`
|
|
123
124
|
- **Auth is middleware's responsibility**: Authentication should be handled by middleware registered before `createRPCMiddleware()`. The middleware chain naturally composes — no built-in auth hook is needed.
|
|
124
125
|
- **No client-side secrets or stack traces**: Error responses always return `"Internal Server Error"` regardless of the underlying error; `console.error(String(err))` is server-side only for debugging and does not surface internals to the client
|
|
125
126
|
|
|
@@ -143,7 +144,7 @@ The framework's security boundary is the **RPC prefix-gated HTTP endpoint**. Inp
|
|
|
143
144
|
**Attackers are expected to**:
|
|
144
145
|
- Be free to send as many requests as the host allows (no rate limiting — host's responsibility)
|
|
145
146
|
- Be free to hit any URL (no auth — host's responsibility via prior middleware)
|
|
146
|
-
- Be rejected with generic
|
|
147
|
+
- Be rejected with generic error bodies (no function-name disclosure in messages, no stack traces); status-code differential still reveals existence — see `wiki/security.md`
|
|
147
148
|
|
|
148
149
|
## Documentation
|
|
149
150
|
|
|
@@ -151,6 +152,7 @@ The framework's security boundary is the **RPC prefix-gated HTTP endpoint**. Inp
|
|
|
151
152
|
- `wiki/getting-started.md` — Installation, project structure, auto-scanning, and your first function
|
|
152
153
|
- `wiki/configuration.md` — Configuration reference (`rpc.config.ts`, `vite.config.ts`, options)
|
|
153
154
|
- `wiki/server-functions.md` — `createServerFunction` API, methods, validation, **request context (`getRequestContext`/`provideRequestContext`)** for per-request data access across async call stacks
|
|
155
|
+
- `wiki/middleware.md` — universal adapter-agnostic middleware via the request context (`locals` bridge, `getRequestMeta`, `sendResponse`, `functionName`)
|
|
154
156
|
- `wiki/nojs-fallback.md` — native (no-JS) `<form>` fallback / progressive enhancement pattern
|
|
155
157
|
- `wiki/client-usage.md` — Client-side usage, type safety, react-query integration
|
|
156
158
|
- `wiki/wire-protocol.md` — HTTP contract, request/response bodies, curl debugging
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,52 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.2.1] - 2026-08-10
|
|
4
|
+
|
|
5
|
+
### Features
|
|
6
|
+
|
|
7
|
+
- **`send` on the request context**: `RequestEvent.send(status, body, headers?)` (plus the `sent` flag) lets middleware and server functions short-circuit the RPC dispatch with a full HTTP response instead of the `{ data }` envelope, mirroring the existing `redirect`/`redirected` pair. All five adapters bind it and skip their JSON send when `sent` is set: Express (via `getResponseDetails().sendResponse`), Fastify (`reply.header()` loop + `reply.status().send()`), Koa (`ctx.set()` loop + `ctx.status`/`ctx.body`), Hono (records only — the post-dispatch handler returns `c.body(JSON.stringify(body), status, { "content-type": "application/json", ...headers })`), and h3 (records only — the post-dispatch handler sets `event.res.status` and `event.res.headers` then returns the body)
|
|
8
|
+
- **`functionName` on the request context**: `RequestEvent.functionName` exposes the dispatched function name so universal middleware can branch per function (e.g. rate limits, per-function authorization)
|
|
9
|
+
- **`sendResponse` helper**: a `sendResponse(status, body, headers?)` context helper, the response counterpart to the `redirect` helper, delegating to the same adapter-bound write path
|
|
10
|
+
- **`getRequestMeta(event)`**: a normalized request reader returning `{ method, pathname, search, searchParams, headers, host, ip, protocol }`, duck-typed across all five adapter request shapes — feature-detects fetch-like `Headers` (h3/Hono) vs plain maps (Express/Fastify/Koa), resolves the URL from `originalUrl ?? url ?? path`, and derives `host`/`protocol`/`ip` with safe fallbacks
|
|
11
|
+
|
|
12
|
+
### Examples
|
|
13
|
+
|
|
14
|
+
- **h3 example**: extract `middleware/bodyLimit.js` — delegates to h3's native `assertBodySize`, which swaps `event.req` for a bounded stream so the cap is enforced while streaming (never fully buffered) and the RPC `readBody` can still consume it afterwards; oversized bodies reject with `413` JSON. Extract `middleware/serveStatic.js` — aliases h3's `serveStatic` from `h3/node`, adds `Content-Length`, `Last-Modified`, and `Cache-Control: public, max-age=31536000, immutable`, and is registered **after** `createRPCMiddleware()` so asset requests never reach server functions; missing files fall through to the SSR handler
|
|
15
|
+
- **demo**: the prerender plugin now writes the app content between `<!-- app-content -->` markers and gains a `configurePreviewServer` middleware that re-renders just that region from the URL query — nojs form state (values + errors) is recovered in `vite preview`, where the baked `dist/index.html` shell otherwise skips `transformIndexHtml`
|
|
16
|
+
- **demo**: `body-limit.ts` stashes multipart bodies as `{ raw: body }` to mirror `@thednp/rpc/express`'s `readBody` streaming semantics; the render page and `getLibraryInfo` now count 9 examples and list the h3 adapter; the features grid grows to 9 cards (3×3) with request-context, no-JS form-fallback, and boundary-enforcement entries
|
|
17
|
+
- **fastify example**: switch the production server to `@fastify/compress` (gzip) for the RPC endpoint and static HTML. `@fastify/compress` attaches its per-route `onSend` hook via `onRoute`, which never fires for the RPC plugin's global `preHandler` handling, so the example registers a scoped `app.post("/_server/*")` catch-all route — the RPC `preHandler` short-circuits before the handler runs, letting compress's hook attach to RPC POSTs while non-RPC POSTs still get a 404. Verified with curl: HTML and RPC POST responses (200 and 404) compress (gzip) with byte-identical decompression (md5 match), and non-RPC POSTs keep their 404
|
|
18
|
+
- Sync all 9 examples to `@thednp/rpc ^0.2.0`
|
|
19
|
+
|
|
20
|
+
### Docs
|
|
21
|
+
|
|
22
|
+
- **New `wiki/middleware.md`** — universal adapter-agnostic middleware via the request context: the `locals` bridge table (Express `res.locals`, Koa `ctx.state`, h3 `event.context`, Fastify/Hono `{}` with `decorateRequest`/`c.set` workarounds), `getRequestMeta`, `functionName`, `sendResponse` per-adapter mapping, and wrap recipes for official framework middleware (Express session, Koa `ctx.state`, h3 `event.context`, Fastify `decorateRequest`, Hono `c.set`/`c.get`)
|
|
23
|
+
- TOC sweep: `- [Middleware](./middleware.md)` entry added to all 11 wiki pages after Server Functions; cross-linked from `server-functions.md` (RequestEvent shape + "Writing Universal Middleware" section), `best-practices.md` (Authentication, Rate Limiting), and `adapters.md`; `wiki/index.md` updated
|
|
24
|
+
- Update `wiki/server-functions.md` RequestEvent reference for `send`/`sent`/`functionName` and re-point its "Next" pointer to `middleware.md`
|
|
25
|
+
- `wiki/nojs-fallback.md`: explain the form markup and detection rule without embedding the whole `createFormFallback` implementation (now links to `demo/src/lib/form-fallback.ts`)
|
|
26
|
+
- `wiki/adapters.md`: replace the h3 body-limit snippet with h3's native `assertBodySize` pattern (bounded stream, never buffered) and add a **Static Assets** section for the extracted `serveStatic` middleware; `wiki/best-practices.md` h3 body limit now recommends `assertBodySize` and warns against iterating `event.req` (which breaks the RPC `readBody` with "Body is unusable")
|
|
27
|
+
- Update `AGENTS.md` (9 examples, h3 adapter, test files table), `llms.txt`, and `README.md` (five adapters, 10 test files, `nojs-fallback` doc link, `pmpm` → `pnpm` typo) for the new adapter, examples, and context API
|
|
28
|
+
- Example READMEs: add the `wiki/middleware.md` resource link to all 9 example READMEs; rewrite `examples/solid-query/README.md` (was a copy-paste of the react-query README — now describes Solid's `createQuery`/`createMutation`, `renderToStringAsync` SSR, and the disabled-query gotcha); expand the h3 example README's production flow for the extracted `bodyLimit`/`serveStatic` middleware
|
|
29
|
+
|
|
30
|
+
### Tests
|
|
31
|
+
|
|
32
|
+
- **100% coverage across all adapters**: 1001/1001 statements, 608/608 branches, 155/155 functions, 981/981 lines (412 tests)
|
|
33
|
+
- Add `send` short-circuit tests to the Express, Fastify, and Koa suites — both with headers (asserting the `headers` loop) and without (covering the `if (headers)` false branch that had dropped branch coverage below 100%)
|
|
34
|
+
- Add `tests/context.test.ts` suite: `sendResponse` delegation (with/without headers, outside-request throw), `getRequestMeta` normalization (Express-style, fetch-like `Headers`, `ip`/`protocol` derivation, bare request, plain-map headers, array-valued header, URL protocol fallback), and `functionName` passthrough
|
|
35
|
+
- Adapter suites assert `functionName` exposure via `getRequestContext()` and `send` short-circuits the JSON dispatch on all five adapters
|
|
36
|
+
- Add `?args=` non-array rejection tests (400 Bad Request) and bare-GET (no `?args=`) dispatch tests to all five adapter suites — **100/100% coverage, 412 tests**
|
|
37
|
+
|
|
38
|
+
### Security
|
|
39
|
+
|
|
40
|
+
- **`safeURL` defensive URL parsing**: `getRequestDetails()` and every adapter's inline `new URL(rawUrl, ...)` call now parse through `safeURL` (`src/server-helpers.ts`), which never throws — a malformed request-target like `/\` or `//` used to trigger an unhandled `TypeError: Invalid URL` rejection outside the dispatch `try` block and **crash raw `node:http` hosts** (and Express 4). Malformed URLs now fall back to a safe root pathname that never matches the RPC prefix, so the request degrades to `next()`/404 instead of crashing the process (High)
|
|
41
|
+
- **GET `?args=` is now validated as a JSON array**: a non-array value (e.g. `?args={"a":1}`) previously spread into `handler(...args)` and threw a confusing `TypeError: object is not iterable` 500; all five adapters now reject it with `400 { error: "Bad Request" }` before dispatch
|
|
42
|
+
- **`wiki/security.md` enumeration claim corrected**: the "prevents function enumeration" wording was overstated — the status code still distinguishes unknown (`404`) from known (`405`/`415`/`403`) functions. Documented that enumeration is mitigated against *message* disclosure only; function names ship in the client bundle so they are not secret. `AGENTS.md` and `llms.txt` updated to match
|
|
43
|
+
- Full source security audit recorded in `SECURITY-AUDIT.md` (High crash finding fixed; remaining findings are LOW/INFO/design notes)
|
|
44
|
+
|
|
45
|
+
### Chores
|
|
46
|
+
|
|
47
|
+
- Bump version to `0.2.1` (package.json + deno.json)
|
|
48
|
+
- Add `@thednp/rpc@0.2.0` to `minimumReleaseAgeExclude` in `pnpm-workspace.yaml`
|
|
49
|
+
|
|
3
50
|
## [0.2.0] - 2026-08-09
|
|
4
51
|
|
|
5
52
|
### Features
|
package/README.md
CHANGED
|
@@ -78,7 +78,7 @@ Every server function call returns a handle with a `cancel()` helper. Under the
|
|
|
78
78
|
<details>
|
|
79
79
|
<summary><b>Your server framework is your business</b></summary>
|
|
80
80
|
|
|
81
|
-
The core plugin doesn't care whether you're running Express, Fastify, Hono, or
|
|
81
|
+
The core plugin doesn't care whether you're running Express, Fastify, Hono, Koa, or h3. Adapters for all five are bundled with the package — you import the one you need, register it as middleware, and you're done. If you're building a plain SPA with no server framework at all, the Vite dev server handles RPC requests directly in development. No adapter needed.
|
|
82
82
|
</details>
|
|
83
83
|
|
|
84
84
|
<details>
|
|
@@ -103,7 +103,7 @@ Generic type inference flows from your server function's arguments and return ty
|
|
|
103
103
|
|
|
104
104
|
| Source | Demo | Clone |
|
|
105
105
|
| ----------------------------------------------------------------------------------------| ----------------------------------------------------------------------------------------------| ---------------------------------------------------------|
|
|
106
|
-
| [examples/spa](https://github.com/thednp/rpc/tree/master/examples/spa) | [StackBlitz](https://stackblitz.com/fork/github/thednp/rpc/tree/master/examples/spa) | `
|
|
106
|
+
| [examples/spa](https://github.com/thednp/rpc/tree/master/examples/spa) | [StackBlitz](https://stackblitz.com/fork/github/thednp/rpc/tree/master/examples/spa) | `pnpm dlx degit thednp/rpc/examples/spa my-app` |
|
|
107
107
|
| [examples/ssr](https://github.com/thednp/rpc/tree/master/examples/ssr) | [StackBlitz](https://stackblitz.com/fork/github/thednp/rpc/tree/master/examples/ssr) | `pnpm dlx degit thednp/rpc/examples/ssr my-app` |
|
|
108
108
|
| [examples/express](https://github.com/thednp/rpc/tree/master/examples/express) | [StackBlitz](https://stackblitz.com/fork/github/thednp/rpc/tree/master/examples/express) | `pnpm dlx degit thednp/rpc/examples/express my-app` |
|
|
109
109
|
| [examples/fastify](https://github.com/thednp/rpc/tree/master/examples/fastify) | [StackBlitz](https://stackblitz.com/fork/github/thednp/rpc/tree/master/examples/fastify) | `pnpm dlx degit thednp/rpc/examples/fastify my-app` |
|
|
@@ -249,7 +249,7 @@ pnpm test-ui # Run tests with UI
|
|
|
249
249
|
pnpm test --run # Single run
|
|
250
250
|
```
|
|
251
251
|
|
|
252
|
-
Tests use **Vitest** with **Istanbul** coverage —
|
|
252
|
+
Tests use **Vitest** with **Istanbul** coverage — 10 test files covering the plugin, scanning, server/client helpers, request context, and all five adapters, at 100% coverage.
|
|
253
253
|
|
|
254
254
|
### Live Testing
|
|
255
255
|
|
|
@@ -335,6 +335,8 @@ The full threat model, including edge cases and configuration options for tighte
|
|
|
335
335
|
- [Getting Started](./wiki/getting-started.md) — Installation, project structure, and your first function
|
|
336
336
|
- [Configuration](./wiki/configuration.md) — Full configuration reference
|
|
337
337
|
- [Server Functions](./wiki/server-functions.md) — Creating server functions
|
|
338
|
+
- [Middleware](./wiki/middleware.md) — Universal middleware via the request context
|
|
339
|
+
- [Native Form Fallback](./wiki/nojs-fallback.md) — Making RPC endpoints work as a no-JS `<form>` action
|
|
338
340
|
- [Client Usage](./wiki/client-usage.md) — Client-side usage
|
|
339
341
|
- [Wire Protocol](./wiki/wire-protocol.md) — The HTTP contract behind the generated clients (curl debugging)
|
|
340
342
|
- [Adapters](./wiki/adapters.md) — Framework adapters
|
|
@@ -38,7 +38,7 @@ type ResponseDetails = {
|
|
|
38
38
|
/** Sets the response status code */
|
|
39
39
|
setStatusCode: (code: number) => void;
|
|
40
40
|
/** Sends a JSON response with the given status code and output */
|
|
41
|
-
sendResponse: (code: number, output:
|
|
41
|
+
sendResponse: (code: number, output: JsonValue) => void;
|
|
42
42
|
};
|
|
43
43
|
/**
|
|
44
44
|
* Normalized view of an incoming request: URL parts, headers, and method.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express.d.mts","names":[],"sources":["../../src/express/types.d.ts","../../src/express/createMiddleware.ts","../../src/express/helpers.ts"],"mappings":";;;;;;;;KAgBY,2BAA2B;;;;;KAM3B,uBACV,UAAU,yCAEV,iBAAiB,QAAQ,8BACtB;;;;UAKY;;;;;;;EAOf,UACE,KAAK,kBAAkB,SACvB,KAAK,iBAAiB,UACtB,MAAM,QAAQ,eAAe,iBAC1B;;;;;;KAOK;;EAEV;;EAEA,YAAY,cAAc;;EAE1B;;EAEA,gBAAgB;;EAEhB,eAAe,cAAc,QAAQ
|
|
1
|
+
{"version":3,"file":"express.d.mts","names":[],"sources":["../../src/express/types.d.ts","../../src/express/createMiddleware.ts","../../src/express/helpers.ts"],"mappings":";;;;;;;;KAgBY,2BAA2B;;;;;KAM3B,uBACV,UAAU,yCAEV,iBAAiB,QAAQ,8BACtB;;;;UAKY;;;;;;;EAOf,UACE,KAAK,kBAAkB,SACvB,KAAK,iBAAiB,UACtB,MAAM,QAAQ,eAAe,iBAC1B;;;;;;KAOK;;EAEV;;EAEA,YAAY,cAAc;;EAE1B;;EAEA,gBAAgB;;EAEhB,eAAe,cAAc,QAAQ;;;;;KAM3B;;EAEV;;EAEA;;EAEA,cAAc;;EAEd,SAAS;;EAET;;;;;;;;;;;cC1BW,kBAAkB;;;;;;;;cAyElB,qBAAqB;;;;;;;;iBCvGZ,UAAU,KAAK,UAAO;;;;;;iBAc5B,WAAW,KAAK,SAAS,MAAM;;;;;;;;cAWlC,WAAQ,KACd,UAAiB,oBACrB,QAAQ;;;;;;cAqFE,mBAAgB,KACtB,kBAAkB,YACtB,OAAO;;;;;;cASG,oBAAiB,KACvB,iBAAiB,aACrB,OAAO;;;;;;;;;;;;cAeG,WAAQ,KACd,iBAAiB,UAAe,kBACrB;;;;;;;cAkBL,mBAAgB,KACtB,kBAAkB,YACtB,OAAO;;;;;;;cAUG,oBAAiB,SACnB,UAAiB,oBACzB;;;;;;;cAqBU,qBAAkB,UACnB,WAAkB,mBAC3B"}
|
package/dist/express/express.mjs
CHANGED
|
@@ -12,6 +12,39 @@ const defaultMiddlewareOptions = {
|
|
|
12
12
|
origin: void 0
|
|
13
13
|
};
|
|
14
14
|
//#endregion
|
|
15
|
+
//#region src/constants.ts
|
|
16
|
+
const FUNCTION_NOT_FOUND = "Function not found";
|
|
17
|
+
const METHOD_NOT_ALLOWED = "Method Not Allowed";
|
|
18
|
+
const REQUEST_FORBIDDEN = "Forbidden";
|
|
19
|
+
const UNSUPPORTED_MEDIA_TYPE = "Unsupported Media Type";
|
|
20
|
+
const BAD_REQUEST = "Bad Request";
|
|
21
|
+
const CLIENT_DISCONNECTED = "client disconnected";
|
|
22
|
+
/** Returns a warning when a middleware name is reused, preventing registration conflicts. @param name - The duplicate middleware name */
|
|
23
|
+
const MIDDLEWARE_NAME_USED = (name) => `The middleware name "${name}" is already used.`;
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/server-helpers.ts
|
|
26
|
+
const SAFE_URL_BASE = "http://localhost";
|
|
27
|
+
/**
|
|
28
|
+
* Parses a raw request URL against a fixed base without ever throwing.
|
|
29
|
+
* Malformed request-targets (e.g. `/\`, `//`, `/\/`) make the WHATWG URL
|
|
30
|
+
* parser throw `TypeError: Invalid URL`; the adapters call this while
|
|
31
|
+
* building the per-request URL **before** their dispatch `try` block, so an
|
|
32
|
+
* unhandled rejection there crashes raw `node:http` hosts (and Express 4).
|
|
33
|
+
* On failure we fall back to the base root: the resulting pathname never
|
|
34
|
+
* matches the RPC prefix, so the request is treated as non-RPC and falls
|
|
35
|
+
* through to `next()` / 404 instead of crashing the process.
|
|
36
|
+
* @param rawUrl - Raw request URL (path + optional query string)
|
|
37
|
+
* @param base - Optional base URL, defaults to a fixed localhost origin
|
|
38
|
+
* @returns A URL object; never throws
|
|
39
|
+
*/
|
|
40
|
+
const safeURL = (rawUrl, base = SAFE_URL_BASE) => {
|
|
41
|
+
try {
|
|
42
|
+
return new URL(rawUrl, base);
|
|
43
|
+
} catch {
|
|
44
|
+
return new URL("/", base);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
//#endregion
|
|
15
48
|
//#region src/express/helpers.ts
|
|
16
49
|
/**
|
|
17
50
|
* Convenience function to load RPC config and attach the RPC middleware to an Express app.
|
|
@@ -140,7 +173,7 @@ const hasPreParsedBody = (req) => {
|
|
|
140
173
|
*/
|
|
141
174
|
const getRequestDetails = (request) => {
|
|
142
175
|
const rawUrl = isExpressRequest(request) ? request.originalUrl : request.url;
|
|
143
|
-
const url =
|
|
176
|
+
const url = safeURL(rawUrl);
|
|
144
177
|
return {
|
|
145
178
|
url: url.pathname,
|
|
146
179
|
search: url.search,
|
|
@@ -180,15 +213,6 @@ const getResponseDetails = (response) => {
|
|
|
180
213
|
};
|
|
181
214
|
};
|
|
182
215
|
//#endregion
|
|
183
|
-
//#region src/constants.ts
|
|
184
|
-
const FUNCTION_NOT_FOUND = "Function not found";
|
|
185
|
-
const METHOD_NOT_ALLOWED = "Method Not Allowed";
|
|
186
|
-
const REQUEST_FORBIDDEN = "Forbidden";
|
|
187
|
-
const UNSUPPORTED_MEDIA_TYPE = "Unsupported Media Type";
|
|
188
|
-
const CLIENT_DISCONNECTED = "client disconnected";
|
|
189
|
-
/** Returns a warning when a middleware name is reused, preventing registration conflicts. @param name - The duplicate middleware name */
|
|
190
|
-
const MIDDLEWARE_NAME_USED = (name) => `The middleware name "${name}" is already used.`;
|
|
191
|
-
//#endregion
|
|
192
216
|
//#region src/express/createMiddleware.ts
|
|
193
217
|
let middlewareCount = 0;
|
|
194
218
|
const middlewareStack = /* @__PURE__ */ new Set();
|
|
@@ -264,7 +288,14 @@ const createRPCMiddleware = (initialOptions = {}) => {
|
|
|
264
288
|
let args = [];
|
|
265
289
|
if (method === "GET") {
|
|
266
290
|
const raw = searchParams.get("args");
|
|
267
|
-
if (raw)
|
|
291
|
+
if (raw) {
|
|
292
|
+
const parsed = JSON.parse(raw);
|
|
293
|
+
if (!Array.isArray(parsed)) {
|
|
294
|
+
sendResponse(400, { error: BAD_REQUEST });
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
args = parsed;
|
|
298
|
+
}
|
|
268
299
|
} else {
|
|
269
300
|
if (hasContentTypeMismatch(serverFunction.options?.contentType ?? "application/json", req.headers["content-type"])) {
|
|
270
301
|
sendResponse(415, { error: UNSUPPORTED_MEDIA_TYPE });
|
|
@@ -281,12 +312,23 @@ const createRPCMiddleware = (initialOptions = {}) => {
|
|
|
281
312
|
res
|
|
282
313
|
},
|
|
283
314
|
locals: res.locals ?? {},
|
|
315
|
+
functionName,
|
|
284
316
|
redirect: (location, status = 303) => {
|
|
285
317
|
requestEvent.redirected = {
|
|
286
318
|
location,
|
|
287
319
|
status
|
|
288
320
|
};
|
|
289
321
|
redirect(res, location, status);
|
|
322
|
+
},
|
|
323
|
+
send: (status, body, headers) => {
|
|
324
|
+
requestEvent.sent = {
|
|
325
|
+
status,
|
|
326
|
+
body,
|
|
327
|
+
headers
|
|
328
|
+
};
|
|
329
|
+
const details = getResponseDetails(res);
|
|
330
|
+
if (headers) for (const [name, value] of Object.entries(headers)) details.setHeader(name, value);
|
|
331
|
+
details.sendResponse(status, body);
|
|
290
332
|
}
|
|
291
333
|
};
|
|
292
334
|
const { data, cancel } = provideRequestContext(requestEvent, () => serverFunction.handler(...args));
|
|
@@ -294,7 +336,7 @@ const createRPCMiddleware = (initialOptions = {}) => {
|
|
|
294
336
|
req.on("close", onClose);
|
|
295
337
|
const result = await data;
|
|
296
338
|
req.off("close", onClose);
|
|
297
|
-
if (!requestEvent.redirected && !res.headersSent) sendResponse(200, { data: result });
|
|
339
|
+
if (!requestEvent.redirected && !requestEvent.sent && !res.headersSent) sendResponse(200, { data: result });
|
|
298
340
|
} catch (err) {
|
|
299
341
|
console.error(String(err));
|
|
300
342
|
const isProduction = process.env.NODE_ENV === "production";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express.mjs","names":[],"sources":["../../src/options.ts","../../src/express/helpers.ts","../../src/constants.ts","../../src/express/createMiddleware.ts"],"sourcesContent":["import type {\n MiddlewareOptions,\n RpcPluginOptions,\n ServerFunctionOptions,\n} from \"./types.d.ts\";\n\nexport const defaultServerFnOptions = {\n contentType: \"application/json\",\n credentials: \"same-origin\",\n method: \"POST\",\n} satisfies ServerFunctionOptions;\n\nexport const defaultRPCOptions: RpcPluginOptions = {\n rpcPrefix: \"__rpc\",\n adapter: \"express\",\n serverFiles: \"exact\",\n scanRoot: undefined,\n};\n\nexport const defaultMiddlewareOptions = {\n rpcPrefix: undefined,\n path: undefined,\n origin: undefined,\n} satisfies MiddlewareOptions;\n","// src/express/helpers.ts\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n} from \"express\";\nimport type { BodyResult, JsonValue } from \"@thednp/rpc\";\nimport type { Buffer } from \"node:buffer\";\nimport type { ViteDevServer } from \"vite\";\nimport type { Express } from \"express\";\nimport { createRPCMiddleware } from \"./createMiddleware.ts\";\nimport type { RequestDetails, ResponseDetails } from \"./types.d.ts\";\n\n/**\n * Convenience function to load RPC config and attach the RPC middleware to an Express app.\n * Dynamically imports loadRPCConfig and creates the middleware with loaded options.\n * @param app - Express application instance\n */\nexport async function attachRPC(app: Express) {\n // The main plugin entry statically imports Vite, so loadRPCConfig is\n // imported lazily: function bundles that never call attachRPC (e.g.\n // serverless functions) keep Vite out of the bundle (or externalized).\n const { loadRPCConfig } = await import(\"@thednp/rpc\");\n const { adapter: _adapter, ...options } = await loadRPCConfig();\n app.use(createRPCMiddleware(options));\n}\n\n/**\n * Attaches Vite's dev server middlewares to an Express app for development mode.\n * @param app - Express application instance\n * @param vite - Running Vite dev server\n */\nexport function attachVite(app: Express, vite: ViteDevServer) {\n app.use(vite.middlewares);\n}\n\n/**\n * Reads and parses the HTTP request body from an Express or Node IncomingMessage.\n * If a body parser middleware (e.g. express.json()) already consumed the stream,\n * uses the pre-parsed body from `req.body`.\n * @param req - Express or Node.js IncomingMessage\n * @returns A promise resolving to the parsed body with its content type\n */\nexport const readBody = (\n req: ExpressRequest | IncomingMessage,\n): Promise<BodyResult> => {\n return new Promise((resolve, reject) => {\n // If an Express body parser already consumed the stream\n // via app.use(express.json()), use req.body directly\n if (hasPreParsedBody(req) && req.body !== undefined) {\n // istanbul ignore next\n const contentType = req.headers[\"content-type\"]?.toLowerCase() || \"\";\n const isJSON = contentType.includes(\"json\");\n const isMultipart = contentType.includes(\"multipart/form-data\");\n const isUrlEncoded = contentType.includes(\"urlencoded\");\n resolve({\n contentType: isMultipart\n ? \"multipart/form-data\"\n : isJSON\n ? \"application/json\"\n : isUrlEncoded\n ? \"application/x-www-form-urlencoded\"\n : \"text/plain\",\n data: isMultipart\n ? (req.body as Record<string, unknown>)\n : isJSON\n ? req.body\n : isUrlEncoded\n ? (req.body as Record<string, unknown>)\n : String(req.body),\n } as BodyResult);\n return;\n }\n\n // Else we parse the body right away\n let body = \"\";\n\n const toggleListeners = (add?: boolean) => {\n const method = add ? \"on\" : \"off\";\n req[method](\"data\", onData);\n req[method](\"end\", onEnd);\n req[method](\"error\", onError);\n };\n\n const onData = (chunk: Buffer) => {\n body += chunk.toString();\n };\n\n const onEnd = () => {\n toggleListeners();\n const incomingType = req.headers[\"content-type\"]?.toLowerCase() || \"\";\n const isJSON = incomingType.includes(\"json\");\n const isMultipart = incomingType.includes(\"multipart/form-data\");\n const isUrlEncoded = incomingType.includes(\"urlencoded\");\n try {\n const data = isMultipart\n ? { raw: body }\n : isUrlEncoded\n ? Object.fromEntries(new URLSearchParams(body))\n : JSON.parse(body);\n resolve({\n contentType: isMultipart\n ? \"multipart/form-data\"\n : isJSON\n ? \"application/json\"\n : isUrlEncoded\n ? \"application/x-www-form-urlencoded\"\n : \"text/plain\",\n data: isMultipart ? (data as Record<string, unknown>) : data,\n } as BodyResult);\n } catch (_e) {\n resolve({ contentType: \"text/plain\", data: String(body) });\n }\n };\n\n const onError = (err: Error) => {\n toggleListeners();\n\n reject(err);\n };\n\n toggleListeners(true);\n });\n};\n\n/**\n * Type guard that checks whether a request is an Express Request (has `originalUrl`).\n * @param req - A Node IncomingMessage or Express Request\n * @returns True if the request is an Express Request\n */\nexport const isExpressRequest = (\n req: IncomingMessage | ExpressRequest,\n): req is ExpressRequest => {\n return \"originalUrl\" in req;\n};\n\n/**\n * Type guard that checks whether a response is an Express Response (has `json` and `send` methods).\n * @param res - A Node ServerResponse or Express Response\n * @returns True if the response is an Express Response\n */\nexport const isExpressResponse = (\n res: ServerResponse | ExpressResponse,\n): res is ExpressResponse => {\n return \"json\" in res && \"send\" in res;\n};\n\n/**\n * Issues an HTTP redirect on an Express or raw Node ServerResponse.\n * Uses Express's native `res.redirect(status, location)` when an Express\n * Response is provided, otherwise writes the status code and `Location`\n * header directly on the raw `ServerResponse` (safe for Connect-compatible\n * middlewares and serverless adapters whose mock responses lack `.redirect`).\n * Defaults to `303 See Other` for convention (Post/Redirect/Get).\n * @param res - Express Response or raw Node ServerResponse\n * @param location - The URL to redirect to\n * @param status - HTTP status code, defaults to 303\n */\nexport const redirect = (\n res: ServerResponse | ExpressResponse,\n location: string,\n status = 303,\n): void => {\n if (isExpressResponse(res)) {\n res.redirect(status, location);\n return;\n }\n res.statusCode = status;\n res.setHeader(\"Location\", location);\n res.end();\n};\n\n/**\n * Type guard that checks whether a request has a pre-parsed body (`body` property).\n * Used to detect if a body-parser middleware already consumed the stream.\n * @param req - A Node IncomingMessage or Express Request\n * @returns True if the request has a body property\n */\nexport const hasPreParsedBody = (\n req: IncomingMessage | ExpressRequest,\n): req is ExpressRequest => {\n return \"body\" in req;\n};\n\n/**\n * Extracts normalized request details from an Express or Node IncomingMessage.\n * Parses the URL to extract pathname, search string, and search params.\n * @param request - Express or Node.js request object\n * @returns Normalized request details including URL, headers, and method\n */\nexport const getRequestDetails = (\n request: ExpressRequest | IncomingMessage,\n): RequestDetails => {\n const rawUrl = (\n isExpressRequest(request) ? request.originalUrl : request.url\n ) as string;\n const url = new URL(rawUrl, \"http://localhost\");\n\n return {\n url: url.pathname,\n search: url.search,\n searchParams: url.searchParams,\n headers: request.headers,\n method: request.method,\n };\n};\n\n/**\n * Wraps an Express or Node ServerResponse with a uniform API for setting headers,\n * status codes, and sending JSON responses. Handles the Express vs raw Node API differences.\n * @param response - Express or Node.js server response object\n * @returns A ResponseDetails object with setHeader, setStatusCode, and sendResponse helpers\n */\nexport const getResponseDetails = (\n response: ExpressResponse | ServerResponse,\n): ResponseDetails => {\n const isResponseSent = response.headersSent || response.writableEnded;\n\n const setHeader = (name: string, value: string) => {\n if (isExpressResponse(response)) {\n response.header(name, value);\n } else {\n response.setHeader(name, value);\n }\n };\n\n const setStatusCode = (code: number) => {\n if (isExpressResponse(response)) {\n response.status(code);\n } else {\n response.statusCode = code;\n }\n };\n\n const sendResponse = (code: number, output: Record<string, JsonValue>) => {\n setStatusCode(code);\n setHeader(\"Content-Type\", \"application/json\");\n\n if (isExpressResponse(response)) {\n response.send(JSON.stringify(output));\n } else {\n response.end(JSON.stringify(output));\n }\n };\n\n return {\n isResponseSent,\n setHeader,\n statusCode: response.statusCode,\n setStatusCode,\n sendResponse,\n };\n};\n","export const OPERATION_ABORTED = \"Operation aborted\";\n\nexport const REQUEST_CANCELLED = \"Request was cancelled\";\n\nexport const FETCH_ERROR_PREFIX = \"Fetch error: \";\n\nexport const NO_SERVER_FUNCTION_FOUND = \"No server function found.\";\n\nexport const ERROR_LOADING_FILE = \"Error loading file:\";\n\nexport const FUNCTION_NOT_FOUND = \"Function not found\";\n\nexport const METHOD_NOT_ALLOWED = \"Method Not Allowed\";\n\nexport const REQUEST_FORBIDDEN = \"Forbidden\";\n\nexport const UNSUPPORTED_MEDIA_TYPE = \"Unsupported Media Type\";\n\nexport const INTERNAL_SERVER_ERROR = \"Internal Server Error\";\n\nexport const CLIENT_DISCONNECTED = \"client disconnected\";\n\n/** Returns a warning when a middleware name is reused, preventing registration conflicts. @param name - The duplicate middleware name */\nexport const MIDDLEWARE_NAME_USED = (name: string) =>\n `The middleware name \"${name}\" is already used.`;\n\n/** Error message when a value fails the safe-identifier validation. @param label - What kind of value was being validated. @param name - The rejected value */\nexport const INVALID_IDENTIFIER = (label: string, name: string) =>\n `Invalid ${label}: \"${name}\" must match /^[A-Za-z_$][A-Za-z0-9_$]*$/`;\n\n/** Error message when a value fails the safe-path-segment validation. @param label - What kind of value was being validated. @param segment - The rejected value */\nexport const INVALID_PATH_SEGMENT = (label: string, segment: string) =>\n `Invalid ${label}: \"${segment}\" must match /^[A-Za-z0-9_$][A-Za-z0-9_$/-]*$/`;\n\n/** Warning message when a specified RPC config file cannot be resolved on disk. @param configFile - The requested config filename. @param configFilePath - The resolved absolute path */\nexport const CONFIG_FILE_NOT_FOUND = (\n configFile: string,\n configFilePath: string,\n) =>\n ` ⚠︎ The specified RPC config file ${configFile} cannot be found at ${configFilePath}, loading the defaults..`;\n\nexport const NO_CONFIG_FOUND = ` ⚡︎ No RPC config found, loading the defaults..`;\n\nexport const FAILED_LOAD_CONFIG = ` ⚠︎ Failed to load RPC config:`;\n\n/** Error template for duplicate server function names across files. @param name - The duplicate registered name */\nexport const DUPLICATE_FUNCTION_NAME = (name: string) =>\n `Duplicate server function \"${name}\" detected. Each server function must have a unique name. Remove or rename the duplicate.`;\n","// src/express/createMidleware.ts\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type {\n NextFunction,\n Request as ExpressRequest,\n Response as ExpressResponse,\n} from \"express\";\nimport type {\n ExpressMiddlewareFn,\n ExpressMiddlewareOptions,\n} from \"./types.d.ts\";\nimport type { Connect } from \"vite\";\nimport type { JsonValue } from \"../types.d.ts\";\nimport type { RequestEvent } from \"@thednp/rpc/server\";\nimport {\n escapeRegExp,\n formatError,\n hasContentTypeMismatch,\n provideRequestContext,\n scanForServerFiles,\n serverFunctionsMap,\n} from \"@thednp/rpc/server\";\nimport { defaultMiddlewareOptions, defaultRPCOptions } from \"../options.ts\";\nimport {\n getRequestDetails,\n getResponseDetails,\n readBody,\n redirect as expressRedirect,\n} from \"./helpers.ts\";\nimport {\n CLIENT_DISCONNECTED,\n FUNCTION_NOT_FOUND,\n METHOD_NOT_ALLOWED,\n MIDDLEWARE_NAME_USED,\n REQUEST_FORBIDDEN,\n UNSUPPORTED_MEDIA_TYPE,\n} from \"../constants.ts\";\n\nlet middlewareCount = 0;\nconst middlewareStack = new Set<string>();\n\n/**\n * Creates an Express middleware with optional path and rpcPrefix filtering.\n * Middleware names are deduplicated — reusing a name throws an error.\n * Prefix and path regexes are compiled once at creation time (hoisted) for performance.\n * @param initialOptions - Options for rpcPrefix, path matching, and the handler function\n * @returns An Express middleware function\n */\nexport const createMiddleware: ExpressMiddlewareFn = (initialOptions = {}) => {\n const options = Object.assign(\n {},\n defaultMiddlewareOptions,\n initialOptions,\n ) as ExpressMiddlewareOptions;\n const middlewareName = options.name;\n const rpcPrefix = options.rpcPrefix;\n const path = options.path;\n const handler = options.handler;\n\n let name = middlewareName;\n if (!name) {\n name = \"viteRPCMiddleware-\" + middlewareCount;\n middlewareCount += 1;\n }\n if (middlewareStack.has(name)) {\n throw new Error(MIDDLEWARE_NAME_USED(name));\n }\n middlewareStack.add(name);\n\n // Hoist regex compilation out of per-request path. Escape the prefix to\n // prevent regex injection via metacharacters in the config string.\n const prefixRegex: RegExp | null = rpcPrefix\n ? new RegExp(`^/${escapeRegExp(rpcPrefix)}/`)\n : null;\n const pathMatcher: RegExp | null = path\n ? (typeof path === \"string\" ? new RegExp(path) : path)\n : null;\n\n const middlewareHandler = async (\n req: IncomingMessage | ExpressRequest,\n res: ServerResponse | ExpressResponse,\n next: Connect.NextFunction | NextFunction,\n ) => {\n const { url } = getRequestDetails(req);\n\n // When serving from production server, scan for server files\n if (serverFunctionsMap.size === 0) {\n await scanForServerFiles();\n }\n\n // No need to continue when no handler provided\n if (!handler) {\n return next?.();\n }\n\n // Path matching\n if (pathMatcher && !pathMatcher.test(url)) return next?.();\n\n // rpcPrefix matching (boundary-safe via escaped regex)\n if (prefixRegex && !prefixRegex.test(url)) {\n return next?.();\n }\n\n // Execute handler\n await handler(req, res, next);\n };\n\n Object.defineProperty(middlewareHandler, \"name\", {\n value: name,\n });\n\n return middlewareHandler;\n};\n\n/**\n * Creates the Express RPC middleware that routes incoming requests to registered server functions.\n * Reads the request body, dispatches to the matching function via serverFunctionsMap,\n * and sends the JSON-serialized result. Handles client disconnection via abort signals.\n * @param initialOptions - Options including rpcPrefix for URL routing\n * @returns An Express middleware function\n */\nexport const createRPCMiddleware: ExpressMiddlewareFn = (\n initialOptions = {},\n) => {\n const options = Object.assign(\n {},\n defaultMiddlewareOptions,\n { rpcPrefix: defaultRPCOptions.rpcPrefix },\n initialOptions,\n ) as ExpressMiddlewareOptions;\n\n // Hoist prefix regex (escaped) and the literal prefix-for-replace out of the\n // per-request handler to avoid regex injection and per-request compilation.\n const rpcPrefix = options.rpcPrefix;\n const prefixRegex = rpcPrefix\n ? new RegExp(`^/${escapeRegExp(rpcPrefix)}/`)\n : /* istanbul ignore next */ null;\n const prefixReplace = `/${rpcPrefix}/`;\n\n return createMiddleware({\n ...options,\n handler: async (\n req: IncomingMessage | ExpressRequest,\n res: ServerResponse | ExpressResponse,\n _next: NextFunction | Connect.NextFunction,\n ) => {\n const { url: path, searchParams } = getRequestDetails(req);\n const { sendResponse } = getResponseDetails(res);\n\n // Validate the url starts with the prefix via the escaped regex\n // istanbul ignore next\n if (prefixRegex && !prefixRegex.test(path)) {\n // falls through to next handler (never reached in practice; the outer\n // createMiddleware already gates on this, but kept for defense-in-depth)\n return;\n }\n\n // Optional origin check: reject requests whose Origin header does not\n // match the configured origin. Requests without an Origin header\n // (curl, native clients) pass through unchecked.\n const origin = options.origin;\n const requestOrigin = req.headers.origin;\n if (origin && requestOrigin && requestOrigin !== origin) {\n sendResponse(403, { error: REQUEST_FORBIDDEN });\n return;\n }\n\n const functionName = path.replace(prefixReplace, \"\");\n const serverFunction = serverFunctionsMap.get(functionName);\n\n if (!serverFunction) {\n sendResponse(404, { error: FUNCTION_NOT_FOUND });\n return;\n }\n\n try {\n const method = serverFunction.options?.method || \"POST\";\n if (req.method?.toUpperCase() !== method) {\n sendResponse(405, { error: METHOD_NOT_ALLOWED });\n return;\n }\n\n let args: JsonValue[] = [];\n if (method === \"GET\") {\n const raw = searchParams.get(\"args\");\n // istanbul ignore else\n if (raw) args = JSON.parse(raw);\n } else {\n // Content-type enforcement: strict for json/text, lenient between forms.\n // Requests without a Content-Type header are exempt (curl/GET compat).\n // Checked BEFORE readBody so mismatched bodies are never buffered.\n if (\n hasContentTypeMismatch(\n serverFunction.options?.contentType ?? \"application/json\",\n req.headers[\"content-type\"],\n )\n ) {\n sendResponse(415, { error: UNSUPPORTED_MEDIA_TYPE });\n return;\n }\n const body = await readBody(req);\n args = Array.isArray(body.data)\n ? body.data as JsonValue[]\n : [body.data as JsonValue];\n }\n // ─── Dispatch ────────────────────────────────────────────────────\n // Establish the per-request context around the *entire* dispatch so\n // server functions (and async continuations spawned by their work)\n // read `getRequestContext()` and can call the framework-level\n // `redirect(location)`. The adapter-specific redirect is bound into the\n // context here; `serverFunction.handler` must be invoked inside the\n // context callback so its async increments run with the context live.\n const requestEvent: RequestEvent = {\n request: req,\n response: res,\n nativeEvent: { req, res },\n locals: (res as ExpressResponse).locals ?? {},\n redirect: (location, status = 303) => {\n requestEvent.redirected = { location, status };\n expressRedirect(res, location, status);\n },\n };\n\n const { data, cancel } = provideRequestContext(\n requestEvent,\n () => serverFunction.handler(...args),\n );\n const onClose = () => cancel(CLIENT_DISCONNECTED);\n req.on(\"close\", onClose);\n const result = await data;\n req.off(\"close\", onClose);\n\n // Skip the JSON send when the server function issued a redirect; the\n // bound adapter redirect already wrote the response.\n // istanbul ignore else\n if (!requestEvent.redirected && !res.headersSent) {\n sendResponse(200, { data: result });\n }\n } catch (err) {\n console.error(String(err));\n const isProduction = process.env.NODE_ENV === \"production\";\n sendResponse(500, formatError(err, isProduction));\n }\n },\n });\n};\n"],"mappings":";;AAYA,MAAa,oBAAsC;CACjD,WAAW;CACX,SAAS;CACT,aAAa;CACb,UAAU,KAAA;AACZ;AAEA,MAAa,2BAA2B;CACtC,WAAW,KAAA;CACX,MAAM,KAAA;CACN,QAAQ,KAAA;AACV;;;;;;;;ACLA,eAAsB,UAAU,KAAc;CAI5C,MAAM,EAAE,kBAAkB,MAAM,OAAO;CACvC,MAAM,EAAE,SAAS,UAAU,GAAG,YAAY,MAAM,cAAc;CAC9D,IAAI,IAAI,oBAAoB,OAAO,CAAC;AACtC;;;;;;AAOA,SAAgB,WAAW,KAAc,MAAqB;CAC5D,IAAI,IAAI,KAAK,WAAW;AAC1B;;;;;;;;AASA,MAAa,YACX,QACwB;CACxB,OAAO,IAAI,SAAS,SAAS,WAAW;EAGtC,IAAI,iBAAiB,GAAG,KAAK,IAAI,SAAS,KAAA,GAAW;GAEnD,MAAM,cAAc,IAAI,QAAQ,eAAe,EAAE,YAAY,KAAK;GAClE,MAAM,SAAS,YAAY,SAAS,MAAM;GAC1C,MAAM,cAAc,YAAY,SAAS,qBAAqB;GAC9D,MAAM,eAAe,YAAY,SAAS,YA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MAAM,EAAE,MAAM,WAAW,sBACvB,oBACM,eAAe,QAAQ,GAAG,IAAI,CACtC;IACA,MAAM,gBAAgB,OAAO,mBAAmB;IAChD,IAAI,GAAG,SAAS,OAAO;IACvB,MAAM,SAAS,MAAM;IACrB,IAAI,IAAI,SAAS,OAAO;IAKxB,IAAI,CAAC,aAAa,cAAc,CAAC,IAAI,aACnC,aAAa,KAAK,EAAE,MAAM,OAAO,CAAC;GAEtC,SAAS,KAAK;IACZ,QAAQ,MAAM,OAAO,GAAG,CAAC;IACzB,MAAM,eAAe,QAAQ,IAAI,aAAa;IAC9C,aAAa,KAAK,YAAY,KAAK,YAAY,CAAC;GAClD;EACF;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"express.mjs","names":[],"sources":["../../src/options.ts","../../src/constants.ts","../../src/server-helpers.ts","../../src/express/helpers.ts","../../src/express/createMiddleware.ts"],"sourcesContent":["import type {\n MiddlewareOptions,\n RpcPluginOptions,\n ServerFunctionOptions,\n} from \"./types.d.ts\";\n\nexport const defaultServerFnOptions = {\n contentType: \"application/json\",\n credentials: \"same-origin\",\n method: \"POST\",\n} satisfies ServerFunctionOptions;\n\nexport const defaultRPCOptions: RpcPluginOptions = {\n rpcPrefix: \"__rpc\",\n adapter: \"express\",\n serverFiles: \"exact\",\n scanRoot: undefined,\n};\n\nexport const defaultMiddlewareOptions = {\n rpcPrefix: undefined,\n path: undefined,\n origin: undefined,\n} satisfies MiddlewareOptions;\n","export const OPERATION_ABORTED = \"Operation aborted\";\n\nexport const REQUEST_CANCELLED = \"Request was cancelled\";\n\nexport const FETCH_ERROR_PREFIX = \"Fetch error: \";\n\nexport const NO_SERVER_FUNCTION_FOUND = \"No server function found.\";\n\nexport const ERROR_LOADING_FILE = \"Error loading file:\";\n\nexport const FUNCTION_NOT_FOUND = \"Function not found\";\n\nexport const METHOD_NOT_ALLOWED = \"Method Not Allowed\";\n\nexport const REQUEST_FORBIDDEN = \"Forbidden\";\n\nexport const UNSUPPORTED_MEDIA_TYPE = \"Unsupported Media Type\";\n\nexport const BAD_REQUEST = \"Bad Request\";\n\nexport const INTERNAL_SERVER_ERROR = \"Internal Server Error\";\n\nexport const CLIENT_DISCONNECTED = \"client disconnected\";\n\n/** Returns a warning when a middleware name is reused, preventing registration conflicts. @param name - The duplicate middleware name */\nexport const MIDDLEWARE_NAME_USED = (name: string) =>\n `The middleware name \"${name}\" is already used.`;\n\n/** Error message when a value fails the safe-identifier validation. @param label - What kind of value was being validated. @param name - The rejected value */\nexport const INVALID_IDENTIFIER = (label: string, name: string) =>\n `Invalid ${label}: \"${name}\" must match /^[A-Za-z_$][A-Za-z0-9_$]*$/`;\n\n/** Error message when a value fails the safe-path-segment validation. @param label - What kind of value was being validated. @param segment - The rejected value */\nexport const INVALID_PATH_SEGMENT = (label: string, segment: string) =>\n `Invalid ${label}: \"${segment}\" must match /^[A-Za-z0-9_$][A-Za-z0-9_$/-]*$/`;\n\n/** Warning message when a specified RPC config file cannot be resolved on disk. @param configFile - The requested config filename. @param configFilePath - The resolved absolute path */\nexport const CONFIG_FILE_NOT_FOUND = (\n configFile: string,\n configFilePath: string,\n) =>\n ` ⚠︎ The specified RPC config file ${configFile} cannot be found at ${configFilePath}, loading the defaults..`;\n\nexport const NO_CONFIG_FOUND = ` ⚡︎ No RPC config found, loading the defaults..`;\n\nexport const FAILED_LOAD_CONFIG = ` ⚠︎ Failed to load RPC config:`;\n\n/** Error template for duplicate server function names across files. @param name - The duplicate registered name */\nexport const DUPLICATE_FUNCTION_NAME = (name: string) =>\n `Duplicate server function \"${name}\" detected. Each server function must have a unique name. Remove or rename the duplicate.`;\n","/** @module Server-side utilities. Exports the `RPCError` class for typed server-side errors, `formatError` for middleware error responses, `isFormContentType` and `hasContentTypeMismatch` for content-type validation, and `walkGlobFiles` for recursively discovering `*.server.*` files. Never import this module in client code — it is server-only. */\nimport type { ContentType, JsonObject, JsonValue } from \"./types.d.ts\";\nimport { readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { INTERNAL_SERVER_ERROR } from \"./constants.ts\";\n\nconst GLOB_REGEX = /^.+\\.server\\.(ts|js|mjs|mts)$/;\n\n/**\n * Recursively walks `dir` and collects absolute paths to files whose\n * basename matches the `*.server.{ts,js,mjs,mts}` glob pattern.\n */\nexport const walkGlobFiles = async (dir: string): Promise<string[]> => {\n const results: string[] = [];\n const stack = [dir];\n while (stack.length) {\n const current = stack.pop()!;\n let entries;\n try {\n entries = await readdir(current, { withFileTypes: true });\n } catch (_e) {\n continue;\n }\n for (const entry of entries) {\n const fullPath = join(current, entry.name);\n if (entry.isFile() && GLOB_REGEX.test(entry.name)) {\n results.push(fullPath);\n } else if (entry.isDirectory()) {\n stack.push(fullPath);\n }\n }\n }\n return results;\n};\n\n/**\n * A typed error thrown from server functions.\n * The middleware serializes the `message` and `code` in the response,\n * allowing clients to recognise and handle specific error conditions.\n */\nexport class RPCError extends Error {\n /** Machine-readable error code (e.g. \"VALIDATION_FAILED\", \"UNAUTHORIZED\") */\n code: string;\n /** Optional diagnostic payload */\n data?: JsonValue;\n constructor(message: string, code = \"INTERNAL\", data?: JsonValue) {\n super(message);\n this.name = \"RPCError\";\n this.code = code;\n this.data = data;\n }\n}\n\n/**\n * Formats an error for the RPC middleware response.\n * In development the full `RPCError` payload is included so developers\n * can quickly identify issues. Unexpected exceptions never expose their\n * message — only the generic \"Internal Server Error\" is sent, preventing\n * information disclosure; server-side diagnostics are preserved via the\n * middleware's `console.error` logging.\n */\nexport const formatError = (\n err: unknown,\n isProduction: boolean,\n): JsonObject => {\n if (isProduction) {\n return { error: INTERNAL_SERVER_ERROR };\n }\n if (err instanceof RPCError) {\n const payload: JsonObject = {\n error: err.message || INTERNAL_SERVER_ERROR,\n code: err.code,\n };\n if (err.data !== undefined) payload.data = err.data;\n return payload;\n }\n return { error: INTERNAL_SERVER_ERROR };\n};\n\n/**\n * Checks whether a content type maps to a form encoding\n * (`multipart/form-data` or `application/x-www-form-urlencoded`).\n * Form-declared functions accept either encoding so native browser\n * submissions (urlencoded) keep working without JavaScript.\n */\nexport const isFormContentType = (contentType: string): boolean =>\n contentType === \"multipart/form-data\" ||\n contentType === \"application/x-www-form-urlencoded\";\n\n/**\n * Detects whether an incoming request's `Content-Type` header conflicts\n * with the function's declared content type. JSON and text functions are\n * enforced strictly (exact match wins), while form functions accept both\n * form encodings because the nojs fallback submits urlencoded forms to\n * multipart-declared endpoints. Requests without a `Content-Type` header\n * (curl, GET, legacy clients) are exempt from enforcement.\n * @param declared - The declared `contentType` from the server function options\n * @param rawHeader - The raw `Content-Type` request header, if present\n */\nexport const hasContentTypeMismatch = (\n declared: ContentType,\n rawHeader: string | undefined,\n): boolean => {\n // No Content-Type header → exempt (url bar, GET, curl compatibility)\n if (!rawHeader) return false;\n // Strip parameters (charset, boundary) before comparison\n const incomingType = rawHeader.trim().toLowerCase().split(\";\")[0].trim();\n if (isFormContentType(declared)) {\n // Forms: reject only non-form encodings (lenient between the two)\n return !isFormContentType(incomingType);\n }\n return incomingType !== declared;\n};\n\n/**\n * Escapes special regex metacharacters in a string.\n * Used to safely embed user-configurable values (like rpcPrefix) into regular expressions,\n * preventing ReDoS and regex injection attacks.\n * @param s - The raw string to escape\n * @returns The escaped string safe for use in new RegExp()\n */\nexport function escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nconst SAFE_URL_BASE = \"http://localhost\";\n\n/**\n * Parses a raw request URL against a fixed base without ever throwing.\n * Malformed request-targets (e.g. `/\\`, `//`, `/\\/`) make the WHATWG URL\n * parser throw `TypeError: Invalid URL`; the adapters call this while\n * building the per-request URL **before** their dispatch `try` block, so an\n * unhandled rejection there crashes raw `node:http` hosts (and Express 4).\n * On failure we fall back to the base root: the resulting pathname never\n * matches the RPC prefix, so the request is treated as non-RPC and falls\n * through to `next()` / 404 instead of crashing the process.\n * @param rawUrl - Raw request URL (path + optional query string)\n * @param base - Optional base URL, defaults to a fixed localhost origin\n * @returns A URL object; never throws\n */\nexport const safeURL = (rawUrl: string, base = SAFE_URL_BASE): URL => {\n try {\n return new URL(rawUrl, base);\n } catch {\n return new URL(\"/\", base);\n }\n};\n","// src/express/helpers.ts\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n} from \"express\";\nimport type { BodyResult, JsonValue } from \"@thednp/rpc\";\nimport type { Buffer } from \"node:buffer\";\nimport type { ViteDevServer } from \"vite\";\nimport type { Express } from \"express\";\nimport { createRPCMiddleware } from \"./createMiddleware.ts\";\nimport type { RequestDetails, ResponseDetails } from \"./types.d.ts\";\nimport { safeURL } from \"../server-helpers.ts\";\n\n/**\n * Convenience function to load RPC config and attach the RPC middleware to an Express app.\n * Dynamically imports loadRPCConfig and creates the middleware with loaded options.\n * @param app - Express application instance\n */\nexport async function attachRPC(app: Express) {\n // The main plugin entry statically imports Vite, so loadRPCConfig is\n // imported lazily: function bundles that never call attachRPC (e.g.\n // serverless functions) keep Vite out of the bundle (or externalized).\n const { loadRPCConfig } = await import(\"@thednp/rpc\");\n const { adapter: _adapter, ...options } = await loadRPCConfig();\n app.use(createRPCMiddleware(options));\n}\n\n/**\n * Attaches Vite's dev server middlewares to an Express app for development mode.\n * @param app - Express application instance\n * @param vite - Running Vite dev server\n */\nexport function attachVite(app: Express, vite: ViteDevServer) {\n app.use(vite.middlewares);\n}\n\n/**\n * Reads and parses the HTTP request body from an Express or Node IncomingMessage.\n * If a body parser middleware (e.g. express.json()) already consumed the stream,\n * uses the pre-parsed body from `req.body`.\n * @param req - Express or Node.js IncomingMessage\n * @returns A promise resolving to the parsed body with its content type\n */\nexport const readBody = (\n req: ExpressRequest | IncomingMessage,\n): Promise<BodyResult> => {\n return new Promise((resolve, reject) => {\n // If an Express body parser already consumed the stream\n // via app.use(express.json()), use req.body directly\n if (hasPreParsedBody(req) && req.body !== undefined) {\n // istanbul ignore next\n const contentType = req.headers[\"content-type\"]?.toLowerCase() || \"\";\n const isJSON = contentType.includes(\"json\");\n const isMultipart = contentType.includes(\"multipart/form-data\");\n const isUrlEncoded = contentType.includes(\"urlencoded\");\n resolve({\n contentType: isMultipart\n ? \"multipart/form-data\"\n : isJSON\n ? \"application/json\"\n : isUrlEncoded\n ? \"application/x-www-form-urlencoded\"\n : \"text/plain\",\n data: isMultipart\n ? (req.body as Record<string, unknown>)\n : isJSON\n ? req.body\n : isUrlEncoded\n ? (req.body as Record<string, unknown>)\n : String(req.body),\n } as BodyResult);\n return;\n }\n\n // Else we parse the body right away\n let body = \"\";\n\n const toggleListeners = (add?: boolean) => {\n const method = add ? \"on\" : \"off\";\n req[method](\"data\", onData);\n req[method](\"end\", onEnd);\n req[method](\"error\", onError);\n };\n\n const onData = (chunk: Buffer) => {\n body += chunk.toString();\n };\n\n const onEnd = () => {\n toggleListeners();\n const incomingType = req.headers[\"content-type\"]?.toLowerCase() || \"\";\n const isJSON = incomingType.includes(\"json\");\n const isMultipart = incomingType.includes(\"multipart/form-data\");\n const isUrlEncoded = incomingType.includes(\"urlencoded\");\n try {\n const data = isMultipart\n ? { raw: body }\n : isUrlEncoded\n ? Object.fromEntries(new URLSearchParams(body))\n : JSON.parse(body);\n resolve({\n contentType: isMultipart\n ? \"multipart/form-data\"\n : isJSON\n ? \"application/json\"\n : isUrlEncoded\n ? \"application/x-www-form-urlencoded\"\n : \"text/plain\",\n data: isMultipart ? (data as Record<string, unknown>) : data,\n } as BodyResult);\n } catch (_e) {\n resolve({ contentType: \"text/plain\", data: String(body) });\n }\n };\n\n const onError = (err: Error) => {\n toggleListeners();\n\n reject(err);\n };\n\n toggleListeners(true);\n });\n};\n\n/**\n * Type guard that checks whether a request is an Express Request (has `originalUrl`).\n * @param req - A Node IncomingMessage or Express Request\n * @returns True if the request is an Express Request\n */\nexport const isExpressRequest = (\n req: IncomingMessage | ExpressRequest,\n): req is ExpressRequest => {\n return \"originalUrl\" in req;\n};\n\n/**\n * Type guard that checks whether a response is an Express Response (has `json` and `send` methods).\n * @param res - A Node ServerResponse or Express Response\n * @returns True if the response is an Express Response\n */\nexport const isExpressResponse = (\n res: ServerResponse | ExpressResponse,\n): res is ExpressResponse => {\n return \"json\" in res && \"send\" in res;\n};\n\n/**\n * Issues an HTTP redirect on an Express or raw Node ServerResponse.\n * Uses Express's native `res.redirect(status, location)` when an Express\n * Response is provided, otherwise writes the status code and `Location`\n * header directly on the raw `ServerResponse` (safe for Connect-compatible\n * middlewares and serverless adapters whose mock responses lack `.redirect`).\n * Defaults to `303 See Other` for convention (Post/Redirect/Get).\n * @param res - Express Response or raw Node ServerResponse\n * @param location - The URL to redirect to\n * @param status - HTTP status code, defaults to 303\n */\nexport const redirect = (\n res: ServerResponse | ExpressResponse,\n location: string,\n status = 303,\n): void => {\n if (isExpressResponse(res)) {\n res.redirect(status, location);\n return;\n }\n res.statusCode = status;\n res.setHeader(\"Location\", location);\n res.end();\n};\n\n/**\n * Type guard that checks whether a request has a pre-parsed body (`body` property).\n * Used to detect if a body-parser middleware already consumed the stream.\n * @param req - A Node IncomingMessage or Express Request\n * @returns True if the request has a body property\n */\nexport const hasPreParsedBody = (\n req: IncomingMessage | ExpressRequest,\n): req is ExpressRequest => {\n return \"body\" in req;\n};\n\n/**\n * Extracts normalized request details from an Express or Node IncomingMessage.\n * Parses the URL to extract pathname, search string, and search params.\n * @param request - Express or Node.js request object\n * @returns Normalized request details including URL, headers, and method\n */\nexport const getRequestDetails = (\n request: ExpressRequest | IncomingMessage,\n): RequestDetails => {\n const rawUrl = (\n isExpressRequest(request) ? request.originalUrl : request.url\n ) as string;\n const url = safeURL(rawUrl);\n\n return {\n url: url.pathname,\n search: url.search,\n searchParams: url.searchParams,\n headers: request.headers,\n method: request.method,\n };\n};\n\n/**\n * Wraps an Express or Node ServerResponse with a uniform API for setting headers,\n * status codes, and sending JSON responses. Handles the Express vs raw Node API differences.\n * @param response - Express or Node.js server response object\n * @returns A ResponseDetails object with setHeader, setStatusCode, and sendResponse helpers\n */\nexport const getResponseDetails = (\n response: ExpressResponse | ServerResponse,\n): ResponseDetails => {\n const isResponseSent = response.headersSent || response.writableEnded;\n\n const setHeader = (name: string, value: string) => {\n if (isExpressResponse(response)) {\n response.header(name, value);\n } else {\n response.setHeader(name, value);\n }\n };\n\n const setStatusCode = (code: number) => {\n if (isExpressResponse(response)) {\n response.status(code);\n } else {\n response.statusCode = code;\n }\n };\n\n const sendResponse = (code: number, output: JsonValue) => {\n setStatusCode(code);\n setHeader(\"Content-Type\", \"application/json\");\n\n if (isExpressResponse(response)) {\n response.send(JSON.stringify(output));\n } else {\n response.end(JSON.stringify(output));\n }\n };\n\n return {\n isResponseSent,\n setHeader,\n statusCode: response.statusCode,\n setStatusCode,\n sendResponse,\n };\n};\n","// src/express/createMidleware.ts\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type {\n NextFunction,\n Request as ExpressRequest,\n Response as ExpressResponse,\n} from \"express\";\nimport type {\n ExpressMiddlewareFn,\n ExpressMiddlewareOptions,\n} from \"./types.d.ts\";\nimport type { Connect } from \"vite\";\nimport type { JsonValue } from \"../types.d.ts\";\nimport type { RequestEvent } from \"@thednp/rpc/server\";\nimport {\n escapeRegExp,\n formatError,\n hasContentTypeMismatch,\n provideRequestContext,\n scanForServerFiles,\n serverFunctionsMap,\n} from \"@thednp/rpc/server\";\nimport { defaultMiddlewareOptions, defaultRPCOptions } from \"../options.ts\";\nimport {\n getRequestDetails,\n getResponseDetails,\n readBody,\n redirect as expressRedirect,\n} from \"./helpers.ts\";\nimport {\n BAD_REQUEST,\n CLIENT_DISCONNECTED,\n FUNCTION_NOT_FOUND,\n METHOD_NOT_ALLOWED,\n MIDDLEWARE_NAME_USED,\n REQUEST_FORBIDDEN,\n UNSUPPORTED_MEDIA_TYPE,\n} from \"../constants.ts\";\n\nlet middlewareCount = 0;\nconst middlewareStack = new Set<string>();\n\n/**\n * Creates an Express middleware with optional path and rpcPrefix filtering.\n * Middleware names are deduplicated — reusing a name throws an error.\n * Prefix and path regexes are compiled once at creation time (hoisted) for performance.\n * @param initialOptions - Options for rpcPrefix, path matching, and the handler function\n * @returns An Express middleware function\n */\nexport const createMiddleware: ExpressMiddlewareFn = (initialOptions = {}) => {\n const options = Object.assign(\n {},\n defaultMiddlewareOptions,\n initialOptions,\n ) as ExpressMiddlewareOptions;\n const middlewareName = options.name;\n const rpcPrefix = options.rpcPrefix;\n const path = options.path;\n const handler = options.handler;\n\n let name = middlewareName;\n if (!name) {\n name = \"viteRPCMiddleware-\" + middlewareCount;\n middlewareCount += 1;\n }\n if (middlewareStack.has(name)) {\n throw new Error(MIDDLEWARE_NAME_USED(name));\n }\n middlewareStack.add(name);\n\n // Hoist regex compilation out of per-request path. Escape the prefix to\n // prevent regex injection via metacharacters in the config string.\n const prefixRegex: RegExp | null = rpcPrefix\n ? new RegExp(`^/${escapeRegExp(rpcPrefix)}/`)\n : null;\n const pathMatcher: RegExp | null = path\n ? (typeof path === \"string\" ? new RegExp(path) : path)\n : null;\n\n const middlewareHandler = async (\n req: IncomingMessage | ExpressRequest,\n res: ServerResponse | ExpressResponse,\n next: Connect.NextFunction | NextFunction,\n ) => {\n const { url } = getRequestDetails(req);\n\n // When serving from production server, scan for server files\n if (serverFunctionsMap.size === 0) {\n await scanForServerFiles();\n }\n\n // No need to continue when no handler provided\n if (!handler) {\n return next?.();\n }\n\n // Path matching\n if (pathMatcher && !pathMatcher.test(url)) return next?.();\n\n // rpcPrefix matching (boundary-safe via escaped regex)\n if (prefixRegex && !prefixRegex.test(url)) {\n return next?.();\n }\n\n // Execute handler\n await handler(req, res, next);\n };\n\n Object.defineProperty(middlewareHandler, \"name\", {\n value: name,\n });\n\n return middlewareHandler;\n};\n\n/**\n * Creates the Express RPC middleware that routes incoming requests to registered server functions.\n * Reads the request body, dispatches to the matching function via serverFunctionsMap,\n * and sends the JSON-serialized result. Handles client disconnection via abort signals.\n * @param initialOptions - Options including rpcPrefix for URL routing\n * @returns An Express middleware function\n */\nexport const createRPCMiddleware: ExpressMiddlewareFn = (\n initialOptions = {},\n) => {\n const options = Object.assign(\n {},\n defaultMiddlewareOptions,\n { rpcPrefix: defaultRPCOptions.rpcPrefix },\n initialOptions,\n ) as ExpressMiddlewareOptions;\n\n // Hoist prefix regex (escaped) and the literal prefix-for-replace out of the\n // per-request handler to avoid regex injection and per-request compilation.\n const rpcPrefix = options.rpcPrefix;\n const prefixRegex = rpcPrefix\n ? new RegExp(`^/${escapeRegExp(rpcPrefix)}/`)\n : /* istanbul ignore next */ null;\n const prefixReplace = `/${rpcPrefix}/`;\n\n return createMiddleware({\n ...options,\n handler: async (\n req: IncomingMessage | ExpressRequest,\n res: ServerResponse | ExpressResponse,\n _next: NextFunction | Connect.NextFunction,\n ) => {\n const { url: path, searchParams } = getRequestDetails(req);\n const { sendResponse } = getResponseDetails(res);\n\n // Validate the url starts with the prefix via the escaped regex\n // istanbul ignore next\n if (prefixRegex && !prefixRegex.test(path)) {\n // falls through to next handler (never reached in practice; the outer\n // createMiddleware already gates on this, but kept for defense-in-depth)\n return;\n }\n\n // Optional origin check: reject requests whose Origin header does not\n // match the configured origin. Requests without an Origin header\n // (curl, native clients) pass through unchecked.\n const origin = options.origin;\n const requestOrigin = req.headers.origin;\n if (origin && requestOrigin && requestOrigin !== origin) {\n sendResponse(403, { error: REQUEST_FORBIDDEN });\n return;\n }\n\n const functionName = path.replace(prefixReplace, \"\");\n const serverFunction = serverFunctionsMap.get(functionName);\n\n if (!serverFunction) {\n sendResponse(404, { error: FUNCTION_NOT_FOUND });\n return;\n }\n\n try {\n const method = serverFunction.options?.method || \"POST\";\n if (req.method?.toUpperCase() !== method) {\n sendResponse(405, { error: METHOD_NOT_ALLOWED });\n return;\n }\n\n let args: JsonValue[] = [];\n if (method === \"GET\") {\n const raw = searchParams.get(\"args\");\n if (raw) {\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) {\n sendResponse(400, { error: BAD_REQUEST });\n return;\n }\n args = parsed as JsonValue[];\n }\n } else {\n // Content-type enforcement: strict for json/text, lenient between forms.\n // Requests without a Content-Type header are exempt (curl/GET compat).\n // Checked BEFORE readBody so mismatched bodies are never buffered.\n if (\n hasContentTypeMismatch(\n serverFunction.options?.contentType ?? \"application/json\",\n req.headers[\"content-type\"],\n )\n ) {\n sendResponse(415, { error: UNSUPPORTED_MEDIA_TYPE });\n return;\n }\n const body = await readBody(req);\n args = Array.isArray(body.data)\n ? body.data as JsonValue[]\n : [body.data as JsonValue];\n }\n // ─── Dispatch ────────────────────────────────────────────────────\n // Establish the per-request context around the *entire* dispatch so\n // server functions (and async continuations spawned by their work)\n // read `getRequestContext()` and can call the framework-level\n // `redirect(location)`. The adapter-specific redirect is bound into the\n // context here; `serverFunction.handler` must be invoked inside the\n // context callback so its async increments run with the context live.\n const requestEvent: RequestEvent = {\n request: req,\n response: res,\n nativeEvent: { req, res },\n locals: (res as ExpressResponse).locals ?? {},\n functionName,\n redirect: (location, status = 303) => {\n requestEvent.redirected = { location, status };\n expressRedirect(res, location, status);\n },\n send: (status, body, headers) => {\n requestEvent.sent = { status, body, headers };\n const details = getResponseDetails(res);\n if (headers) {\n for (const [name, value] of Object.entries(headers)) {\n details.setHeader(name, value);\n }\n }\n details.sendResponse(status, body);\n },\n };\n\n const { data, cancel } = provideRequestContext(\n requestEvent,\n () => serverFunction.handler(...args),\n );\n const onClose = () => cancel(CLIENT_DISCONNECTED);\n req.on(\"close\", onClose);\n const result = await data;\n req.off(\"close\", onClose);\n\n // Skip the JSON send when the server function issued a redirect or\n // short-circuited with `send`; the bound adapter already wrote the\n // response. Express may also have ended the response via headersSent.\n // istanbul ignore else\n if (\n !requestEvent.redirected &&\n !requestEvent.sent &&\n !res.headersSent\n ) {\n sendResponse(200, { data: result });\n }\n } catch (err) {\n console.error(String(err));\n const isProduction = process.env.NODE_ENV === \"production\";\n sendResponse(500, formatError(err, isProduction));\n }\n },\n });\n};\n"],"mappings":";;AAYA,MAAa,oBAAsC;CACjD,WAAW;CACX,SAAS;CACT,aAAa;CACb,UAAU,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oBACM,eAAe,QAAQ,GAAG,IAAI,CACtC;IACA,MAAM,gBAAgB,OAAO,mBAAmB;IAChD,IAAI,GAAG,SAAS,OAAO;IACvB,MAAM,SAAS,MAAM;IACrB,IAAI,IAAI,SAAS,OAAO;IAMxB,IACE,CAAC,aAAa,cACd,CAAC,aAAa,QACd,CAAC,IAAI,aAEL,aAAa,KAAK,EAAE,MAAM,OAAO,CAAC;GAEtC,SAAS,KAAK;IACZ,QAAQ,MAAM,OAAO,GAAG,CAAC;IACzB,MAAM,eAAe,QAAQ,IAAI,aAAa;IAC9C,aAAa,KAAK,YAAY,KAAK,YAAY,CAAC;GAClD;EACF;CACF,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fastify.d.mts","names":[],"sources":["../../src/fastify/types.d.ts","../../src/fastify/createMiddleware.ts","../../src/types.d.ts","../../src/fastify/helpers.ts"],"mappings":";;;;;;;;;;;;;;;KAYY,oBACV,SAAS,iBACT,gBAAgB,QAAQ,+BACxB;;;;KAMU,uBAAuB;;;;KAKvB,6BAA6B,WAAW;;;;KAKxC,0BAA0B;;EAEpC;;;;;KAMU,2BAA2B;;;;;KAM3B,uBACV,UAAU,yCAEV,iBAAiB,QAAQ,8BACtB;;;;UAKY;;;;;;;EAOf,UACE,KAAK,gBACL,KAAK,cACL,MAAM,4BACH;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"fastify.d.mts","names":[],"sources":["../../src/fastify/types.d.ts","../../src/fastify/createMiddleware.ts","../../src/types.d.ts","../../src/fastify/helpers.ts"],"mappings":";;;;;;;;;;;;;;;KAYY,oBACV,SAAS,iBACT,gBAAgB,QAAQ,+BACxB;;;;KAMU,uBAAuB;;;;KAKvB,6BAA6B,WAAW;;;;KAKxC,0BAA0B;;EAEpC;;;;;KAMU,2BAA2B;;;;;KAM3B,uBACV,UAAU,yCAEV,iBAAiB,QAAQ,8BACtB;;;;UAKY;;;;;;;EAOf,UACE,KAAK,gBACL,KAAK,cACL,MAAM,4BACH;;;;;;;;;;cCvBM,kBAAkB;;;;;;;;cAgFlB,qBAAqB;;;;;;KC1CtB;EACN;EAAiC,MAAM;;EACvC;EAA2B;;EAE7B;EACA,MAAM;;EAEJ;EAAoC,MAAM;;;;;;KA8BpC;;;;KAIA;GAAgB,cAAc,YAAY;;;;;KAI1C,aAAa,WAAW;;;;KAIxB,YAAY,gBAAgB,YAAY;;;;;;;;iBCpH9B,UAAU,KAAK,kBAAe;;;;;;;iBAepC,WAAW,KAAK,iBAAiB,MAAM;;;;;;;cAgB1C,WAAQ,KACd,mBACJ,QAAQ;;;;;;;;;;cAoFE,WAAQ,OACZ,cAAY,kBACH"}
|
package/dist/fastify/fastify.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { escapeRegExp, formatError, hasContentTypeMismatch, provideRequestContext, scanForServerFiles, serverFunctionsMap } from "@thednp/rpc/server";
|
|
1
|
+
import { escapeRegExp, formatError, hasContentTypeMismatch, provideRequestContext, safeURL, scanForServerFiles, serverFunctionsMap } from "@thednp/rpc/server";
|
|
2
2
|
import fp from "fastify-plugin";
|
|
3
3
|
//#region src/options.ts
|
|
4
4
|
const defaultRPCOptions = {
|
|
@@ -18,6 +18,7 @@ const FUNCTION_NOT_FOUND = "Function not found";
|
|
|
18
18
|
const METHOD_NOT_ALLOWED = "Method Not Allowed";
|
|
19
19
|
const REQUEST_FORBIDDEN = "Forbidden";
|
|
20
20
|
const UNSUPPORTED_MEDIA_TYPE = "Unsupported Media Type";
|
|
21
|
+
const BAD_REQUEST = "Bad Request";
|
|
21
22
|
const CLIENT_DISCONNECTED = "client disconnected";
|
|
22
23
|
/** Returns a warning when a middleware name is reused, preventing registration conflicts. @param name - The duplicate middleware name */
|
|
23
24
|
const MIDDLEWARE_NAME_USED = (name) => `The middleware name "${name}" is already used.`;
|
|
@@ -154,7 +155,7 @@ const createMiddleware = (initialOptions = {}) => {
|
|
|
154
155
|
const prefixRegex = rpcPrefix ? new RegExp(`^/${escapeRegExp(rpcPrefix)}/`) : null;
|
|
155
156
|
const pathMatcher = path ? typeof path === "string" ? new RegExp(path) : path : null;
|
|
156
157
|
const middlewareHandler = async (req, reply, done) => {
|
|
157
|
-
const url =
|
|
158
|
+
const url = safeURL(req.url).pathname;
|
|
158
159
|
if (serverFunctionsMap.size === 0) await scanForServerFiles();
|
|
159
160
|
if (!handler) {
|
|
160
161
|
done();
|
|
@@ -188,7 +189,7 @@ const createRPCMiddleware = (initialOptions = {}) => {
|
|
|
188
189
|
return createMiddleware({
|
|
189
190
|
...options,
|
|
190
191
|
handler: async (req, reply, _done) => {
|
|
191
|
-
const reqUrl =
|
|
192
|
+
const reqUrl = safeURL(req.url);
|
|
192
193
|
const url = reqUrl.pathname;
|
|
193
194
|
if (prefixRegex && !prefixRegex.test(url)) return;
|
|
194
195
|
const origin = options.origin;
|
|
@@ -212,7 +213,14 @@ const createRPCMiddleware = (initialOptions = {}) => {
|
|
|
212
213
|
let args = [];
|
|
213
214
|
if (method === "GET") {
|
|
214
215
|
const raw = reqUrl.searchParams.get("args");
|
|
215
|
-
if (raw)
|
|
216
|
+
if (raw) {
|
|
217
|
+
const parsed = JSON.parse(raw);
|
|
218
|
+
if (!Array.isArray(parsed)) {
|
|
219
|
+
reply.status(400).send({ error: BAD_REQUEST });
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
args = parsed;
|
|
223
|
+
}
|
|
216
224
|
} else {
|
|
217
225
|
if (hasContentTypeMismatch(serverFunction.options?.contentType ?? "application/json", req.headers["content-type"])) {
|
|
218
226
|
reply.status(415).send({ error: UNSUPPORTED_MEDIA_TYPE });
|
|
@@ -226,12 +234,22 @@ const createRPCMiddleware = (initialOptions = {}) => {
|
|
|
226
234
|
response: reply,
|
|
227
235
|
nativeEvent: req,
|
|
228
236
|
locals: {},
|
|
237
|
+
functionName,
|
|
229
238
|
redirect: (location, status = 303) => {
|
|
230
239
|
requestEvent.redirected = {
|
|
231
240
|
location,
|
|
232
241
|
status
|
|
233
242
|
};
|
|
234
243
|
redirect(reply, location, status);
|
|
244
|
+
},
|
|
245
|
+
send: (status, body, headers) => {
|
|
246
|
+
requestEvent.sent = {
|
|
247
|
+
status,
|
|
248
|
+
body,
|
|
249
|
+
headers
|
|
250
|
+
};
|
|
251
|
+
if (headers) for (const [name, value] of Object.entries(headers)) reply.header(name, value);
|
|
252
|
+
reply.status(status).send(body);
|
|
235
253
|
}
|
|
236
254
|
};
|
|
237
255
|
const { data: dataResult, cancel } = provideRequestContext(requestEvent, () => serverFunction.handler(...args));
|
|
@@ -239,7 +257,7 @@ const createRPCMiddleware = (initialOptions = {}) => {
|
|
|
239
257
|
req.raw.on("close", onClose);
|
|
240
258
|
const data = await dataResult;
|
|
241
259
|
req.raw.off("close", onClose);
|
|
242
|
-
if (!requestEvent.redirected && !reply.raw.headersSent) reply.status(200).send({ data });
|
|
260
|
+
if (!requestEvent.redirected && !requestEvent.sent && !reply.raw.headersSent) reply.status(200).send({ data });
|
|
243
261
|
} catch (err) {
|
|
244
262
|
console.error(String(err));
|
|
245
263
|
const isProduction = process.env.NODE_ENV === "production";
|