lixnet 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
- - **Optional Zod validation** on the server
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 (`server.route`)](#inferred-contract-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 Zod schemas, then expose an HTTP endpoint that forwards the incoming `Request` to `server.handle(...)`.
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,49 @@ await client.call(
172
175
  );
173
176
  ```
174
177
 
178
+ ## Inferred contract (`server.route`)
179
+
180
+ Instead of writing an `Events` type by hand, chain `.route(...)` on the server 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(options)
190
+ .route("helloThere", {
191
+ schema: z.object({ name: z.string() }),
192
+ handler: ({ name }) => ({ message: `Hello ${name}` }),
193
+ })
194
+ // no schema: input is the handler's parameter type minus request/response
195
+ .route("live", { handler: live });
196
+ }
197
+
198
+ export type RpcServer = ReturnType<typeof createRpcServer>;
199
+ ```
200
+
201
+ ```ts
202
+ // cloudflare/io.ts (browser)
203
+ import type { RpcServer } from "./ioServer"; // type-only: erased at build time
204
+ import { LixnetClient } from "lixnet";
205
+
206
+ export const rpcClient = new LixnetClient<RpcServer>({ rpcUrl: "/rpc" });
207
+
208
+ await rpcClient.call("helloThere", { name: "World" }); // { message: string }
209
+ await rpcClient.call("live"); // input omitted: live takes no client input
210
+ ```
211
+
212
+ - 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).
213
+ - 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.
214
+
215
+ Keeping server code out of the client:
216
+
217
+ - 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.
218
+ - 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.
219
+ - 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`.
220
+
175
221
  ## Server: `LixnetServer`
176
222
 
177
223
  ### Registering events
@@ -179,7 +225,7 @@ await client.call(
179
225
  `server.on(...)` accepts either one registration object or an array.
180
226
 
181
227
  - **`event`**: string key matching your `Events` type
182
- - **`schema`** (optional): Zod schema to validate `input`
228
+ - **`schema`** (optional): a Standard Schema (zod, valibot, arktype, ...) to validate `input`
183
229
  - **`handler`**: receives validated input plus `{ request, response }` injections
184
230
 
185
231
  Example registering multiple events:
@@ -215,7 +261,7 @@ Responses are JSON and shaped as either:
215
261
  or
216
262
 
217
263
  ```json
218
- { "error": "..." }
264
+ { "error": "...", "code": "UNAUTHORIZED", "data": {} }
219
265
  ```
220
266
 
221
267
  ### Server configuration
@@ -237,12 +283,93 @@ const server = new LixnetServer<Events>({
237
283
  });
238
284
  ```
239
285
 
286
+ ## Errors (`LixnetError`)
287
+
288
+ Throw a `LixnetError` from a handler to send a specific error; the client throws it back with the same `code`, `status` and `data`:
289
+
290
+ ```ts
291
+ import { LixnetError } from "lixnet";
292
+
293
+ // server
294
+ throw new LixnetError("UNAUTHORIZED", "Session expired");
295
+ throw new LixnetError("TOO_MANY_REQUESTS", "Slow down", { data: { retryAfter: 30 } });
296
+ throw new LixnetError("PLAN_LIMIT", "Upgrade your plan", { status: 402 }); // custom code
297
+
298
+ // client
299
+ try {
300
+ await client.call("me");
301
+ } catch (e) {
302
+ if (LixnetError.is(e) && e.code === "UNAUTHORIZED") redirect("/login");
303
+ }
304
+ ```
305
+
306
+ - 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).
307
+ - `LixnetError.is(e)` is preferred over `instanceof`: it also works when two copies of Lixnet end up in one bundle.
308
+ - 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.
309
+ - 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).
310
+ - `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" })`.
311
+
312
+ Built-in errors (both servers, same messages as before plus a `code`):
313
+
314
+ | `error` | `code` | Status |
315
+ | --- | --- | --- |
316
+ | `"Invalid JSON"` | `BAD_REQUEST` | 400 |
317
+ | `"Invalid request body"` | `BAD_REQUEST` | 400 |
318
+ | `"Event not found"` (missing `event`) | `BAD_REQUEST` | 400 |
319
+ | `"Input not found"` | `BAD_REQUEST` | 400 |
320
+ | `"Event not found"` (unknown `event`) | `NOT_FOUND` | 404 |
321
+ | `"Invalid input"` (schema failure) | `INVALID_INPUT` | 400 |
322
+ | `"Origin not allowed"` (with `cors`) | `FORBIDDEN` | 403 |
323
+ | `"Handler error"` (handler threw a non-`LixnetError`) | `INTERNAL` | 500 |
324
+
325
+ `INVALID_INPUT` always includes the validation issues, so forms can show errors per field:
326
+
327
+ ```json
328
+ {
329
+ "error": "Invalid input",
330
+ "code": "INVALID_INPUT",
331
+ "data": { "issues": [{ "path": ["email"], "message": "Invalid email address" }] }
332
+ }
333
+ ```
334
+
335
+ 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.
336
+
337
+ ## CORS
338
+
339
+ 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`.
340
+
341
+ ```ts
342
+ const server = new LixnetServer({
343
+ cors: {
344
+ origin: ["https://example.com", "http://localhost:3000"], // or "*", or (origin) => boolean
345
+ credentials: true, // cookies; not allowed with origin "*"
346
+ // maxAge: 7200, // preflight cache in seconds (default 7200, Chrome's cap)
347
+ // allowHeaders: ["Content-Type", "Authorization"], // default: whatever the browser asks for
348
+ // exposeHeaders: ["X-Request-Id"],
349
+ },
350
+ });
351
+
352
+ export default {
353
+ async fetch(request: Request) {
354
+ const url = new URL(request.url);
355
+ if (url.pathname === "/rpc" && (request.method === "POST" || request.method === "OPTIONS")) {
356
+ return server.handle(request);
357
+ }
358
+ return new Response("Not found", { status: 404 });
359
+ },
360
+ };
361
+ ```
362
+
363
+ - `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.
364
+ - Every response, errors included, gets `Access-Control-Allow-Origin` (the caller's origin, plus `Vary: Origin`) and `Access-Control-Allow-Credentials` when enabled.
365
+ - 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.
366
+
240
367
  ## Client: `LixnetClient`
241
368
 
242
369
  `client.call(event, input, options?)`:
243
370
 
244
371
  - sends a `POST` with `{ event, input }`
245
- - throws `Error(...)` when the response contains `{ error }`
372
+ - throws a `LixnetError` (with `code`, `status`, `data`) when the response contains `{ error }`; see "Errors" below
246
373
  - otherwise returns `{ data }`’s value
247
374
 
248
375
  ### 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
- export { LixnetServer, LixnetClient, LixnetPeer, LixnetStreamServer, LixnetStreamClient, LixnetResponse };
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, 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
- export { LixnetServer, LixnetClient, LixnetPeer, LixnetStreamServer, LixnetStreamClient, LixnetResponse };
8
+ import { LixnetError, LIXNET_ERROR_STATUS } from "./lib/error";
9
+ export { LixnetServer, LixnetClient, LixnetPeer, LixnetStreamServer, LixnetStreamClient, LixnetResponse, LixnetError, LIXNET_ERROR_STATUS, };
@@ -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
- export default class LixnetClient<Events extends LXN_ServerClient_EventType> {
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]>, options?: RequestInit): Promise<ExtractRPCResponse<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 {};
@@ -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
- if (json.error) {
16
- throw new Error(json.error, json.detail ? { cause: json.detail } : undefined);
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,18 @@
1
+ /**
2
+ * Type-level description of a route added with `LixnetServer.route(...)`: the input the
3
+ * client sends and the output it receives.
4
+ */
5
+ export type LixnetRoute<TInput, TOutput> = {
6
+ input: TInput;
7
+ output: TOutput;
8
+ };
9
+ export type LixnetRoutes = Record<string, LixnetRoute<any, any>>;
10
+ /**
11
+ * Converts `typeof server` (built with `.route(...)`) into the `Events` shape clients use
12
+ * (`name: (input) => output`). Anything else is passed through, so clients accept either.
13
+ */
14
+ export type InferLixnetEvents<T> = T extends {
15
+ readonly "~routes": infer TRoutes extends LixnetRoutes;
16
+ } ? {
17
+ [K in keyof TRoutes]: (input: TRoutes[K]["input"]) => TRoutes[K]["output"];
18
+ } : T;
@@ -0,0 +1 @@
1
+ export {};
@@ -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, LixnetRoutes } 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,28 @@ type LXNServerEventInput<Events extends LXN_ServerClient_EventType, TName extend
10
13
  }, FunctionOutput<Events[TName]>>;
11
14
  schema?: LXNEventSchema<Events, TName>;
12
15
  };
13
- export default class LixnetServer<Events extends LXN_ServerClient_EventType> extends LixnetServerBase<LXNServerEventInput<Events, keyof Events>> {
16
+ export default class LixnetServer<Events extends LXN_ServerClient_EventType = LXN_ServerClient_EventType, Routes extends LixnetRoutes = {}> extends LixnetServerBase<LXNServerEventInput<Events, keyof Events>> {
17
+ /** Type-only: the routes added with `.route(...)`, read by `InferLixnetEvents`. */
18
+ readonly "~routes": Routes;
14
19
  private formatter;
15
- constructor({ formatter, ...options }: LixnetServerBaseOptions & {
20
+ constructor({ formatter, ...options }?: LixnetServerBaseOptions & {
16
21
  formatter?: (this: LixnetResponse) => Response;
17
22
  });
23
+ /**
24
+ * Adds an event whose types are inferred, so no `Events` contract is needed. Chain calls and
25
+ * give the client `typeof server` through an `import type`.
26
+ *
27
+ * With a schema, the handler gets the schema's output and the client sends its input.
28
+ */
29
+ route<K extends string, TSchema extends StandardSchemaV1, TOutput>(event: K, route: {
30
+ schema: TSchema;
31
+ handler: (input: StandardSchemaV1.InferOutput<TSchema> & LixnetServerInjections) => TOutput;
32
+ }): LixnetServer<Events, Routes & Record<K, LixnetRoute<StandardSchemaV1.InferInput<TSchema>, Awaited<TOutput>>>>;
33
+ /** Without a schema, the input is the handler's parameter type minus `request`/`response`. */
34
+ route<K extends string, TParams, TOutput>(event: K, route: {
35
+ schema?: undefined;
36
+ handler: (input: TParams) => TOutput;
37
+ }): LixnetServer<Events, Routes & Record<K, LixnetRoute<Omit<TParams, keyof LixnetServerInjections>, Awaited<TOutput>>>>;
18
38
  on<K extends keyof Events & string>(input: LXNServerEventInput<Events, K> | LXNEventEntries<Events, {
19
39
  [P in keyof Events & string]: LXNServerEventInput<Events, P>;
20
40
  }>): void;
@@ -4,16 +4,23 @@ 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, ...options } = {}) {
8
8
  super(options);
9
9
  this.formatter = formatter ?? getDefaultFormatter(this.defaultHeaders);
10
10
  }
11
+ route(event, route) {
12
+ this.register({ ...route, event });
13
+ return this;
14
+ }
11
15
  on(input) {
12
16
  this.register(input);
13
17
  }
14
18
  async handle(request) {
15
19
  const requestClone = request.clone();
16
20
  const response = new LixnetResponse({ formatter: this.formatter });
21
+ const corsResponse = this.handleCors(request, response);
22
+ if (corsResponse)
23
+ return corsResponse;
17
24
  const parsed = await this.parse(request);
18
25
  if (!parsed.ok) {
19
26
  return this.fail(response, parsed);
@@ -31,12 +38,7 @@ export default class LixnetServer extends LixnetServerBase {
31
38
  return response.format();
32
39
  }
33
40
  catch (error) {
34
- return this.fail(response, {
35
- error: "Handler error",
36
- status: 500,
37
- cause: error,
38
- event: parsed.entry.event,
39
- });
41
+ return this.fail(response, this.failureFromThrown(error, parsed.entry.event));
40
42
  }
41
43
  }
42
44
  }
@@ -1,6 +1,8 @@
1
- import type { z } from "zod";
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?: z.ZodType<any>;
24
+ schema?: StandardSchemaV1;
18
25
  };
19
- type ParsedRpcRequest<TEntry> = {
20
- ok: true;
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 constructor({ debugLog, exposeErrors, logger, defaultHeaders, }: LixnetServerBaseOptions);
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
- error: string;
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 {};
@@ -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
- constructor({ debugLog = false, exposeErrors = false, logger, defaultHeaders = {}, }) {
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 { ok: false, error: "Event not found", status: 404, event: json.event };
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.safeParse(json.input);
55
- if (!result.success) {
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
- cause: result.error,
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.data };
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, this.exposeErrors ? describeError(cause) : undefined);
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]>, options?: LXNStreamCallOptions<FunctionOutput<Events[K]>>): Promise<void>;
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 {};
@@ -1,26 +1,24 @@
1
1
  import withJsonContentType from "./util/withJsonContentType";
2
- function toError(frame) {
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 toError(json);
23
- throw new Error(`Stream request failed with status ${response.status}`);
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 toError(parsed);
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: LixnetServerBaseOptions);
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;
@@ -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) {
@@ -1,6 +1,6 @@
1
- import type { z } from "zod";
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> = z.ZodType<FunctionInput<Events[K]>>;
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
- error(error: string, detail?: string): void;
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
- error(error, detail) {
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.4.0",
3
+ "version": "1.5.0",
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
  }