lixnet 1.5.1 → 1.7.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
@@ -1,5 +1,10 @@
1
1
  <div align="center">
2
- <h1>Lixnet</h1>
2
+ <h1>
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="./assets/wordmark-v2-white.svg?v=4">
5
+ <img alt="Lixnet" src="./assets/wordmark-v2-black.svg?v=4" width="293">
6
+ </picture>
7
+ </h1>
3
8
  <h3>Lightweight, type-safe RPC over HTTP and WebSockets.<br />The tRPC and Next.js Server Actions, but for everyone.</h3>
4
9
 
5
10
  <a href="https://github.com/Nitlix/Lixnet">
@@ -45,6 +50,8 @@ It’s designed to be minimal: no codegen, no schema registry, no client bundler
45
50
  - [Server: `LixnetServer`](#server-lixnetserver)
46
51
  - [Errors](#errors-lixneterror)
47
52
  - [CORS](#cors)
53
+ - [Middleware](#middleware)
54
+ - [Serialization](#serialization)
48
55
  - [Client: `LixnetClient`](#client-lixnetclient)
49
56
  - [Handlers: `request` and `response`](#handlers-request-and-response)
50
57
  - [WebSockets: `LixnetPeer`](#websockets-lixnetpeer)
@@ -204,6 +211,8 @@ export type RpcServer = ReturnType<typeof createRpcServer>;
204
211
 
205
212
  `events` is an alias of `routes` (same types and behaviour) for codebases that still use the events naming; pass one or the other.
206
213
 
214
+ `LixnetStreamServer` takes the same `routes` option and `.route(...)`; see "HTTP streaming" in [FOR_AGENTS.md](FOR_AGENTS.md). `LixnetPeerEvents` does the same for WebSockets (see below).
215
+
207
216
  `.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
217
 
209
218
  ```ts
@@ -277,12 +286,32 @@ or
277
286
  { "error": "...", "code": "UNAUTHORIZED", "data": {} }
278
287
  ```
279
288
 
289
+ With a `serializer`, both shapes also carry `"serializer": "<name>"` and `data` is in that serializer's format (see [Serialization](#serialization)).
290
+
280
291
  ### Server configuration
281
292
 
282
293
  `new LixnetServer({ ... })` supports:
283
294
 
284
295
  - **`defaultHeaders`**: headers included on every response (unless deleted later)
285
- - **`formatter`**: customize how `LixnetResponse` becomes a `Response`
296
+ - **`formatter`**: customize how `LixnetResponse` becomes a `Response`. It sees raw values: `this.responseData` (`undefined` when nothing was staged) and `this.responseErrorData` are not encoded yet. Build bodies with `lixnetDataBody(this)` / `lixnetErrorBody(this)`: they apply the server's `serializer` and add the `serializer` echo that clients check. `lixnetResponseHeaders(this, defaultHeaders, contentType)` gives the default headers plus staged headers and cookies.
297
+
298
+ ```ts
299
+ import { LixnetServer, LixnetResponse, lixnetDataBody, lixnetErrorBody, lixnetResponseHeaders } from "lixnet";
300
+
301
+ const defaultHeaders = { "x-powered-by": "lixnet" };
302
+
303
+ new LixnetServer({
304
+ defaultHeaders,
305
+ formatter(this: LixnetResponse) {
306
+ const headers = lixnetResponseHeaders(this, defaultHeaders, "application/json");
307
+ headers.set("x-formatted", "yes");
308
+ if (this.responseError) {
309
+ return Response.json(lixnetErrorBody(this), { status: this.responseCode || 500, headers });
310
+ }
311
+ return Response.json(lixnetDataBody(this), { status: this.responseCode || 200, headers });
312
+ },
313
+ });
314
+ ```
286
315
  - **`logger`** + **`debugLog`**: currently used for invalid JSON logging
287
316
 
288
317
  Example:
@@ -333,7 +362,12 @@ Built-in errors (both servers, same messages as before plus a `code`):
333
362
  | `"Event not found"` (unknown `event`) | `NOT_FOUND` | 404 |
334
363
  | `"Invalid input"` (schema failure) | `INVALID_INPUT` | 400 |
335
364
  | `"Origin not allowed"` (with `cors`) | `FORBIDDEN` | 403 |
336
- | `"Handler error"` (handler threw a non-`LixnetError`) | `INTERNAL` | 500 |
365
+ | `"Invalid input encoding"` (`serializer` couldn't decode `input`) | `BAD_REQUEST` | 400 |
366
+ | `"This server uses the …"` / `"This server has no serializer, …"` | `BAD_REQUEST` | 400 |
367
+ | `"Handler error"` (handler or middleware threw a non-`LixnetError`) | `INTERNAL` | 500 |
368
+ | `"Could not serialize the response"` (output JSON/the serializer can't encode, e.g. circular) | `INTERNAL` | 500 |
369
+
370
+ `server.handle(...)` always resolves to a `Response`. Error `data` that can't be encoded is dropped and the error kept.
337
371
 
338
372
  `INVALID_INPUT` always includes the validation issues, so forms can show errors per field:
339
373
 
@@ -377,6 +411,97 @@ export default {
377
411
  - Every response, errors included, gets `Access-Control-Allow-Origin` (the caller's origin, plus `Vary: Origin`) and `Access-Control-Allow-Credentials` when enabled.
378
412
  - 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
413
 
414
+ ## Middleware
415
+
416
+ Optional. Middleware runs before a handler and can reject the call, add typed fields to the handler's `ctx`, set headers or cookies, or answer without running the handler. It works on `LixnetServer` and `LixnetStreamServer`.
417
+
418
+ ```ts
419
+ import { LixnetError, LixnetServer, lixnetMiddleware, type LixnetMiddlewareOptions } from "lixnet";
420
+
421
+ const auth = lixnetMiddleware(async ({ request, next }) => {
422
+ const user = await getUser(request.cookies().get("session")?.value);
423
+ if (!user) throw new LixnetError("UNAUTHORIZED", "Sign in first");
424
+ return next({ user }); // merged into ctx for everything after this
425
+ });
426
+
427
+ // Reads what `auth` added, so it annotates the ctx it needs.
428
+ const admin = lixnetMiddleware(async ({ ctx, next }: LixnetMiddlewareOptions<{ user: User }>) => {
429
+ if (!ctx.user.isAdmin) throw new LixnetError("FORBIDDEN", "Admins only");
430
+ return next();
431
+ });
432
+
433
+ const timing = lixnetMiddleware(async ({ event, response, next }) => {
434
+ const start = Date.now();
435
+ try {
436
+ return await next(); // the rest of the chain: later middleware, validation, handler
437
+ } finally {
438
+ response.header("Server-Timing", `${event};dur=${Date.now() - start}`);
439
+ }
440
+ });
441
+
442
+ export const server = new LixnetServer({ use: [timing] }) // every route
443
+ .route("health", { handler: () => "ok" })
444
+ .use(auth) // routes added after this line
445
+ .route("me", { handler: ({ ctx }) => ctx.user }) // ctx.user is typed
446
+ .route("ban", {
447
+ schema: z.object({ id: z.string() }),
448
+ use: [admin], // this route only, after the server's
449
+ handler: ({ id }) => banUser(id),
450
+ });
451
+ ```
452
+
453
+ - **Where it applies:** the `use` constructor option covers every route. `.use(...)` covers only routes registered after it, so `health` above stays public. A route's own `use` (in `.route`, `on` or a `routes` entry) runs after the server's.
454
+ - **Order:** constructor `use` → `.use(...)` calls → the route's `use` → schema validation → handler. Middleware gets `{ request, response, event, input, ctx, next }`.
455
+ - **Middleware runs before validation.** `input` is deserialized but **not validated**: treat it as untrusted (transforms and coercions haven't run yet). An unauthenticated caller gets your `401`, not validation issues that reveal the input shape. A schema failure makes `next()` reject with an `INVALID_INPUT` `LixnetError`, so logging or error-mapping middleware can catch it.
456
+ - **Contract:** return `next()`'s result, throw (a `LixnetError` keeps its code and status), or return `{ output }` to answer without validation or the handler (for example from a cache). Call `next()` at most once and only while the middleware is running: after it returned or threw, `next()` rejects and the handler never runs. Calling `next()` twice or returning anything else answers `500 "Handler error"`. A `next()` you forget to await can't crash the process, but its error is lost, so always `return next()` or `return await next()`.
457
+ - **Typing:** keep the `.use(...)` result by chaining or reassigning it, because it returns a server whose `ctx` type includes what was added. With an `Events` contract, write `new LixnetServer<Events>().use(auth)` and the `on(...)` handlers see `ctx.user`.
458
+ - **Compile-time ctx checks:** what each middleware reads from `ctx` is checked everywhere (`use` option, `.use(...)`, a route's `use`, `routes` entries, `on`), in order. `use: [auth, admin]` and `.use(auth, admin)` compile; `[admin, auth]`, or `admin` with no `auth` before it, is an error on `admin`. Two limits: inline middleware (`use: [async ({ ctx, next }) => ...]`) gets `ctx: any` and isn't checked, so define it with `lixnetMiddleware` and `LixnetMiddlewareOptions<Ctx>`; and a list kept in a plain array variable is checked against the server's ctx only (write it inline or `as const` to get the in-order check).
459
+ - **Streams:** on `LixnetStreamServer`, middleware wraps the whole stream; see "HTTP streaming" in [FOR_AGENTS.md](FOR_AGENTS.md).
460
+ - **Limitation:** in the `routes` option, a schema-less handler's parameter stays `any`. Add a schema, annotate the parameter (`LixnetServerInjections<{ user: User }>`), or use `.route(...)`.
461
+
462
+ Handlers always receive `ctx` (`{}` without middleware), next to `request` and `response`. Those names (and `stream` on stream routes) are **reserved**: a schema output or `Events` input with a `ctx`, `request`, `response` (or `stream`) key is a compile error, `Lixnet: input key "ctx" is reserved`. Rename the field, or `.transform()` it away (only the schema's output counts).
463
+
464
+ ## Serialization
465
+
466
+ Optional. By default inputs and outputs are plain JSON, so a `Date` arrives as a string and `Map`, `Set` and `BigInt` don't survive. Give both sides a `serializer` to keep them:
467
+
468
+ ```ts
469
+ import { LixnetClient, LixnetServer, lixnetJSON } from "lixnet";
470
+
471
+ const server = new LixnetServer({ serializer: lixnetJSON }).route("shift", {
472
+ schema: z.object({ when: z.date() }), // the schema sees a real Date
473
+ handler: ({ when }) => ({ next: new Date(when.getTime() + 86_400_000), tags: new Set(["a"]) }),
474
+ });
475
+
476
+ const client = new LixnetClient<typeof server>({ rpcUrl: "/rpc", serializer: lixnetJSON });
477
+ const { next, tags } = await client.caller.shift({ when: new Date() }); // Date, Set
478
+ ```
479
+
480
+ - **`lixnetJSON`** keeps `Date` (also invalid dates), `Map`, `Set`, `BigInt`, `undefined`, `NaN`/`±Infinity`/`-0`, `RegExp`, `URL`, `Error` (`name` and `message` only, never the stack; arrives as an `Error` with that `name`), `ArrayBuffer`, `DataView` and every typed array (`Uint8Array`, `Int32Array`, `Float64Array`, `BigInt64Array`, ...; a `Buffer` arrives as a `Uint8Array`). Plain JSON passes through unchanged.
481
+ - **What it doesn't keep:** holes in sparse arrays arrive as `null` (like JSON), an object referenced twice arrives as two copies (circular values throw), class instances are sent the way `JSON.stringify` sends them (`toJSON(key)` included), and extremely deep values (around 10k levels) can overflow the stack.
482
+ - **Decoding is strict:** a malformed tagged value is a `400 BAD_REQUEST "Invalid input encoding"` on the server and a `BAD_RESPONSE` `LixnetError` on the client.
483
+ - **Don't mutate what `lixnetJSON.serialize` returns:** for speed it returns its input itself when it's plain JSON, and shares untouched parts otherwise. `lixnetJSON.deserialize` never mutates its input.
484
+ - **Any library works.** A serializer is `{ name, serialize, deserialize }`. For superjson: `{ name: "superjson", serialize: (v) => superjson.serialize(v), deserialize: (v) => superjson.deserialize(v as any) }`. Custom serializers always get `deserialize` called (the "skip decoding" shortcut below is `lixnetJSON`-only).
485
+ - **What it covers:** the input, the output (`response.data(...)` too), error `data` (`response.error(..., { data })` too), stream chunks (`LixnetStreamServer`/`LixnetStreamClient`) and WebSocket calls (`new LixnetPeer({ serializer })`, which both peers need).
486
+ - **Always give routes a schema when a serializer is on.** A schema-less route accepts whatever the caller encodes, so its handler can receive a `Map`, `RegExp` or `BigInt` where it expects a string.
487
+
488
+ ### Mismatches fail loudly
489
+
490
+ The client sends its serializer's `name` in the request body, and a server with a serializer echoes `"serializer": "<name>"` in every JSON body and the first stream frame. Both sides check:
491
+
492
+ - A server with a serializer rejects requests naming another one, or none, with `400 BAD_REQUEST` (`This server uses the "lixnet-json" serializer; give the client the same \`serializer\``). A server without one rejects requests that name one. `"serializer": null` counts as none.
493
+ - A client with a serializer throws a `BAD_RESPONSE` `LixnetError` when a success body or the first stream frame doesn't echo the same name (`Server at <url> did not confirm the "lixnet-json" serializer — is it an older Lixnet or configured without \`serializer\`?`), or when data can't be decoded. Error responses are still thrown as themselves; their `data` is only decoded when the echo matched.
494
+
495
+ | client ↓ / server → | ≤ 1.6.0 | no serializer | serializer |
496
+ | --- | --- | --- | --- |
497
+ | ≤ 1.6.0 | ok | ok (same bytes) | `400 BAD_REQUEST` |
498
+ | no serializer | ok | ok | `400 BAD_REQUEST` |
499
+ | serializer | `BAD_RESPONSE` (the call still ran) | `400 BAD_REQUEST` | ok (same `name`; else `400`) |
500
+
501
+ Turn a serializer on in the server and its clients together. Plain clients (curl, other languages) can't call a server that has a serializer. `LixnetPeer` has **no** negotiation: a peer with another (or no) serializer gets tagged objects without an error, so configure both peers the same.
502
+
503
+ **Performance:** a plain 4.3 KB payload costs about 18% more with `lixnetJSON` than without a serializer on an in-process round trip (12.5 vs 10.5 µs on bun). Plain JSON is detected without allocating and sent as-is, and decoding is skipped when the body has no `"$t"` key. Payloads full of `Date`s or `Map`s cost more. Reproduce with `cd benchmarks && bun serializer.ts`.
504
+
380
505
  ## Client: `LixnetClient`
381
506
 
382
507
  `client.call(event, input, options?)`:
@@ -390,9 +515,37 @@ export default {
390
515
  ```ts
391
516
  const client = new LixnetClient<Events>({
392
517
  rpcUrl: "https://api.example.com/rpc",
518
+ // optional: any fetch-compatible function (defaults to the global fetch)
519
+ fetch: (url, init) => fetch(url, { ...init, credentials: "include" }),
520
+ });
521
+ ```
522
+
523
+ `fetch` is also how you test or SSR without a network or patching `globalThis.fetch`:
524
+
525
+ ```ts
526
+ const client = new LixnetClient<typeof server>({
527
+ rpcUrl: "http://local/rpc",
528
+ fetch: (url, init) => server.handle(new Request(url, init)),
393
529
  });
394
530
  ```
395
531
 
532
+ `LixnetStreamClient` takes the same option.
533
+
534
+ ### Caller (`client.caller`)
535
+
536
+ Every event as a typed function: names autocomplete, input is checked and the result is inferred. Same arguments as `call` (`input`, then `RequestInit` options).
537
+
538
+ ```ts
539
+ const { caller } = rpcClient;
540
+
541
+ const data = await caller.helloThere({ name: "World" }); // { message: string }
542
+ await caller.live(); // input omitted: live takes no client input
543
+
544
+ const { helloThere } = caller; // destructuring works
545
+ ```
546
+
547
+ `LixnetStreamClient` has one too: `await streamClient.caller.generate({ prompt }, { onStreamChunk })`. An event named `then` can only be called with `call(...)`, so the caller is never mistaken for a Promise.
548
+
396
549
  ## Handlers: `request` and `response`
397
550
 
398
551
  Handler signature is:
@@ -443,6 +596,45 @@ peer.on("ping", async ({ t, socket }) => {
443
596
  // peer.handle({ data: event.data, socket: ws });
444
597
  ```
445
598
 
599
+ ### Inferred events (`LixnetPeerEvents`)
600
+
601
+ Like `routes` on `LixnetServer`, each side can define the events it handles as a `LixnetPeerEvents` object and let the other side infer everything with `import type`. Each events object only describes its own side, so both sides can import each other's types without a circular type (two peers typed directly from `typeof` each other would be).
602
+
603
+ ```ts
604
+ // server/events.ts
605
+ import { z } from "zod";
606
+ import { LixnetPeerEvents } from "lixnet";
607
+
608
+ export const serverEvents = new LixnetPeerEvents({
609
+ routes: {
610
+ hello: {
611
+ schema: z.object({ name: z.string() }),
612
+ handler: ({ name, socket }) => `Hello ${name}`,
613
+ },
614
+ },
615
+ }).route("add", { handler: ({ a, b }: { a: number; b: number }) => a + b });
616
+
617
+ // client/events.ts
618
+ export const clientEvents = new LixnetPeerEvents().route("notify", {
619
+ handler: ({ message }: { message: string }) => console.log(message),
620
+ });
621
+
622
+ // server/socket.ts
623
+ import type { clientEvents } from "../client/events";
624
+ const peer = new LixnetPeer<typeof clientEvents>({ events: serverEvents });
625
+ peer.call("notify", { message: "hi" });
626
+
627
+ // client/socket.ts
628
+ import type { serverEvents } from "../server/events";
629
+ const peer = new LixnetPeer<typeof serverEvents>({ events: clientEvents });
630
+ peer.call("hello", { name: "World" }, { callback: (greeting) => greeting /* string */ });
631
+ ```
632
+
633
+ - `events` is an alias of `routes`, and `.route(...)` chains, exactly like `LixnetServer`. Handlers get `socket` next to their input.
634
+ - With a schema, invalid input never reaches the handler; if the caller passed a `callback`, its `onError` gets a `LixnetError` with code `INVALID_INPUT`.
635
+ - A handler can't use the other side's types through its events object (that would bring the cycle back). Return a value for callbacks, or call the other side from the file that creates the peer.
636
+ - `LixnetPeer<ThisToThere, ThereToThis>` with `on(...)` keeps working.
637
+
446
638
  ### WebSocket setup (typical pattern)
447
639
 
448
640
  ```ts
@@ -486,11 +678,19 @@ From `src/exports.ts`:
486
678
 
487
679
  - **`LixnetServer`**
488
680
  - **`LixnetClient`**
489
- - **`LixnetPeer`**
681
+ - **`LixnetPeer`**, **`LixnetPeerEvents`**
682
+ - **`LixnetStreamServer`**, **`LixnetStreamClient`**
490
683
  - **`LixnetResponse`**
684
+ - **`LixnetError`**, **`LIXNET_ERROR_STATUS`**
685
+ - **`lixnetMiddleware`** (types a standalone middleware)
686
+ - **`lixnetJSON`** (built-in serializer)
491
687
 
492
688
  Types:
493
689
 
690
+ - **`LixnetMiddleware`**, **`LixnetMiddlewareOptions`**, **`LixnetMiddlewareResult`**, **`LixnetMiddlewareContext`**, **`LixnetNext`**
691
+ - **`LixnetSerializer`**
692
+ - **`LixnetServerInjections<Ctx>`**, **`LixnetStreamInjections<Ctx>`**
693
+
494
694
  - **`LXN_ServerClient_EventType`**
495
695
  - **`LXNServerHandler`**
496
696
  - **`FunctionInput`**
@@ -500,6 +700,8 @@ Types:
500
700
  ## Contributor docs
501
701
 
502
702
  - **Implementation + extension guide**: [`FOR_AGENTS.md`](FOR_AGENTS.md)
703
+ - **Changelog**: [`CHANGELOG.md`](CHANGELOG.md)
704
+ - **Checks**: `bun run typecheck` (source and tests) and `bun run test` (every test file, each in its own process). CI runs both on every push and pull request, and a release tag publishes to npm only after they pass. `bun run bench` runs the serializer benchmark; it isn't part of CI because timings vary between runs.
503
705
 
504
706
  ## License
505
707
 
package/dist/exports.d.ts CHANGED
@@ -1,16 +1,26 @@
1
1
  import LixnetServer from "./lib/server";
2
2
  import LixnetClient from "./lib/client";
3
3
  import LixnetPeer from "./lib/peer";
4
+ import LixnetPeerEvents from "./lib/peerevents";
4
5
  import LixnetStreamServer from "./lib/streamserver";
5
6
  import LixnetStreamClient from "./lib/streamclient";
6
7
  import { LixnetResponse } from "./lib/util/response";
7
8
  import { LixnetError, LIXNET_ERROR_STATUS } from "./lib/error";
8
- export { LixnetServer, LixnetClient, LixnetPeer, LixnetStreamServer, LixnetStreamClient, LixnetResponse, LixnetError, LIXNET_ERROR_STATUS, };
9
+ import { lixnetMiddleware } from "./lib/middleware";
10
+ import { lixnetJSON } from "./lib/serializer";
11
+ import { dataBody as lixnetDataBody, errorBody as lixnetErrorBody, buildResponseHeaders as lixnetResponseHeaders } from "./lib/util/getDefaultFormatter";
12
+ export { LixnetServer, LixnetClient, LixnetPeer, LixnetPeerEvents, LixnetStreamServer, LixnetStreamClient, LixnetResponse, LixnetError, LIXNET_ERROR_STATUS, lixnetMiddleware, lixnetJSON, lixnetDataBody, lixnetErrorBody, lixnetResponseHeaders, };
13
+ export type { LixnetMiddleware, LixnetMiddlewareOptions, LixnetMiddlewareResult, LixnetMiddlewareContext, LixnetNext, } from "./lib/middleware";
14
+ export type { LixnetSerializer } from "./lib/serializer";
15
+ export type { ErrorBody as LixnetErrorBody } from "./lib/util/getDefaultFormatter";
9
16
  export type { LixnetErrorCode, LixnetIssue } from "./lib/error";
10
- export type { LixnetRoute, LixnetRoutes, LixnetRouteDefinitions, LixnetRoutesFromDefinitions, InferLixnetEvents, } from "./lib/router";
17
+ export type { LixnetRoute, LixnetRoutes, LixnetRouteDefinitions, LixnetRoutesFromDefinitions, LixnetRouteDefinitionInput, LixnetRoutesOption, LixnetRouteUses, InferLixnetEvents, } from "./lib/router";
11
18
  export type { LixnetCookies, LixnetHeaders, LixnetRequest, ReadonlyHeaders, ReadonlyRequestCookies, RequestCookie, } from "./lib/util/request";
12
- export type { LXN_ServerClient_EventType, LXNServerHandler, FunctionInput, LXN_ServerClient_Request, LixnetServerInjections, LXNStreamEmitter, LXNCallArgs, } from "./lib/types";
13
- export type { LXNStreamCallOptions } from "./lib/streamclient";
19
+ export type { LXN_ServerClient_EventType, LXNServerHandler, FunctionInput, LXN_ServerClient_Request, LixnetServerInjections, LXNStreamEmitter, LXNCallArgs, LixnetFetch, LixnetClientOptions, LixnetStreamInjections, } from "./lib/types";
20
+ export type { LixnetPeerInjections } from "./lib/peerevents";
21
+ export type { LixnetPeerCallOptions } from "./lib/peer";
22
+ export type { LXNStreamCallOptions, LixnetStreamCaller } from "./lib/streamclient";
23
+ export type { LixnetCaller } from "./lib/client";
14
24
  export type { LixnetServerBaseOptions } from "./lib/serverbase";
15
25
  export type { LixnetCorsOptions } from "./lib/util/cors";
16
26
  export type { StandardSchemaV1 } from "./lib/standardschema";
package/dist/exports.js CHANGED
@@ -2,8 +2,12 @@
2
2
  import LixnetServer from "./lib/server";
3
3
  import LixnetClient from "./lib/client";
4
4
  import LixnetPeer from "./lib/peer";
5
+ import LixnetPeerEvents from "./lib/peerevents";
5
6
  import LixnetStreamServer from "./lib/streamserver";
6
7
  import LixnetStreamClient from "./lib/streamclient";
7
8
  import { LixnetResponse } from "./lib/util/response";
8
9
  import { LixnetError, LIXNET_ERROR_STATUS } from "./lib/error";
9
- export { LixnetServer, LixnetClient, LixnetPeer, LixnetStreamServer, LixnetStreamClient, LixnetResponse, LixnetError, LIXNET_ERROR_STATUS, };
10
+ import { lixnetMiddleware } from "./lib/middleware";
11
+ import { lixnetJSON } from "./lib/serializer";
12
+ import { dataBody as lixnetDataBody, errorBody as lixnetErrorBody, buildResponseHeaders as lixnetResponseHeaders, } from "./lib/util/getDefaultFormatter";
13
+ export { LixnetServer, LixnetClient, LixnetPeer, LixnetPeerEvents, LixnetStreamServer, LixnetStreamClient, LixnetResponse, LixnetError, LIXNET_ERROR_STATUS, lixnetMiddleware, lixnetJSON, lixnetDataBody, lixnetErrorBody, lixnetResponseHeaders, };
@@ -1,12 +1,31 @@
1
- import type { FunctionInput, LXNCallArgs, LXN_ServerClient_EventType } from "./types";
1
+ import type { FunctionInput, FunctionOutput, LXNCallArgs, LXN_ServerClient_EventType, LixnetClientOptions } from "./types";
2
+ import type { LixnetSerializer } from "./serializer";
2
3
  import type { InferLixnetEvents } from "./router";
4
+ /** The `{ event, input, serializer? }` request body, shared with `LixnetStreamClient`. */
5
+ export declare function requestBody(event: string, input: unknown, serializer?: LixnetSerializer): string;
3
6
  type ExtractRPCResponse<T> = T extends (...args: any) => infer R ? Awaited<R> : never;
7
+ /** One function per event: `caller.greet({ name })` is `client.call("greet", { name })`. */
8
+ export type LixnetCaller<Events> = {
9
+ [K in keyof Events]: (...args: LXNCallArgs<FunctionInput<Events[K]>, RequestInit>) => Promise<FunctionOutput<Events[K]>>;
10
+ };
4
11
  /** `Contract` is either an events contract or `typeof server` for a server built with `.route(...)`. */
5
12
  export default class LixnetClient<Contract extends LXN_ServerClient_EventType, Events extends LXN_ServerClient_EventType = InferLixnetEvents<Contract>> {
6
13
  private rpcUrl;
7
- constructor({ rpcUrl }: {
8
- rpcUrl: string;
9
- });
14
+ private fetcher?;
15
+ private serializer?;
16
+ /**
17
+ * Every event as a typed function: `await client.caller.greet({ name: "World" })`.
18
+ * Destructuring works too (`const { greet } = client.caller`). An event named `then` can only
19
+ * be called through `call(...)`.
20
+ */
21
+ readonly caller: LixnetCaller<Events>;
22
+ constructor({ rpcUrl, fetch, serializer }: LixnetClientOptions);
10
23
  call<K extends keyof Events>(event: K, ...[input, options]: LXNCallArgs<FunctionInput<Events[K]>, RequestInit>): Promise<ExtractRPCResponse<Events[K]>>;
11
24
  }
25
+ /**
26
+ * The serializer to decode a value parsed from `text` with. lixnetJSON offers a faster one for
27
+ * fresh `JSON.parse` output (decodes in place, or not at all when `text` has no tagged value);
28
+ * any other serializer is used as-is. Shared with `LixnetStreamClient`.
29
+ */
30
+ export declare function received<S extends LixnetSerializer | undefined>(serializer: S, text: string): S;
12
31
  export {};
@@ -1,26 +1,70 @@
1
1
  import withJsonContentType from "./util/withJsonContentType";
2
- import { LixnetError, codeForStatus, errorFromBody } from "./error";
2
+ import createCaller from "./util/createCaller";
3
+ import { LixnetError, codeForStatus, decodeResponse, errorFromBody, serializerMismatch } from "./error";
4
+ /** The `{ event, input, serializer? }` request body, shared with `LixnetStreamClient`. */
5
+ export function requestBody(event, input, serializer) {
6
+ // An omitted input is sent as `{}` so the server's schema sees an object.
7
+ const value = input === undefined ? {} : input;
8
+ if (!serializer)
9
+ return JSON.stringify({ event, input: value });
10
+ return JSON.stringify({ event, input: serializer.serialize(value), serializer: serializer.name });
11
+ }
3
12
  /** `Contract` is either an events contract or `typeof server` for a server built with `.route(...)`. */
4
13
  export default class LixnetClient {
5
14
  rpcUrl;
6
- constructor({ rpcUrl }) {
15
+ fetcher;
16
+ serializer;
17
+ /**
18
+ * Every event as a typed function: `await client.caller.greet({ name: "World" })`.
19
+ * Destructuring works too (`const { greet } = client.caller`). An event named `then` can only
20
+ * be called through `call(...)`.
21
+ */
22
+ caller;
23
+ constructor({ rpcUrl, fetch, serializer }) {
7
24
  this.rpcUrl = rpcUrl;
25
+ this.fetcher = fetch;
26
+ this.serializer = serializer;
27
+ this.caller = createCaller((event, ...args) => this.call(event, ...args));
8
28
  }
9
29
  async call(event, ...[input, options = {}]) {
10
- const response = await fetch(this.rpcUrl, {
30
+ // Called unbound: a native fetch invoked as a method of this client throws "Illegal invocation".
31
+ const send = this.fetcher ?? fetch;
32
+ const response = await send(this.rpcUrl, {
11
33
  ...options,
12
34
  method: "POST",
13
35
  headers: withJsonContentType(options.headers),
14
- body: JSON.stringify({ event, input: input === undefined ? {} : input }),
36
+ body: requestBody(event, input, this.serializer),
15
37
  });
16
- const json = await response.json().catch(() => null);
38
+ // As text first: lixnetJSON can skip decoding when the text has no tagged value.
39
+ const text = await response.text().catch(() => "");
40
+ let json = null;
41
+ try {
42
+ json = JSON.parse(text);
43
+ }
44
+ catch { }
17
45
  // Not a Lixnet response, e.g. a proxy's HTML error page.
18
46
  if (json === null || typeof json !== "object") {
19
47
  throw new LixnetError(response.ok ? "BAD_RESPONSE" : codeForStatus(response.status), `Unexpected response from ${this.rpcUrl} (status ${response.status})`, { status: response.status });
20
48
  }
49
+ // A server with a serializer echoes its name; anything else means the two disagree on encoding.
50
+ const serializer = this.serializer;
51
+ const confirmed = json.serializer === serializer?.name;
21
52
  if (typeof json.error === "string") {
22
- throw errorFromBody(json, response.status);
53
+ // Without a confirmed serializer the error is still worth throwing, but its data stays raw.
54
+ throw errorFromBody(json, response.status, confirmed ? received(serializer, text) : undefined, this.rpcUrl);
23
55
  }
24
- return json.data;
56
+ if (!confirmed)
57
+ throw serializerMismatch(this.rpcUrl, serializer?.name, json.serializer, response.status);
58
+ if (!serializer)
59
+ return json.data;
60
+ return decodeResponse(received(serializer, text), json.data, this.rpcUrl, response.status);
25
61
  }
26
62
  }
63
+ /**
64
+ * The serializer to decode a value parsed from `text` with. lixnetJSON offers a faster one for
65
+ * fresh `JSON.parse` output (decodes in place, or not at all when `text` has no tagged value);
66
+ * any other serializer is used as-is. Shared with `LixnetStreamClient`.
67
+ */
68
+ export function received(serializer, text) {
69
+ return (serializer?.deserialize?.["~received"]?.(text) ?? serializer);
70
+ }
@@ -1,3 +1,5 @@
1
+ import type { StandardSchemaV1 } from "./standardschema";
2
+ import type { LixnetSerializer } from "./serializer";
1
3
  /** Built-in error codes and their default HTTP statuses. Any other string is also a valid code. */
2
4
  export declare const LIXNET_ERROR_STATUS: {
3
5
  readonly BAD_REQUEST: 400;
@@ -15,9 +17,26 @@ export type LixnetIssue = {
15
17
  path: (string | number)[];
16
18
  message: string;
17
19
  };
20
+ /** Converts Standard Schema issues into the `LixnetIssue`s sent to the caller. */
21
+ export declare function toIssues(issues: ReadonlyArray<StandardSchemaV1.Issue>): LixnetIssue[];
18
22
  /** Picks a code for a status that came without one (e.g. `response.code(403)` + `response.error(...)`). */
19
23
  export declare function codeForStatus(status: number): LixnetErrorCode;
20
- /** Rebuilds the error a server sent (`{ error, code?, data?, detail? }`) on the client. */
24
+ /**
25
+ * Decodes `value` with the serializer; any failure becomes a `BAD_RESPONSE` `LixnetError` whose
26
+ * `cause` is the decode error. Shared by both clients and `errorFromBody`.
27
+ */
28
+ export declare function decodeResponse(serializer: LixnetSerializer, value: unknown,
29
+ /** The server's URL, for the message. */
30
+ from: string, status?: number, what?: string): unknown;
31
+ /**
32
+ * The `BAD_RESPONSE` thrown when a response's `serializer` echo isn't the client's serializer name
33
+ * (`expected`, `undefined` for a client without one).
34
+ */
35
+ export declare function serializerMismatch(from: string, expected: string | undefined, got: unknown, status?: number): LixnetError;
36
+ /**
37
+ * Rebuilds the error a server sent (`{ error, code?, data?, detail? }`) on the client. Returns a
38
+ * `BAD_RESPONSE` error instead if `data` can't be decoded.
39
+ */
21
40
  export declare function errorFromBody(body: {
22
41
  error: string;
23
42
  code?: string;
@@ -25,7 +44,11 @@ export declare function errorFromBody(body: {
25
44
  detail?: string;
26
45
  },
27
46
  /** Omitted for stream error frames (sent after a 200): derived from the code instead. */
28
- status?: number): LixnetError;
47
+ status?: number,
48
+ /** Decodes `data`; pass it only when the server confirmed the same serializer, else `data` stays raw. */
49
+ serializer?: LixnetSerializer,
50
+ /** The server's URL, for messages. */
51
+ from?: string): LixnetError;
29
52
  /**
30
53
  * An error with a machine-readable `code`, an HTTP `status` and optional JSON `data`.
31
54
  *
package/dist/lib/error.js CHANGED
@@ -9,6 +9,16 @@ export const LIXNET_ERROR_STATUS = {
9
9
  TOO_MANY_REQUESTS: 429,
10
10
  INTERNAL: 500,
11
11
  };
12
+ /** Converts Standard Schema issues into the `LixnetIssue`s sent to the caller. */
13
+ export function toIssues(issues) {
14
+ return issues.map((issue) => ({
15
+ message: issue.message,
16
+ path: (issue.path ?? []).map((segment) => {
17
+ const key = typeof segment === "object" ? segment.key : segment;
18
+ return typeof key === "number" ? key : String(key);
19
+ }),
20
+ }));
21
+ }
12
22
  const LIXNET_ERROR_BRAND = Symbol.for("lixnet.error");
13
23
  /** Picks a code for a status that came without one (e.g. `response.code(403)` + `response.error(...)`). */
14
24
  export function codeForStatus(status) {
@@ -19,15 +29,54 @@ export function codeForStatus(status) {
19
29
  }
20
30
  return status >= 500 ? "INTERNAL" : "BAD_REQUEST";
21
31
  }
22
- /** Rebuilds the error a server sent (`{ error, code?, data?, detail? }`) on the client. */
32
+ /**
33
+ * Decodes `value` with the serializer; any failure becomes a `BAD_RESPONSE` `LixnetError` whose
34
+ * `cause` is the decode error. Shared by both clients and `errorFromBody`.
35
+ */
36
+ export function decodeResponse(serializer, value,
37
+ /** The server's URL, for the message. */
38
+ from, status, what = "the response") {
39
+ try {
40
+ return serializer.deserialize(value);
41
+ }
42
+ catch (cause) {
43
+ throw new LixnetError("BAD_RESPONSE", `Could not deserialize ${what} from ${from}`, { status, cause });
44
+ }
45
+ }
46
+ /**
47
+ * The `BAD_RESPONSE` thrown when a response's `serializer` echo isn't the client's serializer name
48
+ * (`expected`, `undefined` for a client without one).
49
+ */
50
+ export function serializerMismatch(from, expected, got, status) {
51
+ const message = got === undefined
52
+ ? `Server at ${from} did not confirm the "${expected}" serializer — is it an older Lixnet or configured without \`serializer\`?`
53
+ : expected === undefined
54
+ ? `Server at ${from} uses the ${JSON.stringify(got)} serializer; give the client the same \`serializer\``
55
+ : `Server at ${from} uses the ${JSON.stringify(got)} serializer, but the client uses "${expected}"`;
56
+ return new LixnetError("BAD_RESPONSE", message, { status });
57
+ }
58
+ /**
59
+ * Rebuilds the error a server sent (`{ error, code?, data?, detail? }`) on the client. Returns a
60
+ * `BAD_RESPONSE` error instead if `data` can't be decoded.
61
+ */
23
62
  export function errorFromBody(body,
24
63
  /** 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
- });
64
+ status,
65
+ /** Decodes `data`; pass it only when the server confirmed the same serializer, else `data` stays raw. */
66
+ serializer,
67
+ /** The server's URL, for messages. */
68
+ from = "the server") {
69
+ const code = body.code ?? codeForStatus(status ?? 500);
70
+ let data = body.data;
71
+ if (serializer && data !== undefined) {
72
+ try {
73
+ data = decodeResponse(serializer, data, from, status, `the data of the "${code}" error (${body.error})`);
74
+ }
75
+ catch (error) {
76
+ return error;
77
+ }
78
+ }
79
+ return new LixnetError(code, body.error, { status, data, cause: body.detail });
31
80
  }
32
81
  /**
33
82
  * An error with a machine-readable `code`, an HTTP `status` and optional JSON `data`.