lixnet 1.2.7 → 1.2.8

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/.gitattributes CHANGED
@@ -1,2 +1,2 @@
1
- # Auto detect text files and perform LF normalization
1
+ # Auto detect text files and perform LF normalization
2
2
  * text=auto
@@ -1,4 +1,5 @@
1
1
  export default class LixnetClient {
2
+ rpcUrl;
2
3
  constructor({ rpcUrl }) {
3
4
  this.rpcUrl = rpcUrl;
4
5
  }
package/dist/lib/peer.js CHANGED
@@ -2,70 +2,65 @@ function createLixnetId() {
2
2
  return "LX-" + Math.random().toString(36).substring(2, 15);
3
3
  }
4
4
  export default class LixnetPeer {
5
- constructor() {
6
- this.socket = null;
7
- this.rb = {};
8
- this.transmissionLimit = -1;
9
- this.transmissionChunksLimit = 20;
10
- this.call = async (event, data, { callback } = { callback: null }) => {
11
- if (!this.socket)
12
- throw new Error("LIXNET - Socket not set");
13
- let rf = null;
14
- if (typeof callback === "function") {
15
- rf = createLixnetId();
16
- this.rb[rf] = {
17
- method: event,
18
- callback: callback,
19
- };
20
- }
21
- let dataToSend = {
5
+ socket = null;
6
+ rb = {};
7
+ transmissionLimit = -1;
8
+ transmissionChunksLimit = 20;
9
+ setTransmissionChunksLimit(limit) {
10
+ this.transmissionChunksLimit = limit;
11
+ }
12
+ call = async (event, data, { callback } = { callback: null }) => {
13
+ if (!this.socket)
14
+ throw new Error("LIXNET - Socket not set");
15
+ let rf = null;
16
+ if (typeof callback === "function") {
17
+ rf = createLixnetId();
18
+ this.rb[rf] = {
19
+ method: event,
20
+ callback: callback,
21
+ };
22
+ }
23
+ let dataToSend = {
24
+ event,
25
+ data,
26
+ };
27
+ if (rf)
28
+ dataToSend.rf = rf;
29
+ dataToSend = JSON.stringify(dataToSend);
30
+ // No callback needed, just send
31
+ if (this.transmissionLimit !== -1 &&
32
+ dataToSend.length > this.transmissionLimit - 50) {
33
+ // Send in chunks
34
+ let dataString = JSON.stringify(data);
35
+ const tId = createLixnetId();
36
+ const limits = this.getChunkLimits({
37
+ tId,
38
+ dataLength: dataString.length,
39
+ });
40
+ // Send transmission id and rf
41
+ const sendData = {
42
+ tId,
22
43
  event,
23
- data,
44
+ chunkCount: limits.length,
24
45
  };
25
46
  if (rf)
26
- dataToSend.rf = rf;
27
- dataToSend = JSON.stringify(dataToSend);
28
- // No callback needed, just send
29
- if (this.transmissionLimit !== -1 &&
30
- dataToSend.length > this.transmissionLimit - 50) {
31
- // Send in chunks
32
- let dataString = JSON.stringify(data);
33
- const tId = createLixnetId();
34
- const limits = this.getChunkLimits({
35
- tId,
36
- dataLength: dataString.length,
37
- });
38
- // Send transmission id and rf
39
- const sendData = {
40
- tId,
41
- event,
42
- chunkCount: limits.length,
43
- };
44
- if (rf)
45
- sendData.rf = rf;
46
- this.socket.send(JSON.stringify(sendData));
47
- const chunks = {};
48
- for (let i = 0; i < limits.length; i++) {
49
- if (i === limits.length - 1) {
50
- chunks[i] = `${tId}.${i}.${dataString}`;
51
- break;
52
- }
53
- chunks[i] = `${tId}.${i}.${dataString.slice(0, limits[i])}`;
54
- dataString = dataString.slice(limits[i]);
47
+ sendData.rf = rf;
48
+ this.socket.send(JSON.stringify(sendData));
49
+ const chunks = {};
50
+ for (let i = 0; i < limits.length; i++) {
51
+ if (i === limits.length - 1) {
52
+ chunks[i] = `${tId}.${i}.${dataString}`;
53
+ break;
55
54
  }
56
- this.outgoingTransmissions[tId] = chunks;
57
- // Chunks sent. Complete.
58
- return;
55
+ chunks[i] = `${tId}.${i}.${dataString.slice(0, limits[i])}`;
56
+ dataString = dataString.slice(limits[i]);
59
57
  }
60
- this.socket.send(dataToSend);
61
- };
62
- this.eventHandlers = {};
63
- this.transmissions = {};
64
- this.outgoingTransmissions = {};
65
- }
66
- setTransmissionChunksLimit(limit) {
67
- this.transmissionChunksLimit = limit;
68
- }
58
+ this.outgoingTransmissions[tId] = chunks;
59
+ // Chunks sent. Complete.
60
+ return;
61
+ }
62
+ this.socket.send(dataToSend);
63
+ };
69
64
  getChunkLimits({ tId, dataLength, }) {
70
65
  const limits = [];
71
66
  let chunkIndex = 0;
@@ -84,6 +79,7 @@ export default class LixnetPeer {
84
79
  }
85
80
  return limits;
86
81
  }
82
+ eventHandlers = {};
87
83
  setSocket(socket) {
88
84
  this.socket = socket;
89
85
  }
@@ -93,6 +89,8 @@ export default class LixnetPeer {
93
89
  on(event, handler) {
94
90
  this.eventHandlers[event] = handler;
95
91
  }
92
+ transmissions = {};
93
+ outgoingTransmissions = {};
96
94
  transmissionSecurityCheck(tId) {
97
95
  const transmission = this.transmissions[tId];
98
96
  if (!transmission)
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import type { DebugLogger, FunctionInput, FunctionOutput, LXNServerHandler, LXN_ServerClient_EventType, LXN_ServerClient_Request } from "./types";
3
+ import LixnetResponse from "./util/response";
3
4
  type LXNServerEventInput<Events extends LXN_ServerClient_EventType, TName extends keyof Events> = {
4
5
  event: TName;
5
6
  handler: LXNServerHandler<FunctionInput<Events[TName]> & {
@@ -11,11 +12,11 @@ export default class LixnetServer<Events extends LXN_ServerClient_EventType> {
11
12
  private events;
12
13
  private logger;
13
14
  private debugLog;
14
- private jsonResponseMaker;
15
- constructor({ debugLog, logger, jsonResponseMaker, }: {
15
+ private formatter;
16
+ constructor({ debugLog, logger, formatter, }: {
16
17
  debugLog?: boolean;
17
18
  logger?: DebugLogger;
18
- jsonResponseMaker?: (data: any, init?: ResponseInit) => Response;
19
+ formatter?: (this: LixnetResponse) => Response;
19
20
  });
20
21
  on<K extends keyof Events & string>(input: LXNServerEventInput<Events, K> | LXNServerEventInput<Events, K>[]): void;
21
22
  handle(request: Request): Promise<Response>;
@@ -1,13 +1,16 @@
1
1
  import { z } from "zod";
2
2
  import LixnetLog from "./util/log";
3
+ import LixnetResponse from "./util/response";
4
+ import defaultFormatter from "./util/formatter";
3
5
  export default class LixnetServer {
4
- constructor({ debugLog = false, logger, jsonResponseMaker = (data, init) => Response.json(data, init), }) {
5
- this.events = {};
6
- this.logger = LixnetLog;
7
- this.debugLog = false;
6
+ events = {};
7
+ logger = LixnetLog;
8
+ debugLog = false;
9
+ formatter;
10
+ constructor({ debugLog = false, logger, formatter, }) {
8
11
  this.debugLog = debugLog;
9
12
  logger ? (this.logger = logger) : "";
10
- this.jsonResponseMaker = jsonResponseMaker;
13
+ this.formatter = formatter ?? defaultFormatter;
11
14
  }
12
15
  on(input) {
13
16
  if (Array.isArray(input)) {
@@ -21,6 +24,7 @@ export default class LixnetServer {
21
24
  }
22
25
  async handle(request) {
23
26
  const requestClone = request.clone();
27
+ const response = new LixnetResponse({ formatter: this.formatter });
24
28
  let jsonData;
25
29
  try {
26
30
  jsonData = (await request.json());
@@ -32,59 +36,57 @@ export default class LixnetServer {
32
36
  message: "Invalid JSON",
33
37
  })
34
38
  : "";
35
- return this.jsonResponseMaker({
36
- error: "Invalid JSON",
37
- }, { status: 400 });
39
+ response.error("Invalid JSON");
40
+ return response.format();
41
+ }
42
+ if (jsonData === null ||
43
+ typeof jsonData !== "object" ||
44
+ Array.isArray(jsonData)) {
45
+ response.error("Invalid request body");
46
+ return response.format();
38
47
  }
39
48
  if (!jsonData.event) {
40
- return this.jsonResponseMaker({ error: "Event not found" }, { status: 400 });
49
+ response.error("Event not found");
50
+ return response.format();
41
51
  }
42
- if (!jsonData.input) {
43
- return this.jsonResponseMaker({ error: "Input not found" }, { status: 400 });
52
+ if (!("input" in jsonData)) {
53
+ response.error("Input not found");
54
+ return response.format();
44
55
  }
45
56
  const event = this.events[jsonData.event];
46
57
  if (!event) {
47
- return this.jsonResponseMaker({
48
- error: "Event not found",
49
- }, { status: 404 });
58
+ response.error("Event not found");
59
+ return response.format();
50
60
  }
51
61
  try {
52
62
  const validatedInput = event.schema
53
63
  ? event.schema.parse(jsonData.input)
54
64
  : jsonData.input;
55
65
  try {
56
- let additionalInit = {};
57
- const clonedReq = new Request(requestClone);
58
- clonedReq.setAdditionalInit = (init) => {
59
- additionalInit = init;
60
- };
61
- const newRequest = clonedReq;
62
- const result = await event.handler({
63
- request: newRequest,
66
+ const newRequest = requestClone;
67
+ const data = await event.handler({
64
68
  ...validatedInput,
69
+ request: newRequest,
70
+ response: response,
65
71
  });
66
- if (result instanceof Response) {
67
- return result;
72
+ //check data isnt void/null/undefined
73
+ if (!(data === undefined || data === null)) {
74
+ response.data(data);
68
75
  }
69
- return this.jsonResponseMaker({
70
- data: result,
71
- }, additionalInit);
76
+ return response.format();
72
77
  }
73
78
  catch (error) {
74
- return this.jsonResponseMaker({
75
- error: "Handler error",
76
- details: error,
77
- }, { status: 500 });
79
+ response.error("Handler error");
80
+ return response.format();
78
81
  }
79
82
  }
80
83
  catch (error) {
81
84
  if (error instanceof z.ZodError) {
82
- return this.jsonResponseMaker({
83
- error: "Invalid input",
84
- details: error.issues,
85
- }, { status: 400 });
85
+ response.error("Invalid input");
86
+ return response.format();
86
87
  }
87
- throw error;
88
+ response.error("Invalid input");
89
+ return response.format();
88
90
  }
89
91
  }
90
92
  }
@@ -10,6 +10,5 @@ export type FunctionOutput<T> = T extends (...args: any) => infer R ? Awaited<R>
10
10
  };
11
11
  export type LXNServerHandler<Input, Output> = (input: Input) => Promise<Output> | Output;
12
12
  export type LXN_ServerClient_EventType = object;
13
- export type LXN_ServerClient_Request = Request & {
14
- setAdditionalInit: (init: ResponseInit) => void;
15
- };
13
+ /** The inbound `Request` passed to handlers (headers, URL, method, etc.). */
14
+ export type LXN_ServerClient_Request = Request;
@@ -0,0 +1,2 @@
1
+ import LixnetResponse from "./response";
2
+ export default function jsonFormatter(this: LixnetResponse): Response;
@@ -0,0 +1,26 @@
1
+ export default function jsonFormatter() {
2
+ const headers = new Headers({
3
+ "Content-Type": "application/json",
4
+ });
5
+ for (const [headerName, headerValue] of Object.entries(this.responseHeaders)) {
6
+ headers.set(headerName, headerValue);
7
+ }
8
+ for (const [cookieName, cookie] of Object.entries(this.responseCookies)) {
9
+ if (cookie.type === "value") {
10
+ const opts = cookie.options ?? {};
11
+ headers.set('Set-Cookie', `${cookieName}=${cookie.value}; ${Object.entries(opts).map(([key, value]) => `${key}=${value}`).join('; ')}`);
12
+ }
13
+ else if (cookie.type === "delete") {
14
+ headers.set('Set-Cookie', `${cookieName}=; Max-Age=0; Path=/; HttpOnly; Secure; SameSite=Strict`);
15
+ }
16
+ else {
17
+ throw new Error(`Unknown cookie type: ${cookie.type}`);
18
+ }
19
+ }
20
+ return Response.json({
21
+ data: this.responseData,
22
+ }, {
23
+ status: 200,
24
+ headers: headers,
25
+ });
26
+ }
@@ -0,0 +1,32 @@
1
+ type CookieOptions = {
2
+ domain?: string;
3
+ path?: string;
4
+ maxAge?: number;
5
+ httpOnly?: boolean;
6
+ secure?: boolean;
7
+ sameSite?: 'lax' | 'strict' | 'none';
8
+ };
9
+ export default class LixnetResponse {
10
+ responseData: any;
11
+ responseError: string | null;
12
+ responseCode: number;
13
+ responseHeaders: Record<string, string>;
14
+ responseCookies: Record<string, {
15
+ type: "value" | "delete";
16
+ value?: string;
17
+ options?: CookieOptions;
18
+ }>;
19
+ constructor({ formatter }: {
20
+ formatter?: (this: LixnetResponse) => Response;
21
+ });
22
+ data(data: any): void;
23
+ header(headerName: string, headerValue: string): void;
24
+ error(error: string): void;
25
+ code(code: number): void;
26
+ headers(headers: Record<string, string>): void;
27
+ cookie(cookieName: string, cookieValue: string, cookieOptions: CookieOptions): void;
28
+ deleteCookie(cookieName: string): void;
29
+ format: (this: LixnetResponse) => Response;
30
+ setFormatter(formatter: (this: LixnetResponse) => Response): void;
31
+ }
32
+ export {};
@@ -0,0 +1,65 @@
1
+ export default class LixnetResponse {
2
+ responseData;
3
+ responseError = null;
4
+ responseCode = 200;
5
+ responseHeaders = {};
6
+ responseCookies = {};
7
+ constructor({ formatter }) {
8
+ this.responseData = null;
9
+ this.format = formatter ?? (() => {
10
+ const headers = new Headers();
11
+ for (const [headerName, headerValue] of Object.entries(this.responseHeaders)) {
12
+ headers.set(headerName, headerValue);
13
+ }
14
+ for (const [cookieName, cookie] of Object.entries(this.responseCookies)) {
15
+ if (cookie.type === "value") {
16
+ const opts = cookie.options ?? {};
17
+ headers.set('Set-Cookie', `${cookieName}=${cookie.value}; ${Object.entries(opts).map(([key, value]) => `${key}=${value}`).join('; ')}`);
18
+ }
19
+ else if (cookie.type === "delete") {
20
+ headers.set('Set-Cookie', `${cookieName}=; Max-Age=0; Path=/; HttpOnly; Secure; SameSite=Strict`);
21
+ }
22
+ else {
23
+ throw new Error(`Unknown cookie type: ${cookie.type}`);
24
+ }
25
+ }
26
+ return Response.json(this.responseError ? { error: this.responseError } : { data: this.responseData }, {
27
+ status: this.responseCode ? this.responseCode : this.responseError ? 400 : 200,
28
+ headers: headers
29
+ });
30
+ });
31
+ }
32
+ data(data) {
33
+ this.responseData = data;
34
+ }
35
+ header(headerName, headerValue) {
36
+ this.responseHeaders[headerName] = headerValue;
37
+ }
38
+ error(error) {
39
+ this.responseError = error;
40
+ }
41
+ code(code) {
42
+ this.responseCode = code;
43
+ }
44
+ headers(headers) {
45
+ for (const [headerName, headerValue] of Object.entries(headers)) {
46
+ this.header(headerName, headerValue);
47
+ }
48
+ }
49
+ cookie(cookieName, cookieValue, cookieOptions) {
50
+ this.responseCookies[cookieName] = {
51
+ type: "value",
52
+ value: cookieValue,
53
+ options: cookieOptions,
54
+ };
55
+ }
56
+ deleteCookie(cookieName) {
57
+ this.responseCookies[cookieName] = {
58
+ type: "delete",
59
+ };
60
+ }
61
+ format;
62
+ setFormatter(formatter) {
63
+ this.format = formatter;
64
+ }
65
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "lixnet",
3
- "version": "1.2.7",
4
- "author": "Nitlix",
3
+ "version": "1.2.8",
4
+ "author": "nitlix",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -16,9 +16,9 @@
16
16
  "@types/bun": "latest"
17
17
  },
18
18
  "peerDependencies": {
19
- "typescript": "^5.8.3"
19
+ "typescript": "^5.9.3"
20
20
  },
21
21
  "dependencies": {
22
- "zod": "^4.0.17"
22
+ "zod": "^4.3.6"
23
23
  }
24
24
  }