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,44 @@
1
+ export const DEFAULT_CORS_MAX_AGE = 7200;
2
+ export function assertCorsOptions(cors) {
3
+ if (cors.origin === "*" && cors.credentials) {
4
+ throw new Error('LIXNET - cors.origin "*" cannot be combined with credentials: true');
5
+ }
6
+ }
7
+ export function isOriginAllowed(cors, origin) {
8
+ if (cors.origin === "*")
9
+ return true;
10
+ if (typeof cors.origin === "function")
11
+ return cors.origin(origin);
12
+ if (Array.isArray(cors.origin))
13
+ return cors.origin.includes(origin);
14
+ return cors.origin === origin;
15
+ }
16
+ /** Headers for an actual (non-preflight) response to an allowed origin. */
17
+ export function corsHeaders(cors, origin) {
18
+ if (cors.origin === "*") {
19
+ return {
20
+ "Access-Control-Allow-Origin": "*",
21
+ ...(cors.exposeHeaders?.length
22
+ ? { "Access-Control-Expose-Headers": cors.exposeHeaders.join(", ") }
23
+ : {}),
24
+ };
25
+ }
26
+ return {
27
+ "Access-Control-Allow-Origin": origin,
28
+ Vary: "Origin",
29
+ ...(cors.credentials ? { "Access-Control-Allow-Credentials": "true" } : {}),
30
+ ...(cors.exposeHeaders?.length
31
+ ? { "Access-Control-Expose-Headers": cors.exposeHeaders.join(", ") }
32
+ : {}),
33
+ };
34
+ }
35
+ /** Headers for a preflight (`OPTIONS`) response to an allowed origin. */
36
+ export function preflightHeaders(cors, origin, requestedHeaders) {
37
+ const allowHeaders = cors.allowHeaders?.join(", ") ?? requestedHeaders;
38
+ return {
39
+ ...corsHeaders(cors, origin),
40
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
41
+ ...(allowHeaders ? { "Access-Control-Allow-Headers": allowHeaders } : {}),
42
+ "Access-Control-Max-Age": String(cors.maxAge ?? DEFAULT_CORS_MAX_AGE),
43
+ };
44
+ }
@@ -1,2 +1,11 @@
1
- import { LixnetResponse } from "./response";
1
+ import type { LixnetResponse } from "./response";
2
+ /** The `{ error, code, data?, detail? }` body for an errored response (also used for stream error frames). */
3
+ export declare function errorBody(response: LixnetResponse): {
4
+ detail?: string | undefined;
5
+ data?: {} | null | undefined;
6
+ error: string | null;
7
+ code: string;
8
+ };
9
+ /** Defaults, then staged header sets/deletes, then staged cookies as `Set-Cookie`. */
10
+ export declare function buildResponseHeaders(response: LixnetResponse, defaultHeaders: Record<string, string>, contentType: string): Headers;
2
11
  export default function (defaultHeaders: Record<string, string>): (this: LixnetResponse) => Response;
@@ -1,61 +1,71 @@
1
- export default function (defaultHeaders) {
2
- function formatter() {
3
- const headers = new Headers({
4
- "Content-Type": "application/json",
5
- "X-Server": "Lixnet",
6
- ...defaultHeaders,
7
- });
8
- for (const [headerName, headerValue] of Object.entries(this.responseHeaders)) {
9
- headers.set(headerName, headerValue);
1
+ import { codeForStatus } from "../error";
2
+ /** The `{ error, code, data?, detail? }` body for an errored response (also used for stream error frames). */
3
+ export function errorBody(response) {
4
+ return {
5
+ error: response.responseError,
6
+ code: response.responseErrorCode ?? codeForStatus(response.responseCode || 500),
7
+ ...(response.responseErrorData !== undefined ? { data: response.responseErrorData } : {}),
8
+ ...(response.responseErrorDetail ? { detail: response.responseErrorDetail } : {}),
9
+ };
10
+ }
11
+ /** Defaults, then staged header sets/deletes, then staged cookies as `Set-Cookie`. */
12
+ export function buildResponseHeaders(response, defaultHeaders, contentType) {
13
+ const headers = new Headers({
14
+ "Content-Type": contentType,
15
+ "X-Server": "Lixnet",
16
+ ...defaultHeaders,
17
+ });
18
+ for (const [headerName, headerValue] of Object.entries(response.responseHeaders)) {
19
+ headers.set(headerName, headerValue);
20
+ }
21
+ for (const headerName of response.responseHeaderDeletes) {
22
+ headers.delete(headerName);
23
+ }
24
+ for (const [cookieName, cookie] of Object.entries(response.responseCookies)) {
25
+ if (cookie.type === "value") {
26
+ const opts = cookie.options ?? {};
27
+ // Encoded so any value is header-safe; request.cookies() decodes it back.
28
+ const parts = [`${cookieName}=${encodeURIComponent(cookie.value ?? "")}`];
29
+ if (opts.domain)
30
+ parts.push(`Domain=${opts.domain}`);
31
+ if (opts.path)
32
+ parts.push(`Path=${opts.path}`);
33
+ if ("maxAge" in opts && typeof opts.maxAge === "number") {
34
+ parts.push(`Max-Age=${opts.maxAge}`);
35
+ }
36
+ if (opts.httpOnly)
37
+ parts.push("HttpOnly");
38
+ if (opts.secure)
39
+ parts.push("Secure");
40
+ if (opts.sameSite)
41
+ parts.push(`SameSite=${opts.sameSite}`);
42
+ headers.append("Set-Cookie", parts.join("; "));
10
43
  }
11
- for (const headerName of this.responseHeaderDeletes) {
12
- headers.delete(headerName);
44
+ else if (cookie.type === "delete") {
45
+ const opts = (cookie.options ?? {});
46
+ const parts = [`${cookieName}=`, "Max-Age=0"];
47
+ parts.push(`Path=${opts.path ?? "/"}`);
48
+ if (opts.domain)
49
+ parts.push(`Domain=${opts.domain}`);
50
+ if (opts.httpOnly)
51
+ parts.push("HttpOnly");
52
+ if (opts.secure)
53
+ parts.push("Secure");
54
+ if (opts.sameSite)
55
+ parts.push(`SameSite=${opts.sameSite}`);
56
+ headers.append("Set-Cookie", parts.join("; "));
13
57
  }
14
- for (const [cookieName, cookie] of Object.entries(this.responseCookies)) {
15
- if (cookie.type === "value") {
16
- const opts = cookie.options ?? {};
17
- //detect value escapes
18
- if (cookie.value?.includes(";") || cookie.value?.includes("=") || cookie.value?.includes("\n") || cookie.value?.includes("\r")) {
19
- throw new Error("Cookie value contains invalid characters");
20
- }
21
- const parts = [`${cookieName}=${cookie.value ?? ""}`];
22
- if (opts.domain)
23
- parts.push(`Domain=${opts.domain}`);
24
- if (opts.path)
25
- parts.push(`Path=${opts.path}`);
26
- if ("maxAge" in opts && typeof opts.maxAge === "number") {
27
- parts.push(`Max-Age=${opts.maxAge}`);
28
- }
29
- if (opts.httpOnly)
30
- parts.push("HttpOnly");
31
- if (opts.secure)
32
- parts.push("Secure");
33
- if (opts.sameSite)
34
- parts.push(`SameSite=${opts.sameSite}`);
35
- headers.append("Set-Cookie", parts.join("; "));
36
- }
37
- else if (cookie.type === "delete") {
38
- const opts = (cookie.options ?? {});
39
- const parts = [`${cookieName}=`, "Max-Age=0"];
40
- parts.push(`Path=${opts.path ?? "/"}`);
41
- if (opts.domain)
42
- parts.push(`Domain=${opts.domain}`);
43
- if (opts.httpOnly)
44
- parts.push("HttpOnly");
45
- if (opts.secure)
46
- parts.push("Secure");
47
- if (opts.sameSite)
48
- parts.push(`SameSite=${opts.sameSite}`);
49
- headers.append("Set-Cookie", parts.join("; "));
50
- }
51
- else {
52
- throw new Error(`Unknown cookie type: ${cookie.type}`);
53
- }
58
+ else {
59
+ throw new Error(`Unknown cookie type: ${cookie.type}`);
54
60
  }
61
+ }
62
+ return headers;
63
+ }
64
+ export default function (defaultHeaders) {
65
+ function formatter() {
66
+ const headers = buildResponseHeaders(this, defaultHeaders, "application/json");
55
67
  if (this.responseError) {
56
- return Response.json({
57
- error: this.responseError,
58
- }, {
68
+ return Response.json(errorBody(this), {
59
69
  status: this.responseCode || 500,
60
70
  headers: headers,
61
71
  });
@@ -1,4 +1,5 @@
1
- export default function ({ error, message, }: {
1
+ export default function ({ error, message, cause, }: {
2
2
  error?: boolean;
3
3
  message: string;
4
+ cause?: unknown;
4
5
  }): void;
@@ -1,6 +1,7 @@
1
- export default function ({ error = false, message, }) {
1
+ export default function ({ error = false, message, cause, }) {
2
+ const args = cause === undefined ? [message] : [message, cause];
2
3
  if (error) {
3
- return console.error(`[LIXNET]`, message);
4
+ return console.error(`[LIXNET]`, ...args);
4
5
  }
5
- return console.log(`[LIXNET]`, message);
6
+ return console.log(`[LIXNET]`, ...args);
6
7
  }
@@ -1,3 +1,4 @@
1
+ import type { LixnetResponse } from "./response";
1
2
  export type RequestCookie = {
2
3
  name: string;
3
4
  value: string;
@@ -68,6 +69,8 @@ export declare function wrapLixnetRequest(request: Request, response: {
68
69
  options?: unknown;
69
70
  }>;
70
71
  }): LixnetRequest;
72
+ /** Wraps `request` so its cookie/header writes are staged on `response`. */
73
+ export declare function createLixnetRequest(request: Request, response: LixnetResponse): LixnetRequest;
71
74
  /** @deprecated Use {@link LixnetCookies}. */
72
75
  export type ReadonlyRequestCookies = LixnetCookies;
73
76
  /** @deprecated Use {@link LixnetHeaders}. */
@@ -254,3 +254,15 @@ export function wrapLixnetRequest(request, response) {
254
254
  },
255
255
  });
256
256
  }
257
+ /** Wraps `request` so its cookie/header writes are staged on `response`. */
258
+ export function createLixnetRequest(request, response) {
259
+ return wrapLixnetRequest(request, {
260
+ header: response.header.bind(response),
261
+ deleteHeader: response.deleteHeader.bind(response),
262
+ cookie: response.cookie.bind(response),
263
+ deleteCookie: response.deleteCookie.bind(response),
264
+ responseHeaders: response.responseHeaders,
265
+ responseHeaderDeletes: response.responseHeaderDeletes,
266
+ responseCookies: response.responseCookies,
267
+ });
268
+ }
@@ -11,6 +11,12 @@ export type CookieFullOptions = CookieBaseOptions & {
11
11
  export declare class LixnetResponse {
12
12
  responseData: any;
13
13
  responseError: string | null;
14
+ /** Extra error information, only sent when the server has `exposeErrors` enabled. */
15
+ responseErrorDetail: string | null;
16
+ /** Error code sent as `code`; derived from the status when not set. */
17
+ responseErrorCode: string | null;
18
+ /** JSON-serialisable data sent with the error as `data`. */
19
+ responseErrorData: unknown;
14
20
  responseCode: number;
15
21
  responseHeaders: Record<string, string>;
16
22
  responseHeaderDeletes: Set<string>;
@@ -25,7 +31,15 @@ export declare class LixnetResponse {
25
31
  data(data: any): void;
26
32
  header(headerName: string, headerValue: string): void;
27
33
  deleteHeader(headerName: string): void;
28
- error(error: string): void;
34
+ /**
35
+ * Turns the response into an error. Prefer throwing a `LixnetError` from the handler; this is
36
+ * for staging one without throwing. A string second argument is the `detail` (legacy form).
37
+ */
38
+ error(error: string, options?: string | {
39
+ code?: string;
40
+ data?: unknown;
41
+ detail?: string;
42
+ }): void;
29
43
  code(code: number): void;
30
44
  headers(headers: Record<string, string>): void;
31
45
  cookie(cookieName: string, cookieValue: string, cookieOptions?: CookieFullOptions): void;
@@ -1,6 +1,26 @@
1
+ // RFC 6265 cookie-name token characters.
2
+ const COOKIE_NAME_PATTERN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
3
+ const COOKIE_ATTRIBUTE_PATTERN = /[;\r\n]/;
4
+ function assertCookie(cookieName, options) {
5
+ if (!COOKIE_NAME_PATTERN.test(cookieName)) {
6
+ throw new Error(`Invalid cookie name: ${JSON.stringify(cookieName)}`);
7
+ }
8
+ if (options?.domain && COOKIE_ATTRIBUTE_PATTERN.test(options.domain)) {
9
+ throw new Error("Cookie domain contains invalid characters");
10
+ }
11
+ if (options?.path && COOKIE_ATTRIBUTE_PATTERN.test(options.path)) {
12
+ throw new Error("Cookie path contains invalid characters");
13
+ }
14
+ }
1
15
  export class LixnetResponse {
2
16
  responseData;
3
17
  responseError = null;
18
+ /** Extra error information, only sent when the server has `exposeErrors` enabled. */
19
+ responseErrorDetail = null;
20
+ /** Error code sent as `code`; derived from the status when not set. */
21
+ responseErrorCode = null;
22
+ /** JSON-serialisable data sent with the error as `data`. */
23
+ responseErrorData = undefined;
4
24
  responseCode = 0;
5
25
  responseHeaders = {};
6
26
  responseHeaderDeletes = new Set();
@@ -21,8 +41,16 @@ export class LixnetResponse {
21
41
  delete this.responseHeaders[headerName.toLowerCase()];
22
42
  this.responseHeaderDeletes.add(headerName.toLowerCase());
23
43
  }
24
- error(error) {
44
+ /**
45
+ * Turns the response into an error. Prefer throwing a `LixnetError` from the handler; this is
46
+ * for staging one without throwing. A string second argument is the `detail` (legacy form).
47
+ */
48
+ error(error, options) {
49
+ const { code, data, detail } = typeof options === "string" ? { detail: options } : (options ?? {});
25
50
  this.responseError = error;
51
+ this.responseErrorCode = code ?? null;
52
+ this.responseErrorData = data;
53
+ this.responseErrorDetail = detail ?? null;
26
54
  }
27
55
  code(code) {
28
56
  this.responseCode = code;
@@ -33,6 +61,7 @@ export class LixnetResponse {
33
61
  }
34
62
  }
35
63
  cookie(cookieName, cookieValue, cookieOptions) {
64
+ assertCookie(cookieName, cookieOptions);
36
65
  this.responseCookies[cookieName] = {
37
66
  type: "value",
38
67
  value: cookieValue,
@@ -40,6 +69,7 @@ export class LixnetResponse {
40
69
  };
41
70
  }
42
71
  deleteCookie(cookieName, options) {
72
+ assertCookie(cookieName, options);
43
73
  this.responseCookies[cookieName] = {
44
74
  type: "delete",
45
75
  options,
@@ -0,0 +1,2 @@
1
+ /** Merges caller headers, defaulting `Content-Type` to JSON unless the caller set one. */
2
+ export default function (init?: HeadersInit): Headers;
@@ -0,0 +1,8 @@
1
+ /** Merges caller headers, defaulting `Content-Type` to JSON unless the caller set one. */
2
+ export default function (init) {
3
+ const headers = new Headers(init);
4
+ if (!headers.has("Content-Type")) {
5
+ headers.set("Content-Type", "application/json");
6
+ }
7
+ return headers;
8
+ }
@@ -0,0 +1,2 @@
1
+ /** Prefix for generated ids (callback refs and chunked transmission ids). */
2
+ export declare const LIXNET_ID_PREFIX = "LXN-";
@@ -0,0 +1,2 @@
1
+ /** Prefix for generated ids (callback refs and chunked transmission ids). */
2
+ export const LIXNET_ID_PREFIX = "LXN-";
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "lixnet",
3
- "version": "1.3.14",
3
+ "version": "1.5.0",
4
4
  "author": "nitlix-hq",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
8
- "url": "https://github.com/nitlix-hq/Lixnet"
8
+ "url": "git+https://github.com/nitlix-studios/Lixnet.git"
9
9
  },
10
- "homepage": "https://github.com/nitlix-hq/Lixnet",
10
+ "homepage": "https://github.com/nitlix-studios/Lixnet",
11
11
  "description": "RPC over HTTP and WebSockets, simplified.",
12
12
  "module": "./dist/exports.js",
13
13
  "main": "./dist/exports.js",
@@ -23,12 +23,9 @@
23
23
  ],
24
24
  "type": "module",
25
25
  "devDependencies": {
26
- "@types/bun": "latest"
27
- },
28
- "peerDependencies": {
29
- "typescript": "^5.9.3"
30
- },
31
- "dependencies": {
26
+ "@types/bun": "latest",
27
+ "typescript": "^5.9.3",
28
+ "valibot": "^1.5.0",
32
29
  "zod": "^4.3.6"
33
30
  }
34
31
  }