lixnet 1.6.0 → 1.7.1

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/dist/lib/peer.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { LIXNET_ID_PREFIX } from "./vars";
2
- import { errorFromBody, toIssues } from "./error";
2
+ import { LixnetError, errorFromBody, toIssues } from "./error";
3
3
  function createLixnetId() {
4
4
  return LIXNET_ID_PREFIX + Math.random().toString(36).substring(2, 15);
5
5
  }
@@ -16,14 +16,26 @@ export default class LixnetPeer {
16
16
  setTransmissionChunksLimit(limit) {
17
17
  this.transmissionChunksLimit = limit;
18
18
  }
19
- constructor({ events } = {}) {
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, } = {}) {
20
25
  if (events)
21
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;
22
34
  }
23
35
  call = async (event, ...args) => {
24
36
  const [input, { callback = null, onError } = {}] = args;
25
37
  // Like LixnetClient, an omitted input is sent as `{}` so the other side's schema sees an object.
26
- const data = input === undefined ? {} : input;
38
+ const data = this.encode(input === undefined ? {} : input);
27
39
  if (!this.socket)
28
40
  throw new Error("LIXNET - Socket not set");
29
41
  let rf = null;
@@ -258,7 +270,15 @@ export default class LixnetPeer {
258
270
  callback.onError?.(errorFromBody(data.error));
259
271
  }
260
272
  else {
261
- callback.callback(data.data);
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);
262
282
  }
263
283
  }
264
284
  return;
@@ -276,6 +296,15 @@ export default class LixnetPeer {
276
296
  if (!Object.hasOwn(this.eventHandlers, eventName))
277
297
  return;
278
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
+ }
306
+ return;
307
+ }
279
308
  if (schema) {
280
309
  const result = await schema["~standard"].validate(data);
281
310
  if (result.issues) {
@@ -300,7 +329,7 @@ export default class LixnetPeer {
300
329
  if (rf) {
301
330
  socket.send(JSON.stringify({
302
331
  rb: rf,
303
- data: result,
332
+ data: this.encode(result),
304
333
  }));
305
334
  }
306
335
  }
@@ -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.
@@ -19,14 +20,27 @@ export type InferLixnetEvents<T> = T extends {
19
20
  [K in keyof TRoutes]: (input: TRoutes[K]["input"]) => TRoutes[K]["output"];
20
21
  } : T;
21
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, TInjections = LixnetServerInjections> = {
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], TInjections>) => unknown;
33
+ handler: (input: RouteHandlerInput<TSchemas[K], [
34
+ TCtx
35
+ ] extends [never] ? TInjections : TInjections & {
36
+ ctx: RouteContext<TCtx, TUses, K>;
37
+ }>) => unknown;
38
+ };
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>[];
30
44
  };
31
45
  };
32
46
  /** The input a route definition's caller sends: the schema's input, else the handler's parameter minus injections. */
@@ -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;
@@ -0,0 +1,385 @@
1
+ const TAG = "$t";
2
+ const SKIP = Symbol("skip");
3
+ /** Thrown by the fast encode past `MAX_DEPTH`: the value is encoded again, tracking cycles. */
4
+ const DEEP = Symbol("deep");
5
+ const MAX_DEPTH = 500;
6
+ const OBJECT = Object.prototype;
7
+ const ARRAY = Array.prototype;
8
+ /**
9
+ * Binary views, tagged by kind (their `Symbol.toStringTag`, so a Node/Bun `Buffer` is sent as a
10
+ * `Uint8Array`). The payload is the view's own bytes in base64, in the platform's byte order
11
+ * (little-endian on every runtime Lixnet targets).
12
+ */
13
+ const VIEWS = new Map(Object.entries({
14
+ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array,
15
+ Float32Array, Float64Array, BigInt64Array, BigUint64Array, DataView,
16
+ // Feature-detected: not every runtime has it yet.
17
+ ...(globalThis.Float16Array && { Float16Array: globalThis.Float16Array }),
18
+ }));
19
+ const NUMBERS = new Map([["NaN", NaN], ["Infinity", Infinity], ["-Infinity", -Infinity], ["-0", -0]]);
20
+ // Padded base64 (length checked separately). A simple class run: no backtracking stack on large payloads.
21
+ const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
22
+ const INTEGER = /^-?\d+$/;
23
+ function toBase64(bytes) {
24
+ let binary = "";
25
+ for (let i = 0; i < bytes.length; i += 0x8000) {
26
+ binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
27
+ }
28
+ return btoa(binary);
29
+ }
30
+ function fromBase64(base64) {
31
+ if (typeof base64 !== "string" || base64.length % 4 || !BASE64.test(base64))
32
+ fail("invalid base64");
33
+ const binary = atob(base64);
34
+ const bytes = new Uint8Array(binary.length);
35
+ for (let i = 0; i < binary.length; i++)
36
+ bytes[i] = binary.charCodeAt(i);
37
+ return bytes;
38
+ }
39
+ function fail(message) {
40
+ throw new TypeError(`lixnetJSON: ${message}`);
41
+ }
42
+ const isArray = (v, length) => Array.isArray(v) && (length === undefined || v.length === length);
43
+ const isString = (v) => typeof v === "string";
44
+ /** Plain assignment of `__proto__` would set the prototype instead of a key. */
45
+ function setKey(target, key, value) {
46
+ if (key === "__proto__") {
47
+ Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
48
+ }
49
+ else {
50
+ target[key] = value;
51
+ }
52
+ }
53
+ /** Array, Map and Set members can't be dropped, so functions/symbols become `null` like in JSON arrays. */
54
+ function member(value, parents, depth, key) {
55
+ const encoded = encode(value, parents, depth, key, true);
56
+ return encoded === SKIP ? null : encoded;
57
+ }
58
+ /** Tagged form of a built-in type JSON can't carry, or `undefined` for anything else. */
59
+ function special(object) {
60
+ if (object instanceof Date) {
61
+ return { [TAG]: "Date", v: Number.isNaN(object.getTime()) ? null : object.toISOString() };
62
+ }
63
+ if (object instanceof RegExp)
64
+ return { [TAG]: "RegExp", v: [object.source, object.flags] };
65
+ if (typeof URL !== "undefined" && object instanceof URL)
66
+ return { [TAG]: "URL", v: object.href };
67
+ // Name and message only: the stack and cause stay on the side that threw.
68
+ if (object instanceof Error)
69
+ return { [TAG]: "Error", v: [String(object.name), String(object.message)] };
70
+ if (object instanceof ArrayBuffer)
71
+ return { [TAG]: "ArrayBuffer", v: toBase64(new Uint8Array(object)) };
72
+ if (ArrayBuffer.isView(object) && VIEWS.has(object[Symbol.toStringTag])) {
73
+ // Only the view's own bytes, never the rest of a shared buffer.
74
+ const bytes = new Uint8Array(object.buffer, object.byteOffset, object.byteLength);
75
+ return { [TAG]: object[Symbol.toStringTag], v: toBase64(bytes) };
76
+ }
77
+ return undefined;
78
+ }
79
+ /**
80
+ * Copy-on-write: returns `value` itself when `JSON.stringify` already writes it the way lixnetJSON
81
+ * would, so plain JSON costs one read-only walk. An array or object is copied only once one of its
82
+ * members changes (and then only from the first such member on), so untouched subtrees are shared.
83
+ *
84
+ * `key` is what `toJSON(key)` receives, as with `JSON.stringify`. `json` is false for a value that
85
+ * `toJSON` just returned: like `JSON.stringify`, that value's own `toJSON` isn't called again (so
86
+ * if it has one, it's copied into a plain object for `JSON.stringify` not to call it either).
87
+ *
88
+ * `parents` is null on the fast pass, which only counts depth; past `MAX_DEPTH` it throws `DEEP`
89
+ * and `serialize` encodes again with a parents set, which tells a cycle from a deep value.
90
+ * Recursive, so extremely deep values (~10k+ levels) can overflow the stack, as `JSON.stringify` can.
91
+ */
92
+ function encode(value, parents, depth, key, json) {
93
+ switch (typeof value) {
94
+ case "string":
95
+ case "boolean":
96
+ return value;
97
+ case "number":
98
+ if (Number.isFinite(value) && !Object.is(value, -0))
99
+ return value;
100
+ return { [TAG]: "number", v: Object.is(value, -0) ? "-0" : String(value) };
101
+ case "bigint":
102
+ return { [TAG]: "bigint", v: value.toString() };
103
+ case "undefined":
104
+ return { [TAG]: "undefined" };
105
+ case "function":
106
+ case "symbol":
107
+ // Dropped, like JSON.stringify does.
108
+ return SKIP;
109
+ }
110
+ if (value === null)
111
+ return null;
112
+ const object = value;
113
+ if (parents === null) {
114
+ if (depth > MAX_DEPTH)
115
+ throw DEEP;
116
+ }
117
+ else if (parents.has(object)) {
118
+ fail("cannot serialize a circular structure");
119
+ }
120
+ // Plain objects and arrays (the common case) can't be any of the special types.
121
+ const proto = Object.getPrototypeOf(object);
122
+ const plain = proto === OBJECT || proto === ARRAY;
123
+ if (!plain) {
124
+ const tagged = special(object);
125
+ if (tagged !== undefined)
126
+ return tagged;
127
+ }
128
+ const hasToJSON = typeof object.toJSON === "function";
129
+ if (json && hasToJSON)
130
+ return encode(object.toJSON(String(key)), parents, depth, key, false);
131
+ // Only plain objects and arrays without a toJSON can be handed to JSON.stringify as they are:
132
+ // it would call that toJSON, unbox `new Number(1)`, print `JSON.rawJSON` text... So anything
133
+ // else is copied, like before.
134
+ const copy = hasToJSON || !plain;
135
+ parents?.add(object);
136
+ depth++;
137
+ let result;
138
+ if (Array.isArray(object)) {
139
+ const length = object.length;
140
+ let out = copy ? new Array(length) : undefined;
141
+ for (let i = 0; i < length; i++) {
142
+ const item = object[i];
143
+ // Holes in sparse arrays become `null`, as with JSON (not `undefined`).
144
+ const encoded = item === undefined && !(i in object) ? null : member(item, parents, depth, i);
145
+ if (out === undefined) {
146
+ if (encoded === item)
147
+ continue;
148
+ out = new Array(length);
149
+ for (let j = 0; j < i; j++)
150
+ out[j] = object[j];
151
+ }
152
+ out[i] = encoded;
153
+ }
154
+ result = out ?? object;
155
+ }
156
+ else if (!plain && object instanceof Map) {
157
+ // Map and Set members get "" as their toJSON key.
158
+ result = { [TAG]: "Map", v: Array.from(object, ([k, item]) => [member(k, parents, depth, ""), member(item, parents, depth, "")]) };
159
+ }
160
+ else if (!plain && object instanceof Set) {
161
+ result = { [TAG]: "Set", v: Array.from(object, (item) => member(item, parents, depth, "")) };
162
+ }
163
+ else {
164
+ const keys = Object.keys(object);
165
+ let out = copy ? {} : undefined;
166
+ for (let i = 0; i < keys.length; i++) {
167
+ const k = keys[i];
168
+ const item = object[k];
169
+ const encoded = encode(item, parents, depth, k, true);
170
+ if (out === undefined) {
171
+ if (encoded === item)
172
+ continue;
173
+ out = {};
174
+ for (let j = 0; j < i; j++)
175
+ setKey(out, keys[j], object[keys[j]]);
176
+ }
177
+ if (encoded !== SKIP)
178
+ setKey(out, k, encoded);
179
+ }
180
+ // A plain object that has a `$t` key of its own is wrapped so it isn't read as a tagged value.
181
+ result = Object.hasOwn(object, TAG) ? { [TAG]: "object", v: out ?? object } : out ?? object;
182
+ }
183
+ parents?.delete(object);
184
+ return result;
185
+ }
186
+ function decodeObject(object, owned) {
187
+ if (object === null || typeof object !== "object" || Array.isArray(object))
188
+ fail("object tag needs an object");
189
+ const source = object;
190
+ const keys = Object.keys(source);
191
+ if (owned) {
192
+ // In place: only members that decode to something else are written back.
193
+ for (let i = 0; i < keys.length; i++) {
194
+ const item = source[keys[i]];
195
+ if (item === null || typeof item !== "object")
196
+ continue;
197
+ const decoded = decode(item, true);
198
+ if (decoded !== item)
199
+ setKey(source, keys[i], decoded);
200
+ }
201
+ return source;
202
+ }
203
+ const out = {};
204
+ for (let i = 0; i < keys.length; i++)
205
+ setKey(out, keys[i], decode(source[keys[i]], false));
206
+ return out;
207
+ }
208
+ /**
209
+ * Strict: every tag checks its payload and throws a TypeError on anything the encoder can't produce.
210
+ * `owned` (Lixnet's own call sites, on fresh `JSON.parse` output) decodes arrays and plain objects
211
+ * in place; otherwise they're copied and the input is left untouched.
212
+ */
213
+ function decode(value, owned) {
214
+ if (value === null || typeof value !== "object")
215
+ return value;
216
+ if (Array.isArray(value)) {
217
+ if (!owned)
218
+ return value.map((item) => decode(item, false));
219
+ for (let i = 0; i < value.length; i++) {
220
+ const item = value[i];
221
+ if (item === null || typeof item !== "object")
222
+ continue;
223
+ const decoded = decode(item, true);
224
+ if (decoded !== item)
225
+ value[i] = decoded;
226
+ }
227
+ return value;
228
+ }
229
+ const object = value;
230
+ const tag = object[TAG];
231
+ if (tag === undefined)
232
+ return decodeObject(object, owned);
233
+ const v = object.v;
234
+ switch (tag) {
235
+ case "number":
236
+ if (!NUMBERS.has(v))
237
+ fail("invalid number");
238
+ return NUMBERS.get(v);
239
+ case "bigint":
240
+ if (!isString(v) || !INTEGER.test(v))
241
+ fail("invalid bigint");
242
+ return BigInt(v);
243
+ case "undefined":
244
+ return undefined;
245
+ case "Date": {
246
+ if (v !== null && !isString(v))
247
+ fail("invalid Date");
248
+ const date = new Date(v === null ? NaN : v);
249
+ if (v !== null && Number.isNaN(date.getTime()))
250
+ fail("invalid Date");
251
+ return date;
252
+ }
253
+ case "RegExp":
254
+ if (!isArray(v, 2) || !isString(v[0]) || !isString(v[1]))
255
+ fail("invalid RegExp");
256
+ try {
257
+ return new RegExp(v[0], v[1]);
258
+ }
259
+ catch {
260
+ fail("invalid RegExp");
261
+ }
262
+ case "URL":
263
+ if (!isString(v))
264
+ fail("invalid URL");
265
+ try {
266
+ return new URL(v);
267
+ }
268
+ catch {
269
+ fail("invalid URL");
270
+ }
271
+ case "Error": {
272
+ if (!isArray(v, 2) || !isString(v[0]) || !isString(v[1]))
273
+ fail("invalid Error");
274
+ const error = new Error(v[1]);
275
+ error.name = v[0];
276
+ return error;
277
+ }
278
+ case "ArrayBuffer":
279
+ return fromBase64(v).buffer;
280
+ case "Map":
281
+ if (!isArray(v) || !v.every((entry) => isArray(entry, 2)))
282
+ fail("invalid Map");
283
+ return new Map(v.map(([key, item]) => [decode(key, owned), decode(item, owned)]));
284
+ case "Set":
285
+ if (!isArray(v))
286
+ fail("invalid Set");
287
+ return new Set(v.map((item) => decode(item, owned)));
288
+ case "object":
289
+ return decodeObject(v, owned);
290
+ }
291
+ const View = isString(tag) ? VIEWS.get(tag) : undefined;
292
+ if (!View)
293
+ fail(`unknown tag ${JSON.stringify(tag)}`);
294
+ const bytes = fromBase64(v);
295
+ const size = View.BYTES_PER_ELEMENT ?? 1;
296
+ if (bytes.length % size)
297
+ fail(`invalid ${tag} length`);
298
+ return View === Uint8Array ? bytes : new View(bytes.buffer, 0, bytes.length / size);
299
+ }
300
+ /** Whether a primitive needs a tag: anything but strings, booleans and finite numbers other than -0. */
301
+ function taggedPrimitive(v) {
302
+ // Number.isFinite/Object.is, not arithmetic tricks: those made Bun's JIT unstable here (2-4x).
303
+ return typeof v === "number" ? !Number.isFinite(v) || Object.is(v, -0) : typeof v !== "string" && typeof v !== "boolean";
304
+ }
305
+ /**
306
+ * The fast check `serialize` runs first: allocates nothing and stops at the first thing
307
+ * `JSON.stringify` wouldn't write the way lixnetJSON does. Conservative: anything other than a
308
+ * plain object or array (`Object.prototype` / `Array.prototype`), any `toJSON` key, an own `$t`
309
+ * key, a tagged primitive or a very deep (or circular) value answers true, and `encode` decides.
310
+ * This walk is the whole cost of plain JSON, so it's tuned for Bun/JSC (see the comments).
311
+ */
312
+ function needsEncoding(value, depth) {
313
+ if (depth > MAX_DEPTH)
314
+ return true;
315
+ const proto = Object.getPrototypeOf(value);
316
+ if (proto === ARRAY) {
317
+ if (value.toJSON !== undefined)
318
+ return true;
319
+ for (let i = 0; i < value.length; i++) {
320
+ const item = value[i];
321
+ if (typeof item === "object" ? item !== null && needsEncoding(item, depth + 1) : taggedPrimitive(item))
322
+ return true;
323
+ }
324
+ return false;
325
+ }
326
+ if (proto !== OBJECT || value.toJSON !== undefined || Object.hasOwn(value, TAG))
327
+ return true;
328
+ // for-in is ~2x faster than Object.keys here. It would also visit enumerable keys someone added
329
+ // to Object.prototype, which can only make the answer more conservative.
330
+ for (const key in value) {
331
+ const item = value[key];
332
+ if (typeof item === "object" ? item !== null && needsEncoding(item, depth + 1) : taggedPrimitive(item))
333
+ return true;
334
+ }
335
+ return false;
336
+ }
337
+ function serialize(value) {
338
+ // Plain JSON (the common case) is returned as it is.
339
+ if (typeof value === "object" ? value === null || !needsEncoding(value, 0) : !taggedPrimitive(value))
340
+ return value;
341
+ let encoded;
342
+ try {
343
+ encoded = encode(value, null, 0, "", true);
344
+ }
345
+ catch (error) {
346
+ if (error !== DEEP)
347
+ throw error;
348
+ // Deep or circular: again, with cycle tracking.
349
+ encoded = encode(value, new Set(), 0, "", true);
350
+ }
351
+ return encoded === SKIP ? { [TAG]: "undefined" } : encoded;
352
+ }
353
+ const NAME = "lixnet-json";
354
+ const ownedDecoder = { name: NAME, serialize, deserialize: (value) => decode(value, true) };
355
+ const passThrough = { name: NAME, serialize, deserialize: (value) => value };
356
+ /** Public: copies, so a caller's own object is never modified. */
357
+ const deserialize = Object.assign((value) => decode(value, false), {
358
+ // Lixnet only uses this on fresh `JSON.parse` output it owns, so it decodes in place, and skips
359
+ // decoding when the text has no `"$t"` at all (then there's no tagged value to decode). A key
360
+ // written with an escape (`"\u0024t"`) gets past the text check, but then simply stays a plain
361
+ // object: it can't turn into another type, so that's acceptable.
362
+ "~received": (text) => (hasTagKey(text) ? ownedDecoder : passThrough),
363
+ });
364
+ /**
365
+ * Whether `text` contains `"$t"`. Searches for `$t` and checks the quotes around it: much faster
366
+ * than `includes('"$t"')`, whose first character, `"`, is everywhere in JSON.
367
+ */
368
+ function hasTagKey(text) {
369
+ for (let i = text.indexOf(TAG); i !== -1; i = text.indexOf(TAG, i + 2)) {
370
+ if (text.charCodeAt(i - 1) === 34 && text.charCodeAt(i + 2) === 34)
371
+ return true;
372
+ }
373
+ return false;
374
+ }
375
+ /**
376
+ * The built-in serializer. Plain JSON passes through unchanged; on top of it, it keeps `Date`,
377
+ * `Map`, `Set`, `BigInt`, `undefined`, `NaN` / `±Infinity` / `-0`, `RegExp`, `URL`, `Error`
378
+ * (name and message only), `ArrayBuffer`, `DataView` and every typed array (`Buffer` arrives as a
379
+ * `Uint8Array`). Decoding is strict: a malformed tagged value throws a `TypeError`. Other class
380
+ * instances are sent like `JSON.stringify` sends them (`toJSON()`, else their own enumerable fields).
381
+ *
382
+ * `serialize` shares what needs no encoding with its input (plain JSON comes back as the same
383
+ * object), so don't mutate its result. `deserialize` always returns new arrays and objects.
384
+ */
385
+ export const lixnetJSON = { name: NAME, serialize, deserialize };
@@ -1,44 +1,62 @@
1
1
  import LixnetServerBase, { type LixnetServerBaseOptions } from "./serverbase";
2
- import type { FunctionInput, FunctionOutput, LXNEventEntries, LXNEventSchema, LXNServerHandler, LXN_ServerClient_EventType } from "./types";
2
+ import type { FunctionInput, FunctionOutput, LXNEventEntries, LXNEventSchema, LXNServerHandler, LXN_ServerClient_EventType, LixnetReservedInputCheck, LixnetReservedSchemasCheck, LixnetReservedKey } from "./types";
3
3
  import { LixnetResponse } from "./util/response";
4
- import { type LixnetRequest } from "./util/request";
5
4
  import type { StandardSchemaV1 } from "./standardschema";
6
- import type { LixnetRouteDefinitions, LixnetRoute, LixnetRoutes, LixnetRoutesFromDefinitions, LixnetRoutesOption } from "./router";
5
+ import type { LixnetRouteDefinitions, LixnetRoute, LixnetRoutes, LixnetRoutesFromDefinitions, LixnetRoutesOption, LixnetRouteUses } from "./router";
7
6
  import type { LixnetServerInjections } from "./types";
8
- type LXNServerEventInput<Events extends LXN_ServerClient_EventType, TName extends keyof Events> = {
7
+ import type { LixnetCheckMiddleware, LixnetMiddleware, LixnetMiddlewareContext, LixnetRouteUsesCheck, LixnetUseCheck } from "./middleware";
8
+ type Middleware = readonly LixnetMiddleware<any, any>[];
9
+ type LXNServerEventInput<Events extends LXN_ServerClient_EventType, TName extends keyof Events, TCtx = {}, TUse extends Middleware = Middleware> = {
9
10
  event: TName;
10
- handler: LXNServerHandler<FunctionInput<Events[TName]> & {
11
- request: LixnetRequest;
12
- response: LixnetResponse;
13
- }, FunctionOutput<Events[TName]>>;
11
+ /** Middleware for this event only, run after the server's. */
12
+ use?: TUse;
13
+ handler: LXNServerHandler<FunctionInput<Events[TName]> & LixnetServerInjections<TCtx>, FunctionOutput<Events[TName]>>;
14
14
  schema?: LXNEventSchema<Events, TName>;
15
15
  };
16
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
17
  handler: (input: any) => unknown;
18
- }> = {}> extends LixnetServerBase<LXNServerEventInput<Events, keyof Events>> {
18
+ }> = {}, const TUse extends Middleware = [], TUses = {}> extends LixnetServerBase<LXNServerEventInput<Events, keyof Events, any>> {
19
19
  /** Type-only: routes from the `routes` option and `.route(...)`, read by `InferLixnetEvents`. */
20
20
  readonly "~routes": Routes & LixnetRoutesFromDefinitions<TDefs>;
21
21
  private formatter;
22
22
  constructor({ formatter, routes, events, ...options }?: LixnetServerBaseOptions & {
23
23
  formatter?: (this: LixnetResponse) => Response;
24
- } & LixnetRoutesOption<TDefs & LixnetRouteDefinitions<TSchemas>>);
24
+ /** Middleware for every route. Each may read what the ones before it add to `ctx`. */
25
+ use?: TUse;
26
+ } & LixnetUseCheck<TUse, {}> & LixnetRoutesOption<TDefs & LixnetRouteDefinitions<TSchemas, LixnetServerInjections, LixnetMiddlewareContext<TUse>, TUses> & LixnetRouteUses<TUses> & LixnetRouteUsesCheck<TUses, LixnetMiddlewareContext<TUse>> & LixnetReservedSchemasCheck<TSchemas, LixnetReservedKey>>);
27
+ /**
28
+ * Adds middleware for the routes registered after this call (not earlier ones). Each can add
29
+ * fields to `ctx`: `server.use(auth).route("me", { handler: ({ ctx }) => ctx.user })`.
30
+ *
31
+ * Reassign or chain the result to keep the added `ctx` types.
32
+ */
33
+ use<const M extends Middleware>(...middleware: M & LixnetCheckMiddleware<M, LixnetMiddlewareContext<TUse>>): LixnetServer<Events, Routes, TSchemas, TDefs, [...TUse, ...M], TUses>;
34
+ /** Without a schema or input of its own: the handler gets only the injections (typed `ctx` included). */
35
+ route<K extends string, TOutput, const U extends Middleware>(event: K, route: {
36
+ schema?: undefined;
37
+ use?: U;
38
+ handler: (input: LixnetServerInjections<LixnetMiddlewareContext<TUse> & LixnetMiddlewareContext<U>>) => TOutput;
39
+ } & LixnetUseCheck<U, LixnetMiddlewareContext<TUse>>): LixnetServer<Events, Routes & Record<K, LixnetRoute<{}, Awaited<TOutput>>>, TSchemas, TDefs, TUse, TUses>;
40
+ /** Without a schema, the input is the handler's parameter type minus `request`/`response`/`ctx`. */
41
+ route<K extends string, TParams, TOutput, const U extends Middleware>(event: K, route: {
42
+ schema?: undefined;
43
+ use?: U;
44
+ handler: (input: TParams & LixnetServerInjections<LixnetMiddlewareContext<TUse> & LixnetMiddlewareContext<U>>) => TOutput;
45
+ } & LixnetUseCheck<U, LixnetMiddlewareContext<TUse>>): LixnetServer<Events, Routes & Record<K, LixnetRoute<Omit<TParams, keyof LixnetServerInjections>, Awaited<TOutput>>>, TSchemas, TDefs, TUse, TUses>;
25
46
  /**
26
47
  * Adds an event whose types are inferred, so no `Events` contract is needed. Chain calls and
27
48
  * give the client `typeof server` through an `import type`.
28
49
  *
29
50
  * With a schema, the handler gets the schema's output and the client sends its input.
30
51
  */
31
- route<K extends string, TSchema extends StandardSchemaV1, TOutput>(event: K, route: {
52
+ route<K extends string, TSchema extends StandardSchemaV1, TOutput, const U extends Middleware>(event: K, route: {
32
53
  schema: TSchema;
33
- handler: (input: StandardSchemaV1.InferOutput<TSchema> & LixnetServerInjections) => TOutput;
34
- }): LixnetServer<Events, Routes & Record<K, LixnetRoute<StandardSchemaV1.InferInput<TSchema>, Awaited<TOutput>>>, TSchemas, TDefs>;
35
- /** Without a schema, the input is the handler's parameter type minus `request`/`response`. */
36
- route<K extends string, TParams, TOutput>(event: K, route: {
37
- schema?: undefined;
38
- handler: (input: TParams) => TOutput;
39
- }): LixnetServer<Events, Routes & Record<K, LixnetRoute<Omit<TParams, keyof LixnetServerInjections>, Awaited<TOutput>>>, TSchemas, TDefs>;
40
- on<K extends keyof Events & string>(input: LXNServerEventInput<Events, K> | LXNEventEntries<Events, {
41
- [P in keyof Events & string]: LXNServerEventInput<Events, P>;
54
+ /** Middleware for this route only, run after the server's. */
55
+ use?: U;
56
+ handler: (input: StandardSchemaV1.InferOutput<TSchema> & LixnetServerInjections<LixnetMiddlewareContext<TUse> & LixnetMiddlewareContext<U>>) => TOutput;
57
+ } & LixnetUseCheck<U, LixnetMiddlewareContext<TUse>> & LixnetReservedInputCheck<StandardSchemaV1.InferOutput<TSchema>, LixnetReservedKey, "schema">): LixnetServer<Events, Routes & Record<K, LixnetRoute<StandardSchemaV1.InferInput<TSchema>, Awaited<TOutput>>>, TSchemas, TDefs, TUse, TUses>;
58
+ on<K extends keyof Events & string, const U extends Middleware>(input: LXNServerEventInput<Events, K, LixnetMiddlewareContext<TUse> & LixnetMiddlewareContext<U>, U> & LixnetUseCheck<U, LixnetMiddlewareContext<TUse>> & LixnetReservedInputCheck<FunctionInput<Events[K]>, LixnetReservedKey, "handler"> | LXNEventEntries<Events, {
59
+ [P in keyof Events & string]: LXNServerEventInput<Events, P, LixnetMiddlewareContext<TUse>> & LixnetReservedInputCheck<FunctionInput<Events[P]>, LixnetReservedKey, "handler">;
42
60
  }>): void;
43
61
  handle(request: Request): Promise<Response>;
44
62
  }
@@ -11,6 +11,16 @@ export default class LixnetServer extends LixnetServerBase {
11
11
  this.register({ ...route, event });
12
12
  }
13
13
  }
14
+ /**
15
+ * Adds middleware for the routes registered after this call (not earlier ones). Each can add
16
+ * fields to `ctx`: `server.use(auth).route("me", { handler: ({ ctx }) => ctx.user })`.
17
+ *
18
+ * Reassign or chain the result to keep the added `ctx` types.
19
+ */
20
+ use(...middleware) {
21
+ this.addMiddleware(middleware);
22
+ return this;
23
+ }
14
24
  route(event, route) {
15
25
  this.register({ ...route, event });
16
26
  return this;
@@ -19,7 +29,7 @@ export default class LixnetServer extends LixnetServerBase {
19
29
  this.register(input);
20
30
  }
21
31
  async handle(request) {
22
- const response = new LixnetResponse({ formatter: this.formatter });
32
+ const response = new LixnetResponse({ formatter: this.formatter, serializer: this.serializer });
23
33
  const corsResponse = this.handleCors(request, response);
24
34
  if (corsResponse)
25
35
  return corsResponse;
@@ -28,15 +38,15 @@ export default class LixnetServer extends LixnetServerBase {
28
38
  return this.fail(response, parsed);
29
39
  }
30
40
  try {
31
- const data = await parsed.entry.handler({
32
- ...parsed.input,
41
+ const output = await this.invoke(parsed.entry, parsed.input, {
33
42
  request: createLixnetRequest(request, response, parsed.body),
34
43
  response: response,
35
44
  });
36
- //check data isnt void/null/undefined
37
- if (!(data === undefined || data === null)) {
38
- response.data(data);
45
+ // A null/undefined return keeps data staged with `response.data()`. Raw: encoded when formatted.
46
+ if (output != null || response.responseData === undefined) {
47
+ response.data(output);
39
48
  }
49
+ // Throws a 500 LixnetError "Could not serialize the response" if the output can't be encoded.
40
50
  return response.format();
41
51
  }
42
52
  catch (error) {