lixnet 1.4.0 → 1.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +146 -6
- package/dist/exports.d.ts +7 -2
- package/dist/exports.js +2 -1
- package/dist/lib/client.d.ts +5 -3
- package/dist/lib/client.js +11 -5
- package/dist/lib/error.d.ts +46 -0
- package/dist/lib/error.js +57 -0
- package/dist/lib/router.d.ts +40 -0
- package/dist/lib/router.js +1 -0
- package/dist/lib/server.d.ts +37 -4
- package/dist/lib/server.js +12 -7
- package/dist/lib/serverbase.d.ts +32 -21
- package/dist/lib/serverbase.js +87 -12
- package/dist/lib/standardschema.d.ts +37 -0
- package/dist/lib/standardschema.js +1 -0
- package/dist/lib/streamclient.d.ts +4 -3
- package/dist/lib/streamclient.js +6 -8
- package/dist/lib/streamserver.d.ts +2 -2
- package/dist/lib/streamserver.js +7 -14
- package/dist/lib/types.d.ts +6 -4
- package/dist/lib/util/cors.d.ts +19 -0
- package/dist/lib/util/cors.js +44 -0
- package/dist/lib/util/getDefaultFormatter.d.ts +8 -1
- package/dist/lib/util/getDefaultFormatter.js +11 -4
- package/dist/lib/util/response.d.ts +13 -1
- package/dist/lib/util/response.js +12 -1
- package/package.json +2 -4
package/README.md
CHANGED
|
@@ -32,7 +32,7 @@ It gives you:
|
|
|
32
32
|
|
|
33
33
|
- **HTTP RPC** via `fetch` (`LixnetServer` + `LixnetClient`)
|
|
34
34
|
- **WebSocket events + callbacks** (`LixnetPeer`)
|
|
35
|
-
- **
|
|
35
|
+
- **Zero dependencies**, with optional validation through any [Standard Schema](https://standardschema.dev) library (zod, valibot, arktype, ...)
|
|
36
36
|
- **Next.js-like** `request.cookies()` / `request.headers()` ergonomics inside handlers (without pulling in Next)
|
|
37
37
|
|
|
38
38
|
It’s designed to be minimal: no codegen, no schema registry, no client bundler magic.
|
|
@@ -41,7 +41,10 @@ It’s designed to be minimal: no codegen, no schema registry, no client bundler
|
|
|
41
41
|
|
|
42
42
|
- [Quickstart (HTTP RPC)](#quickstart-http-rpc)
|
|
43
43
|
- [Framework adapters (server wiring)](#framework-adapters-server-wiring)
|
|
44
|
+
- [Inferred contract (`routes` / `server.route`)](#inferred-contract-routes--serverroute)
|
|
44
45
|
- [Server: `LixnetServer`](#server-lixnetserver)
|
|
46
|
+
- [Errors](#errors-lixneterror)
|
|
47
|
+
- [CORS](#cors)
|
|
45
48
|
- [Client: `LixnetClient`](#client-lixnetclient)
|
|
46
49
|
- [Handlers: `request` and `response`](#handlers-request-and-response)
|
|
47
50
|
- [WebSockets: `LixnetPeer`](#websockets-lixnetpeer)
|
|
@@ -54,7 +57,7 @@ It’s designed to be minimal: no codegen, no schema registry, no client bundler
|
|
|
54
57
|
Install:
|
|
55
58
|
|
|
56
59
|
```sh
|
|
57
|
-
bun add lixnet zod
|
|
60
|
+
bun add lixnet zod # zod is optional: any Standard Schema library (zod, valibot, arktype) works
|
|
58
61
|
```
|
|
59
62
|
|
|
60
63
|
Other package managers:
|
|
@@ -76,7 +79,7 @@ type Events = {
|
|
|
76
79
|
|
|
77
80
|
### 2) Create the RPC server
|
|
78
81
|
|
|
79
|
-
Register handlers with optional
|
|
82
|
+
Register handlers with optional schemas (any Standard Schema library), then expose an HTTP endpoint that forwards the incoming `Request` to `server.handle(...)`.
|
|
80
83
|
|
|
81
84
|
```ts
|
|
82
85
|
import { z } from "zod";
|
|
@@ -172,6 +175,62 @@ await client.call(
|
|
|
172
175
|
);
|
|
173
176
|
```
|
|
174
177
|
|
|
178
|
+
## Inferred contract (`routes` / `server.route`)
|
|
179
|
+
|
|
180
|
+
Instead of writing an `Events` type by hand, pass your events as `routes` (or chain `.route(...)`) and let the client infer everything from `typeof server`. Experimental: `Events` + `on()` keeps working and both can be used side by side.
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
// cloudflare/ioServer.ts (worker only)
|
|
184
|
+
import { z } from "zod";
|
|
185
|
+
import { LixnetServer } from "lixnet";
|
|
186
|
+
import live from "./(functions)/live";
|
|
187
|
+
|
|
188
|
+
export default function createRpcServer(options: { defaultHeaders?: Record<string, string> } = {}) {
|
|
189
|
+
return new LixnetServer({
|
|
190
|
+
...options,
|
|
191
|
+
routes: {
|
|
192
|
+
helloThere: {
|
|
193
|
+
schema: z.object({ name: z.string() }),
|
|
194
|
+
handler: ({ name }) => ({ message: `Hello ${name}` }), // name: string, from the schema
|
|
195
|
+
},
|
|
196
|
+
// no schema: input is the handler's parameter type minus request/response
|
|
197
|
+
live: { handler: live },
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export type RpcServer = ReturnType<typeof createRpcServer>;
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
`events` is an alias of `routes` (same types and behaviour) for codebases that still use the events naming; pass one or the other.
|
|
206
|
+
|
|
207
|
+
`.route(name, { schema?, handler })` does the same one route at a time and can be chained after `routes`, e.g. to add events conditionally:
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
new LixnetServer({ routes: { helloThere: { ... } } })
|
|
211
|
+
.route("live", { handler: live });
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
// cloudflare/io.ts (browser)
|
|
216
|
+
import type { RpcServer } from "./ioServer"; // type-only: erased at build time
|
|
217
|
+
import { LixnetClient } from "lixnet";
|
|
218
|
+
|
|
219
|
+
export const rpcClient = new LixnetClient<RpcServer>({ rpcUrl: "/rpc" });
|
|
220
|
+
|
|
221
|
+
await rpcClient.call("helloThere", { name: "World" }); // { message: string }
|
|
222
|
+
await rpcClient.call("live"); // input omitted: live takes no client input
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
- With a schema, the handler receives the schema's output and the client sends the schema's input (so `z.string().transform(Number)` means the client sends a string).
|
|
226
|
+
- Without a schema, annotate the handler's parameter; `request`/`response` are removed from the client input. Anything else in that parameter (e.g. an optional `db`) becomes client input, so keep server-only values out of handler params.
|
|
227
|
+
|
|
228
|
+
Keeping server code out of the client:
|
|
229
|
+
|
|
230
|
+
- Always `import type` the server type. Enable `verbatimModuleSyntax` (or the `consistent-type-imports` lint rule) so an accidental value import fails instead of bundling the worker (sharp, wasm, ...) into the browser.
|
|
231
|
+
- The bundle is safe either way, but type-checking still follows the import into the server files. Keep `ioServer.ts` thin (it imports handlers only) and give handlers explicit return types, so the client's tsconfig doesn't have to resolve worker-only types.
|
|
232
|
+
- If the client tsconfig still can't resolve worker types, emit declarations from the worker project (`tsc --emitDeclarationOnly`) and `import type` from the generated `.d.ts`.
|
|
233
|
+
|
|
175
234
|
## Server: `LixnetServer`
|
|
176
235
|
|
|
177
236
|
### Registering events
|
|
@@ -179,7 +238,7 @@ await client.call(
|
|
|
179
238
|
`server.on(...)` accepts either one registration object or an array.
|
|
180
239
|
|
|
181
240
|
- **`event`**: string key matching your `Events` type
|
|
182
|
-
- **`schema`** (optional):
|
|
241
|
+
- **`schema`** (optional): a Standard Schema (zod, valibot, arktype, ...) to validate `input`
|
|
183
242
|
- **`handler`**: receives validated input plus `{ request, response }` injections
|
|
184
243
|
|
|
185
244
|
Example registering multiple events:
|
|
@@ -215,7 +274,7 @@ Responses are JSON and shaped as either:
|
|
|
215
274
|
or
|
|
216
275
|
|
|
217
276
|
```json
|
|
218
|
-
{ "error": "..." }
|
|
277
|
+
{ "error": "...", "code": "UNAUTHORIZED", "data": {} }
|
|
219
278
|
```
|
|
220
279
|
|
|
221
280
|
### Server configuration
|
|
@@ -237,12 +296,93 @@ const server = new LixnetServer<Events>({
|
|
|
237
296
|
});
|
|
238
297
|
```
|
|
239
298
|
|
|
299
|
+
## Errors (`LixnetError`)
|
|
300
|
+
|
|
301
|
+
Throw a `LixnetError` from a handler to send a specific error; the client throws it back with the same `code`, `status` and `data`:
|
|
302
|
+
|
|
303
|
+
```ts
|
|
304
|
+
import { LixnetError } from "lixnet";
|
|
305
|
+
|
|
306
|
+
// server
|
|
307
|
+
throw new LixnetError("UNAUTHORIZED", "Session expired");
|
|
308
|
+
throw new LixnetError("TOO_MANY_REQUESTS", "Slow down", { data: { retryAfter: 30 } });
|
|
309
|
+
throw new LixnetError("PLAN_LIMIT", "Upgrade your plan", { status: 402 }); // custom code
|
|
310
|
+
|
|
311
|
+
// client
|
|
312
|
+
try {
|
|
313
|
+
await client.call("me");
|
|
314
|
+
} catch (e) {
|
|
315
|
+
if (LixnetError.is(e) && e.code === "UNAUTHORIZED") redirect("/login");
|
|
316
|
+
}
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
- Built-in codes and their default statuses (`LIXNET_ERROR_STATUS`): `BAD_REQUEST` 400, `INVALID_INPUT` 400, `UNAUTHORIZED` 401, `FORBIDDEN` 403, `NOT_FOUND` 404, `CONFLICT` 409, `TOO_MANY_REQUESTS` 429, `INTERNAL` 500. Any other string works as a code (default status 400).
|
|
320
|
+
- `LixnetError.is(e)` is preferred over `instanceof`: it also works when two copies of Lixnet end up in one bundle.
|
|
321
|
+
- Every client error is a `LixnetError` (it extends `Error`, so `e.message` is unchanged), including non-Lixnet responses such as a proxy's HTML 502.
|
|
322
|
+
- For errors the caller is expected to handle as part of the result, returning a typed union (`{ ok: false, ... }`) is still the better fit; `LixnetError` is for cross-cutting cases (auth, permissions, rate limits, validation).
|
|
323
|
+
- `response.code(403); response.error("Forbidden")` still works; the code is derived from the status (`FORBIDDEN`), or pass one: `response.error("Forbidden", { code: "NO_ACCESS" })`.
|
|
324
|
+
|
|
325
|
+
Built-in errors (both servers, same messages as before plus a `code`):
|
|
326
|
+
|
|
327
|
+
| `error` | `code` | Status |
|
|
328
|
+
| --- | --- | --- |
|
|
329
|
+
| `"Invalid JSON"` | `BAD_REQUEST` | 400 |
|
|
330
|
+
| `"Invalid request body"` | `BAD_REQUEST` | 400 |
|
|
331
|
+
| `"Event not found"` (missing `event`) | `BAD_REQUEST` | 400 |
|
|
332
|
+
| `"Input not found"` | `BAD_REQUEST` | 400 |
|
|
333
|
+
| `"Event not found"` (unknown `event`) | `NOT_FOUND` | 404 |
|
|
334
|
+
| `"Invalid input"` (schema failure) | `INVALID_INPUT` | 400 |
|
|
335
|
+
| `"Origin not allowed"` (with `cors`) | `FORBIDDEN` | 403 |
|
|
336
|
+
| `"Handler error"` (handler threw a non-`LixnetError`) | `INTERNAL` | 500 |
|
|
337
|
+
|
|
338
|
+
`INVALID_INPUT` always includes the validation issues, so forms can show errors per field:
|
|
339
|
+
|
|
340
|
+
```json
|
|
341
|
+
{
|
|
342
|
+
"error": "Invalid input",
|
|
343
|
+
"code": "INVALID_INPUT",
|
|
344
|
+
"data": { "issues": [{ "path": ["email"], "message": "Invalid email address" }] }
|
|
345
|
+
}
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
Error responses always go through the formatter, so `defaultHeaders` and CORS headers are included. Keep the `error` strings stable; match on `code` in new code.
|
|
349
|
+
|
|
350
|
+
## CORS
|
|
351
|
+
|
|
352
|
+
When the RPC server is on another origin than the app (e.g. a Worker on `api.example.com`), pass `cors` instead of hand-writing CORS headers and an `OPTIONS` branch. Works on `LixnetServer` and `LixnetStreamServer`.
|
|
353
|
+
|
|
354
|
+
```ts
|
|
355
|
+
const server = new LixnetServer({
|
|
356
|
+
cors: {
|
|
357
|
+
origin: ["https://example.com", "http://localhost:3000"], // or "*", or (origin) => boolean
|
|
358
|
+
credentials: true, // cookies; not allowed with origin "*"
|
|
359
|
+
// maxAge: 7200, // preflight cache in seconds (default 7200, Chrome's cap)
|
|
360
|
+
// allowHeaders: ["Content-Type", "Authorization"], // default: whatever the browser asks for
|
|
361
|
+
// exposeHeaders: ["X-Request-Id"],
|
|
362
|
+
},
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
export default {
|
|
366
|
+
async fetch(request: Request) {
|
|
367
|
+
const url = new URL(request.url);
|
|
368
|
+
if (url.pathname === "/rpc" && (request.method === "POST" || request.method === "OPTIONS")) {
|
|
369
|
+
return server.handle(request);
|
|
370
|
+
}
|
|
371
|
+
return new Response("Not found", { status: 404 });
|
|
372
|
+
},
|
|
373
|
+
};
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
- `OPTIONS` preflights get `204` with `Access-Control-Max-Age` (default 7200), so the browser preflights at most once per 2 hours per origin instead of before every call.
|
|
377
|
+
- Every response, errors included, gets `Access-Control-Allow-Origin` (the caller's origin, plus `Vary: Origin`) and `Access-Control-Allow-Credentials` when enabled.
|
|
378
|
+
- Requests whose `Origin` isn't allowed get `403 { "error": "Origin not allowed" }` without running the handler. Requests without an `Origin` header (server-to-server, SSR) are not CORS and pass through.
|
|
379
|
+
|
|
240
380
|
## Client: `LixnetClient`
|
|
241
381
|
|
|
242
382
|
`client.call(event, input, options?)`:
|
|
243
383
|
|
|
244
384
|
- sends a `POST` with `{ event, input }`
|
|
245
|
-
- throws `
|
|
385
|
+
- throws a `LixnetError` (with `code`, `status`, `data`) when the response contains `{ error }`; see "Errors" below
|
|
246
386
|
- otherwise returns `{ data }`’s value
|
|
247
387
|
|
|
248
388
|
### Client creation
|
package/dist/exports.d.ts
CHANGED
|
@@ -4,8 +4,13 @@ import LixnetPeer from "./lib/peer";
|
|
|
4
4
|
import LixnetStreamServer from "./lib/streamserver";
|
|
5
5
|
import LixnetStreamClient from "./lib/streamclient";
|
|
6
6
|
import { LixnetResponse } from "./lib/util/response";
|
|
7
|
-
|
|
7
|
+
import { LixnetError, LIXNET_ERROR_STATUS } from "./lib/error";
|
|
8
|
+
export { LixnetServer, LixnetClient, LixnetPeer, LixnetStreamServer, LixnetStreamClient, LixnetResponse, LixnetError, LIXNET_ERROR_STATUS, };
|
|
9
|
+
export type { LixnetErrorCode, LixnetIssue } from "./lib/error";
|
|
10
|
+
export type { LixnetRoute, LixnetRoutes, LixnetRouteDefinitions, LixnetRoutesFromDefinitions, InferLixnetEvents, } from "./lib/router";
|
|
8
11
|
export type { LixnetCookies, LixnetHeaders, LixnetRequest, ReadonlyHeaders, ReadonlyRequestCookies, RequestCookie, } from "./lib/util/request";
|
|
9
|
-
export type { LXN_ServerClient_EventType, LXNServerHandler, FunctionInput, LXN_ServerClient_Request, LixnetServerInjections, LXNStreamEmitter, } from "./lib/types";
|
|
12
|
+
export type { LXN_ServerClient_EventType, LXNServerHandler, FunctionInput, LXN_ServerClient_Request, LixnetServerInjections, LXNStreamEmitter, LXNCallArgs, } from "./lib/types";
|
|
10
13
|
export type { LXNStreamCallOptions } from "./lib/streamclient";
|
|
11
14
|
export type { LixnetServerBaseOptions } from "./lib/serverbase";
|
|
15
|
+
export type { LixnetCorsOptions } from "./lib/util/cors";
|
|
16
|
+
export type { StandardSchemaV1 } from "./lib/standardschema";
|
package/dist/exports.js
CHANGED
|
@@ -5,4 +5,5 @@ import LixnetPeer from "./lib/peer";
|
|
|
5
5
|
import LixnetStreamServer from "./lib/streamserver";
|
|
6
6
|
import LixnetStreamClient from "./lib/streamclient";
|
|
7
7
|
import { LixnetResponse } from "./lib/util/response";
|
|
8
|
-
|
|
8
|
+
import { LixnetError, LIXNET_ERROR_STATUS } from "./lib/error";
|
|
9
|
+
export { LixnetServer, LixnetClient, LixnetPeer, LixnetStreamServer, LixnetStreamClient, LixnetResponse, LixnetError, LIXNET_ERROR_STATUS, };
|
package/dist/lib/client.d.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import type { FunctionInput, LXN_ServerClient_EventType } from "./types";
|
|
1
|
+
import type { FunctionInput, LXNCallArgs, LXN_ServerClient_EventType } from "./types";
|
|
2
|
+
import type { InferLixnetEvents } from "./router";
|
|
2
3
|
type ExtractRPCResponse<T> = T extends (...args: any) => infer R ? Awaited<R> : never;
|
|
3
|
-
|
|
4
|
+
/** `Contract` is either an events contract or `typeof server` for a server built with `.route(...)`. */
|
|
5
|
+
export default class LixnetClient<Contract extends LXN_ServerClient_EventType, Events extends LXN_ServerClient_EventType = InferLixnetEvents<Contract>> {
|
|
4
6
|
private rpcUrl;
|
|
5
7
|
constructor({ rpcUrl }: {
|
|
6
8
|
rpcUrl: string;
|
|
7
9
|
});
|
|
8
|
-
call<K extends keyof Events>(event: K, input: FunctionInput<Events[K]>,
|
|
10
|
+
call<K extends keyof Events>(event: K, ...[input, options]: LXNCallArgs<FunctionInput<Events[K]>, RequestInit>): Promise<ExtractRPCResponse<Events[K]>>;
|
|
9
11
|
}
|
|
10
12
|
export {};
|
package/dist/lib/client.js
CHANGED
|
@@ -1,19 +1,25 @@
|
|
|
1
1
|
import withJsonContentType from "./util/withJsonContentType";
|
|
2
|
+
import { LixnetError, codeForStatus, errorFromBody } from "./error";
|
|
3
|
+
/** `Contract` is either an events contract or `typeof server` for a server built with `.route(...)`. */
|
|
2
4
|
export default class LixnetClient {
|
|
3
5
|
rpcUrl;
|
|
4
6
|
constructor({ rpcUrl }) {
|
|
5
7
|
this.rpcUrl = rpcUrl;
|
|
6
8
|
}
|
|
7
|
-
async call(event, input, options = {}) {
|
|
9
|
+
async call(event, ...[input, options = {}]) {
|
|
8
10
|
const response = await fetch(this.rpcUrl, {
|
|
9
11
|
...options,
|
|
10
12
|
method: "POST",
|
|
11
13
|
headers: withJsonContentType(options.headers),
|
|
12
|
-
body: JSON.stringify({ event, input }),
|
|
14
|
+
body: JSON.stringify({ event, input: input === undefined ? {} : input }),
|
|
13
15
|
});
|
|
14
|
-
const json = await response.json();
|
|
15
|
-
|
|
16
|
-
|
|
16
|
+
const json = await response.json().catch(() => null);
|
|
17
|
+
// Not a Lixnet response, e.g. a proxy's HTML error page.
|
|
18
|
+
if (json === null || typeof json !== "object") {
|
|
19
|
+
throw new LixnetError(response.ok ? "BAD_RESPONSE" : codeForStatus(response.status), `Unexpected response from ${this.rpcUrl} (status ${response.status})`, { status: response.status });
|
|
20
|
+
}
|
|
21
|
+
if (typeof json.error === "string") {
|
|
22
|
+
throw errorFromBody(json, response.status);
|
|
17
23
|
}
|
|
18
24
|
return json.data;
|
|
19
25
|
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** Built-in error codes and their default HTTP statuses. Any other string is also a valid code. */
|
|
2
|
+
export declare const LIXNET_ERROR_STATUS: {
|
|
3
|
+
readonly BAD_REQUEST: 400;
|
|
4
|
+
readonly INVALID_INPUT: 400;
|
|
5
|
+
readonly UNAUTHORIZED: 401;
|
|
6
|
+
readonly FORBIDDEN: 403;
|
|
7
|
+
readonly NOT_FOUND: 404;
|
|
8
|
+
readonly CONFLICT: 409;
|
|
9
|
+
readonly TOO_MANY_REQUESTS: 429;
|
|
10
|
+
readonly INTERNAL: 500;
|
|
11
|
+
};
|
|
12
|
+
export type LixnetErrorCode = keyof typeof LIXNET_ERROR_STATUS | (string & {});
|
|
13
|
+
/** One validation problem, sent as `data.issues` with `INVALID_INPUT`. */
|
|
14
|
+
export type LixnetIssue = {
|
|
15
|
+
path: (string | number)[];
|
|
16
|
+
message: string;
|
|
17
|
+
};
|
|
18
|
+
/** Picks a code for a status that came without one (e.g. `response.code(403)` + `response.error(...)`). */
|
|
19
|
+
export declare function codeForStatus(status: number): LixnetErrorCode;
|
|
20
|
+
/** Rebuilds the error a server sent (`{ error, code?, data?, detail? }`) on the client. */
|
|
21
|
+
export declare function errorFromBody(body: {
|
|
22
|
+
error: string;
|
|
23
|
+
code?: string;
|
|
24
|
+
data?: unknown;
|
|
25
|
+
detail?: string;
|
|
26
|
+
},
|
|
27
|
+
/** Omitted for stream error frames (sent after a 200): derived from the code instead. */
|
|
28
|
+
status?: number): LixnetError;
|
|
29
|
+
/**
|
|
30
|
+
* An error with a machine-readable `code`, an HTTP `status` and optional JSON `data`.
|
|
31
|
+
*
|
|
32
|
+
* Throw it from a handler to send it to the client as-is; `LixnetClient` throws it back on the
|
|
33
|
+
* client, so `catch (e) { if (LixnetError.is(e) && e.code === "UNAUTHORIZED") ... }` works.
|
|
34
|
+
*/
|
|
35
|
+
export declare class LixnetError<TData = unknown> extends Error {
|
|
36
|
+
readonly code: LixnetErrorCode;
|
|
37
|
+
readonly status: number;
|
|
38
|
+
readonly data: TData | undefined;
|
|
39
|
+
constructor(code: LixnetErrorCode, message?: string, options?: {
|
|
40
|
+
status?: number;
|
|
41
|
+
data?: TData;
|
|
42
|
+
cause?: unknown;
|
|
43
|
+
});
|
|
44
|
+
/** Like `instanceof`, but also works across duplicate copies of Lixnet in one bundle. */
|
|
45
|
+
static is(error: unknown): error is LixnetError;
|
|
46
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** Built-in error codes and their default HTTP statuses. Any other string is also a valid code. */
|
|
2
|
+
export const LIXNET_ERROR_STATUS = {
|
|
3
|
+
BAD_REQUEST: 400,
|
|
4
|
+
INVALID_INPUT: 400,
|
|
5
|
+
UNAUTHORIZED: 401,
|
|
6
|
+
FORBIDDEN: 403,
|
|
7
|
+
NOT_FOUND: 404,
|
|
8
|
+
CONFLICT: 409,
|
|
9
|
+
TOO_MANY_REQUESTS: 429,
|
|
10
|
+
INTERNAL: 500,
|
|
11
|
+
};
|
|
12
|
+
const LIXNET_ERROR_BRAND = Symbol.for("lixnet.error");
|
|
13
|
+
/** Picks a code for a status that came without one (e.g. `response.code(403)` + `response.error(...)`). */
|
|
14
|
+
export function codeForStatus(status) {
|
|
15
|
+
// INVALID_INPUT is skipped so a bare 400 maps to the generic BAD_REQUEST.
|
|
16
|
+
for (const [code, codeStatus] of Object.entries(LIXNET_ERROR_STATUS)) {
|
|
17
|
+
if (codeStatus === status && code !== "INVALID_INPUT")
|
|
18
|
+
return code;
|
|
19
|
+
}
|
|
20
|
+
return status >= 500 ? "INTERNAL" : "BAD_REQUEST";
|
|
21
|
+
}
|
|
22
|
+
/** Rebuilds the error a server sent (`{ error, code?, data?, detail? }`) on the client. */
|
|
23
|
+
export function errorFromBody(body,
|
|
24
|
+
/** Omitted for stream error frames (sent after a 200): derived from the code instead. */
|
|
25
|
+
status) {
|
|
26
|
+
return new LixnetError(body.code ?? codeForStatus(status ?? 500), body.error, {
|
|
27
|
+
status,
|
|
28
|
+
data: body.data,
|
|
29
|
+
cause: body.detail,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* An error with a machine-readable `code`, an HTTP `status` and optional JSON `data`.
|
|
34
|
+
*
|
|
35
|
+
* Throw it from a handler to send it to the client as-is; `LixnetClient` throws it back on the
|
|
36
|
+
* client, so `catch (e) { if (LixnetError.is(e) && e.code === "UNAUTHORIZED") ... }` works.
|
|
37
|
+
*/
|
|
38
|
+
export class LixnetError extends Error {
|
|
39
|
+
code;
|
|
40
|
+
status;
|
|
41
|
+
data;
|
|
42
|
+
constructor(code, message = code, options = {}) {
|
|
43
|
+
super(message, options.cause === undefined ? undefined : { cause: options.cause });
|
|
44
|
+
this.name = "LixnetError";
|
|
45
|
+
this.code = code;
|
|
46
|
+
this.status =
|
|
47
|
+
options.status ??
|
|
48
|
+
LIXNET_ERROR_STATUS[code] ??
|
|
49
|
+
400;
|
|
50
|
+
this.data = options.data;
|
|
51
|
+
Object.defineProperty(this, LIXNET_ERROR_BRAND, { value: true });
|
|
52
|
+
}
|
|
53
|
+
/** Like `instanceof`, but also works across duplicate copies of Lixnet in one bundle. */
|
|
54
|
+
static is(error) {
|
|
55
|
+
return typeof error === "object" && error !== null && LIXNET_ERROR_BRAND in error;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { StandardSchemaV1 } from "./standardschema";
|
|
2
|
+
import type { LixnetServerInjections } from "./types";
|
|
3
|
+
/**
|
|
4
|
+
* Type-level description of a route added with `LixnetServer.route(...)`: the input the
|
|
5
|
+
* client sends and the output it receives.
|
|
6
|
+
*/
|
|
7
|
+
export type LixnetRoute<TInput, TOutput> = {
|
|
8
|
+
input: TInput;
|
|
9
|
+
output: TOutput;
|
|
10
|
+
};
|
|
11
|
+
export type LixnetRoutes = Record<string, LixnetRoute<any, any>>;
|
|
12
|
+
/**
|
|
13
|
+
* Converts `typeof server` (built with `.route(...)`) into the `Events` shape clients use
|
|
14
|
+
* (`name: (input) => output`). Anything else is passed through, so clients accept either.
|
|
15
|
+
*/
|
|
16
|
+
export type InferLixnetEvents<T> = T extends {
|
|
17
|
+
readonly "~routes": infer TRoutes extends LixnetRoutes;
|
|
18
|
+
} ? {
|
|
19
|
+
[K in keyof TRoutes]: (input: TRoutes[K]["input"]) => TRoutes[K]["output"];
|
|
20
|
+
} : T;
|
|
21
|
+
type RouteHandlerInput<TSchema> = TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> & LixnetServerInjections : any;
|
|
22
|
+
/**
|
|
23
|
+
* The `routes` constructor option: `{ name: { schema?, handler } }`. Each handler is typed from
|
|
24
|
+
* its own schema; without one, annotate the handler's parameter.
|
|
25
|
+
*/
|
|
26
|
+
export type LixnetRouteDefinitions<TSchemas> = {
|
|
27
|
+
[K in keyof TSchemas]: {
|
|
28
|
+
schema?: TSchemas[K];
|
|
29
|
+
handler: (input: RouteHandlerInput<TSchemas[K]>) => unknown;
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
/** Turns the `routes` option's type into routes, the same shape `.route(...)` records. */
|
|
33
|
+
export type LixnetRoutesFromDefinitions<TDefs> = {
|
|
34
|
+
[K in keyof TDefs]: TDefs[K] extends {
|
|
35
|
+
handler: (input: infer TParams) => infer TOutput;
|
|
36
|
+
} ? LixnetRoute<TDefs[K] extends {
|
|
37
|
+
schema: infer TSchema extends StandardSchemaV1;
|
|
38
|
+
} ? StandardSchemaV1.InferInput<TSchema> : Omit<TParams, keyof LixnetServerInjections>, Awaited<TOutput>> : never;
|
|
39
|
+
};
|
|
40
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/lib/server.d.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import LixnetServerBase, { type LixnetServerBaseOptions } from "./serverbase";
|
|
2
2
|
import type { FunctionInput, FunctionOutput, LXNEventEntries, LXNEventSchema, LXNServerHandler, LXN_ServerClient_EventType } from "./types";
|
|
3
3
|
import { LixnetResponse } from "./util/response";
|
|
4
|
-
import { LixnetRequest } from "./util/request";
|
|
4
|
+
import { type LixnetRequest } from "./util/request";
|
|
5
|
+
import type { StandardSchemaV1 } from "./standardschema";
|
|
6
|
+
import type { LixnetRoute, LixnetRouteDefinitions, LixnetRoutes, LixnetRoutesFromDefinitions } from "./router";
|
|
7
|
+
import type { LixnetServerInjections } from "./types";
|
|
5
8
|
type LXNServerEventInput<Events extends LXN_ServerClient_EventType, TName extends keyof Events> = {
|
|
6
9
|
event: TName;
|
|
7
10
|
handler: LXNServerHandler<FunctionInput<Events[TName]> & {
|
|
@@ -10,11 +13,41 @@ type LXNServerEventInput<Events extends LXN_ServerClient_EventType, TName extend
|
|
|
10
13
|
}, FunctionOutput<Events[TName]>>;
|
|
11
14
|
schema?: LXNEventSchema<Events, TName>;
|
|
12
15
|
};
|
|
13
|
-
|
|
16
|
+
/**
|
|
17
|
+
* Routes with inferred types, as `{ name: { schema?, handler } }`: the same as calling
|
|
18
|
+
* `.route(name, ...)` for each. `events` is an alias of `routes`; pass one or the other.
|
|
19
|
+
*/
|
|
20
|
+
type LixnetServerRoutesOption<TRouteDefinitions> = {
|
|
21
|
+
routes?: TRouteDefinitions;
|
|
22
|
+
events?: never;
|
|
23
|
+
} | {
|
|
24
|
+
events?: TRouteDefinitions;
|
|
25
|
+
routes?: never;
|
|
26
|
+
};
|
|
27
|
+
export default class LixnetServer<Events extends LXN_ServerClient_EventType = LXN_ServerClient_EventType, Routes extends LixnetRoutes = {}, TSchemas extends Record<string, unknown> = {}, TDefs extends Record<string, {
|
|
28
|
+
handler: (input: any) => unknown;
|
|
29
|
+
}> = {}> extends LixnetServerBase<LXNServerEventInput<Events, keyof Events>> {
|
|
30
|
+
/** Type-only: routes from the `routes` option and `.route(...)`, read by `InferLixnetEvents`. */
|
|
31
|
+
readonly "~routes": Routes & LixnetRoutesFromDefinitions<TDefs>;
|
|
14
32
|
private formatter;
|
|
15
|
-
constructor({ formatter, ...options }
|
|
33
|
+
constructor({ formatter, routes, events, ...options }?: LixnetServerBaseOptions & {
|
|
16
34
|
formatter?: (this: LixnetResponse) => Response;
|
|
17
|
-
});
|
|
35
|
+
} & LixnetServerRoutesOption<TDefs & LixnetRouteDefinitions<TSchemas>>);
|
|
36
|
+
/**
|
|
37
|
+
* Adds an event whose types are inferred, so no `Events` contract is needed. Chain calls and
|
|
38
|
+
* give the client `typeof server` through an `import type`.
|
|
39
|
+
*
|
|
40
|
+
* With a schema, the handler gets the schema's output and the client sends its input.
|
|
41
|
+
*/
|
|
42
|
+
route<K extends string, TSchema extends StandardSchemaV1, TOutput>(event: K, route: {
|
|
43
|
+
schema: TSchema;
|
|
44
|
+
handler: (input: StandardSchemaV1.InferOutput<TSchema> & LixnetServerInjections) => TOutput;
|
|
45
|
+
}): LixnetServer<Events, Routes & Record<K, LixnetRoute<StandardSchemaV1.InferInput<TSchema>, Awaited<TOutput>>>, TSchemas, TDefs>;
|
|
46
|
+
/** Without a schema, the input is the handler's parameter type minus `request`/`response`. */
|
|
47
|
+
route<K extends string, TParams, TOutput>(event: K, route: {
|
|
48
|
+
schema?: undefined;
|
|
49
|
+
handler: (input: TParams) => TOutput;
|
|
50
|
+
}): LixnetServer<Events, Routes & Record<K, LixnetRoute<Omit<TParams, keyof LixnetServerInjections>, Awaited<TOutput>>>, TSchemas, TDefs>;
|
|
18
51
|
on<K extends keyof Events & string>(input: LXNServerEventInput<Events, K> | LXNEventEntries<Events, {
|
|
19
52
|
[P in keyof Events & string]: LXNServerEventInput<Events, P>;
|
|
20
53
|
}>): void;
|
package/dist/lib/server.js
CHANGED
|
@@ -4,9 +4,16 @@ import { createLixnetRequest } from "./util/request";
|
|
|
4
4
|
import getDefaultFormatter from "./util/getDefaultFormatter";
|
|
5
5
|
export default class LixnetServer extends LixnetServerBase {
|
|
6
6
|
formatter;
|
|
7
|
-
constructor({ formatter, ...options }) {
|
|
7
|
+
constructor({ formatter, routes, events, ...options } = {}) {
|
|
8
8
|
super(options);
|
|
9
9
|
this.formatter = formatter ?? getDefaultFormatter(this.defaultHeaders);
|
|
10
|
+
for (const [event, route] of Object.entries(routes ?? events ?? {})) {
|
|
11
|
+
this.register({ ...route, event });
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
route(event, route) {
|
|
15
|
+
this.register({ ...route, event });
|
|
16
|
+
return this;
|
|
10
17
|
}
|
|
11
18
|
on(input) {
|
|
12
19
|
this.register(input);
|
|
@@ -14,6 +21,9 @@ export default class LixnetServer extends LixnetServerBase {
|
|
|
14
21
|
async handle(request) {
|
|
15
22
|
const requestClone = request.clone();
|
|
16
23
|
const response = new LixnetResponse({ formatter: this.formatter });
|
|
24
|
+
const corsResponse = this.handleCors(request, response);
|
|
25
|
+
if (corsResponse)
|
|
26
|
+
return corsResponse;
|
|
17
27
|
const parsed = await this.parse(request);
|
|
18
28
|
if (!parsed.ok) {
|
|
19
29
|
return this.fail(response, parsed);
|
|
@@ -31,12 +41,7 @@ export default class LixnetServer extends LixnetServerBase {
|
|
|
31
41
|
return response.format();
|
|
32
42
|
}
|
|
33
43
|
catch (error) {
|
|
34
|
-
return this.fail(response,
|
|
35
|
-
error: "Handler error",
|
|
36
|
-
status: 500,
|
|
37
|
-
cause: error,
|
|
38
|
-
event: parsed.entry.event,
|
|
39
|
-
});
|
|
44
|
+
return this.fail(response, this.failureFromThrown(error, parsed.entry.event));
|
|
40
45
|
}
|
|
41
46
|
}
|
|
42
47
|
}
|
package/dist/lib/serverbase.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { StandardSchemaV1 } from "./standardschema";
|
|
2
2
|
import type { DebugLogger } from "./types";
|
|
3
3
|
import type { LixnetResponse } from "./util/response";
|
|
4
|
+
import { type LixnetErrorCode } from "./error";
|
|
5
|
+
import { type LixnetCorsOptions } from "./util/cors";
|
|
4
6
|
export type LixnetServerBaseOptions = {
|
|
5
7
|
/** Log failed requests (including the thrown error) through `logger`. */
|
|
6
8
|
debugLog?: boolean;
|
|
@@ -11,22 +13,33 @@ export type LixnetServerBaseOptions = {
|
|
|
11
13
|
exposeErrors?: boolean;
|
|
12
14
|
logger?: DebugLogger;
|
|
13
15
|
defaultHeaders?: Record<string, string>;
|
|
16
|
+
/**
|
|
17
|
+
* Handle CORS: answers `OPTIONS` preflights (cached for `maxAge`, default 7200s), adds CORS
|
|
18
|
+
* headers to every response, and rejects requests from origins that aren't allowed.
|
|
19
|
+
*/
|
|
20
|
+
cors?: LixnetCorsOptions;
|
|
14
21
|
};
|
|
15
22
|
type EventEntry = {
|
|
16
23
|
event: PropertyKey;
|
|
17
|
-
schema?:
|
|
24
|
+
schema?: StandardSchemaV1;
|
|
18
25
|
};
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
entry: TEntry;
|
|
22
|
-
input: any;
|
|
23
|
-
} | {
|
|
24
|
-
ok: false;
|
|
26
|
+
/** A failed request, before it's written to the response. */
|
|
27
|
+
type Failure = {
|
|
25
28
|
error: string;
|
|
26
29
|
status: number;
|
|
30
|
+
code: LixnetErrorCode;
|
|
31
|
+
data?: unknown;
|
|
32
|
+
/** Logged with `debugLog`; its message becomes `detail` with `exposeErrors`. */
|
|
27
33
|
cause?: unknown;
|
|
28
34
|
event?: string;
|
|
29
35
|
};
|
|
36
|
+
type ParsedRpcRequest<TEntry> = {
|
|
37
|
+
ok: true;
|
|
38
|
+
entry: TEntry;
|
|
39
|
+
input: any;
|
|
40
|
+
} | ({
|
|
41
|
+
ok: false;
|
|
42
|
+
} & Failure);
|
|
30
43
|
/** Shared request parsing and error handling for `LixnetServer` and `LixnetStreamServer`. */
|
|
31
44
|
export default abstract class LixnetServerBase<TEntry extends EventEntry> {
|
|
32
45
|
protected events: Record<string, TEntry>;
|
|
@@ -34,21 +47,19 @@ export default abstract class LixnetServerBase<TEntry extends EventEntry> {
|
|
|
34
47
|
protected debugLog: boolean;
|
|
35
48
|
protected exposeErrors: boolean;
|
|
36
49
|
protected defaultHeaders: Record<string, string>;
|
|
37
|
-
protected
|
|
50
|
+
protected cors?: LixnetCorsOptions;
|
|
51
|
+
protected constructor({ debugLog, exposeErrors, logger, defaultHeaders, cors, }: LixnetServerBaseOptions);
|
|
38
52
|
protected register(input: TEntry | TEntry[]): void;
|
|
39
53
|
protected parse(request: Request): Promise<ParsedRpcRequest<TEntry>>;
|
|
54
|
+
/**
|
|
55
|
+
* With `cors` set: answers preflights and rejects disallowed origins (returns the Response),
|
|
56
|
+
* otherwise stages CORS headers on `response` (handlers can still override them) and returns null.
|
|
57
|
+
*/
|
|
58
|
+
protected handleCors(request: Request, response: LixnetResponse): Response | null;
|
|
59
|
+
/** A `LixnetError` is sent as thrown; anything else becomes a generic 500 "Handler error". */
|
|
60
|
+
protected failureFromThrown(error: unknown, event: string): Failure;
|
|
40
61
|
/** Logs the failure (with `debugLog`) and stages it on the response with its status. */
|
|
41
|
-
protected stageFailure(response: LixnetResponse, { error, status, cause, event }:
|
|
42
|
-
|
|
43
|
-
status: number;
|
|
44
|
-
cause?: unknown;
|
|
45
|
-
event?: string;
|
|
46
|
-
}): void;
|
|
47
|
-
protected fail(response: LixnetResponse, failure: {
|
|
48
|
-
error: string;
|
|
49
|
-
status: number;
|
|
50
|
-
cause?: unknown;
|
|
51
|
-
event?: string;
|
|
52
|
-
}): Response;
|
|
62
|
+
protected stageFailure(response: LixnetResponse, { error, status, code, data, cause, event }: Failure): void;
|
|
63
|
+
protected fail(response: LixnetResponse, failure: Failure): Response;
|
|
53
64
|
}
|
|
54
65
|
export {};
|
package/dist/lib/serverbase.js
CHANGED
|
@@ -1,9 +1,22 @@
|
|
|
1
1
|
import LixnetLog from "./util/log";
|
|
2
|
+
import { LixnetError } from "./error";
|
|
3
|
+
import { assertCorsOptions, corsHeaders, isOriginAllowed, preflightHeaders, } from "./util/cors";
|
|
4
|
+
function toIssues(issues) {
|
|
5
|
+
return issues.map((issue) => ({
|
|
6
|
+
message: issue.message,
|
|
7
|
+
path: (issue.path ?? []).map((segment) => {
|
|
8
|
+
const key = typeof segment === "object" ? segment.key : segment;
|
|
9
|
+
return typeof key === "number" ? key : String(key);
|
|
10
|
+
}),
|
|
11
|
+
}));
|
|
12
|
+
}
|
|
2
13
|
function describeError(cause) {
|
|
3
14
|
if (cause === undefined)
|
|
4
15
|
return undefined;
|
|
5
16
|
if (cause instanceof Error)
|
|
6
17
|
return cause.message;
|
|
18
|
+
if (Array.isArray(cause))
|
|
19
|
+
return cause.map((issue) => issue?.message ?? String(issue)).join("; ");
|
|
7
20
|
return String(cause);
|
|
8
21
|
}
|
|
9
22
|
/** Shared request parsing and error handling for `LixnetServer` and `LixnetStreamServer`. */
|
|
@@ -13,7 +26,11 @@ export default class LixnetServerBase {
|
|
|
13
26
|
debugLog;
|
|
14
27
|
exposeErrors;
|
|
15
28
|
defaultHeaders;
|
|
16
|
-
|
|
29
|
+
cors;
|
|
30
|
+
constructor({ debugLog = false, exposeErrors = false, logger, defaultHeaders = {}, cors, }) {
|
|
31
|
+
if (cors)
|
|
32
|
+
assertCorsOptions(cors);
|
|
33
|
+
this.cors = cors;
|
|
17
34
|
this.debugLog = debugLog;
|
|
18
35
|
this.exposeErrors = exposeErrors;
|
|
19
36
|
this.defaultHeaders = defaultHeaders;
|
|
@@ -32,39 +49,93 @@ export default class LixnetServerBase {
|
|
|
32
49
|
json = await request.json();
|
|
33
50
|
}
|
|
34
51
|
catch (cause) {
|
|
35
|
-
return { ok: false, error: "Invalid JSON", status: 400, cause };
|
|
52
|
+
return { ok: false, error: "Invalid JSON", status: 400, code: "BAD_REQUEST", cause };
|
|
36
53
|
}
|
|
37
54
|
if (json === null || typeof json !== "object" || Array.isArray(json)) {
|
|
38
|
-
return { ok: false, error: "Invalid request body", status: 400 };
|
|
55
|
+
return { ok: false, error: "Invalid request body", status: 400, code: "BAD_REQUEST" };
|
|
39
56
|
}
|
|
40
57
|
if (typeof json.event !== "string" || !json.event) {
|
|
41
|
-
return { ok: false, error: "Event not found", status: 400 };
|
|
58
|
+
return { ok: false, error: "Event not found", status: 400, code: "BAD_REQUEST" };
|
|
42
59
|
}
|
|
43
60
|
if (!("input" in json)) {
|
|
44
|
-
return { ok: false, error: "Input not found", status: 400 };
|
|
61
|
+
return { ok: false, error: "Input not found", status: 400, code: "BAD_REQUEST" };
|
|
45
62
|
}
|
|
46
63
|
// hasOwn so names like "constructor" or "toString" don't resolve to prototype members.
|
|
47
64
|
if (!Object.hasOwn(this.events, json.event)) {
|
|
48
|
-
return {
|
|
65
|
+
return {
|
|
66
|
+
ok: false,
|
|
67
|
+
error: "Event not found",
|
|
68
|
+
status: 404,
|
|
69
|
+
code: "NOT_FOUND",
|
|
70
|
+
event: json.event,
|
|
71
|
+
};
|
|
49
72
|
}
|
|
50
73
|
const entry = this.events[json.event];
|
|
51
74
|
if (!entry.schema) {
|
|
52
75
|
return { ok: true, entry, input: json.input };
|
|
53
76
|
}
|
|
54
|
-
const result = entry.schema.
|
|
55
|
-
if (
|
|
77
|
+
const result = await entry.schema["~standard"].validate(json.input);
|
|
78
|
+
if (result.issues) {
|
|
56
79
|
return {
|
|
57
80
|
ok: false,
|
|
58
81
|
error: "Invalid input",
|
|
59
82
|
status: 400,
|
|
60
|
-
|
|
83
|
+
code: "INVALID_INPUT",
|
|
84
|
+
// Validation messages are meant for the caller, so they're always sent.
|
|
85
|
+
data: { issues: toIssues(result.issues) },
|
|
86
|
+
cause: result.issues,
|
|
61
87
|
event: json.event,
|
|
62
88
|
};
|
|
63
89
|
}
|
|
64
|
-
return { ok: true, entry, input: result.
|
|
90
|
+
return { ok: true, entry, input: result.value };
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* With `cors` set: answers preflights and rejects disallowed origins (returns the Response),
|
|
94
|
+
* otherwise stages CORS headers on `response` (handlers can still override them) and returns null.
|
|
95
|
+
*/
|
|
96
|
+
handleCors(request, response) {
|
|
97
|
+
if (!this.cors)
|
|
98
|
+
return null;
|
|
99
|
+
// No Origin header: same-origin GET or a server-to-server call (e.g. SSR), not CORS.
|
|
100
|
+
const origin = request.headers.get("Origin");
|
|
101
|
+
if (!origin) {
|
|
102
|
+
return request.method === "OPTIONS" ? new Response(null, { status: 204 }) : null;
|
|
103
|
+
}
|
|
104
|
+
if (!isOriginAllowed(this.cors, origin)) {
|
|
105
|
+
if (request.method === "OPTIONS")
|
|
106
|
+
return new Response(null, { status: 403 });
|
|
107
|
+
return this.fail(response, {
|
|
108
|
+
error: "Origin not allowed",
|
|
109
|
+
status: 403,
|
|
110
|
+
code: "FORBIDDEN",
|
|
111
|
+
cause: origin,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
if (request.method === "OPTIONS") {
|
|
115
|
+
return new Response(null, {
|
|
116
|
+
status: 204,
|
|
117
|
+
headers: preflightHeaders(this.cors, origin, request.headers.get("Access-Control-Request-Headers")),
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
response.headers(corsHeaders(this.cors, origin));
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
/** A `LixnetError` is sent as thrown; anything else becomes a generic 500 "Handler error". */
|
|
124
|
+
failureFromThrown(error, event) {
|
|
125
|
+
if (LixnetError.is(error)) {
|
|
126
|
+
return {
|
|
127
|
+
error: error.message,
|
|
128
|
+
status: error.status,
|
|
129
|
+
code: error.code,
|
|
130
|
+
data: error.data,
|
|
131
|
+
cause: error.cause ?? error,
|
|
132
|
+
event,
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
return { error: "Handler error", status: 500, code: "INTERNAL", cause: error, event };
|
|
65
136
|
}
|
|
66
137
|
/** Logs the failure (with `debugLog`) and stages it on the response with its status. */
|
|
67
|
-
stageFailure(response, { error, status, cause, event }) {
|
|
138
|
+
stageFailure(response, { error, status, code, data, cause, event }) {
|
|
68
139
|
if (this.debugLog) {
|
|
69
140
|
this.logger({
|
|
70
141
|
error: true,
|
|
@@ -73,7 +144,11 @@ export default class LixnetServerBase {
|
|
|
73
144
|
});
|
|
74
145
|
}
|
|
75
146
|
response.code(status);
|
|
76
|
-
response.error(error,
|
|
147
|
+
response.error(error, {
|
|
148
|
+
code,
|
|
149
|
+
data,
|
|
150
|
+
detail: this.exposeErrors ? describeError(cause) : undefined,
|
|
151
|
+
});
|
|
77
152
|
}
|
|
78
153
|
fail(response, failure) {
|
|
79
154
|
this.stageFailure(response, failure);
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standard Schema v1 interface (https://standardschema.dev), copied in as the spec intends so
|
|
3
|
+
* Lixnet needs no runtime or type dependency. Implemented by zod (3.24+/4), valibot, arktype,
|
|
4
|
+
* Effect Schema and others. MIT licensed by the Standard Schema authors.
|
|
5
|
+
*/
|
|
6
|
+
export interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
7
|
+
readonly "~standard": StandardSchemaV1.Props<Input, Output>;
|
|
8
|
+
}
|
|
9
|
+
export declare namespace StandardSchemaV1 {
|
|
10
|
+
interface Props<Input = unknown, Output = Input> {
|
|
11
|
+
readonly version: 1;
|
|
12
|
+
readonly vendor: string;
|
|
13
|
+
readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
|
|
14
|
+
readonly types?: Types<Input, Output> | undefined;
|
|
15
|
+
}
|
|
16
|
+
type Result<Output> = SuccessResult<Output> | FailureResult;
|
|
17
|
+
interface SuccessResult<Output> {
|
|
18
|
+
readonly value: Output;
|
|
19
|
+
readonly issues?: undefined;
|
|
20
|
+
}
|
|
21
|
+
interface FailureResult {
|
|
22
|
+
readonly issues: ReadonlyArray<Issue>;
|
|
23
|
+
}
|
|
24
|
+
interface Issue {
|
|
25
|
+
readonly message: string;
|
|
26
|
+
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
|
|
27
|
+
}
|
|
28
|
+
interface PathSegment {
|
|
29
|
+
readonly key: PropertyKey;
|
|
30
|
+
}
|
|
31
|
+
interface Types<Input = unknown, Output = Input> {
|
|
32
|
+
readonly input: Input;
|
|
33
|
+
readonly output: Output;
|
|
34
|
+
}
|
|
35
|
+
type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["input"];
|
|
36
|
+
type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
|
|
37
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -1,16 +1,17 @@
|
|
|
1
|
-
import type { FunctionInput, FunctionOutput, LXN_ServerClient_EventType } from "./types";
|
|
1
|
+
import type { FunctionInput, FunctionOutput, LXNCallArgs, LXN_ServerClient_EventType } from "./types";
|
|
2
|
+
import type { InferLixnetEvents } from "./router";
|
|
2
3
|
type Prettify<T> = {
|
|
3
4
|
[K in keyof T]: T[K];
|
|
4
5
|
} & {};
|
|
5
6
|
export type LXNStreamCallOptions<TChunk> = Prettify<{
|
|
6
7
|
onStreamChunk?: (chunk: TChunk) => void;
|
|
7
8
|
} & Omit<RequestInit, "method" | "body">>;
|
|
8
|
-
export default class LixnetStreamClient<Events extends LXN_ServerClient_EventType
|
|
9
|
+
export default class LixnetStreamClient<Contract extends LXN_ServerClient_EventType, Events extends LXN_ServerClient_EventType = InferLixnetEvents<Contract>> {
|
|
9
10
|
private rpcUrl;
|
|
10
11
|
constructor({ rpcUrl }: {
|
|
11
12
|
rpcUrl: string;
|
|
12
13
|
});
|
|
13
14
|
/** Resolves when the stream ends; throws if the server returns or streams an error. */
|
|
14
|
-
call<K extends keyof Events>(event: K, input: FunctionInput<Events[K]>,
|
|
15
|
+
call<K extends keyof Events>(event: K, ...[input, options]: LXNCallArgs<FunctionInput<Events[K]>, LXNStreamCallOptions<FunctionOutput<Events[K]>>>): Promise<void>;
|
|
15
16
|
}
|
|
16
17
|
export {};
|
package/dist/lib/streamclient.js
CHANGED
|
@@ -1,26 +1,24 @@
|
|
|
1
1
|
import withJsonContentType from "./util/withJsonContentType";
|
|
2
|
-
|
|
3
|
-
return new Error(frame.error, frame.detail ? { cause: frame.detail } : undefined);
|
|
4
|
-
}
|
|
2
|
+
import { LixnetError, codeForStatus, errorFromBody } from "./error";
|
|
5
3
|
export default class LixnetStreamClient {
|
|
6
4
|
rpcUrl;
|
|
7
5
|
constructor({ rpcUrl }) {
|
|
8
6
|
this.rpcUrl = rpcUrl;
|
|
9
7
|
}
|
|
10
8
|
/** Resolves when the stream ends; throws if the server returns or streams an error. */
|
|
11
|
-
async call(event, input, options = {}) {
|
|
9
|
+
async call(event, ...[input, options = {}]) {
|
|
12
10
|
const { onStreamChunk, ...fetchOptions } = options;
|
|
13
11
|
const response = await fetch(this.rpcUrl, {
|
|
14
12
|
...fetchOptions,
|
|
15
13
|
method: "POST",
|
|
16
14
|
headers: withJsonContentType(fetchOptions.headers),
|
|
17
|
-
body: JSON.stringify({ event, input }),
|
|
15
|
+
body: JSON.stringify({ event, input: input === undefined ? {} : input }),
|
|
18
16
|
});
|
|
19
17
|
if (!response.ok) {
|
|
20
18
|
const json = await response.json().catch(() => null);
|
|
21
19
|
if (json && typeof json.error === "string")
|
|
22
|
-
throw
|
|
23
|
-
throw new
|
|
20
|
+
throw errorFromBody(json, response.status);
|
|
21
|
+
throw new LixnetError(codeForStatus(response.status), `Stream request failed with status ${response.status}`, { status: response.status });
|
|
24
22
|
}
|
|
25
23
|
if (!response.body)
|
|
26
24
|
throw new Error("Stream response has no body");
|
|
@@ -39,7 +37,7 @@ export default class LixnetStreamClient {
|
|
|
39
37
|
return; // skip malformed line
|
|
40
38
|
}
|
|
41
39
|
if (typeof parsed?.error === "string")
|
|
42
|
-
throw
|
|
40
|
+
throw errorFromBody(parsed);
|
|
43
41
|
if (parsed?.stream === true)
|
|
44
42
|
onStreamChunk?.(parsed.data);
|
|
45
43
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import LixnetServerBase, { type LixnetServerBaseOptions } from "./serverbase";
|
|
2
2
|
import type { FunctionInput, FunctionOutput, LXN_ServerClient_EventType, LXNEventEntries, LXNEventSchema, LXNStreamEmitter } from "./types";
|
|
3
3
|
import { LixnetResponse } from "./util/response";
|
|
4
|
-
import { LixnetRequest } from "./util/request";
|
|
4
|
+
import { type LixnetRequest } from "./util/request";
|
|
5
5
|
type LXNStreamServerEventInput<Events extends LXN_ServerClient_EventType, K extends keyof Events> = {
|
|
6
6
|
event: K;
|
|
7
7
|
handler: (input: FunctionInput<Events[K]> & {
|
|
@@ -13,7 +13,7 @@ type LXNStreamServerEventInput<Events extends LXN_ServerClient_EventType, K exte
|
|
|
13
13
|
};
|
|
14
14
|
export default class LixnetStreamServer<Events extends LXN_ServerClient_EventType> extends LixnetServerBase<LXNStreamServerEventInput<Events, keyof Events>> {
|
|
15
15
|
private errorFormatter;
|
|
16
|
-
constructor(options
|
|
16
|
+
constructor(options?: LixnetServerBaseOptions);
|
|
17
17
|
on<K extends keyof Events & string>(input: LXNStreamServerEventInput<Events, K> | LXNEventEntries<Events, {
|
|
18
18
|
[P in keyof Events & string]: LXNStreamServerEventInput<Events, P>;
|
|
19
19
|
}>): void;
|
package/dist/lib/streamserver.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import LixnetServerBase from "./serverbase";
|
|
2
2
|
import { LixnetResponse } from "./util/response";
|
|
3
3
|
import { createLixnetRequest } from "./util/request";
|
|
4
|
-
import getDefaultFormatter, { buildResponseHeaders } from "./util/getDefaultFormatter";
|
|
4
|
+
import getDefaultFormatter, { buildResponseHeaders, errorBody } from "./util/getDefaultFormatter";
|
|
5
5
|
export default class LixnetStreamServer extends LixnetServerBase {
|
|
6
6
|
errorFormatter;
|
|
7
|
-
constructor(options) {
|
|
7
|
+
constructor(options = {}) {
|
|
8
8
|
super(options);
|
|
9
9
|
this.errorFormatter = getDefaultFormatter(this.defaultHeaders);
|
|
10
10
|
}
|
|
@@ -14,6 +14,9 @@ export default class LixnetStreamServer extends LixnetServerBase {
|
|
|
14
14
|
async handle(request) {
|
|
15
15
|
const requestClone = request.clone();
|
|
16
16
|
const response = new LixnetResponse({ formatter: this.errorFormatter });
|
|
17
|
+
const corsResponse = this.handleCors(request, response);
|
|
18
|
+
if (corsResponse)
|
|
19
|
+
return corsResponse;
|
|
17
20
|
const parsed = await this.parse(request);
|
|
18
21
|
if (!parsed.ok) {
|
|
19
22
|
return this.fail(response, parsed);
|
|
@@ -67,24 +70,14 @@ export default class LixnetStreamServer extends LixnetServerBase {
|
|
|
67
70
|
start();
|
|
68
71
|
}
|
|
69
72
|
catch (error) {
|
|
70
|
-
const failure =
|
|
71
|
-
error: "Handler error",
|
|
72
|
-
status: 500,
|
|
73
|
-
cause: error,
|
|
74
|
-
event: event.event,
|
|
75
|
-
};
|
|
73
|
+
const failure = this.failureFromThrown(error, event.event);
|
|
76
74
|
if (!started) {
|
|
77
75
|
resolve(this.fail(response, failure));
|
|
78
76
|
return;
|
|
79
77
|
}
|
|
80
78
|
// Headers are already sent, so report the error as the final frame.
|
|
81
79
|
this.stageFailure(response, failure);
|
|
82
|
-
write(
|
|
83
|
-
error: response.responseError,
|
|
84
|
-
...(response.responseErrorDetail
|
|
85
|
-
? { detail: response.responseErrorDetail }
|
|
86
|
-
: {}),
|
|
87
|
-
});
|
|
80
|
+
write(errorBody(response));
|
|
88
81
|
}
|
|
89
82
|
finally {
|
|
90
83
|
if (started && !closed) {
|
package/dist/lib/types.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import { LixnetRequest } from "./util/request";
|
|
3
|
-
import { LixnetResponse } from "./util/response";
|
|
1
|
+
import type { StandardSchemaV1 } from "./standardschema";
|
|
2
|
+
import type { LixnetRequest } from "./util/request";
|
|
3
|
+
import type { LixnetResponse } from "./util/response";
|
|
4
4
|
export type DebugLogger = ({ error, message, cause, }: {
|
|
5
5
|
error?: boolean;
|
|
6
6
|
message: string;
|
|
@@ -13,10 +13,12 @@ export type FunctionInput<T> = T extends (input: infer TInput) => any ? TInput :
|
|
|
13
13
|
export type FunctionOutput<T> = T extends (...args: any) => infer R ? Awaited<R> : {
|
|
14
14
|
_TYPE_ERROR_: "Event definition must be a function type";
|
|
15
15
|
};
|
|
16
|
+
/** `input` may be omitted when the event has no required input fields (e.g. `() => ...`). */
|
|
17
|
+
export type LXNCallArgs<TInput, TOptions> = {} extends TInput ? [input?: TInput, options?: TOptions] : [input: TInput, options?: TOptions];
|
|
16
18
|
export type LXNServerHandler<Input, Output> = (input: Input) => Promise<Output> | Output;
|
|
17
19
|
export type LXN_ServerClient_EventType = object;
|
|
18
20
|
/** A schema whose parsed output must match the event's declared input type. */
|
|
19
|
-
export type LXNEventSchema<Events, K extends keyof Events> =
|
|
21
|
+
export type LXNEventSchema<Events, K extends keyof Events> = StandardSchemaV1<any, FunctionInput<Events[K]>>;
|
|
20
22
|
/** One registration per event name, so arrays passed to `on()` are typed per element. */
|
|
21
23
|
export type LXNEventEntries<Events, TEntry extends {
|
|
22
24
|
[K in keyof Events & string]: unknown;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export type LixnetCorsOptions = {
|
|
2
|
+
/** Allowed origins: exact origins (`"https://app.example.com"`), `"*"` for any, or a predicate. */
|
|
3
|
+
origin: string | string[] | ((origin: string) => boolean);
|
|
4
|
+
/** Send `Access-Control-Allow-Credentials: true` (cookies). Not allowed with `origin: "*"`. */
|
|
5
|
+
credentials?: boolean;
|
|
6
|
+
/** Seconds a browser may cache a preflight. Defaults to 7200 (Chrome's cap; Firefox allows 86400). */
|
|
7
|
+
maxAge?: number;
|
|
8
|
+
/** Request headers the client may send. Defaults to whatever the preflight asks for. */
|
|
9
|
+
allowHeaders?: string[];
|
|
10
|
+
/** Response headers the client may read besides the CORS-safelisted ones. */
|
|
11
|
+
exposeHeaders?: string[];
|
|
12
|
+
};
|
|
13
|
+
export declare const DEFAULT_CORS_MAX_AGE = 7200;
|
|
14
|
+
export declare function assertCorsOptions(cors: LixnetCorsOptions): void;
|
|
15
|
+
export declare function isOriginAllowed(cors: LixnetCorsOptions, origin: string): boolean;
|
|
16
|
+
/** Headers for an actual (non-preflight) response to an allowed origin. */
|
|
17
|
+
export declare function corsHeaders(cors: LixnetCorsOptions, origin: string): Record<string, string>;
|
|
18
|
+
/** Headers for a preflight (`OPTIONS`) response to an allowed origin. */
|
|
19
|
+
export declare function preflightHeaders(cors: LixnetCorsOptions, origin: string, requestedHeaders: string | null): Record<string, string>;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export const DEFAULT_CORS_MAX_AGE = 7200;
|
|
2
|
+
export function assertCorsOptions(cors) {
|
|
3
|
+
if (cors.origin === "*" && cors.credentials) {
|
|
4
|
+
throw new Error('LIXNET - cors.origin "*" cannot be combined with credentials: true');
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
export function isOriginAllowed(cors, origin) {
|
|
8
|
+
if (cors.origin === "*")
|
|
9
|
+
return true;
|
|
10
|
+
if (typeof cors.origin === "function")
|
|
11
|
+
return cors.origin(origin);
|
|
12
|
+
if (Array.isArray(cors.origin))
|
|
13
|
+
return cors.origin.includes(origin);
|
|
14
|
+
return cors.origin === origin;
|
|
15
|
+
}
|
|
16
|
+
/** Headers for an actual (non-preflight) response to an allowed origin. */
|
|
17
|
+
export function corsHeaders(cors, origin) {
|
|
18
|
+
if (cors.origin === "*") {
|
|
19
|
+
return {
|
|
20
|
+
"Access-Control-Allow-Origin": "*",
|
|
21
|
+
...(cors.exposeHeaders?.length
|
|
22
|
+
? { "Access-Control-Expose-Headers": cors.exposeHeaders.join(", ") }
|
|
23
|
+
: {}),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
"Access-Control-Allow-Origin": origin,
|
|
28
|
+
Vary: "Origin",
|
|
29
|
+
...(cors.credentials ? { "Access-Control-Allow-Credentials": "true" } : {}),
|
|
30
|
+
...(cors.exposeHeaders?.length
|
|
31
|
+
? { "Access-Control-Expose-Headers": cors.exposeHeaders.join(", ") }
|
|
32
|
+
: {}),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** Headers for a preflight (`OPTIONS`) response to an allowed origin. */
|
|
36
|
+
export function preflightHeaders(cors, origin, requestedHeaders) {
|
|
37
|
+
const allowHeaders = cors.allowHeaders?.join(", ") ?? requestedHeaders;
|
|
38
|
+
return {
|
|
39
|
+
...corsHeaders(cors, origin),
|
|
40
|
+
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
|
41
|
+
...(allowHeaders ? { "Access-Control-Allow-Headers": allowHeaders } : {}),
|
|
42
|
+
"Access-Control-Max-Age": String(cors.maxAge ?? DEFAULT_CORS_MAX_AGE),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
import { LixnetResponse } from "./response";
|
|
1
|
+
import type { LixnetResponse } from "./response";
|
|
2
|
+
/** The `{ error, code, data?, detail? }` body for an errored response (also used for stream error frames). */
|
|
3
|
+
export declare function errorBody(response: LixnetResponse): {
|
|
4
|
+
detail?: string | undefined;
|
|
5
|
+
data?: {} | null | undefined;
|
|
6
|
+
error: string | null;
|
|
7
|
+
code: string;
|
|
8
|
+
};
|
|
2
9
|
/** Defaults, then staged header sets/deletes, then staged cookies as `Set-Cookie`. */
|
|
3
10
|
export declare function buildResponseHeaders(response: LixnetResponse, defaultHeaders: Record<string, string>, contentType: string): Headers;
|
|
4
11
|
export default function (defaultHeaders: Record<string, string>): (this: LixnetResponse) => Response;
|
|
@@ -1,3 +1,13 @@
|
|
|
1
|
+
import { codeForStatus } from "../error";
|
|
2
|
+
/** The `{ error, code, data?, detail? }` body for an errored response (also used for stream error frames). */
|
|
3
|
+
export function errorBody(response) {
|
|
4
|
+
return {
|
|
5
|
+
error: response.responseError,
|
|
6
|
+
code: response.responseErrorCode ?? codeForStatus(response.responseCode || 500),
|
|
7
|
+
...(response.responseErrorData !== undefined ? { data: response.responseErrorData } : {}),
|
|
8
|
+
...(response.responseErrorDetail ? { detail: response.responseErrorDetail } : {}),
|
|
9
|
+
};
|
|
10
|
+
}
|
|
1
11
|
/** Defaults, then staged header sets/deletes, then staged cookies as `Set-Cookie`. */
|
|
2
12
|
export function buildResponseHeaders(response, defaultHeaders, contentType) {
|
|
3
13
|
const headers = new Headers({
|
|
@@ -55,10 +65,7 @@ export default function (defaultHeaders) {
|
|
|
55
65
|
function formatter() {
|
|
56
66
|
const headers = buildResponseHeaders(this, defaultHeaders, "application/json");
|
|
57
67
|
if (this.responseError) {
|
|
58
|
-
return Response.json({
|
|
59
|
-
error: this.responseError,
|
|
60
|
-
...(this.responseErrorDetail ? { detail: this.responseErrorDetail } : {}),
|
|
61
|
-
}, {
|
|
68
|
+
return Response.json(errorBody(this), {
|
|
62
69
|
status: this.responseCode || 500,
|
|
63
70
|
headers: headers,
|
|
64
71
|
});
|
|
@@ -13,6 +13,10 @@ export declare class LixnetResponse {
|
|
|
13
13
|
responseError: string | null;
|
|
14
14
|
/** Extra error information, only sent when the server has `exposeErrors` enabled. */
|
|
15
15
|
responseErrorDetail: string | null;
|
|
16
|
+
/** Error code sent as `code`; derived from the status when not set. */
|
|
17
|
+
responseErrorCode: string | null;
|
|
18
|
+
/** JSON-serialisable data sent with the error as `data`. */
|
|
19
|
+
responseErrorData: unknown;
|
|
16
20
|
responseCode: number;
|
|
17
21
|
responseHeaders: Record<string, string>;
|
|
18
22
|
responseHeaderDeletes: Set<string>;
|
|
@@ -27,7 +31,15 @@ export declare class LixnetResponse {
|
|
|
27
31
|
data(data: any): void;
|
|
28
32
|
header(headerName: string, headerValue: string): void;
|
|
29
33
|
deleteHeader(headerName: string): void;
|
|
30
|
-
|
|
34
|
+
/**
|
|
35
|
+
* Turns the response into an error. Prefer throwing a `LixnetError` from the handler; this is
|
|
36
|
+
* for staging one without throwing. A string second argument is the `detail` (legacy form).
|
|
37
|
+
*/
|
|
38
|
+
error(error: string, options?: string | {
|
|
39
|
+
code?: string;
|
|
40
|
+
data?: unknown;
|
|
41
|
+
detail?: string;
|
|
42
|
+
}): void;
|
|
31
43
|
code(code: number): void;
|
|
32
44
|
headers(headers: Record<string, string>): void;
|
|
33
45
|
cookie(cookieName: string, cookieValue: string, cookieOptions?: CookieFullOptions): void;
|
|
@@ -17,6 +17,10 @@ export class LixnetResponse {
|
|
|
17
17
|
responseError = null;
|
|
18
18
|
/** Extra error information, only sent when the server has `exposeErrors` enabled. */
|
|
19
19
|
responseErrorDetail = null;
|
|
20
|
+
/** Error code sent as `code`; derived from the status when not set. */
|
|
21
|
+
responseErrorCode = null;
|
|
22
|
+
/** JSON-serialisable data sent with the error as `data`. */
|
|
23
|
+
responseErrorData = undefined;
|
|
20
24
|
responseCode = 0;
|
|
21
25
|
responseHeaders = {};
|
|
22
26
|
responseHeaderDeletes = new Set();
|
|
@@ -37,8 +41,15 @@ export class LixnetResponse {
|
|
|
37
41
|
delete this.responseHeaders[headerName.toLowerCase()];
|
|
38
42
|
this.responseHeaderDeletes.add(headerName.toLowerCase());
|
|
39
43
|
}
|
|
40
|
-
|
|
44
|
+
/**
|
|
45
|
+
* Turns the response into an error. Prefer throwing a `LixnetError` from the handler; this is
|
|
46
|
+
* for staging one without throwing. A string second argument is the `detail` (legacy form).
|
|
47
|
+
*/
|
|
48
|
+
error(error, options) {
|
|
49
|
+
const { code, data, detail } = typeof options === "string" ? { detail: options } : (options ?? {});
|
|
41
50
|
this.responseError = error;
|
|
51
|
+
this.responseErrorCode = code ?? null;
|
|
52
|
+
this.responseErrorData = data;
|
|
42
53
|
this.responseErrorDetail = detail ?? null;
|
|
43
54
|
}
|
|
44
55
|
code(code) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "lixnet",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.1",
|
|
4
4
|
"author": "nitlix-hq",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -25,9 +25,7 @@
|
|
|
25
25
|
"devDependencies": {
|
|
26
26
|
"@types/bun": "latest",
|
|
27
27
|
"typescript": "^5.9.3",
|
|
28
|
+
"valibot": "^1.5.0",
|
|
28
29
|
"zod": "^4.3.6"
|
|
29
|
-
},
|
|
30
|
-
"peerDependencies": {
|
|
31
|
-
"zod": "^4.0.0"
|
|
32
30
|
}
|
|
33
31
|
}
|