lixnet 1.6.0 → 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 +135 -3
- package/dist/exports.d.ts +8 -2
- package/dist/exports.js +4 -1
- package/dist/lib/client.d.ts +11 -1
- package/dist/lib/client.js +38 -6
- package/dist/lib/error.d.ts +22 -2
- package/dist/lib/error.js +46 -7
- package/dist/lib/middleware.d.ts +88 -0
- package/dist/lib/middleware.js +60 -0
- package/dist/lib/peer.d.ts +10 -1
- package/dist/lib/peer.js +34 -5
- package/dist/lib/router.d.ts +18 -4
- package/dist/lib/serializer.d.ts +35 -0
- package/dist/lib/serializer.js +385 -0
- package/dist/lib/server.d.ts +38 -20
- package/dist/lib/server.js +16 -6
- package/dist/lib/serverbase.d.ts +43 -4
- package/dist/lib/serverbase.js +88 -19
- package/dist/lib/streamclient.d.ts +2 -1
- package/dist/lib/streamclient.js +39 -12
- package/dist/lib/streamserver.d.ts +40 -15
- package/dist/lib/streamserver.js +124 -22
- package/dist/lib/types.d.ts +25 -2
- package/dist/lib/util/getDefaultFormatter.d.ts +33 -4
- package/dist/lib/util/getDefaultFormatter.js +99 -16
- package/dist/lib/util/response.d.ts +12 -2
- package/dist/lib/util/response.js +12 -4
- package/package.json +7 -1
package/dist/lib/serverbase.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import type { StandardSchemaV1 } from "./standardschema";
|
|
2
2
|
import type { DebugLogger } from "./types";
|
|
3
3
|
import type { LixnetResponse } from "./util/response";
|
|
4
|
+
import type { LixnetRequest } from "./util/request";
|
|
5
|
+
import { type LixnetMiddleware } from "./middleware";
|
|
6
|
+
import type { LixnetSerializer } from "./serializer";
|
|
4
7
|
import { type LixnetErrorCode } from "./error";
|
|
5
8
|
import { type LixnetCorsOptions } from "./util/cors";
|
|
6
9
|
export type LixnetServerBaseOptions = {
|
|
@@ -18,10 +21,27 @@ export type LixnetServerBaseOptions = {
|
|
|
18
21
|
* headers to every response, and rejects requests from origins that aren't allowed.
|
|
19
22
|
*/
|
|
20
23
|
cors?: LixnetCorsOptions;
|
|
24
|
+
/**
|
|
25
|
+
* Middleware run before every route, in order (routes added with `.use(...)` later get those too).
|
|
26
|
+
* Each can add fields to the handler's `ctx`.
|
|
27
|
+
*/
|
|
28
|
+
use?: readonly LixnetMiddleware<any, any>[];
|
|
29
|
+
/**
|
|
30
|
+
* Serializer for inputs, outputs and error `data`, for types JSON can't carry (e.g. `lixnetJSON`).
|
|
31
|
+
* The client must use the same one: requests with another (or none) are rejected.
|
|
32
|
+
*/
|
|
33
|
+
serializer?: LixnetSerializer;
|
|
21
34
|
};
|
|
22
35
|
type EventEntry = {
|
|
23
36
|
event: PropertyKey;
|
|
24
37
|
schema?: StandardSchemaV1;
|
|
38
|
+
handler: (input: any) => unknown;
|
|
39
|
+
/** The route's own middleware, run after the server's. */
|
|
40
|
+
use?: readonly LixnetMiddleware<any, any>[];
|
|
41
|
+
};
|
|
42
|
+
/** An entry as stored: with the full middleware chain resolved when it was registered. */
|
|
43
|
+
type StoredEntry<TEntry> = TEntry & {
|
|
44
|
+
middleware: readonly LixnetMiddleware<any, any>[];
|
|
25
45
|
};
|
|
26
46
|
/** A failed request, before it's written to the response. */
|
|
27
47
|
type Failure = {
|
|
@@ -33,25 +53,43 @@ type Failure = {
|
|
|
33
53
|
cause?: unknown;
|
|
34
54
|
event?: string;
|
|
35
55
|
};
|
|
36
|
-
/**
|
|
56
|
+
/**
|
|
57
|
+
* `input` is deserialized but not validated: validation runs in `invoke`, after middleware.
|
|
58
|
+
* `body` is the raw request body, kept so handlers can re-read it without `request.clone()`.
|
|
59
|
+
*/
|
|
37
60
|
type ParsedRpcRequest<TEntry> = {
|
|
38
61
|
ok: true;
|
|
39
|
-
entry: TEntry
|
|
62
|
+
entry: StoredEntry<TEntry>;
|
|
40
63
|
input: any;
|
|
41
64
|
body: string;
|
|
42
65
|
} | ({
|
|
43
66
|
ok: false;
|
|
44
67
|
} & Failure);
|
|
68
|
+
type Injections = {
|
|
69
|
+
request: LixnetRequest;
|
|
70
|
+
response: LixnetResponse;
|
|
71
|
+
} & Record<string, unknown>;
|
|
45
72
|
/** Shared request parsing and error handling for `LixnetServer` and `LixnetStreamServer`. */
|
|
46
73
|
export default abstract class LixnetServerBase<TEntry extends EventEntry> {
|
|
47
|
-
protected events: Record<string, TEntry
|
|
74
|
+
protected events: Record<string, StoredEntry<TEntry>>;
|
|
75
|
+
protected middleware: LixnetMiddleware<any, any>[];
|
|
76
|
+
protected serializer?: LixnetSerializer;
|
|
48
77
|
protected logger: DebugLogger;
|
|
49
78
|
protected debugLog: boolean;
|
|
50
79
|
protected exposeErrors: boolean;
|
|
51
80
|
protected defaultHeaders: Record<string, string>;
|
|
52
81
|
protected cors?: LixnetCorsOptions;
|
|
53
|
-
protected constructor({ debugLog, exposeErrors, logger, defaultHeaders, cors, }: LixnetServerBaseOptions);
|
|
82
|
+
protected constructor({ debugLog, exposeErrors, logger, defaultHeaders, cors, use, serializer, }: LixnetServerBaseOptions);
|
|
83
|
+
/** Each entry keeps the server middleware registered so far, so `.use(...)` only affects later routes. */
|
|
54
84
|
protected register(input: TEntry | TEntry[]): void;
|
|
85
|
+
protected addMiddleware(middleware: readonly LixnetMiddleware<any, any>[]): void;
|
|
86
|
+
/**
|
|
87
|
+
* Runs the entry's middleware, then validates the input against its schema, then runs its
|
|
88
|
+
* handler with `ctx` and the injections. Resolves (or returns, when sync) the output.
|
|
89
|
+
* Middleware sees the deserialized input; the handler gets the schema's output. A validation
|
|
90
|
+
* failure is thrown as an `INVALID_INPUT` `LixnetError` inside the chain, so middleware can catch it.
|
|
91
|
+
*/
|
|
92
|
+
protected invoke(entry: StoredEntry<TEntry>, input: any, injections: Injections): Promise<unknown> | unknown;
|
|
55
93
|
protected parse(request: Request): Promise<ParsedRpcRequest<TEntry>>;
|
|
56
94
|
/**
|
|
57
95
|
* With `cors` set: answers preflights and rejects disallowed origins (returns the Response),
|
|
@@ -62,6 +100,7 @@ export default abstract class LixnetServerBase<TEntry extends EventEntry> {
|
|
|
62
100
|
protected failureFromThrown(error: unknown, event: string): Failure;
|
|
63
101
|
/** Logs the failure (with `debugLog`) and stages it on the response with its status. */
|
|
64
102
|
protected stageFailure(response: LixnetResponse, { error, status, code, data, cause, event }: Failure): void;
|
|
103
|
+
/** Stages the failure and formats it. Never throws: if formatting fails, a bare 500 is sent. */
|
|
65
104
|
protected fail(response: LixnetResponse, failure: Failure): Response;
|
|
66
105
|
}
|
|
67
106
|
export {};
|
package/dist/lib/serverbase.js
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
import LixnetLog from "./util/log";
|
|
2
|
+
import { runMiddleware } from "./middleware";
|
|
2
3
|
import { LixnetError, toIssues } from "./error";
|
|
3
4
|
import { assertCorsOptions, corsHeaders, isOriginAllowed, preflightHeaders, } from "./util/cors";
|
|
5
|
+
/** The schema's output, or an `INVALID_INPUT` error with the issues (always sent: they're for the caller). */
|
|
6
|
+
function validOutput(result) {
|
|
7
|
+
if (!result.issues)
|
|
8
|
+
return result.value;
|
|
9
|
+
throw new LixnetError("INVALID_INPUT", "Invalid input", {
|
|
10
|
+
data: { issues: toIssues(result.issues) },
|
|
11
|
+
cause: result.issues,
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
/** Last step of the chain: validate (without an extra tick when the schema is sync), then call the handler. */
|
|
15
|
+
function callHandler(entry, input, injections, ctx) {
|
|
16
|
+
if (!entry.schema)
|
|
17
|
+
return entry.handler({ ...input, ...injections, ctx });
|
|
18
|
+
const result = entry.schema["~standard"].validate(input);
|
|
19
|
+
if (result instanceof Promise) {
|
|
20
|
+
return result.then((r) => entry.handler({ ...validOutput(r), ...injections, ctx }));
|
|
21
|
+
}
|
|
22
|
+
return entry.handler({ ...validOutput(result), ...injections, ctx });
|
|
23
|
+
}
|
|
4
24
|
function describeError(cause) {
|
|
5
25
|
if (cause === undefined)
|
|
6
26
|
return undefined;
|
|
@@ -13,26 +33,49 @@ function describeError(cause) {
|
|
|
13
33
|
/** Shared request parsing and error handling for `LixnetServer` and `LixnetStreamServer`. */
|
|
14
34
|
export default class LixnetServerBase {
|
|
15
35
|
events = {};
|
|
36
|
+
middleware;
|
|
37
|
+
serializer;
|
|
16
38
|
logger = LixnetLog;
|
|
17
39
|
debugLog;
|
|
18
40
|
exposeErrors;
|
|
19
41
|
defaultHeaders;
|
|
20
42
|
cors;
|
|
21
|
-
constructor({ debugLog = false, exposeErrors = false, logger, defaultHeaders = {}, cors, }) {
|
|
43
|
+
constructor({ debugLog = false, exposeErrors = false, logger, defaultHeaders = {}, cors, use = [], serializer, }) {
|
|
22
44
|
if (cors)
|
|
23
45
|
assertCorsOptions(cors);
|
|
24
46
|
this.cors = cors;
|
|
25
47
|
this.debugLog = debugLog;
|
|
26
48
|
this.exposeErrors = exposeErrors;
|
|
27
49
|
this.defaultHeaders = defaultHeaders;
|
|
50
|
+
this.middleware = [...use];
|
|
51
|
+
this.serializer = serializer;
|
|
28
52
|
if (logger)
|
|
29
53
|
this.logger = logger;
|
|
30
54
|
}
|
|
55
|
+
/** Each entry keeps the server middleware registered so far, so `.use(...)` only affects later routes. */
|
|
31
56
|
register(input) {
|
|
32
57
|
const entries = Array.isArray(input) ? input : [input];
|
|
33
58
|
for (const entry of entries) {
|
|
34
|
-
this.events[entry.event] =
|
|
59
|
+
this.events[entry.event] = {
|
|
60
|
+
...entry,
|
|
61
|
+
middleware: [...this.middleware, ...(entry.use ?? [])],
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
addMiddleware(middleware) {
|
|
66
|
+
this.middleware.push(...middleware);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Runs the entry's middleware, then validates the input against its schema, then runs its
|
|
70
|
+
* handler with `ctx` and the injections. Resolves (or returns, when sync) the output.
|
|
71
|
+
* Middleware sees the deserialized input; the handler gets the schema's output. A validation
|
|
72
|
+
* failure is thrown as an `INVALID_INPUT` `LixnetError` inside the chain, so middleware can catch it.
|
|
73
|
+
*/
|
|
74
|
+
invoke(entry, input, injections) {
|
|
75
|
+
if (entry.middleware.length === 0) {
|
|
76
|
+
return callHandler(entry, input, injections, {});
|
|
35
77
|
}
|
|
78
|
+
return runMiddleware(entry.middleware, { request: injections.request, response: injections.response, event: entry.event, input }, (ctx) => callHandler(entry, input, injections, ctx));
|
|
36
79
|
}
|
|
37
80
|
async parse(request) {
|
|
38
81
|
// Read once as text: handlers get it back through LixnetRequest's body methods.
|
|
@@ -48,6 +91,19 @@ export default class LixnetServerBase {
|
|
|
48
91
|
if (json === null || typeof json !== "object" || Array.isArray(json)) {
|
|
49
92
|
return { ok: false, error: "Invalid request body", status: 400, code: "BAD_REQUEST" };
|
|
50
93
|
}
|
|
94
|
+
// The client names its serializer; it must be the server's (both absent is plain JSON).
|
|
95
|
+
// `null` counts as absent: some clients always send the field.
|
|
96
|
+
const expected = this.serializer?.name;
|
|
97
|
+
if ((json.serializer ?? undefined) !== expected) {
|
|
98
|
+
return {
|
|
99
|
+
ok: false,
|
|
100
|
+
error: expected
|
|
101
|
+
? `This server uses the "${expected}" serializer; give the client the same \`serializer\``
|
|
102
|
+
: `This server has no serializer, but the request used ${JSON.stringify(json.serializer)}`,
|
|
103
|
+
status: 400,
|
|
104
|
+
code: "BAD_REQUEST",
|
|
105
|
+
};
|
|
106
|
+
}
|
|
51
107
|
if (typeof json.event !== "string" || !json.event) {
|
|
52
108
|
return { ok: false, error: "Event not found", status: 400, code: "BAD_REQUEST" };
|
|
53
109
|
}
|
|
@@ -65,23 +121,26 @@ export default class LixnetServerBase {
|
|
|
65
121
|
};
|
|
66
122
|
}
|
|
67
123
|
const entry = this.events[json.event];
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
124
|
+
let input = json.input;
|
|
125
|
+
if (this.serializer) {
|
|
126
|
+
try {
|
|
127
|
+
// lixnetJSON (and only it) offers a faster decoder for JSON it doesn't have to copy,
|
|
128
|
+
// which skips decoding when the body has no tagged value (see `~received`).
|
|
129
|
+
const received = this.serializer.deserialize["~received"];
|
|
130
|
+
input = (received ? received(body) : this.serializer).deserialize(input);
|
|
131
|
+
}
|
|
132
|
+
catch (cause) {
|
|
133
|
+
return {
|
|
134
|
+
ok: false,
|
|
135
|
+
error: "Invalid input encoding",
|
|
136
|
+
status: 400,
|
|
137
|
+
code: "BAD_REQUEST",
|
|
138
|
+
cause,
|
|
139
|
+
event: json.event,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
83
142
|
}
|
|
84
|
-
return { ok: true, entry, input
|
|
143
|
+
return { ok: true, entry, input, body };
|
|
85
144
|
}
|
|
86
145
|
/**
|
|
87
146
|
* With `cors` set: answers preflights and rejects disallowed origins (returns the Response),
|
|
@@ -137,6 +196,7 @@ export default class LixnetServerBase {
|
|
|
137
196
|
cause,
|
|
138
197
|
});
|
|
139
198
|
}
|
|
199
|
+
// `data` stays raw: the body helpers encode it with the response's serializer.
|
|
140
200
|
response.code(status);
|
|
141
201
|
response.error(error, {
|
|
142
202
|
code,
|
|
@@ -144,8 +204,17 @@ export default class LixnetServerBase {
|
|
|
144
204
|
detail: this.exposeErrors ? describeError(cause) : undefined,
|
|
145
205
|
});
|
|
146
206
|
}
|
|
207
|
+
/** Stages the failure and formats it. Never throws: if formatting fails, a bare 500 is sent. */
|
|
147
208
|
fail(response, failure) {
|
|
148
209
|
this.stageFailure(response, failure);
|
|
149
|
-
|
|
210
|
+
try {
|
|
211
|
+
return response.format();
|
|
212
|
+
}
|
|
213
|
+
catch (cause) {
|
|
214
|
+
if (this.debugLog) {
|
|
215
|
+
this.logger({ error: true, message: "Could not format the error response", cause });
|
|
216
|
+
}
|
|
217
|
+
return Response.json({ error: "Could not serialize the response", code: "INTERNAL" }, { status: 500, headers: { "X-Server": "Lixnet" } });
|
|
218
|
+
}
|
|
150
219
|
}
|
|
151
220
|
}
|
|
@@ -13,9 +13,10 @@ export type LixnetStreamCaller<Events> = {
|
|
|
13
13
|
export default class LixnetStreamClient<Contract extends LXN_ServerClient_EventType, Events extends LXN_ServerClient_EventType = InferLixnetEvents<Contract>> {
|
|
14
14
|
private rpcUrl;
|
|
15
15
|
private fetcher?;
|
|
16
|
+
private serializer?;
|
|
16
17
|
/** Every stream event as a typed function, like `LixnetClient.caller`. */
|
|
17
18
|
readonly caller: LixnetStreamCaller<Events>;
|
|
18
|
-
constructor({ rpcUrl, fetch }: LixnetClientOptions);
|
|
19
|
+
constructor({ rpcUrl, fetch, serializer }: LixnetClientOptions);
|
|
19
20
|
/** Resolves when the stream ends; throws if the server returns or streams an error. */
|
|
20
21
|
call<K extends keyof Events>(event: K, ...[input, options]: LXNCallArgs<FunctionInput<Events[K]>, LXNStreamCallOptions<FunctionOutput<Events[K]>>>): Promise<void>;
|
|
21
22
|
}
|
package/dist/lib/streamclient.js
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import withJsonContentType from "./util/withJsonContentType";
|
|
2
2
|
import createCaller from "./util/createCaller";
|
|
3
|
-
import { LixnetError, codeForStatus, errorFromBody } from "./error";
|
|
3
|
+
import { LixnetError, codeForStatus, decodeResponse, errorFromBody, serializerMismatch } from "./error";
|
|
4
|
+
import { received, requestBody } from "./client";
|
|
4
5
|
export default class LixnetStreamClient {
|
|
5
6
|
rpcUrl;
|
|
6
7
|
fetcher;
|
|
8
|
+
serializer;
|
|
7
9
|
/** Every stream event as a typed function, like `LixnetClient.caller`. */
|
|
8
10
|
caller;
|
|
9
|
-
constructor({ rpcUrl, fetch }) {
|
|
11
|
+
constructor({ rpcUrl, fetch, serializer }) {
|
|
10
12
|
this.rpcUrl = rpcUrl;
|
|
11
13
|
this.fetcher = fetch;
|
|
14
|
+
this.serializer = serializer;
|
|
12
15
|
this.caller = createCaller((event, ...args) => this.call(event, ...args));
|
|
13
16
|
}
|
|
14
17
|
/** Resolves when the stream ends; throws if the server returns or streams an error. */
|
|
@@ -20,19 +23,30 @@ export default class LixnetStreamClient {
|
|
|
20
23
|
...fetchOptions,
|
|
21
24
|
method: "POST",
|
|
22
25
|
headers: withJsonContentType(fetchOptions.headers),
|
|
23
|
-
body:
|
|
26
|
+
body: requestBody(event, input, this.serializer),
|
|
24
27
|
});
|
|
25
28
|
if (!response.ok) {
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
+
const text = await response.text().catch(() => "");
|
|
30
|
+
let json = null;
|
|
31
|
+
try {
|
|
32
|
+
json = JSON.parse(text);
|
|
33
|
+
}
|
|
34
|
+
catch { }
|
|
35
|
+
if (json && typeof json.error === "string") {
|
|
36
|
+
// Data is decoded only when the server confirmed the same serializer.
|
|
37
|
+
const confirmed = json.serializer === this.serializer?.name;
|
|
38
|
+
throw errorFromBody(json, response.status, confirmed ? received(this.serializer, text) : undefined, this.rpcUrl);
|
|
39
|
+
}
|
|
29
40
|
throw new LixnetError(codeForStatus(response.status), `Stream request failed with status ${response.status}`, { status: response.status });
|
|
30
41
|
}
|
|
31
|
-
if (!response.body)
|
|
32
|
-
throw new
|
|
42
|
+
if (!response.body) {
|
|
43
|
+
throw new LixnetError("BAD_RESPONSE", `Stream response from ${this.rpcUrl} has no body`, { status: response.status });
|
|
44
|
+
}
|
|
33
45
|
const reader = response.body.getReader();
|
|
34
46
|
const decoder = new TextDecoder();
|
|
35
47
|
let buffer = "";
|
|
48
|
+
let checked = false;
|
|
49
|
+
let serializer = this.serializer;
|
|
36
50
|
const handleLine = (line) => {
|
|
37
51
|
const trimmed = line.trim();
|
|
38
52
|
if (!trimmed)
|
|
@@ -44,10 +58,23 @@ export default class LixnetStreamClient {
|
|
|
44
58
|
catch {
|
|
45
59
|
return; // skip malformed line
|
|
46
60
|
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
61
|
+
const isError = typeof parsed?.error === "string";
|
|
62
|
+
if (!isError && parsed?.stream !== true)
|
|
63
|
+
return;
|
|
64
|
+
// Only the first frame echoes the server's serializer: check it once per stream.
|
|
65
|
+
if (!checked) {
|
|
66
|
+
checked = true;
|
|
67
|
+
if (parsed.serializer !== this.serializer?.name) {
|
|
68
|
+
if (!isError)
|
|
69
|
+
throw serializerMismatch(this.rpcUrl, this.serializer?.name, parsed.serializer);
|
|
70
|
+
serializer = undefined; // keep the error, leave its data raw
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
// Per line: lixnetJSON skips decoding frames whose text has no tagged value.
|
|
74
|
+
const lineSerializer = received(serializer, trimmed);
|
|
75
|
+
if (isError)
|
|
76
|
+
throw errorFromBody(parsed, undefined, lineSerializer, this.rpcUrl);
|
|
77
|
+
onStreamChunk?.(lineSerializer ? decodeResponse(lineSerializer, parsed.data, this.rpcUrl) : parsed.data);
|
|
51
78
|
};
|
|
52
79
|
try {
|
|
53
80
|
while (true) {
|
|
@@ -1,14 +1,19 @@
|
|
|
1
1
|
import LixnetServerBase, { type LixnetServerBaseOptions } from "./serverbase";
|
|
2
|
-
import type { FunctionInput, FunctionOutput, LXN_ServerClient_EventType, LXNEventEntries, LXNEventSchema, LXNStreamEmitter, LixnetStreamInjections } from "./types";
|
|
2
|
+
import type { FunctionInput, FunctionOutput, LXN_ServerClient_EventType, LXNEventEntries, LXNEventSchema, LXNStreamEmitter, LixnetStreamInjections, LixnetReservedInputCheck, LixnetReservedSchemasCheck, LixnetStreamReservedKey } from "./types";
|
|
3
3
|
import { LixnetResponse } from "./util/response";
|
|
4
4
|
import { type LixnetRequest } from "./util/request";
|
|
5
|
+
import type { LixnetCheckMiddleware, LixnetMiddleware, LixnetMiddlewareContext, LixnetRouteUsesCheck, LixnetUseCheck } from "./middleware";
|
|
5
6
|
import type { StandardSchemaV1 } from "./standardschema";
|
|
6
|
-
import type { LixnetRouteDefinitionInput, LixnetRouteDefinitions, LixnetRoute, LixnetRoutes, LixnetRoutesOption } from "./router";
|
|
7
|
-
type
|
|
7
|
+
import type { LixnetRouteDefinitionInput, LixnetRouteDefinitions, LixnetRoute, LixnetRoutes, LixnetRoutesOption, LixnetRouteUses } from "./router";
|
|
8
|
+
type Middleware = readonly LixnetMiddleware<any, any>[];
|
|
9
|
+
type LXNStreamServerEventInput<Events extends LXN_ServerClient_EventType, K extends keyof Events, TCtx = {}, TUse extends Middleware = Middleware> = {
|
|
8
10
|
event: K;
|
|
11
|
+
/** Middleware for this event only, run after the server's. */
|
|
12
|
+
use?: TUse;
|
|
9
13
|
handler: (input: FunctionInput<Events[K]> & {
|
|
10
14
|
request: LixnetRequest;
|
|
11
15
|
response: LixnetResponse;
|
|
16
|
+
ctx: TCtx;
|
|
12
17
|
stream: LXNStreamEmitter<FunctionOutput<Events[K]>>;
|
|
13
18
|
}) => unknown;
|
|
14
19
|
schema?: LXNEventSchema<Events, K>;
|
|
@@ -27,28 +32,48 @@ type StreamRoutesFromDefinitions<TDefs> = {
|
|
|
27
32
|
};
|
|
28
33
|
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
34
|
handler: (input: any) => unknown;
|
|
30
|
-
}> = {}> extends LixnetServerBase<LXNStreamServerEventInput<Events, keyof Events>> {
|
|
35
|
+
}> = {}, const TUse extends Middleware = [], TUses = {}> extends LixnetServerBase<LXNStreamServerEventInput<Events, keyof Events, any>> {
|
|
31
36
|
/** Type-only: routes from the `routes` option and `.route(...)`, read by `InferLixnetEvents`. */
|
|
32
37
|
readonly "~routes": Routes & StreamRoutesFromDefinitions<TDefs>;
|
|
33
38
|
private errorFormatter;
|
|
34
|
-
constructor({ routes, events, ...options }?: LixnetServerBaseOptions &
|
|
39
|
+
constructor({ routes, events, ...options }?: LixnetServerBaseOptions & {
|
|
40
|
+
/** Middleware for every stream route. Each may read what the ones before it add to `ctx`. */
|
|
41
|
+
use?: TUse;
|
|
42
|
+
} & LixnetUseCheck<TUse, {}> & LixnetRoutesOption<TDefs & LixnetRouteDefinitions<TSchemas, LixnetStreamInjections, LixnetMiddlewareContext<TUse>, TUses> & LixnetRouteUses<TUses> & LixnetRouteUsesCheck<TUses, LixnetMiddlewareContext<TUse>> & LixnetReservedSchemasCheck<TSchemas, LixnetStreamReservedKey>>);
|
|
43
|
+
/**
|
|
44
|
+
* Adds middleware for the stream routes registered after this call. Each can add fields to `ctx`.
|
|
45
|
+
* `next()` spans the whole stream: it resolves after the last chunk is sent (to the generator's
|
|
46
|
+
* return value) and rejects if the stream fails.
|
|
47
|
+
*/
|
|
48
|
+
use<const M extends Middleware>(...middleware: M & LixnetCheckMiddleware<M, LixnetMiddlewareContext<TUse>>): LixnetStreamServer<Events, Routes, TSchemas, TDefs, [...TUse, ...M], TUses>;
|
|
49
|
+
/** Without a schema or input of its own: the handler gets only the injections (typed `ctx` included). */
|
|
50
|
+
route<K extends string, TResult, const U extends Middleware>(event: K, route: {
|
|
51
|
+
schema?: undefined;
|
|
52
|
+
use?: U;
|
|
53
|
+
handler: (input: LixnetStreamInjections<LixnetMiddlewareContext<TUse> & LixnetMiddlewareContext<U>>) => TResult;
|
|
54
|
+
} & LixnetUseCheck<U, LixnetMiddlewareContext<TUse>>): LixnetStreamServer<Events, Routes & Record<K, LixnetRoute<{}, StreamChunk<TResult, unknown>>>, TSchemas, TDefs, TUse, TUses>;
|
|
55
|
+
/** Without a schema, the input is the handler's parameter type minus `request`/`response`/`ctx`/`stream`. */
|
|
56
|
+
route<K extends string, TParams, TResult, const U extends Middleware>(event: K, route: {
|
|
57
|
+
schema?: undefined;
|
|
58
|
+
use?: U;
|
|
59
|
+
handler: (input: TParams & LixnetStreamInjections<LixnetMiddlewareContext<TUse> & LixnetMiddlewareContext<U>>) => TResult;
|
|
60
|
+
} & LixnetUseCheck<U, LixnetMiddlewareContext<TUse>>): LixnetStreamServer<Events, Routes & Record<K, LixnetRoute<Omit<TParams, keyof LixnetStreamInjections>, StreamChunk<TResult, TParams>>>, TSchemas, TDefs, TUse, TUses>;
|
|
35
61
|
/**
|
|
36
62
|
* Adds a stream event whose types are inferred. The client's chunk type is what the handler
|
|
37
63
|
* yields (`async function* () { yield chunk }`), or, with `stream.emit(...)`, the type of an
|
|
38
64
|
* annotated `stream: LXNStreamEmitter<T>` parameter.
|
|
39
65
|
*/
|
|
40
|
-
route<K extends string, TSchema extends StandardSchemaV1, TResult>(event: K, route: {
|
|
66
|
+
route<K extends string, TSchema extends StandardSchemaV1, TResult, const U extends Middleware>(event: K, route: {
|
|
41
67
|
schema: TSchema;
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
}): LixnetStreamServer<Events, Routes & Record<K, LixnetRoute<Omit<TParams, keyof LixnetStreamInjections>, StreamChunk<TResult, TParams>>>, TSchemas, TDefs>;
|
|
49
|
-
on<K extends keyof Events & string>(input: LXNStreamServerEventInput<Events, K> | LXNEventEntries<Events, {
|
|
50
|
-
[P in keyof Events & string]: LXNStreamServerEventInput<Events, P>;
|
|
68
|
+
/** Middleware for this route only, run after the server's. */
|
|
69
|
+
use?: U;
|
|
70
|
+
handler: (input: StandardSchemaV1.InferOutput<TSchema> & LixnetStreamInjections<LixnetMiddlewareContext<TUse> & LixnetMiddlewareContext<U>>) => TResult;
|
|
71
|
+
} & LixnetUseCheck<U, LixnetMiddlewareContext<TUse>> & LixnetReservedInputCheck<StandardSchemaV1.InferOutput<TSchema>, LixnetStreamReservedKey, "schema">): LixnetStreamServer<Events, Routes & Record<K, LixnetRoute<StandardSchemaV1.InferInput<TSchema>, StreamChunk<TResult, unknown>>>, TSchemas, TDefs, TUse, TUses>;
|
|
72
|
+
on<K extends keyof Events & string, const U extends Middleware>(input: LXNStreamServerEventInput<Events, K, LixnetMiddlewareContext<TUse> & LixnetMiddlewareContext<U>, U> & LixnetUseCheck<U, LixnetMiddlewareContext<TUse>> & LixnetReservedInputCheck<FunctionInput<Events[K]>, LixnetStreamReservedKey, "handler"> | LXNEventEntries<Events, {
|
|
73
|
+
[P in keyof Events & string]: LXNStreamServerEventInput<Events, P, LixnetMiddlewareContext<TUse>> & LixnetReservedInputCheck<FunctionInput<Events[P]>, LixnetStreamReservedKey, "handler">;
|
|
51
74
|
}>): void;
|
|
75
|
+
/** Wraps each handler so the chain's last step also sends its output (see `drain`). */
|
|
76
|
+
protected register(input: LXNStreamServerEventInput<Events, keyof Events, any> | LXNStreamServerEventInput<Events, keyof Events, any>[]): void;
|
|
52
77
|
handle(request: Request): Promise<Response>;
|
|
53
78
|
}
|
|
54
79
|
export {};
|