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 +206 -4
- package/dist/exports.d.ts +14 -4
- package/dist/exports.js +5 -1
- package/dist/lib/client.d.ts +23 -4
- package/dist/lib/client.js +51 -7
- package/dist/lib/error.d.ts +25 -2
- package/dist/lib/error.js +56 -7
- package/dist/lib/middleware.d.ts +88 -0
- package/dist/lib/middleware.js +60 -0
- package/dist/lib/peer.d.ts +37 -9
- package/dist/lib/peer.js +75 -7
- package/dist/lib/peerevents.d.ts +50 -0
- package/dist/lib/peerevents.js +33 -0
- package/dist/lib/router.d.ts +39 -10
- package/dist/lib/serializer.d.ts +35 -0
- package/dist/lib/serializer.js +385 -0
- package/dist/lib/server.d.ts +38 -31
- package/dist/lib/server.js +17 -8
- package/dist/lib/serverbase.d.ts +44 -3
- package/dist/lib/serverbase.js +92 -29
- package/dist/lib/streamclient.d.ts +10 -4
- package/dist/lib/streamclient.js +48 -13
- package/dist/lib/streamserver.d.ts +64 -7
- package/dist/lib/streamserver.js +139 -16
- package/dist/lib/types.d.ts +37 -1
- package/dist/lib/util/createCaller.d.ts +6 -0
- package/dist/lib/util/createCaller.js +20 -0
- package/dist/lib/util/getDefaultFormatter.d.ts +33 -4
- package/dist/lib/util/getDefaultFormatter.js +99 -16
- package/dist/lib/util/request.d.ts +7 -2
- package/dist/lib/util/request.js +42 -23
- package/dist/lib/util/response.d.ts +12 -2
- package/dist/lib/util/response.js +12 -4
- package/package.json +7 -1
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import type { LixnetRequest } from "./util/request";
|
|
2
|
+
import type { LixnetResponse } from "./util/response";
|
|
3
|
+
/**
|
|
4
|
+
* What `next()` resolves to: the handler's (or the next middleware's) `output`. Return it from the
|
|
5
|
+
* middleware. `~ctx` is type-only: it carries the context this middleware added.
|
|
6
|
+
*/
|
|
7
|
+
export type LixnetMiddlewareResult<TAdd = {}> = {
|
|
8
|
+
output: unknown;
|
|
9
|
+
readonly "~ctx"?: TAdd;
|
|
10
|
+
};
|
|
11
|
+
/** Runs the rest of the chain. Fields passed in are merged into `ctx` for everything after it. */
|
|
12
|
+
export type LixnetNext = <TAdd extends object = {}>(add?: TAdd) => Promise<LixnetMiddlewareResult<TAdd>>;
|
|
13
|
+
export type LixnetMiddlewareOptions<TCtx = any> = {
|
|
14
|
+
request: LixnetRequest;
|
|
15
|
+
response: LixnetResponse;
|
|
16
|
+
/** The event being called. */
|
|
17
|
+
event: string;
|
|
18
|
+
/**
|
|
19
|
+
* The input, deserialized but **not yet validated**: the route's schema runs after all
|
|
20
|
+
* middleware, right before the handler. Treat it as untrusted.
|
|
21
|
+
*/
|
|
22
|
+
input: unknown;
|
|
23
|
+
/** Context added by the middleware that ran before this one. */
|
|
24
|
+
ctx: TCtx;
|
|
25
|
+
next: LixnetNext;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Runs before a handler. Call `next()` (optionally with fields to add to `ctx`) and return its
|
|
29
|
+
* result, throw (e.g. a `LixnetError`) to reject the call, or return `{ output }` to answer
|
|
30
|
+
* without running the handler.
|
|
31
|
+
*/
|
|
32
|
+
export type LixnetMiddleware<TAdd extends object = {}, TCtx = any> = (options: LixnetMiddlewareOptions<TCtx>) => LixnetMiddlewareResult<TAdd> | Promise<LixnetMiddlewareResult<TAdd>>;
|
|
33
|
+
type ContextAddedBy<M> = M extends (options: any) => infer R ? Awaited<R> extends LixnetMiddlewareResult<infer TAdd> ? TAdd : {} : {};
|
|
34
|
+
type UnionToIntersection<U> = (U extends any ? (x: U) => void : never) extends (x: infer I) => void ? I : never;
|
|
35
|
+
/**
|
|
36
|
+
* The `ctx` a list of middleware gives the handler: everything each one adds. The bare
|
|
37
|
+
* `LixnetMiddleware[]` constraint (an omitted, uninferred `use`) adds nothing.
|
|
38
|
+
*/
|
|
39
|
+
export type LixnetMiddlewareContext<TUse> = readonly LixnetMiddleware<any, any>[] extends TUse ? {} : TUse extends readonly (infer M)[] ? [M] extends [never] ? {} : UnionToIntersection<ContextAddedBy<M>> : {};
|
|
40
|
+
/** The `ctx` a middleware reads: its options' `ctx` type (`any` when it doesn't annotate one). */
|
|
41
|
+
type ContextRequiredBy<M> = M extends (options: infer O) => any ? O extends {
|
|
42
|
+
ctx: infer TCtx;
|
|
43
|
+
} ? TCtx : any : any;
|
|
44
|
+
/**
|
|
45
|
+
* Checks a `use` list against the `ctx` available before it, in order: each middleware may read
|
|
46
|
+
* `TCtx` plus what the ones before it add. A valid list maps to itself; a middleware whose `ctx`
|
|
47
|
+
* isn't provided maps to `LixnetMiddleware<any, …ctx it would get>`, so the compile error points at
|
|
48
|
+
* it and names the missing fields. Non-tuple arrays are checked against `TCtx` only.
|
|
49
|
+
*/
|
|
50
|
+
export type LixnetCheckMiddleware<TUse, TCtx> = TUse extends readonly [infer M, ...infer Rest] ? readonly [
|
|
51
|
+
TCtx extends ContextRequiredBy<M> ? M : LixnetMiddleware<any, TCtx>,
|
|
52
|
+
...LixnetCheckMiddleware<Rest, TCtx & ContextAddedBy<M>>
|
|
53
|
+
] : readonly LixnetMiddleware<any, TCtx>[];
|
|
54
|
+
/**
|
|
55
|
+
* Intersected into a route (or options) object whose `use` is `TUse`: `{}` when the list passes
|
|
56
|
+
* {@link LixnetCheckMiddleware}, otherwise `{ use: <checked list> }`, so the error lands on the
|
|
57
|
+
* offending middleware while `TUse` (and the handler's `ctx`) is still inferred from `use` alone.
|
|
58
|
+
*/
|
|
59
|
+
export type LixnetUseCheck<TUse, TCtx> = TUse extends readonly unknown[] ? TUse extends LixnetCheckMiddleware<TUse, TCtx> ? {} : {
|
|
60
|
+
use?: LixnetCheckMiddleware<TUse, TCtx>;
|
|
61
|
+
} : {};
|
|
62
|
+
/** {@link LixnetUseCheck} for each entry of the `routes` constructor option (`TUses`: each entry's `use`). */
|
|
63
|
+
export type LixnetRouteUsesCheck<TUses, TCtx> = {
|
|
64
|
+
[K in Extract<keyof TUses, string>]: LixnetUseCheck<TUses[K], TCtx>;
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Types a middleware defined on its own, so the context it adds is inferred:
|
|
68
|
+
*
|
|
69
|
+
* ```ts
|
|
70
|
+
* const auth = lixnetMiddleware(async ({ request, next }) => {
|
|
71
|
+
* const user = await getUser(request.cookies().get("session")?.value);
|
|
72
|
+
* if (!user) throw new LixnetError("UNAUTHORIZED");
|
|
73
|
+
* return next({ user });
|
|
74
|
+
* });
|
|
75
|
+
* ```
|
|
76
|
+
*
|
|
77
|
+
* To read context added by an earlier middleware, annotate the options:
|
|
78
|
+
* `async ({ ctx, next }: LixnetMiddlewareOptions<{ user: User }>) => ...`.
|
|
79
|
+
*/
|
|
80
|
+
export declare function lixnetMiddleware<TAdd extends object = {}, TCtx = any>(middleware: LixnetMiddleware<TAdd, TCtx>): LixnetMiddleware<TAdd, TCtx>;
|
|
81
|
+
/** Runs `stack` in order, then `handler` with the merged context. Resolves to the final output. */
|
|
82
|
+
export declare function runMiddleware(stack: readonly LixnetMiddleware<any, any>[], base: {
|
|
83
|
+
request: LixnetRequest;
|
|
84
|
+
response: LixnetResponse;
|
|
85
|
+
event: string;
|
|
86
|
+
input: unknown;
|
|
87
|
+
}, handler: (ctx: object) => unknown): Promise<unknown>;
|
|
88
|
+
export {};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Types a middleware defined on its own, so the context it adds is inferred:
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* const auth = lixnetMiddleware(async ({ request, next }) => {
|
|
6
|
+
* const user = await getUser(request.cookies().get("session")?.value);
|
|
7
|
+
* if (!user) throw new LixnetError("UNAUTHORIZED");
|
|
8
|
+
* return next({ user });
|
|
9
|
+
* });
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* To read context added by an earlier middleware, annotate the options:
|
|
13
|
+
* `async ({ ctx, next }: LixnetMiddlewareOptions<{ user: User }>) => ...`.
|
|
14
|
+
*/
|
|
15
|
+
export function lixnetMiddleware(middleware) {
|
|
16
|
+
return middleware;
|
|
17
|
+
}
|
|
18
|
+
const noop = () => { };
|
|
19
|
+
/** `next()` lifecycle per middleware. */
|
|
20
|
+
const IDLE = 0;
|
|
21
|
+
const CALLED = 1;
|
|
22
|
+
const RETURNED = 2;
|
|
23
|
+
/** Runs `stack` in order, then `handler` with the merged context. Resolves to the final output. */
|
|
24
|
+
export async function runMiddleware(stack, base, handler) {
|
|
25
|
+
const run = async (index, ctx) => {
|
|
26
|
+
if (index === stack.length)
|
|
27
|
+
return { output: await handler(ctx) };
|
|
28
|
+
let state = IDLE;
|
|
29
|
+
let result;
|
|
30
|
+
try {
|
|
31
|
+
result = await stack[index]({
|
|
32
|
+
...base,
|
|
33
|
+
ctx,
|
|
34
|
+
next: (add) => {
|
|
35
|
+
let promise;
|
|
36
|
+
if (state === IDLE) {
|
|
37
|
+
state = CALLED;
|
|
38
|
+
promise = run(index + 1, add ? { ...ctx, ...add } : ctx);
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
const misuse = state === CALLED ? "more than once" : "after the middleware returned";
|
|
42
|
+
promise = Promise.reject(new Error(`Lixnet middleware called next() ${misuse} (event "${base.event}")`));
|
|
43
|
+
}
|
|
44
|
+
// An un-awaited next() must never become an unhandled rejection; awaiting still rejects.
|
|
45
|
+
promise.catch(noop);
|
|
46
|
+
return promise;
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
// Thrown or returned: the response is decided, so the rest of the chain must not run.
|
|
52
|
+
state = RETURNED;
|
|
53
|
+
}
|
|
54
|
+
if (result === null || typeof result !== "object" || !("output" in result)) {
|
|
55
|
+
throw new Error(`Lixnet middleware must return the result of next() or { output } (event "${base.event}")`);
|
|
56
|
+
}
|
|
57
|
+
return result;
|
|
58
|
+
};
|
|
59
|
+
return (await run(0, {})).output;
|
|
60
|
+
}
|
package/dist/lib/peer.d.ts
CHANGED
|
@@ -1,31 +1,59 @@
|
|
|
1
|
+
import type { InferLixnetEvents } from "./router";
|
|
2
|
+
import type { LXNCallArgs } from "./types";
|
|
3
|
+
import type LixnetPeerEvents from "./peerevents";
|
|
4
|
+
import { LixnetError } from "./error";
|
|
5
|
+
import type { LixnetSerializer } from "./serializer";
|
|
1
6
|
export type PeerEventInput<T> = T extends (input: infer TInput) => any ? TInput : never;
|
|
2
|
-
type
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
7
|
+
type PeerEventOutput<T> = T extends (...args: any) => infer R ? Awaited<R> : never;
|
|
8
|
+
export type LixnetPeerCallOptions<TOutput> = {
|
|
9
|
+
/** Called with the other peer's handler result. Without it, the event is fire-and-forget. */
|
|
10
|
+
callback?: ((data: TOutput) => any) | null;
|
|
11
|
+
/** Called instead of `callback` when the other peer rejects the call (e.g. invalid input). */
|
|
12
|
+
onError?: (error: LixnetError) => void;
|
|
13
|
+
};
|
|
14
|
+
type Caller<Remote> = <K extends keyof Remote>(event: K, ...args: LXNCallArgs<PeerEventInput<Remote[K]>, LixnetPeerCallOptions<PeerEventOutput<Remote[K]>>>) => Promise<void>;
|
|
15
|
+
/**
|
|
16
|
+
* `ThisToThereEvents` is what this side can call: an events contract, or `typeof otherSideEvents`
|
|
17
|
+
* for a `LixnetPeerEvents`. `ThereToThisEvents` types the legacy `on(...)` handlers; with
|
|
18
|
+
* `events` passed to the constructor it isn't needed.
|
|
19
|
+
*/
|
|
20
|
+
export default class LixnetPeer<ThisToThereEvents extends object, ThereToThisEvents extends object = {}, SocketType extends WebSocket = WebSocket> {
|
|
6
21
|
socket: SocketType | null;
|
|
7
22
|
rb: {
|
|
8
23
|
[key: string]: {
|
|
9
|
-
method:
|
|
10
|
-
callback: (data:
|
|
24
|
+
method: PropertyKey;
|
|
25
|
+
callback: (data: any) => any;
|
|
26
|
+
onError?: (error: LixnetError) => void;
|
|
11
27
|
};
|
|
12
28
|
};
|
|
13
29
|
transmissionLimit: number;
|
|
14
30
|
transmissionChunksLimit: number;
|
|
15
31
|
setTransmissionChunksLimit(limit: number): void;
|
|
16
|
-
|
|
32
|
+
private serializer?;
|
|
33
|
+
/**
|
|
34
|
+
* `serializer` (e.g. `lixnetJSON`) encodes call inputs and callback results, for types JSON
|
|
35
|
+
* can't carry. Both peers must use the same one.
|
|
36
|
+
*/
|
|
37
|
+
constructor({ events, serializer, }?: {
|
|
38
|
+
events?: LixnetPeerEvents<any, any, any>;
|
|
39
|
+
serializer?: LixnetSerializer;
|
|
40
|
+
});
|
|
41
|
+
private encode;
|
|
42
|
+
private decode;
|
|
43
|
+
call: Caller<InferLixnetEvents<ThisToThereEvents>>;
|
|
17
44
|
private getChunkLimits;
|
|
45
|
+
/** Handlers by event name, from `events` and `on(...)`. */
|
|
18
46
|
private eventHandlers;
|
|
19
47
|
setSocket(socket: SocketType): void;
|
|
20
48
|
setTransmissionLimit(limit: number): void;
|
|
21
49
|
on<K extends keyof ThereToThisEvents>(event: K, handler: (input: PeerEventInput<ThereToThisEvents[K]> & {
|
|
22
50
|
socket: SocketType;
|
|
23
|
-
}) =>
|
|
51
|
+
}) => PeerEventOutput<ThereToThisEvents[K]> | Promise<PeerEventOutput<ThereToThisEvents[K]>>): void;
|
|
24
52
|
transmissions: Record<string, {
|
|
25
53
|
chunks: Record<number, string>;
|
|
26
54
|
chunkTimes: Record<number, number>;
|
|
27
55
|
chunkCount: number;
|
|
28
|
-
event:
|
|
56
|
+
event: PropertyKey;
|
|
29
57
|
rf: string | null;
|
|
30
58
|
}>;
|
|
31
59
|
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 { LixnetError, 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,26 @@ export default class LixnetPeer {
|
|
|
10
16
|
setTransmissionChunksLimit(limit) {
|
|
11
17
|
this.transmissionChunksLimit = limit;
|
|
12
18
|
}
|
|
13
|
-
|
|
19
|
+
serializer;
|
|
20
|
+
/**
|
|
21
|
+
* `serializer` (e.g. `lixnetJSON`) encodes call inputs and callback results, for types JSON
|
|
22
|
+
* can't carry. Both peers must use the same one.
|
|
23
|
+
*/
|
|
24
|
+
constructor({ events, serializer, } = {}) {
|
|
25
|
+
if (events)
|
|
26
|
+
Object.assign(this.eventHandlers, events.entries);
|
|
27
|
+
this.serializer = serializer;
|
|
28
|
+
}
|
|
29
|
+
encode(value) {
|
|
30
|
+
return this.serializer ? this.serializer.serialize(value) : value;
|
|
31
|
+
}
|
|
32
|
+
decode(value) {
|
|
33
|
+
return this.serializer ? this.serializer.deserialize(value) : value;
|
|
34
|
+
}
|
|
35
|
+
call = async (event, ...args) => {
|
|
36
|
+
const [input, { callback = null, onError } = {}] = args;
|
|
37
|
+
// Like LixnetClient, an omitted input is sent as `{}` so the other side's schema sees an object.
|
|
38
|
+
const data = this.encode(input === undefined ? {} : input);
|
|
14
39
|
if (!this.socket)
|
|
15
40
|
throw new Error("LIXNET - Socket not set");
|
|
16
41
|
let rf = null;
|
|
@@ -19,6 +44,7 @@ export default class LixnetPeer {
|
|
|
19
44
|
this.rb[rf] = {
|
|
20
45
|
method: event,
|
|
21
46
|
callback: callback,
|
|
47
|
+
onError,
|
|
22
48
|
};
|
|
23
49
|
}
|
|
24
50
|
let dataToSend = {
|
|
@@ -85,6 +111,7 @@ export default class LixnetPeer {
|
|
|
85
111
|
}
|
|
86
112
|
return limits;
|
|
87
113
|
}
|
|
114
|
+
/** Handlers by event name, from `events` and `on(...)`. */
|
|
88
115
|
eventHandlers = {};
|
|
89
116
|
setSocket(socket) {
|
|
90
117
|
this.socket = socket;
|
|
@@ -93,7 +120,7 @@ export default class LixnetPeer {
|
|
|
93
120
|
this.transmissionLimit = limit;
|
|
94
121
|
}
|
|
95
122
|
on(event, handler) {
|
|
96
|
-
this.eventHandlers[event] = handler;
|
|
123
|
+
this.eventHandlers[event] = { handler };
|
|
97
124
|
}
|
|
98
125
|
transmissions = {};
|
|
99
126
|
outgoingTransmissions = {};
|
|
@@ -237,8 +264,22 @@ export default class LixnetPeer {
|
|
|
237
264
|
// Receied callback
|
|
238
265
|
const callback = this.rb[data.rb];
|
|
239
266
|
if (callback) {
|
|
240
|
-
callback.callback(data.data);
|
|
241
267
|
delete this.rb[data.rb];
|
|
268
|
+
// Rejected by the other side: `{ rb, error: { error, code, data? } }`.
|
|
269
|
+
if (data.error && typeof data.error === "object") {
|
|
270
|
+
callback.onError?.(errorFromBody(data.error));
|
|
271
|
+
}
|
|
272
|
+
else {
|
|
273
|
+
let result;
|
|
274
|
+
try {
|
|
275
|
+
result = this.decode(data.data);
|
|
276
|
+
}
|
|
277
|
+
catch (cause) {
|
|
278
|
+
callback.onError?.(new LixnetError("BAD_RESPONSE", "Could not deserialize the callback data", { cause }));
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
callback.callback(result);
|
|
282
|
+
}
|
|
242
283
|
}
|
|
243
284
|
return;
|
|
244
285
|
}
|
|
@@ -251,17 +292,44 @@ export default class LixnetPeer {
|
|
|
251
292
|
});
|
|
252
293
|
}
|
|
253
294
|
async handleEvent({ eventName, data, rf, socket, }) {
|
|
254
|
-
|
|
255
|
-
if (!
|
|
295
|
+
// hasOwn so names like "constructor" don't resolve to prototype members.
|
|
296
|
+
if (!Object.hasOwn(this.eventHandlers, eventName))
|
|
297
|
+
return;
|
|
298
|
+
const { handler, schema } = this.eventHandlers[eventName];
|
|
299
|
+
try {
|
|
300
|
+
data = this.decode(data);
|
|
301
|
+
}
|
|
302
|
+
catch {
|
|
303
|
+
if (rf) {
|
|
304
|
+
socket.send(JSON.stringify({ rb: rf, error: { error: "Invalid input encoding", code: "BAD_REQUEST" } }));
|
|
305
|
+
}
|
|
256
306
|
return;
|
|
257
|
-
|
|
307
|
+
}
|
|
308
|
+
if (schema) {
|
|
309
|
+
const result = await schema["~standard"].validate(data);
|
|
310
|
+
if (result.issues) {
|
|
311
|
+
if (rf) {
|
|
312
|
+
socket.send(JSON.stringify({
|
|
313
|
+
rb: rf,
|
|
314
|
+
error: {
|
|
315
|
+
error: "Invalid input",
|
|
316
|
+
code: "INVALID_INPUT",
|
|
317
|
+
data: { issues: toIssues(result.issues) },
|
|
318
|
+
},
|
|
319
|
+
}));
|
|
320
|
+
}
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
data = result.value;
|
|
324
|
+
}
|
|
325
|
+
const result = await handler({
|
|
258
326
|
...(typeof data === "object" ? data : {}),
|
|
259
327
|
socket,
|
|
260
328
|
});
|
|
261
329
|
if (rf) {
|
|
262
330
|
socket.send(JSON.stringify({
|
|
263
331
|
rb: rf,
|
|
264
|
-
data: result,
|
|
332
|
+
data: this.encode(result),
|
|
265
333
|
}));
|
|
266
334
|
}
|
|
267
335
|
}
|
|
@@ -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
|
+
}
|
package/dist/lib/router.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { StandardSchemaV1 } from "./standardschema";
|
|
2
2
|
import type { LixnetServerInjections } from "./types";
|
|
3
|
+
import type { LixnetMiddleware, LixnetMiddlewareContext } from "./middleware";
|
|
3
4
|
/**
|
|
4
5
|
* Type-level description of a route added with `LixnetServer.route(...)`: the input the
|
|
5
6
|
* client sends and the output it receives.
|
|
@@ -18,23 +19,51 @@ export type InferLixnetEvents<T> = T extends {
|
|
|
18
19
|
} ? {
|
|
19
20
|
[K in keyof TRoutes]: (input: TRoutes[K]["input"]) => TRoutes[K]["output"];
|
|
20
21
|
} : T;
|
|
21
|
-
type RouteHandlerInput<TSchema> = TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> &
|
|
22
|
+
type RouteHandlerInput<TSchema, TInjections> = TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> & TInjections : any;
|
|
23
|
+
/** The `ctx` a route definition's handler gets: the server's, plus its own `use`'s. */
|
|
24
|
+
type RouteContext<TCtx, TUses, K> = TCtx & (K extends keyof TUses ? LixnetMiddlewareContext<TUses[K]> : {});
|
|
22
25
|
/**
|
|
23
|
-
* The `routes` constructor option: `{ name: { schema?, handler } }`. Each handler is typed from
|
|
24
|
-
* its own schema; without one, annotate the handler's parameter.
|
|
26
|
+
* The `routes` constructor option: `{ name: { schema?, use?, handler } }`. Each handler is typed from
|
|
27
|
+
* its own schema; without one, annotate the handler's parameter. `TCtx` and `TUses` (servers
|
|
28
|
+
* only) type `ctx` from the server's and the route's middleware.
|
|
25
29
|
*/
|
|
26
|
-
export type LixnetRouteDefinitions<TSchemas> = {
|
|
30
|
+
export type LixnetRouteDefinitions<TSchemas, TInjections = LixnetServerInjections, TCtx = never, TUses = {}> = {
|
|
27
31
|
[K in keyof TSchemas]: {
|
|
28
32
|
schema?: TSchemas[K];
|
|
29
|
-
handler: (input: RouteHandlerInput<TSchemas[K]
|
|
33
|
+
handler: (input: RouteHandlerInput<TSchemas[K], [
|
|
34
|
+
TCtx
|
|
35
|
+
] extends [never] ? TInjections : TInjections & {
|
|
36
|
+
ctx: RouteContext<TCtx, TUses, K>;
|
|
37
|
+
}>) => unknown;
|
|
30
38
|
};
|
|
31
39
|
};
|
|
40
|
+
/** Infers each route definition's `use`, so its handler's `ctx` includes what that middleware adds. */
|
|
41
|
+
export type LixnetRouteUses<TUses> = {
|
|
42
|
+
[K in keyof TUses]: {
|
|
43
|
+
use?: TUses[K] & readonly LixnetMiddleware<any, any>[];
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
/** The input a route definition's caller sends: the schema's input, else the handler's parameter minus injections. */
|
|
47
|
+
export type LixnetRouteDefinitionInput<TDef, TInjections = LixnetServerInjections> = TDef extends {
|
|
48
|
+
schema: infer TSchema extends StandardSchemaV1;
|
|
49
|
+
} ? StandardSchemaV1.InferInput<TSchema> : TDef extends {
|
|
50
|
+
handler: (input: infer TParams) => any;
|
|
51
|
+
} ? Omit<TParams, keyof TInjections> : never;
|
|
32
52
|
/** Turns the `routes` option's type into routes, the same shape `.route(...)` records. */
|
|
33
|
-
export type LixnetRoutesFromDefinitions<TDefs> = {
|
|
53
|
+
export type LixnetRoutesFromDefinitions<TDefs, TInjections = LixnetServerInjections> = {
|
|
34
54
|
[K in keyof TDefs]: TDefs[K] extends {
|
|
35
|
-
handler: (input:
|
|
36
|
-
} ? LixnetRoute<TDefs[K]
|
|
37
|
-
|
|
38
|
-
|
|
55
|
+
handler: (input: any) => infer TOutput;
|
|
56
|
+
} ? LixnetRoute<LixnetRouteDefinitionInput<TDefs[K], TInjections>, Awaited<TOutput>> : never;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* `routes` (or its alias `events`) as `{ name: { schema?, handler } }`: the same as calling
|
|
60
|
+
* `.route(name, ...)` for each. Pass one or the other.
|
|
61
|
+
*/
|
|
62
|
+
export type LixnetRoutesOption<TRouteDefinitions> = {
|
|
63
|
+
routes?: TRouteDefinitions;
|
|
64
|
+
events?: never;
|
|
65
|
+
} | {
|
|
66
|
+
events?: TRouteDefinitions;
|
|
67
|
+
routes?: never;
|
|
39
68
|
};
|
|
40
69
|
export {};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turns values into JSON-safe data and back, for types JSON can't carry (`Date`, `Map`, `BigInt`...).
|
|
3
|
+
* Give the same serializer to both sides: the client sends its `name` and the server rejects
|
|
4
|
+
* requests whose serializer doesn't match its own.
|
|
5
|
+
*
|
|
6
|
+
* Any library fits, e.g. superjson:
|
|
7
|
+
* `{ name: "superjson", serialize: (v) => superjson.serialize(v), deserialize: (v) => superjson.deserialize(v as any) }`.
|
|
8
|
+
*/
|
|
9
|
+
export type LixnetSerializer = {
|
|
10
|
+
/** Identifies the format on the wire; both sides must use the same one. */
|
|
11
|
+
name: string;
|
|
12
|
+
/** Value to JSON-safe data (passed to `JSON.stringify` afterwards). */
|
|
13
|
+
serialize: (value: unknown) => unknown;
|
|
14
|
+
/** JSON-parsed data back to the value. */
|
|
15
|
+
deserialize: (value: unknown) => unknown;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Internal hint on a `deserialize` function (so a serializer spread from `lixnetJSON` with its own
|
|
19
|
+
* `deserialize` never inherits it). Lixnet's call sites pass the raw JSON text a value was parsed
|
|
20
|
+
* from and decode with the serializer it returns.
|
|
21
|
+
*/
|
|
22
|
+
export type LixnetReceivedHint = {
|
|
23
|
+
"~received"?: (text: string) => LixnetSerializer;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* The built-in serializer. Plain JSON passes through unchanged; on top of it, it keeps `Date`,
|
|
27
|
+
* `Map`, `Set`, `BigInt`, `undefined`, `NaN` / `±Infinity` / `-0`, `RegExp`, `URL`, `Error`
|
|
28
|
+
* (name and message only), `ArrayBuffer`, `DataView` and every typed array (`Buffer` arrives as a
|
|
29
|
+
* `Uint8Array`). Decoding is strict: a malformed tagged value throws a `TypeError`. Other class
|
|
30
|
+
* instances are sent like `JSON.stringify` sends them (`toJSON()`, else their own enumerable fields).
|
|
31
|
+
*
|
|
32
|
+
* `serialize` shares what needs no encoding with its input (plain JSON comes back as the same
|
|
33
|
+
* object), so don't mutate its result. `deserialize` always returns new arrays and objects.
|
|
34
|
+
*/
|
|
35
|
+
export declare const lixnetJSON: LixnetSerializer;
|