lixnet 1.3.14 → 1.5.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.
@@ -0,0 +1,65 @@
1
+ import type { StandardSchemaV1 } from "./standardschema";
2
+ import type { DebugLogger } from "./types";
3
+ import type { LixnetResponse } from "./util/response";
4
+ import { type LixnetErrorCode } from "./error";
5
+ import { type LixnetCorsOptions } from "./util/cors";
6
+ export type LixnetServerBaseOptions = {
7
+ /** Log failed requests (including the thrown error) through `logger`. */
8
+ debugLog?: boolean;
9
+ /**
10
+ * Add the underlying error message to error responses as `detail`.
11
+ * Off by default: exception messages can leak internals (SQL, connection strings).
12
+ */
13
+ exposeErrors?: boolean;
14
+ logger?: DebugLogger;
15
+ defaultHeaders?: Record<string, string>;
16
+ /**
17
+ * Handle CORS: answers `OPTIONS` preflights (cached for `maxAge`, default 7200s), adds CORS
18
+ * headers to every response, and rejects requests from origins that aren't allowed.
19
+ */
20
+ cors?: LixnetCorsOptions;
21
+ };
22
+ type EventEntry = {
23
+ event: PropertyKey;
24
+ schema?: StandardSchemaV1;
25
+ };
26
+ /** A failed request, before it's written to the response. */
27
+ type Failure = {
28
+ error: string;
29
+ status: number;
30
+ code: LixnetErrorCode;
31
+ data?: unknown;
32
+ /** Logged with `debugLog`; its message becomes `detail` with `exposeErrors`. */
33
+ cause?: unknown;
34
+ event?: string;
35
+ };
36
+ type ParsedRpcRequest<TEntry> = {
37
+ ok: true;
38
+ entry: TEntry;
39
+ input: any;
40
+ } | ({
41
+ ok: false;
42
+ } & Failure);
43
+ /** Shared request parsing and error handling for `LixnetServer` and `LixnetStreamServer`. */
44
+ export default abstract class LixnetServerBase<TEntry extends EventEntry> {
45
+ protected events: Record<string, TEntry>;
46
+ protected logger: DebugLogger;
47
+ protected debugLog: boolean;
48
+ protected exposeErrors: boolean;
49
+ protected defaultHeaders: Record<string, string>;
50
+ protected cors?: LixnetCorsOptions;
51
+ protected constructor({ debugLog, exposeErrors, logger, defaultHeaders, cors, }: LixnetServerBaseOptions);
52
+ protected register(input: TEntry | TEntry[]): void;
53
+ protected parse(request: Request): Promise<ParsedRpcRequest<TEntry>>;
54
+ /**
55
+ * With `cors` set: answers preflights and rejects disallowed origins (returns the Response),
56
+ * otherwise stages CORS headers on `response` (handlers can still override them) and returns null.
57
+ */
58
+ protected handleCors(request: Request, response: LixnetResponse): Response | null;
59
+ /** A `LixnetError` is sent as thrown; anything else becomes a generic 500 "Handler error". */
60
+ protected failureFromThrown(error: unknown, event: string): Failure;
61
+ /** Logs the failure (with `debugLog`) and stages it on the response with its status. */
62
+ protected stageFailure(response: LixnetResponse, { error, status, code, data, cause, event }: Failure): void;
63
+ protected fail(response: LixnetResponse, failure: Failure): Response;
64
+ }
65
+ export {};
@@ -0,0 +1,157 @@
1
+ import LixnetLog from "./util/log";
2
+ import { LixnetError } from "./error";
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
+ function describeError(cause) {
14
+ if (cause === undefined)
15
+ return undefined;
16
+ if (cause instanceof Error)
17
+ return cause.message;
18
+ if (Array.isArray(cause))
19
+ return cause.map((issue) => issue?.message ?? String(issue)).join("; ");
20
+ return String(cause);
21
+ }
22
+ /** Shared request parsing and error handling for `LixnetServer` and `LixnetStreamServer`. */
23
+ export default class LixnetServerBase {
24
+ events = {};
25
+ logger = LixnetLog;
26
+ debugLog;
27
+ exposeErrors;
28
+ defaultHeaders;
29
+ cors;
30
+ constructor({ debugLog = false, exposeErrors = false, logger, defaultHeaders = {}, cors, }) {
31
+ if (cors)
32
+ assertCorsOptions(cors);
33
+ this.cors = cors;
34
+ this.debugLog = debugLog;
35
+ this.exposeErrors = exposeErrors;
36
+ this.defaultHeaders = defaultHeaders;
37
+ if (logger)
38
+ this.logger = logger;
39
+ }
40
+ register(input) {
41
+ const entries = Array.isArray(input) ? input : [input];
42
+ for (const entry of entries) {
43
+ this.events[entry.event] = entry;
44
+ }
45
+ }
46
+ async parse(request) {
47
+ let json;
48
+ try {
49
+ json = await request.json();
50
+ }
51
+ catch (cause) {
52
+ return { ok: false, error: "Invalid JSON", status: 400, code: "BAD_REQUEST", cause };
53
+ }
54
+ if (json === null || typeof json !== "object" || Array.isArray(json)) {
55
+ return { ok: false, error: "Invalid request body", status: 400, code: "BAD_REQUEST" };
56
+ }
57
+ if (typeof json.event !== "string" || !json.event) {
58
+ return { ok: false, error: "Event not found", status: 400, code: "BAD_REQUEST" };
59
+ }
60
+ if (!("input" in json)) {
61
+ return { ok: false, error: "Input not found", status: 400, code: "BAD_REQUEST" };
62
+ }
63
+ // hasOwn so names like "constructor" or "toString" don't resolve to prototype members.
64
+ if (!Object.hasOwn(this.events, json.event)) {
65
+ return {
66
+ ok: false,
67
+ error: "Event not found",
68
+ status: 404,
69
+ code: "NOT_FOUND",
70
+ event: json.event,
71
+ };
72
+ }
73
+ const entry = this.events[json.event];
74
+ if (!entry.schema) {
75
+ return { ok: true, entry, input: json.input };
76
+ }
77
+ const result = await entry.schema["~standard"].validate(json.input);
78
+ if (result.issues) {
79
+ return {
80
+ ok: false,
81
+ error: "Invalid input",
82
+ status: 400,
83
+ code: "INVALID_INPUT",
84
+ // Validation messages are meant for the caller, so they're always sent.
85
+ data: { issues: toIssues(result.issues) },
86
+ cause: result.issues,
87
+ event: json.event,
88
+ };
89
+ }
90
+ return { ok: true, entry, input: result.value };
91
+ }
92
+ /**
93
+ * With `cors` set: answers preflights and rejects disallowed origins (returns the Response),
94
+ * otherwise stages CORS headers on `response` (handlers can still override them) and returns null.
95
+ */
96
+ handleCors(request, response) {
97
+ if (!this.cors)
98
+ return null;
99
+ // No Origin header: same-origin GET or a server-to-server call (e.g. SSR), not CORS.
100
+ const origin = request.headers.get("Origin");
101
+ if (!origin) {
102
+ return request.method === "OPTIONS" ? new Response(null, { status: 204 }) : null;
103
+ }
104
+ if (!isOriginAllowed(this.cors, origin)) {
105
+ if (request.method === "OPTIONS")
106
+ return new Response(null, { status: 403 });
107
+ return this.fail(response, {
108
+ error: "Origin not allowed",
109
+ status: 403,
110
+ code: "FORBIDDEN",
111
+ cause: origin,
112
+ });
113
+ }
114
+ if (request.method === "OPTIONS") {
115
+ return new Response(null, {
116
+ status: 204,
117
+ headers: preflightHeaders(this.cors, origin, request.headers.get("Access-Control-Request-Headers")),
118
+ });
119
+ }
120
+ response.headers(corsHeaders(this.cors, origin));
121
+ return null;
122
+ }
123
+ /** A `LixnetError` is sent as thrown; anything else becomes a generic 500 "Handler error". */
124
+ failureFromThrown(error, event) {
125
+ if (LixnetError.is(error)) {
126
+ return {
127
+ error: error.message,
128
+ status: error.status,
129
+ code: error.code,
130
+ data: error.data,
131
+ cause: error.cause ?? error,
132
+ event,
133
+ };
134
+ }
135
+ return { error: "Handler error", status: 500, code: "INTERNAL", cause: error, event };
136
+ }
137
+ /** Logs the failure (with `debugLog`) and stages it on the response with its status. */
138
+ stageFailure(response, { error, status, code, data, cause, event }) {
139
+ if (this.debugLog) {
140
+ this.logger({
141
+ error: true,
142
+ message: event ? `${error} (event "${event}")` : error,
143
+ cause,
144
+ });
145
+ }
146
+ response.code(status);
147
+ response.error(error, {
148
+ code,
149
+ data,
150
+ detail: this.exposeErrors ? describeError(cause) : undefined,
151
+ });
152
+ }
153
+ fail(response, failure) {
154
+ this.stageFailure(response, failure);
155
+ return response.format();
156
+ }
157
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Standard Schema v1 interface (https://standardschema.dev), copied in as the spec intends so
3
+ * Lixnet needs no runtime or type dependency. Implemented by zod (3.24+/4), valibot, arktype,
4
+ * Effect Schema and others. MIT licensed by the Standard Schema authors.
5
+ */
6
+ export interface StandardSchemaV1<Input = unknown, Output = Input> {
7
+ readonly "~standard": StandardSchemaV1.Props<Input, Output>;
8
+ }
9
+ export declare namespace StandardSchemaV1 {
10
+ interface Props<Input = unknown, Output = Input> {
11
+ readonly version: 1;
12
+ readonly vendor: string;
13
+ readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
14
+ readonly types?: Types<Input, Output> | undefined;
15
+ }
16
+ type Result<Output> = SuccessResult<Output> | FailureResult;
17
+ interface SuccessResult<Output> {
18
+ readonly value: Output;
19
+ readonly issues?: undefined;
20
+ }
21
+ interface FailureResult {
22
+ readonly issues: ReadonlyArray<Issue>;
23
+ }
24
+ interface Issue {
25
+ readonly message: string;
26
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
27
+ }
28
+ interface PathSegment {
29
+ readonly key: PropertyKey;
30
+ }
31
+ interface Types<Input = unknown, Output = Input> {
32
+ readonly input: Input;
33
+ readonly output: Output;
34
+ }
35
+ type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["input"];
36
+ type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
37
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,15 +1,17 @@
1
- import type { FunctionInput, FunctionOutput, LXN_ServerClient_EventType } from "./types";
1
+ import type { FunctionInput, FunctionOutput, LXNCallArgs, LXN_ServerClient_EventType } from "./types";
2
+ import type { InferLixnetEvents } from "./router";
2
3
  type Prettify<T> = {
3
4
  [K in keyof T]: T[K];
4
5
  } & {};
5
6
  export type LXNStreamCallOptions<TChunk> = Prettify<{
6
7
  onStreamChunk?: (chunk: TChunk) => void;
7
8
  } & Omit<RequestInit, "method" | "body">>;
8
- export default class LixnetStreamClient<Events extends LXN_ServerClient_EventType> {
9
+ export default class LixnetStreamClient<Contract extends LXN_ServerClient_EventType, Events extends LXN_ServerClient_EventType = InferLixnetEvents<Contract>> {
9
10
  private rpcUrl;
10
11
  constructor({ rpcUrl }: {
11
12
  rpcUrl: string;
12
13
  });
13
- call<K extends keyof Events>(event: K, input: FunctionInput<Events[K]>, options?: LXNStreamCallOptions<FunctionOutput<Events[K]>>): Promise<void>;
14
+ /** Resolves when the stream ends; throws if the server returns or streams an error. */
15
+ call<K extends keyof Events>(event: K, ...[input, options]: LXNCallArgs<FunctionInput<Events[K]>, LXNStreamCallOptions<FunctionOutput<Events[K]>>>): Promise<void>;
14
16
  }
15
17
  export {};
@@ -1,47 +1,61 @@
1
+ import withJsonContentType from "./util/withJsonContentType";
2
+ import { LixnetError, codeForStatus, errorFromBody } from "./error";
1
3
  export default class LixnetStreamClient {
2
4
  rpcUrl;
3
5
  constructor({ rpcUrl }) {
4
6
  this.rpcUrl = rpcUrl;
5
7
  }
6
- async call(event, input, options = {}) {
8
+ /** Resolves when the stream ends; throws if the server returns or streams an error. */
9
+ async call(event, ...[input, options = {}]) {
7
10
  const { onStreamChunk, ...fetchOptions } = options;
8
11
  const response = await fetch(this.rpcUrl, {
9
- method: "POST",
10
- headers: { "Content-Type": "application/json" },
11
- body: JSON.stringify({ event, input }),
12
12
  ...fetchOptions,
13
+ method: "POST",
14
+ headers: withJsonContentType(fetchOptions.headers),
15
+ body: JSON.stringify({ event, input: input === undefined ? {} : input }),
13
16
  });
17
+ if (!response.ok) {
18
+ const json = await response.json().catch(() => null);
19
+ if (json && typeof json.error === "string")
20
+ throw errorFromBody(json, response.status);
21
+ throw new LixnetError(codeForStatus(response.status), `Stream request failed with status ${response.status}`, { status: response.status });
22
+ }
14
23
  if (!response.body)
15
24
  throw new Error("Stream response has no body");
16
25
  const reader = response.body.getReader();
17
26
  const decoder = new TextDecoder();
18
27
  let buffer = "";
19
- while (true) {
20
- const { done, value } = await reader.read();
21
- if (done)
22
- break;
23
- buffer += decoder.decode(value, { stream: true });
24
- const lines = buffer.split("\n");
25
- buffer = lines.pop();
26
- for (const line of lines) {
27
- const trimmed = line.trim();
28
- if (!trimmed)
29
- continue;
30
- try {
31
- const parsed = JSON.parse(trimmed);
32
- if (parsed.stream === true && onStreamChunk)
33
- onStreamChunk(parsed.data);
34
- }
35
- catch { /* skip malformed line */ }
36
- }
37
- }
38
- if (buffer.trim()) {
28
+ const handleLine = (line) => {
29
+ const trimmed = line.trim();
30
+ if (!trimmed)
31
+ return;
32
+ let parsed;
39
33
  try {
40
- const parsed = JSON.parse(buffer.trim());
41
- if (parsed.stream === true && onStreamChunk)
42
- onStreamChunk(parsed.data);
34
+ parsed = JSON.parse(trimmed);
35
+ }
36
+ catch {
37
+ return; // skip malformed line
43
38
  }
44
- catch { /* skip */ }
39
+ if (typeof parsed?.error === "string")
40
+ throw errorFromBody(parsed);
41
+ if (parsed?.stream === true)
42
+ onStreamChunk?.(parsed.data);
43
+ };
44
+ try {
45
+ while (true) {
46
+ const { done, value } = await reader.read();
47
+ if (done)
48
+ break;
49
+ buffer += decoder.decode(value, { stream: true });
50
+ const lines = buffer.split("\n");
51
+ buffer = lines.pop();
52
+ lines.forEach(handleLine);
53
+ }
54
+ handleLine(buffer + decoder.decode());
55
+ }
56
+ catch (error) {
57
+ await reader.cancel().catch(() => { });
58
+ throw error;
45
59
  }
46
60
  }
47
61
  }
@@ -1,7 +1,7 @@
1
- import { z } from "zod";
2
- import type { DebugLogger, FunctionInput, FunctionOutput, LXN_ServerClient_EventType, LXNStreamEmitter } from "./types";
1
+ import LixnetServerBase, { type LixnetServerBaseOptions } from "./serverbase";
2
+ import type { FunctionInput, FunctionOutput, LXN_ServerClient_EventType, LXNEventEntries, LXNEventSchema, LXNStreamEmitter } from "./types";
3
3
  import { LixnetResponse } from "./util/response";
4
- import { LixnetRequest } from "./util/request";
4
+ import { type LixnetRequest } from "./util/request";
5
5
  type LXNStreamServerEventInput<Events extends LXN_ServerClient_EventType, K extends keyof Events> = {
6
6
  event: K;
7
7
  handler: (input: FunctionInput<Events[K]> & {
@@ -9,19 +9,14 @@ type LXNStreamServerEventInput<Events extends LXN_ServerClient_EventType, K exte
9
9
  response: LixnetResponse;
10
10
  stream: LXNStreamEmitter<FunctionOutput<Events[K]>>;
11
11
  }) => Promise<void> | void;
12
- schema?: z.ZodSchema<any>;
12
+ schema?: LXNEventSchema<Events, K>;
13
13
  };
14
- export default class LixnetStreamServer<Events extends LXN_ServerClient_EventType> {
15
- private events;
16
- private logger;
17
- private debugLog;
18
- private defaultHeaders;
19
- constructor({ debugLog, logger, defaultHeaders, }: {
20
- debugLog?: boolean;
21
- logger?: DebugLogger;
22
- defaultHeaders?: Record<string, string>;
23
- });
24
- on<K extends keyof Events & string>(input: LXNStreamServerEventInput<Events, K> | LXNStreamServerEventInput<Events, K>[]): void;
14
+ export default class LixnetStreamServer<Events extends LXN_ServerClient_EventType> extends LixnetServerBase<LXNStreamServerEventInput<Events, keyof Events>> {
15
+ private errorFormatter;
16
+ constructor(options?: LixnetServerBaseOptions);
17
+ on<K extends keyof Events & string>(input: LXNStreamServerEventInput<Events, K> | LXNEventEntries<Events, {
18
+ [P in keyof Events & string]: LXNStreamServerEventInput<Events, P>;
19
+ }>): void;
25
20
  handle(request: Request): Promise<Response>;
26
21
  }
27
22
  export {};
@@ -1,106 +1,91 @@
1
- import { z } from "zod";
2
- import LixnetLog from "./util/log";
1
+ import LixnetServerBase from "./serverbase";
3
2
  import { LixnetResponse } from "./util/response";
4
- import { wrapLixnetRequest } from "./util/request";
5
- export default class LixnetStreamServer {
6
- events = {};
7
- logger = LixnetLog;
8
- debugLog = false;
9
- defaultHeaders;
10
- constructor({ debugLog = false, logger, defaultHeaders = {}, }) {
11
- this.debugLog = debugLog;
12
- this.defaultHeaders = defaultHeaders;
13
- logger ? (this.logger = logger) : "";
3
+ import { createLixnetRequest } from "./util/request";
4
+ import getDefaultFormatter, { buildResponseHeaders, errorBody } from "./util/getDefaultFormatter";
5
+ export default class LixnetStreamServer extends LixnetServerBase {
6
+ errorFormatter;
7
+ constructor(options = {}) {
8
+ super(options);
9
+ this.errorFormatter = getDefaultFormatter(this.defaultHeaders);
14
10
  }
15
11
  on(input) {
16
- if (Array.isArray(input)) {
17
- input.forEach((ev) => {
18
- this.events[ev.event] = ev;
19
- });
20
- }
21
- else {
22
- this.events[input.event] = input;
23
- }
12
+ this.register(input);
24
13
  }
25
14
  async handle(request) {
26
15
  const requestClone = request.clone();
27
- let jsonData;
28
- try {
29
- jsonData = await request.json();
30
- }
31
- catch {
32
- if (this.debugLog)
33
- this.logger({ error: true, message: "Invalid JSON" });
34
- return Response.json({ error: "Invalid JSON" }, { status: 400 });
35
- }
36
- if (jsonData === null || typeof jsonData !== "object" || Array.isArray(jsonData)) {
37
- return Response.json({ error: "Invalid request body" }, { status: 400 });
38
- }
39
- if (!jsonData.event) {
40
- return Response.json({ error: "Event not found" }, { status: 400 });
41
- }
42
- if (!("input" in jsonData)) {
43
- return Response.json({ error: "Input not found" }, { status: 400 });
44
- }
45
- const event = this.events[jsonData.event];
46
- if (!event) {
47
- return Response.json({ error: "Event not found" }, { status: 404 });
48
- }
49
- let validatedInput;
50
- try {
51
- validatedInput = event.schema
52
- ? event.schema.parse(jsonData.input)
53
- : jsonData.input;
16
+ const response = new LixnetResponse({ formatter: this.errorFormatter });
17
+ const corsResponse = this.handleCors(request, response);
18
+ if (corsResponse)
19
+ return corsResponse;
20
+ const parsed = await this.parse(request);
21
+ if (!parsed.ok) {
22
+ return this.fail(response, parsed);
54
23
  }
55
- catch (error) {
56
- if (error instanceof z.ZodError) {
57
- return Response.json({ error: "Invalid input" }, { status: 400 });
58
- }
59
- return Response.json({ error: "Handler error" }, { status: 500 });
60
- }
61
- const response = new LixnetResponse({ formatter: function () { return new Response(); } });
62
- const newRequest = wrapLixnetRequest(requestClone, {
63
- header: response.header.bind(response),
64
- deleteHeader: response.deleteHeader.bind(response),
65
- cookie: response.cookie.bind(response),
66
- deleteCookie: response.deleteCookie.bind(response),
67
- responseHeaders: response.responseHeaders,
68
- responseHeaderDeletes: response.responseHeaderDeletes,
69
- responseCookies: response.responseCookies,
70
- });
24
+ const event = parsed.entry;
25
+ const validatedInput = parsed.input;
26
+ const newRequest = createLixnetRequest(requestClone, response);
71
27
  const encoder = new TextEncoder();
72
- let streamController;
28
+ const abort = new AbortController();
29
+ let controller;
30
+ let closed = false;
73
31
  const body = new ReadableStream({
74
- start(controller) { streamController = controller; },
75
- });
76
- const stream = {
77
- emit: (chunk) => {
78
- streamController.enqueue(encoder.encode(JSON.stringify({ stream: true, data: chunk }) + "\n"));
32
+ start(c) {
33
+ controller = c;
34
+ },
35
+ cancel() {
36
+ // Client disconnected: stop emitting and let the handler observe it via stream.signal.
37
+ closed = true;
38
+ abort.abort();
79
39
  },
40
+ });
41
+ const write = (frame) => {
42
+ if (closed)
43
+ return;
44
+ controller.enqueue(encoder.encode(JSON.stringify(frame) + "\n"));
80
45
  };
81
- (async () => {
82
- try {
83
- await event.handler({ ...validatedInput, request: newRequest, response, stream });
84
- }
85
- catch {
86
- if (this.debugLog)
87
- this.logger({ error: true, message: "Stream handler error" });
88
- }
89
- finally {
90
- streamController.close();
91
- }
92
- })();
93
- const headers = new Headers({
94
- "Content-Type": "application/x-ndjson",
95
- "X-Server": "Lixnet",
96
- ...this.defaultHeaders,
46
+ // The Response is only created on the first emit (or when the handler finishes), so
47
+ // status, headers and cookies staged before that point are all sent, and an error
48
+ // thrown before anything is streamed becomes a normal JSON error response.
49
+ return new Promise((resolve) => {
50
+ let started = false;
51
+ const start = () => {
52
+ if (started)
53
+ return;
54
+ started = true;
55
+ resolve(new Response(body, {
56
+ status: response.responseCode || 200,
57
+ headers: buildResponseHeaders(response, this.defaultHeaders, "application/x-ndjson"),
58
+ }));
59
+ };
60
+ const stream = {
61
+ signal: abort.signal,
62
+ emit: (chunk) => {
63
+ start();
64
+ write({ stream: true, data: chunk });
65
+ },
66
+ };
67
+ (async () => {
68
+ try {
69
+ await event.handler({ ...validatedInput, request: newRequest, response, stream });
70
+ start();
71
+ }
72
+ catch (error) {
73
+ const failure = this.failureFromThrown(error, event.event);
74
+ if (!started) {
75
+ resolve(this.fail(response, failure));
76
+ return;
77
+ }
78
+ // Headers are already sent, so report the error as the final frame.
79
+ this.stageFailure(response, failure);
80
+ write(errorBody(response));
81
+ }
82
+ finally {
83
+ if (started && !closed) {
84
+ closed = true;
85
+ controller.close();
86
+ }
87
+ }
88
+ })();
97
89
  });
98
- for (const [name, value] of Object.entries(response.responseHeaders)) {
99
- headers.set(name, value);
100
- }
101
- for (const name of response.responseHeaderDeletes) {
102
- headers.delete(name);
103
- }
104
- return new Response(body, { status: 200, headers });
105
90
  }
106
91
  }
@@ -1,8 +1,11 @@
1
- import { LixnetRequest } from "./util/request";
2
- import { LixnetResponse } from "./util/response";
3
- export type DebugLogger = ({ error, message, }: {
1
+ import type { StandardSchemaV1 } from "./standardschema";
2
+ import type { LixnetRequest } from "./util/request";
3
+ import type { LixnetResponse } from "./util/response";
4
+ export type DebugLogger = ({ error, message, cause, }: {
4
5
  error?: boolean;
5
6
  message: string;
7
+ /** The underlying exception or validation error, when there is one. */
8
+ cause?: unknown;
6
9
  }) => void;
7
10
  export type FunctionInput<T> = T extends (input: infer TInput) => any ? TInput : {
8
11
  _TYPE_ERROR_: "Event definition must be a function type";
@@ -10,8 +13,16 @@ export type FunctionInput<T> = T extends (input: infer TInput) => any ? TInput :
10
13
  export type FunctionOutput<T> = T extends (...args: any) => infer R ? Awaited<R> : {
11
14
  _TYPE_ERROR_: "Event definition must be a function type";
12
15
  };
16
+ /** `input` may be omitted when the event has no required input fields (e.g. `() => ...`). */
17
+ export type LXNCallArgs<TInput, TOptions> = {} extends TInput ? [input?: TInput, options?: TOptions] : [input: TInput, options?: TOptions];
13
18
  export type LXNServerHandler<Input, Output> = (input: Input) => Promise<Output> | Output;
14
19
  export type LXN_ServerClient_EventType = object;
20
+ /** A schema whose parsed output must match the event's declared input type. */
21
+ export type LXNEventSchema<Events, K extends keyof Events> = StandardSchemaV1<any, FunctionInput<Events[K]>>;
22
+ /** One registration per event name, so arrays passed to `on()` are typed per element. */
23
+ export type LXNEventEntries<Events, TEntry extends {
24
+ [K in keyof Events & string]: unknown;
25
+ }> = TEntry[keyof Events & string][];
15
26
  /** The inbound request passed to handlers (Next.js–style `cookies()` / `headers()`). */
16
27
  export type { LixnetRequest as LXN_ServerClient_Request } from "./util/request";
17
28
  export type LixnetServerInjections = {
@@ -20,5 +31,8 @@ export type LixnetServerInjections = {
20
31
  };
21
32
  /** The `stream` object injected into stream event handlers. */
22
33
  export type LXNStreamEmitter<TChunk> = {
34
+ /** Sends a chunk. The first call sends the response headers; later header/cookie changes are ignored. */
23
35
  emit: (chunk: TChunk) => void;
36
+ /** Aborted when the client disconnects; `emit` becomes a no-op from then on. */
37
+ signal: AbortSignal;
24
38
  };
@@ -0,0 +1,19 @@
1
+ export type LixnetCorsOptions = {
2
+ /** Allowed origins: exact origins (`"https://app.example.com"`), `"*"` for any, or a predicate. */
3
+ origin: string | string[] | ((origin: string) => boolean);
4
+ /** Send `Access-Control-Allow-Credentials: true` (cookies). Not allowed with `origin: "*"`. */
5
+ credentials?: boolean;
6
+ /** Seconds a browser may cache a preflight. Defaults to 7200 (Chrome's cap; Firefox allows 86400). */
7
+ maxAge?: number;
8
+ /** Request headers the client may send. Defaults to whatever the preflight asks for. */
9
+ allowHeaders?: string[];
10
+ /** Response headers the client may read besides the CORS-safelisted ones. */
11
+ exposeHeaders?: string[];
12
+ };
13
+ export declare const DEFAULT_CORS_MAX_AGE = 7200;
14
+ export declare function assertCorsOptions(cors: LixnetCorsOptions): void;
15
+ export declare function isOriginAllowed(cors: LixnetCorsOptions, origin: string): boolean;
16
+ /** Headers for an actual (non-preflight) response to an allowed origin. */
17
+ export declare function corsHeaders(cors: LixnetCorsOptions, origin: string): Record<string, string>;
18
+ /** Headers for a preflight (`OPTIONS`) response to an allowed origin. */
19
+ export declare function preflightHeaders(cors: LixnetCorsOptions, origin: string, requestedHeaders: string | null): Record<string, string>;