lixnet 1.5.0 → 1.6.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
@@ -41,7 +41,7 @@ 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
+ - [Inferred contract (`routes` / `server.route`)](#inferred-contract-routes--serverroute)
45
45
  - [Server: `LixnetServer`](#server-lixnetserver)
46
46
  - [Errors](#errors-lixneterror)
47
47
  - [CORS](#cors)
@@ -175,9 +175,9 @@ await client.call(
175
175
  );
176
176
  ```
177
177
 
178
- ## Inferred contract (`server.route`)
178
+ ## Inferred contract (`routes` / `server.route`)
179
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.
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
181
 
182
182
  ```ts
183
183
  // cloudflare/ioServer.ts (worker only)
@@ -186,18 +186,33 @@ import { LixnetServer } from "lixnet";
186
186
  import live from "./(functions)/live";
187
187
 
188
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 });
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
+ });
196
200
  }
197
201
 
198
202
  export type RpcServer = ReturnType<typeof createRpcServer>;
199
203
  ```
200
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
+ `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).
208
+
209
+ `.route(name, { schema?, handler })` does the same one route at a time and can be chained after `routes`, e.g. to add events conditionally:
210
+
211
+ ```ts
212
+ new LixnetServer({ routes: { helloThere: { ... } } })
213
+ .route("live", { handler: live });
214
+ ```
215
+
201
216
  ```ts
202
217
  // cloudflare/io.ts (browser)
203
218
  import type { RpcServer } from "./ioServer"; // type-only: erased at build time
@@ -377,9 +392,37 @@ export default {
377
392
  ```ts
378
393
  const client = new LixnetClient<Events>({
379
394
  rpcUrl: "https://api.example.com/rpc",
395
+ // optional: any fetch-compatible function (defaults to the global fetch)
396
+ fetch: (url, init) => fetch(url, { ...init, credentials: "include" }),
380
397
  });
381
398
  ```
382
399
 
400
+ `fetch` is also how you test or SSR without a network or patching `globalThis.fetch`:
401
+
402
+ ```ts
403
+ const client = new LixnetClient<typeof server>({
404
+ rpcUrl: "http://local/rpc",
405
+ fetch: (url, init) => server.handle(new Request(url, init)),
406
+ });
407
+ ```
408
+
409
+ `LixnetStreamClient` takes the same option.
410
+
411
+ ### Caller (`client.caller`)
412
+
413
+ Every event as a typed function: names autocomplete, input is checked and the result is inferred. Same arguments as `call` (`input`, then `RequestInit` options).
414
+
415
+ ```ts
416
+ const { caller } = rpcClient;
417
+
418
+ const data = await caller.helloThere({ name: "World" }); // { message: string }
419
+ await caller.live(); // input omitted: live takes no client input
420
+
421
+ const { helloThere } = caller; // destructuring works
422
+ ```
423
+
424
+ `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.
425
+
383
426
  ## Handlers: `request` and `response`
384
427
 
385
428
  Handler signature is:
@@ -430,6 +473,45 @@ peer.on("ping", async ({ t, socket }) => {
430
473
  // peer.handle({ data: event.data, socket: ws });
431
474
  ```
432
475
 
476
+ ### Inferred events (`LixnetPeerEvents`)
477
+
478
+ 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).
479
+
480
+ ```ts
481
+ // server/events.ts
482
+ import { z } from "zod";
483
+ import { LixnetPeerEvents } from "lixnet";
484
+
485
+ export const serverEvents = new LixnetPeerEvents({
486
+ routes: {
487
+ hello: {
488
+ schema: z.object({ name: z.string() }),
489
+ handler: ({ name, socket }) => `Hello ${name}`,
490
+ },
491
+ },
492
+ }).route("add", { handler: ({ a, b }: { a: number; b: number }) => a + b });
493
+
494
+ // client/events.ts
495
+ export const clientEvents = new LixnetPeerEvents().route("notify", {
496
+ handler: ({ message }: { message: string }) => console.log(message),
497
+ });
498
+
499
+ // server/socket.ts
500
+ import type { clientEvents } from "../client/events";
501
+ const peer = new LixnetPeer<typeof clientEvents>({ events: serverEvents });
502
+ peer.call("notify", { message: "hi" });
503
+
504
+ // client/socket.ts
505
+ import type { serverEvents } from "../server/events";
506
+ const peer = new LixnetPeer<typeof serverEvents>({ events: clientEvents });
507
+ peer.call("hello", { name: "World" }, { callback: (greeting) => greeting /* string */ });
508
+ ```
509
+
510
+ - `events` is an alias of `routes`, and `.route(...)` chains, exactly like `LixnetServer`. Handlers get `socket` next to their input.
511
+ - With a schema, invalid input never reaches the handler; if the caller passed a `callback`, its `onError` gets a `LixnetError` with code `INVALID_INPUT`.
512
+ - 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.
513
+ - `LixnetPeer<ThisToThere, ThereToThis>` with `on(...)` keeps working.
514
+
433
515
  ### WebSocket setup (typical pattern)
434
516
 
435
517
  ```ts
@@ -473,7 +555,8 @@ From `src/exports.ts`:
473
555
 
474
556
  - **`LixnetServer`**
475
557
  - **`LixnetClient`**
476
- - **`LixnetPeer`**
558
+ - **`LixnetPeer`**, **`LixnetPeerEvents`**
559
+ - **`LixnetStreamServer`**, **`LixnetStreamClient`**
477
560
  - **`LixnetResponse`**
478
561
 
479
562
  Types:
package/dist/exports.d.ts CHANGED
@@ -1,16 +1,20 @@
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
+ export { LixnetServer, LixnetClient, LixnetPeer, LixnetPeerEvents, LixnetStreamServer, LixnetStreamClient, LixnetResponse, LixnetError, LIXNET_ERROR_STATUS, };
9
10
  export type { LixnetErrorCode, LixnetIssue } from "./lib/error";
10
- export type { LixnetRoute, LixnetRoutes, InferLixnetEvents } from "./lib/router";
11
+ export type { LixnetRoute, LixnetRoutes, LixnetRouteDefinitions, LixnetRoutesFromDefinitions, LixnetRouteDefinitionInput, LixnetRoutesOption, InferLixnetEvents, } from "./lib/router";
11
12
  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";
13
+ export type { LXN_ServerClient_EventType, LXNServerHandler, FunctionInput, LXN_ServerClient_Request, LixnetServerInjections, LXNStreamEmitter, LXNCallArgs, LixnetFetch, LixnetClientOptions, LixnetStreamInjections, } from "./lib/types";
14
+ export type { LixnetPeerInjections } from "./lib/peerevents";
15
+ export type { LixnetPeerCallOptions } from "./lib/peer";
16
+ export type { LXNStreamCallOptions, LixnetStreamCaller } from "./lib/streamclient";
17
+ export type { LixnetCaller } from "./lib/client";
14
18
  export type { LixnetServerBaseOptions } from "./lib/serverbase";
15
19
  export type { LixnetCorsOptions } from "./lib/util/cors";
16
20
  export type { StandardSchemaV1 } from "./lib/standardschema";
package/dist/exports.js CHANGED
@@ -2,8 +2,9 @@
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
+ export { LixnetServer, LixnetClient, LixnetPeer, LixnetPeerEvents, LixnetStreamServer, LixnetStreamClient, LixnetResponse, LixnetError, LIXNET_ERROR_STATUS, };
@@ -1,12 +1,21 @@
1
- import type { FunctionInput, LXNCallArgs, LXN_ServerClient_EventType } from "./types";
1
+ import type { FunctionInput, FunctionOutput, LXNCallArgs, LXN_ServerClient_EventType, LixnetClientOptions } from "./types";
2
2
  import type { InferLixnetEvents } from "./router";
3
3
  type ExtractRPCResponse<T> = T extends (...args: any) => infer R ? Awaited<R> : never;
4
+ /** One function per event: `caller.greet({ name })` is `client.call("greet", { name })`. */
5
+ export type LixnetCaller<Events> = {
6
+ [K in keyof Events]: (...args: LXNCallArgs<FunctionInput<Events[K]>, RequestInit>) => Promise<FunctionOutput<Events[K]>>;
7
+ };
4
8
  /** `Contract` is either an events contract or `typeof server` for a server built with `.route(...)`. */
5
9
  export default class LixnetClient<Contract extends LXN_ServerClient_EventType, Events extends LXN_ServerClient_EventType = InferLixnetEvents<Contract>> {
6
10
  private rpcUrl;
7
- constructor({ rpcUrl }: {
8
- rpcUrl: string;
9
- });
11
+ private fetcher?;
12
+ /**
13
+ * Every event as a typed function: `await client.caller.greet({ name: "World" })`.
14
+ * Destructuring works too (`const { greet } = client.caller`). An event named `then` can only
15
+ * be called through `call(...)`.
16
+ */
17
+ readonly caller: LixnetCaller<Events>;
18
+ constructor({ rpcUrl, fetch }: LixnetClientOptions);
10
19
  call<K extends keyof Events>(event: K, ...[input, options]: LXNCallArgs<FunctionInput<Events[K]>, RequestInit>): Promise<ExtractRPCResponse<Events[K]>>;
11
20
  }
12
21
  export {};
@@ -1,13 +1,25 @@
1
1
  import withJsonContentType from "./util/withJsonContentType";
2
+ import createCaller from "./util/createCaller";
2
3
  import { LixnetError, codeForStatus, errorFromBody } from "./error";
3
4
  /** `Contract` is either an events contract or `typeof server` for a server built with `.route(...)`. */
4
5
  export default class LixnetClient {
5
6
  rpcUrl;
6
- constructor({ rpcUrl }) {
7
+ fetcher;
8
+ /**
9
+ * Every event as a typed function: `await client.caller.greet({ name: "World" })`.
10
+ * Destructuring works too (`const { greet } = client.caller`). An event named `then` can only
11
+ * be called through `call(...)`.
12
+ */
13
+ caller;
14
+ constructor({ rpcUrl, fetch }) {
7
15
  this.rpcUrl = rpcUrl;
16
+ this.fetcher = fetch;
17
+ this.caller = createCaller((event, ...args) => this.call(event, ...args));
8
18
  }
9
19
  async call(event, ...[input, options = {}]) {
10
- const response = await fetch(this.rpcUrl, {
20
+ // Called unbound: a native fetch invoked as a method of this client throws "Illegal invocation".
21
+ const send = this.fetcher ?? fetch;
22
+ const response = await send(this.rpcUrl, {
11
23
  ...options,
12
24
  method: "POST",
13
25
  headers: withJsonContentType(options.headers),
@@ -1,3 +1,4 @@
1
+ import type { StandardSchemaV1 } from "./standardschema";
1
2
  /** Built-in error codes and their default HTTP statuses. Any other string is also a valid code. */
2
3
  export declare const LIXNET_ERROR_STATUS: {
3
4
  readonly BAD_REQUEST: 400;
@@ -15,6 +16,8 @@ export type LixnetIssue = {
15
16
  path: (string | number)[];
16
17
  message: string;
17
18
  };
19
+ /** Converts Standard Schema issues into the `LixnetIssue`s sent to the caller. */
20
+ export declare function toIssues(issues: ReadonlyArray<StandardSchemaV1.Issue>): LixnetIssue[];
18
21
  /** Picks a code for a status that came without one (e.g. `response.code(403)` + `response.error(...)`). */
19
22
  export declare function codeForStatus(status: number): LixnetErrorCode;
20
23
  /** Rebuilds the error a server sent (`{ error, code?, data?, detail? }`) on the client. */
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) {
@@ -1,31 +1,50 @@
1
+ import type { InferLixnetEvents } from "./router";
2
+ import type { LXNCallArgs } from "./types";
3
+ import type LixnetPeerEvents from "./peerevents";
4
+ import { LixnetError } from "./error";
1
5
  export type PeerEventInput<T> = T extends (input: infer TInput) => any ? TInput : never;
2
- type Caller<ThisToThereEvents extends Record<string, any>> = <K extends keyof ThisToThereEvents>(event: K, input: PeerEventInput<ThisToThereEvents[K]>, options?: {
3
- callback: ((data: Awaited<ReturnType<ThisToThereEvents[K]>>) => any) | null;
4
- }) => Promise<void>;
5
- export default class LixnetPeer<ThisToThereEvents extends Record<string, any>, ThereToThisEvents extends Record<string, any>, SocketType extends WebSocket = WebSocket> {
6
+ type PeerEventOutput<T> = T extends (...args: any) => infer R ? Awaited<R> : never;
7
+ export type LixnetPeerCallOptions<TOutput> = {
8
+ /** Called with the other peer's handler result. Without it, the event is fire-and-forget. */
9
+ callback?: ((data: TOutput) => any) | null;
10
+ /** Called instead of `callback` when the other peer rejects the call (e.g. invalid input). */
11
+ onError?: (error: LixnetError) => void;
12
+ };
13
+ type Caller<Remote> = <K extends keyof Remote>(event: K, ...args: LXNCallArgs<PeerEventInput<Remote[K]>, LixnetPeerCallOptions<PeerEventOutput<Remote[K]>>>) => Promise<void>;
14
+ /**
15
+ * `ThisToThereEvents` is what this side can call: an events contract, or `typeof otherSideEvents`
16
+ * for a `LixnetPeerEvents`. `ThereToThisEvents` types the legacy `on(...)` handlers; with
17
+ * `events` passed to the constructor it isn't needed.
18
+ */
19
+ export default class LixnetPeer<ThisToThereEvents extends object, ThereToThisEvents extends object = {}, SocketType extends WebSocket = WebSocket> {
6
20
  socket: SocketType | null;
7
21
  rb: {
8
22
  [key: string]: {
9
- method: keyof ThisToThereEvents;
10
- callback: (data: Awaited<ReturnType<ThisToThereEvents[keyof ThisToThereEvents]>>) => any;
23
+ method: PropertyKey;
24
+ callback: (data: any) => any;
25
+ onError?: (error: LixnetError) => void;
11
26
  };
12
27
  };
13
28
  transmissionLimit: number;
14
29
  transmissionChunksLimit: number;
15
30
  setTransmissionChunksLimit(limit: number): void;
16
- call: Caller<ThisToThereEvents>;
31
+ constructor({ events }?: {
32
+ events?: LixnetPeerEvents<any, any, any>;
33
+ });
34
+ call: Caller<InferLixnetEvents<ThisToThereEvents>>;
17
35
  private getChunkLimits;
36
+ /** Handlers by event name, from `events` and `on(...)`. */
18
37
  private eventHandlers;
19
38
  setSocket(socket: SocketType): void;
20
39
  setTransmissionLimit(limit: number): void;
21
40
  on<K extends keyof ThereToThisEvents>(event: K, handler: (input: PeerEventInput<ThereToThisEvents[K]> & {
22
41
  socket: SocketType;
23
- }) => ReturnType<ThereToThisEvents[K]>): void;
42
+ }) => PeerEventOutput<ThereToThisEvents[K]> | Promise<PeerEventOutput<ThereToThisEvents[K]>>): void;
24
43
  transmissions: Record<string, {
25
44
  chunks: Record<number, string>;
26
45
  chunkTimes: Record<number, number>;
27
46
  chunkCount: number;
28
- event: keyof ThereToThisEvents;
47
+ event: PropertyKey;
29
48
  rf: string | null;
30
49
  }>;
31
50
  outgoingTransmissions: Record<string, Record<number, string>>;
package/dist/lib/peer.js CHANGED
@@ -1,7 +1,13 @@
1
1
  import { LIXNET_ID_PREFIX } from "./vars";
2
+ import { errorFromBody, toIssues } from "./error";
2
3
  function createLixnetId() {
3
4
  return LIXNET_ID_PREFIX + Math.random().toString(36).substring(2, 15);
4
5
  }
6
+ /**
7
+ * `ThisToThereEvents` is what this side can call: an events contract, or `typeof otherSideEvents`
8
+ * for a `LixnetPeerEvents`. `ThereToThisEvents` types the legacy `on(...)` handlers; with
9
+ * `events` passed to the constructor it isn't needed.
10
+ */
5
11
  export default class LixnetPeer {
6
12
  socket = null;
7
13
  rb = {};
@@ -10,7 +16,14 @@ export default class LixnetPeer {
10
16
  setTransmissionChunksLimit(limit) {
11
17
  this.transmissionChunksLimit = limit;
12
18
  }
13
- call = async (event, data, { callback } = { callback: null }) => {
19
+ constructor({ events } = {}) {
20
+ if (events)
21
+ Object.assign(this.eventHandlers, events.entries);
22
+ }
23
+ call = async (event, ...args) => {
24
+ const [input, { callback = null, onError } = {}] = args;
25
+ // Like LixnetClient, an omitted input is sent as `{}` so the other side's schema sees an object.
26
+ const data = input === undefined ? {} : input;
14
27
  if (!this.socket)
15
28
  throw new Error("LIXNET - Socket not set");
16
29
  let rf = null;
@@ -19,6 +32,7 @@ export default class LixnetPeer {
19
32
  this.rb[rf] = {
20
33
  method: event,
21
34
  callback: callback,
35
+ onError,
22
36
  };
23
37
  }
24
38
  let dataToSend = {
@@ -85,6 +99,7 @@ export default class LixnetPeer {
85
99
  }
86
100
  return limits;
87
101
  }
102
+ /** Handlers by event name, from `events` and `on(...)`. */
88
103
  eventHandlers = {};
89
104
  setSocket(socket) {
90
105
  this.socket = socket;
@@ -93,7 +108,7 @@ export default class LixnetPeer {
93
108
  this.transmissionLimit = limit;
94
109
  }
95
110
  on(event, handler) {
96
- this.eventHandlers[event] = handler;
111
+ this.eventHandlers[event] = { handler };
97
112
  }
98
113
  transmissions = {};
99
114
  outgoingTransmissions = {};
@@ -237,8 +252,14 @@ export default class LixnetPeer {
237
252
  // Receied callback
238
253
  const callback = this.rb[data.rb];
239
254
  if (callback) {
240
- callback.callback(data.data);
241
255
  delete this.rb[data.rb];
256
+ // Rejected by the other side: `{ rb, error: { error, code, data? } }`.
257
+ if (data.error && typeof data.error === "object") {
258
+ callback.onError?.(errorFromBody(data.error));
259
+ }
260
+ else {
261
+ callback.callback(data.data);
262
+ }
242
263
  }
243
264
  return;
244
265
  }
@@ -251,10 +272,28 @@ export default class LixnetPeer {
251
272
  });
252
273
  }
253
274
  async handleEvent({ eventName, data, rf, socket, }) {
254
- const eventHandler = this.eventHandlers[eventName];
255
- if (!eventHandler)
275
+ // hasOwn so names like "constructor" don't resolve to prototype members.
276
+ if (!Object.hasOwn(this.eventHandlers, eventName))
256
277
  return;
257
- const result = await eventHandler({
278
+ const { handler, schema } = this.eventHandlers[eventName];
279
+ if (schema) {
280
+ const result = await schema["~standard"].validate(data);
281
+ if (result.issues) {
282
+ if (rf) {
283
+ socket.send(JSON.stringify({
284
+ rb: rf,
285
+ error: {
286
+ error: "Invalid input",
287
+ code: "INVALID_INPUT",
288
+ data: { issues: toIssues(result.issues) },
289
+ },
290
+ }));
291
+ }
292
+ return;
293
+ }
294
+ data = result.value;
295
+ }
296
+ const result = await handler({
258
297
  ...(typeof data === "object" ? data : {}),
259
298
  socket,
260
299
  });
@@ -0,0 +1,50 @@
1
+ import type { StandardSchemaV1 } from "./standardschema";
2
+ import type { LixnetRouteDefinitions, LixnetRoute, LixnetRoutes, LixnetRoutesFromDefinitions, LixnetRoutesOption } from "./router";
3
+ /** Injected into every `LixnetPeerEvents` handler next to its input. */
4
+ export type LixnetPeerInjections = {
5
+ socket: WebSocket;
6
+ };
7
+ /** A registered peer event, read by `LixnetPeer` when dispatching. */
8
+ export type LixnetPeerEventEntry = {
9
+ schema?: StandardSchemaV1;
10
+ handler: (input: any) => unknown;
11
+ };
12
+ /**
13
+ * The events one side of a WebSocket handles, with inferred types: the peer counterpart of
14
+ * `LixnetServer`'s `routes` / `.route(...)`.
15
+ *
16
+ * Define each side's events on their own, `import type` the other side's, and pass both to the peer:
17
+ *
18
+ * ```ts
19
+ * // server/events.ts
20
+ * export const serverEvents = new LixnetPeerEvents({
21
+ * routes: { hello: { schema: z.object({ name: z.string() }), handler: ({ name }) => `Hi ${name}` } },
22
+ * });
23
+ *
24
+ * // server/socket.ts
25
+ * import type { clientEvents } from "../client/events";
26
+ * const peer = new LixnetPeer<typeof clientEvents>({ events: serverEvents });
27
+ * ```
28
+ *
29
+ * The events object never refers to the other side's types, so the two sides can import each
30
+ * other's types without a circular type.
31
+ */
32
+ export default class LixnetPeerEvents<Routes extends LixnetRoutes = {}, TSchemas extends Record<string, unknown> = {}, TDefs extends Record<string, {
33
+ handler: (input: any) => unknown;
34
+ }> = {}> {
35
+ /** Type-only: routes from the `routes` option and `.route(...)`, read by `InferLixnetEvents`. */
36
+ readonly "~routes": Routes & LixnetRoutesFromDefinitions<TDefs, LixnetPeerInjections>;
37
+ /** Registered events by name. */
38
+ readonly entries: Record<string, LixnetPeerEventEntry>;
39
+ constructor({ routes, events, }?: LixnetRoutesOption<TDefs & LixnetRouteDefinitions<TSchemas, LixnetPeerInjections>>);
40
+ /** With a schema, the handler gets the schema's output and the other peer sends its input. */
41
+ route<K extends string, TSchema extends StandardSchemaV1, TOutput>(event: K, route: {
42
+ schema: TSchema;
43
+ handler: (input: StandardSchemaV1.InferOutput<TSchema> & LixnetPeerInjections) => TOutput;
44
+ }): LixnetPeerEvents<Routes & Record<K, LixnetRoute<StandardSchemaV1.InferInput<TSchema>, Awaited<TOutput>>>, TSchemas, TDefs>;
45
+ /** Without a schema, the input is the handler's parameter type minus `socket`. */
46
+ route<K extends string, TParams, TOutput>(event: K, route: {
47
+ schema?: undefined;
48
+ handler: (input: TParams) => TOutput;
49
+ }): LixnetPeerEvents<Routes & Record<K, LixnetRoute<Omit<TParams, keyof LixnetPeerInjections>, Awaited<TOutput>>>, TSchemas, TDefs>;
50
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The events one side of a WebSocket handles, with inferred types: the peer counterpart of
3
+ * `LixnetServer`'s `routes` / `.route(...)`.
4
+ *
5
+ * Define each side's events on their own, `import type` the other side's, and pass both to the peer:
6
+ *
7
+ * ```ts
8
+ * // server/events.ts
9
+ * export const serverEvents = new LixnetPeerEvents({
10
+ * routes: { hello: { schema: z.object({ name: z.string() }), handler: ({ name }) => `Hi ${name}` } },
11
+ * });
12
+ *
13
+ * // server/socket.ts
14
+ * import type { clientEvents } from "../client/events";
15
+ * const peer = new LixnetPeer<typeof clientEvents>({ events: serverEvents });
16
+ * ```
17
+ *
18
+ * The events object never refers to the other side's types, so the two sides can import each
19
+ * other's types without a circular type.
20
+ */
21
+ export default class LixnetPeerEvents {
22
+ /** Registered events by name. */
23
+ entries = {};
24
+ constructor({ routes, events, } = {}) {
25
+ for (const [event, route] of Object.entries(routes ?? events ?? {})) {
26
+ this.entries[event] = route;
27
+ }
28
+ }
29
+ route(event, route) {
30
+ this.entries[event] = route;
31
+ return this;
32
+ }
33
+ }
@@ -1,3 +1,5 @@
1
+ import type { StandardSchemaV1 } from "./standardschema";
2
+ import type { LixnetServerInjections } from "./types";
1
3
  /**
2
4
  * Type-level description of a route added with `LixnetServer.route(...)`: the input the
3
5
  * client sends and the output it receives.
@@ -16,3 +18,38 @@ export type InferLixnetEvents<T> = T extends {
16
18
  } ? {
17
19
  [K in keyof TRoutes]: (input: TRoutes[K]["input"]) => TRoutes[K]["output"];
18
20
  } : T;
21
+ type RouteHandlerInput<TSchema, TInjections> = TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> & TInjections : 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, TInjections = LixnetServerInjections> = {
27
+ [K in keyof TSchemas]: {
28
+ schema?: TSchemas[K];
29
+ handler: (input: RouteHandlerInput<TSchemas[K], TInjections>) => unknown;
30
+ };
31
+ };
32
+ /** The input a route definition's caller sends: the schema's input, else the handler's parameter minus injections. */
33
+ export type LixnetRouteDefinitionInput<TDef, TInjections = LixnetServerInjections> = TDef extends {
34
+ schema: infer TSchema extends StandardSchemaV1;
35
+ } ? StandardSchemaV1.InferInput<TSchema> : TDef extends {
36
+ handler: (input: infer TParams) => any;
37
+ } ? Omit<TParams, keyof TInjections> : never;
38
+ /** Turns the `routes` option's type into routes, the same shape `.route(...)` records. */
39
+ export type LixnetRoutesFromDefinitions<TDefs, TInjections = LixnetServerInjections> = {
40
+ [K in keyof TDefs]: TDefs[K] extends {
41
+ handler: (input: any) => infer TOutput;
42
+ } ? LixnetRoute<LixnetRouteDefinitionInput<TDefs[K], TInjections>, Awaited<TOutput>> : never;
43
+ };
44
+ /**
45
+ * `routes` (or its alias `events`) as `{ name: { schema?, handler } }`: the same as calling
46
+ * `.route(name, ...)` for each. Pass one or the other.
47
+ */
48
+ export type LixnetRoutesOption<TRouteDefinitions> = {
49
+ routes?: TRouteDefinitions;
50
+ events?: never;
51
+ } | {
52
+ events?: TRouteDefinitions;
53
+ routes?: never;
54
+ };
55
+ export {};
@@ -3,7 +3,7 @@ import type { FunctionInput, FunctionOutput, LXNEventEntries, LXNEventSchema, LX
3
3
  import { LixnetResponse } from "./util/response";
4
4
  import { type LixnetRequest } from "./util/request";
5
5
  import type { StandardSchemaV1 } from "./standardschema";
6
- import type { LixnetRoute, LixnetRoutes } from "./router";
6
+ import type { LixnetRouteDefinitions, LixnetRoute, LixnetRoutes, LixnetRoutesFromDefinitions, LixnetRoutesOption } from "./router";
7
7
  import type { LixnetServerInjections } from "./types";
8
8
  type LXNServerEventInput<Events extends LXN_ServerClient_EventType, TName extends keyof Events> = {
9
9
  event: TName;
@@ -13,13 +13,15 @@ type LXNServerEventInput<Events extends LXN_ServerClient_EventType, TName extend
13
13
  }, FunctionOutput<Events[TName]>>;
14
14
  schema?: LXNEventSchema<Events, TName>;
15
15
  };
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;
16
+ export default class LixnetServer<Events extends LXN_ServerClient_EventType = LXN_ServerClient_EventType, Routes extends LixnetRoutes = {}, TSchemas extends Record<string, unknown> = {}, TDefs extends Record<string, {
17
+ handler: (input: any) => unknown;
18
+ }> = {}> extends LixnetServerBase<LXNServerEventInput<Events, keyof Events>> {
19
+ /** Type-only: routes from the `routes` option and `.route(...)`, read by `InferLixnetEvents`. */
20
+ readonly "~routes": Routes & LixnetRoutesFromDefinitions<TDefs>;
19
21
  private formatter;
20
- constructor({ formatter, ...options }?: LixnetServerBaseOptions & {
22
+ constructor({ formatter, routes, events, ...options }?: LixnetServerBaseOptions & {
21
23
  formatter?: (this: LixnetResponse) => Response;
22
- });
24
+ } & LixnetRoutesOption<TDefs & LixnetRouteDefinitions<TSchemas>>);
23
25
  /**
24
26
  * Adds an event whose types are inferred, so no `Events` contract is needed. Chain calls and
25
27
  * give the client `typeof server` through an `import type`.
@@ -29,12 +31,12 @@ export default class LixnetServer<Events extends LXN_ServerClient_EventType = LX
29
31
  route<K extends string, TSchema extends StandardSchemaV1, TOutput>(event: K, route: {
30
32
  schema: TSchema;
31
33
  handler: (input: StandardSchemaV1.InferOutput<TSchema> & LixnetServerInjections) => TOutput;
32
- }): LixnetServer<Events, Routes & Record<K, LixnetRoute<StandardSchemaV1.InferInput<TSchema>, Awaited<TOutput>>>>;
34
+ }): LixnetServer<Events, Routes & Record<K, LixnetRoute<StandardSchemaV1.InferInput<TSchema>, Awaited<TOutput>>>, TSchemas, TDefs>;
33
35
  /** Without a schema, the input is the handler's parameter type minus `request`/`response`. */
34
36
  route<K extends string, TParams, TOutput>(event: K, route: {
35
37
  schema?: undefined;
36
38
  handler: (input: TParams) => TOutput;
37
- }): LixnetServer<Events, Routes & Record<K, LixnetRoute<Omit<TParams, keyof LixnetServerInjections>, Awaited<TOutput>>>>;
39
+ }): LixnetServer<Events, Routes & Record<K, LixnetRoute<Omit<TParams, keyof LixnetServerInjections>, Awaited<TOutput>>>, TSchemas, TDefs>;
38
40
  on<K extends keyof Events & string>(input: LXNServerEventInput<Events, K> | LXNEventEntries<Events, {
39
41
  [P in keyof Events & string]: LXNServerEventInput<Events, P>;
40
42
  }>): void;
@@ -4,9 +4,12 @@ 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
+ }
10
13
  }
11
14
  route(event, route) {
12
15
  this.register({ ...route, event });
@@ -16,7 +19,6 @@ export default class LixnetServer extends LixnetServerBase {
16
19
  this.register(input);
17
20
  }
18
21
  async handle(request) {
19
- const requestClone = request.clone();
20
22
  const response = new LixnetResponse({ formatter: this.formatter });
21
23
  const corsResponse = this.handleCors(request, response);
22
24
  if (corsResponse)
@@ -28,7 +30,7 @@ export default class LixnetServer extends LixnetServerBase {
28
30
  try {
29
31
  const data = await parsed.entry.handler({
30
32
  ...parsed.input,
31
- request: createLixnetRequest(requestClone, response),
33
+ request: createLixnetRequest(request, response, parsed.body),
32
34
  response: response,
33
35
  });
34
36
  //check data isnt void/null/undefined
@@ -33,10 +33,12 @@ type Failure = {
33
33
  cause?: unknown;
34
34
  event?: string;
35
35
  };
36
+ /** `body` is the raw request body, kept so handlers can re-read it without `request.clone()`. */
36
37
  type ParsedRpcRequest<TEntry> = {
37
38
  ok: true;
38
39
  entry: TEntry;
39
40
  input: any;
41
+ body: string;
40
42
  } | ({
41
43
  ok: false;
42
44
  } & Failure);
@@ -1,15 +1,6 @@
1
1
  import LixnetLog from "./util/log";
2
- import { LixnetError } from "./error";
2
+ import { LixnetError, toIssues } from "./error";
3
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
- }
13
4
  function describeError(cause) {
14
5
  if (cause === undefined)
15
6
  return undefined;
@@ -44,9 +35,12 @@ export default class LixnetServerBase {
44
35
  }
45
36
  }
46
37
  async parse(request) {
38
+ // Read once as text: handlers get it back through LixnetRequest's body methods.
39
+ let body;
47
40
  let json;
48
41
  try {
49
- json = await request.json();
42
+ body = await request.text();
43
+ json = JSON.parse(body);
50
44
  }
51
45
  catch (cause) {
52
46
  return { ok: false, error: "Invalid JSON", status: 400, code: "BAD_REQUEST", cause };
@@ -72,7 +66,7 @@ export default class LixnetServerBase {
72
66
  }
73
67
  const entry = this.events[json.event];
74
68
  if (!entry.schema) {
75
- return { ok: true, entry, input: json.input };
69
+ return { ok: true, entry, input: json.input, body };
76
70
  }
77
71
  const result = await entry.schema["~standard"].validate(json.input);
78
72
  if (result.issues) {
@@ -87,7 +81,7 @@ export default class LixnetServerBase {
87
81
  event: json.event,
88
82
  };
89
83
  }
90
- return { ok: true, entry, input: result.value };
84
+ return { ok: true, entry, input: result.value, body };
91
85
  }
92
86
  /**
93
87
  * With `cors` set: answers preflights and rejects disallowed origins (returns the Response),
@@ -1,4 +1,4 @@
1
- import type { FunctionInput, FunctionOutput, LXNCallArgs, LXN_ServerClient_EventType } from "./types";
1
+ import type { FunctionInput, FunctionOutput, LXNCallArgs, LXN_ServerClient_EventType, LixnetClientOptions } from "./types";
2
2
  import type { InferLixnetEvents } from "./router";
3
3
  type Prettify<T> = {
4
4
  [K in keyof T]: T[K];
@@ -6,11 +6,16 @@ type Prettify<T> = {
6
6
  export type LXNStreamCallOptions<TChunk> = Prettify<{
7
7
  onStreamChunk?: (chunk: TChunk) => void;
8
8
  } & Omit<RequestInit, "method" | "body">>;
9
+ /** One function per stream event: `caller.generate(input, { onStreamChunk })` is `client.call("generate", ...)`. */
10
+ export type LixnetStreamCaller<Events> = {
11
+ [K in keyof Events]: (...args: LXNCallArgs<FunctionInput<Events[K]>, LXNStreamCallOptions<FunctionOutput<Events[K]>>>) => Promise<void>;
12
+ };
9
13
  export default class LixnetStreamClient<Contract extends LXN_ServerClient_EventType, Events extends LXN_ServerClient_EventType = InferLixnetEvents<Contract>> {
10
14
  private rpcUrl;
11
- constructor({ rpcUrl }: {
12
- rpcUrl: string;
13
- });
15
+ private fetcher?;
16
+ /** Every stream event as a typed function, like `LixnetClient.caller`. */
17
+ readonly caller: LixnetStreamCaller<Events>;
18
+ constructor({ rpcUrl, fetch }: LixnetClientOptions);
14
19
  /** Resolves when the stream ends; throws if the server returns or streams an error. */
15
20
  call<K extends keyof Events>(event: K, ...[input, options]: LXNCallArgs<FunctionInput<Events[K]>, LXNStreamCallOptions<FunctionOutput<Events[K]>>>): Promise<void>;
16
21
  }
@@ -1,14 +1,22 @@
1
1
  import withJsonContentType from "./util/withJsonContentType";
2
+ import createCaller from "./util/createCaller";
2
3
  import { LixnetError, codeForStatus, errorFromBody } from "./error";
3
4
  export default class LixnetStreamClient {
4
5
  rpcUrl;
5
- constructor({ rpcUrl }) {
6
+ fetcher;
7
+ /** Every stream event as a typed function, like `LixnetClient.caller`. */
8
+ caller;
9
+ constructor({ rpcUrl, fetch }) {
6
10
  this.rpcUrl = rpcUrl;
11
+ this.fetcher = fetch;
12
+ this.caller = createCaller((event, ...args) => this.call(event, ...args));
7
13
  }
8
14
  /** Resolves when the stream ends; throws if the server returns or streams an error. */
9
15
  async call(event, ...[input, options = {}]) {
10
16
  const { onStreamChunk, ...fetchOptions } = options;
11
- const response = await fetch(this.rpcUrl, {
17
+ // Called unbound: a native fetch invoked as a method of this client throws "Illegal invocation".
18
+ const send = this.fetcher ?? fetch;
19
+ const response = await send(this.rpcUrl, {
12
20
  ...fetchOptions,
13
21
  method: "POST",
14
22
  headers: withJsonContentType(fetchOptions.headers),
@@ -1,19 +1,51 @@
1
1
  import LixnetServerBase, { type LixnetServerBaseOptions } from "./serverbase";
2
- import type { FunctionInput, FunctionOutput, LXN_ServerClient_EventType, LXNEventEntries, LXNEventSchema, LXNStreamEmitter } from "./types";
2
+ import type { FunctionInput, FunctionOutput, LXN_ServerClient_EventType, LXNEventEntries, LXNEventSchema, LXNStreamEmitter, LixnetStreamInjections } from "./types";
3
3
  import { LixnetResponse } from "./util/response";
4
4
  import { type LixnetRequest } from "./util/request";
5
+ import type { StandardSchemaV1 } from "./standardschema";
6
+ import type { LixnetRouteDefinitionInput, LixnetRouteDefinitions, LixnetRoute, LixnetRoutes, LixnetRoutesOption } from "./router";
5
7
  type LXNStreamServerEventInput<Events extends LXN_ServerClient_EventType, K extends keyof Events> = {
6
8
  event: K;
7
9
  handler: (input: FunctionInput<Events[K]> & {
8
10
  request: LixnetRequest;
9
11
  response: LixnetResponse;
10
12
  stream: LXNStreamEmitter<FunctionOutput<Events[K]>>;
11
- }) => Promise<void> | void;
13
+ }) => unknown;
12
14
  schema?: LXNEventSchema<Events, K>;
13
15
  };
14
- export default class LixnetStreamServer<Events extends LXN_ServerClient_EventType> extends LixnetServerBase<LXNStreamServerEventInput<Events, keyof Events>> {
16
+ /**
17
+ * A stream route's chunk type: what the handler yields when it's a generator, else the chunk type
18
+ * of a `stream` it annotates (`stream: LXNStreamEmitter<T>`), else `unknown`.
19
+ */
20
+ type StreamChunk<TResult, TParams> = TResult extends AsyncIterable<infer TChunk> | Generator<infer TChunk> ? TChunk : TParams extends {
21
+ stream: LXNStreamEmitter<infer TChunk>;
22
+ } ? TChunk : unknown;
23
+ type StreamRoutesFromDefinitions<TDefs> = {
24
+ [K in keyof TDefs]: TDefs[K] extends {
25
+ handler: (input: infer TParams) => infer TResult;
26
+ } ? LixnetRoute<LixnetRouteDefinitionInput<TDefs[K], LixnetStreamInjections>, StreamChunk<TResult, TParams>> : never;
27
+ };
28
+ export default class LixnetStreamServer<Events extends LXN_ServerClient_EventType = LXN_ServerClient_EventType, Routes extends LixnetRoutes = {}, TSchemas extends Record<string, unknown> = {}, TDefs extends Record<string, {
29
+ handler: (input: any) => unknown;
30
+ }> = {}> extends LixnetServerBase<LXNStreamServerEventInput<Events, keyof Events>> {
31
+ /** Type-only: routes from the `routes` option and `.route(...)`, read by `InferLixnetEvents`. */
32
+ readonly "~routes": Routes & StreamRoutesFromDefinitions<TDefs>;
15
33
  private errorFormatter;
16
- constructor(options?: LixnetServerBaseOptions);
34
+ constructor({ routes, events, ...options }?: LixnetServerBaseOptions & LixnetRoutesOption<TDefs & LixnetRouteDefinitions<TSchemas, LixnetStreamInjections>>);
35
+ /**
36
+ * Adds a stream event whose types are inferred. The client's chunk type is what the handler
37
+ * yields (`async function* () { yield chunk }`), or, with `stream.emit(...)`, the type of an
38
+ * annotated `stream: LXNStreamEmitter<T>` parameter.
39
+ */
40
+ route<K extends string, TSchema extends StandardSchemaV1, TResult>(event: K, route: {
41
+ schema: TSchema;
42
+ handler: (input: StandardSchemaV1.InferOutput<TSchema> & LixnetStreamInjections) => TResult;
43
+ }): LixnetStreamServer<Events, Routes & Record<K, LixnetRoute<StandardSchemaV1.InferInput<TSchema>, StreamChunk<TResult, unknown>>>, TSchemas, TDefs>;
44
+ /** Without a schema, the input is the handler's parameter type minus `request`/`response`/`stream`. */
45
+ route<K extends string, TParams, TResult>(event: K, route: {
46
+ schema?: undefined;
47
+ handler: (input: TParams) => TResult;
48
+ }): LixnetStreamServer<Events, Routes & Record<K, LixnetRoute<Omit<TParams, keyof LixnetStreamInjections>, StreamChunk<TResult, TParams>>>, TSchemas, TDefs>;
17
49
  on<K extends keyof Events & string>(input: LXNStreamServerEventInput<Events, K> | LXNEventEntries<Events, {
18
50
  [P in keyof Events & string]: LXNStreamServerEventInput<Events, P>;
19
51
  }>): void;
@@ -2,17 +2,30 @@ import LixnetServerBase from "./serverbase";
2
2
  import { LixnetResponse } from "./util/response";
3
3
  import { createLixnetRequest } from "./util/request";
4
4
  import getDefaultFormatter, { buildResponseHeaders, errorBody } from "./util/getDefaultFormatter";
5
+ function isIterable(value) {
6
+ if (value === null || typeof value !== "object")
7
+ return false;
8
+ // Sync iterables only when they're generators, so a returned array isn't streamed by accident.
9
+ return (typeof value[Symbol.asyncIterator] === "function" ||
10
+ (typeof value[Symbol.iterator] === "function" && typeof value.next === "function"));
11
+ }
5
12
  export default class LixnetStreamServer extends LixnetServerBase {
6
13
  errorFormatter;
7
- constructor(options = {}) {
14
+ constructor({ routes, events, ...options } = {}) {
8
15
  super(options);
9
16
  this.errorFormatter = getDefaultFormatter(this.defaultHeaders);
17
+ for (const [event, route] of Object.entries(routes ?? events ?? {})) {
18
+ this.register({ ...route, event });
19
+ }
20
+ }
21
+ route(event, route) {
22
+ this.register({ ...route, event });
23
+ return this;
10
24
  }
11
25
  on(input) {
12
26
  this.register(input);
13
27
  }
14
28
  async handle(request) {
15
- const requestClone = request.clone();
16
29
  const response = new LixnetResponse({ formatter: this.errorFormatter });
17
30
  const corsResponse = this.handleCors(request, response);
18
31
  if (corsResponse)
@@ -23,7 +36,7 @@ export default class LixnetStreamServer extends LixnetServerBase {
23
36
  }
24
37
  const event = parsed.entry;
25
38
  const validatedInput = parsed.input;
26
- const newRequest = createLixnetRequest(requestClone, response);
39
+ const newRequest = createLixnetRequest(request, response, parsed.body);
27
40
  const encoder = new TextEncoder();
28
41
  const abort = new AbortController();
29
42
  let controller;
@@ -66,7 +79,15 @@ export default class LixnetStreamServer extends LixnetServerBase {
66
79
  };
67
80
  (async () => {
68
81
  try {
69
- await event.handler({ ...validatedInput, request: newRequest, response, stream });
82
+ const result = await event.handler({ ...validatedInput, request: newRequest, response, stream });
83
+ // Generator handlers: each yielded value is a chunk. Stops early if the client disconnects.
84
+ if (isIterable(result)) {
85
+ for await (const chunk of result) {
86
+ if (closed)
87
+ break;
88
+ stream.emit(chunk);
89
+ }
90
+ }
70
91
  start();
71
92
  }
72
93
  catch (error) {
@@ -17,6 +17,16 @@ export type FunctionOutput<T> = T extends (...args: any) => infer R ? Awaited<R>
17
17
  export type LXNCallArgs<TInput, TOptions> = {} extends TInput ? [input?: TInput, options?: TOptions] : [input: TInput, options?: TOptions];
18
18
  export type LXNServerHandler<Input, Output> = (input: Input) => Promise<Output> | Output;
19
19
  export type LXN_ServerClient_EventType = object;
20
+ /**
21
+ * The `fetch` a client sends requests with. Any `fetch`-compatible function works, e.g. a
22
+ * wrapper adding auth, or `(url, init) => server.handle(new Request(url, init))` for tests and SSR.
23
+ */
24
+ export type LixnetFetch = (url: string, init: RequestInit) => Promise<Response>;
25
+ export type LixnetClientOptions = {
26
+ rpcUrl: string;
27
+ /** Defaults to the global `fetch`, looked up on every call. */
28
+ fetch?: LixnetFetch;
29
+ };
20
30
  /** A schema whose parsed output must match the event's declared input type. */
21
31
  export type LXNEventSchema<Events, K extends keyof Events> = StandardSchemaV1<any, FunctionInput<Events[K]>>;
22
32
  /** One registration per event name, so arrays passed to `on()` are typed per element. */
@@ -36,3 +46,6 @@ export type LXNStreamEmitter<TChunk> = {
36
46
  /** Aborted when the client disconnects; `emit` becomes a no-op from then on. */
37
47
  signal: AbortSignal;
38
48
  };
49
+ export type LixnetStreamInjections = LixnetServerInjections & {
50
+ stream: LXNStreamEmitter<unknown>;
51
+ };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * A Proxy where every property is a function calling that event: `caller.greet(input, options)`
3
+ * is `call("greet", input, options)`. `then` (and symbols) read as undefined, so the caller isn't
4
+ * mistaken for a Promise when awaited or returned from an async function.
5
+ */
6
+ export default function createCaller<T>(call: (event: string, ...args: any[]) => unknown): T;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * A Proxy where every property is a function calling that event: `caller.greet(input, options)`
3
+ * is `call("greet", input, options)`. `then` (and symbols) read as undefined, so the caller isn't
4
+ * mistaken for a Promise when awaited or returned from an async function.
5
+ */
6
+ export default function createCaller(call) {
7
+ const functions = new Map();
8
+ return new Proxy(Object.create(null), {
9
+ get(_, event) {
10
+ if (typeof event !== "string" || event === "then")
11
+ return undefined;
12
+ let fn = functions.get(event);
13
+ if (!fn) {
14
+ fn = (...args) => call(event, ...args);
15
+ functions.set(event, fn);
16
+ }
17
+ return fn;
18
+ },
19
+ });
20
+ }
@@ -68,9 +68,14 @@ export declare function wrapLixnetRequest(request: Request, response: {
68
68
  value?: string;
69
69
  options?: unknown;
70
70
  }>;
71
- }): LixnetRequest;
71
+ },
72
+ /**
73
+ * The request body, when the server already read it. Body methods (`json()`, `text()`,
74
+ * `body`, `clone()`, ...) are then served from it, so the request never needs cloning.
75
+ */
76
+ body?: string): LixnetRequest;
72
77
  /** Wraps `request` so its cookie/header writes are staged on `response`. */
73
- export declare function createLixnetRequest(request: Request, response: LixnetResponse): LixnetRequest;
78
+ export declare function createLixnetRequest(request: Request, response: LixnetResponse, body?: string): LixnetRequest;
74
79
  /** @deprecated Use {@link LixnetCookies}. */
75
80
  export type ReadonlyRequestCookies = LixnetCookies;
76
81
  /** @deprecated Use {@link LixnetHeaders}. */
@@ -125,7 +125,8 @@ export class LixnetHeaders {
125
125
  h;
126
126
  mut;
127
127
  constructor(headers, mut) {
128
- this.h = new Headers(headers);
128
+ // Not copied: incoming request headers are immutable, and writes go to the response.
129
+ this.h = headers;
129
130
  this.mut = mut;
130
131
  }
131
132
  get(name) {
@@ -206,9 +207,32 @@ export class LixnetHeaders {
206
207
  this.mut.deleteHeader(name);
207
208
  }
208
209
  }
210
+ /** `Request` body readers answered from the already-read body instead of the (consumed) stream. */
211
+ function bodyReaders(request, body) {
212
+ let bytes;
213
+ const getBytes = () => (bytes ??= new TextEncoder().encode(body));
214
+ let stream;
215
+ return {
216
+ text: async () => body,
217
+ json: async () => JSON.parse(body),
218
+ bytes: async () => getBytes().slice(),
219
+ arrayBuffer: async () => getBytes().slice().buffer,
220
+ blob: async () => new Blob([body], { type: request.headers.get("content-type") ?? "" }),
221
+ formData: () => new Response(body, { headers: request.headers }).formData(),
222
+ clone: () => new Request(request, { body }),
223
+ get body() {
224
+ return (stream ??= new Response(body).body);
225
+ },
226
+ bodyUsed: false,
227
+ };
228
+ }
209
229
  /** Used by the server only; not part of the public package API. */
210
- export function wrapLixnetRequest(request, response) {
211
- const snapshot = new Headers(request.headers);
230
+ export function wrapLixnetRequest(request, response,
231
+ /**
232
+ * The request body, when the server already read it. Body methods (`json()`, `text()`,
233
+ * `body`, `clone()`, ...) are then served from it, so the request never needs cloning.
234
+ */
235
+ body) {
212
236
  const cookieMut = {
213
237
  setCookie: (name, value, options) => response.cookie(name, value, options),
214
238
  deleteCookie: (name, options) => response.deleteCookie(name, options),
@@ -234,18 +258,20 @@ export function wrapLixnetRequest(request, response) {
234
258
  return out;
235
259
  },
236
260
  };
261
+ // Created on first use: most handlers never touch cookies or headers.
262
+ let cookies;
263
+ let headers;
264
+ const injected = {
265
+ cookies: () => (cookies ??= new LixnetCookies(request.headers.get("cookie"), cookieMut)),
266
+ headers: () => (headers ??= new LixnetHeaders(request.headers, headerMut)),
267
+ };
268
+ const readers = body === undefined ? undefined : bodyReaders(request, body);
237
269
  return new Proxy(request, {
238
270
  get(target, prop, receiver) {
239
- if (prop === "cookies") {
240
- return function cookies() {
241
- return new LixnetCookies(snapshot.get("cookie"), cookieMut);
242
- };
243
- }
244
- if (prop === "headers") {
245
- return function headers() {
246
- return new LixnetHeaders(snapshot, headerMut);
247
- };
248
- }
271
+ if (prop in injected)
272
+ return injected[prop];
273
+ if (readers && prop in readers)
274
+ return readers[prop];
249
275
  // `receiver` here is this Proxy itself, not `target`. Native accessor properties
250
276
  // (e.g. Workers' `Request.prototype.cf`) are branded getters that check `this` is
251
277
  // the real internal object — invoking them with the Proxy as receiver throws
@@ -255,14 +281,7 @@ export function wrapLixnetRequest(request, response) {
255
281
  });
256
282
  }
257
283
  /** Wraps `request` so its cookie/header writes are staged on `response`. */
258
- export function createLixnetRequest(request, response) {
259
- return wrapLixnetRequest(request, {
260
- header: response.header.bind(response),
261
- deleteHeader: response.deleteHeader.bind(response),
262
- cookie: response.cookie.bind(response),
263
- deleteCookie: response.deleteCookie.bind(response),
264
- responseHeaders: response.responseHeaders,
265
- responseHeaderDeletes: response.responseHeaderDeletes,
266
- responseCookies: response.responseCookies,
267
- });
284
+ export function createLixnetRequest(request, response, body) {
285
+ // LixnetResponse has every member wrapLixnetRequest needs; it's only ever called as a method.
286
+ return wrapLixnetRequest(request, response, body);
268
287
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lixnet",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "author": "nitlix-hq",
5
5
  "license": "MIT",
6
6
  "repository": {