lixnet 1.0.2 → 1.1.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/dist/exports.js CHANGED
@@ -1,12 +1,4 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.LixnetPeer = exports.LixnetClient = exports.LixnetServer = void 0;
7
- const server_1 = __importDefault(require("./lib/server"));
8
- exports.LixnetServer = server_1.default;
9
- const client_1 = __importDefault(require("./lib/client"));
10
- exports.LixnetClient = client_1.default;
11
- const peer_1 = __importDefault(require("./lib/peer"));
12
- exports.LixnetPeer = peer_1.default;
1
+ import LixnetServer from "./lib/server";
2
+ import LixnetClient from "./lib/client";
3
+ import LixnetPeer from "./lib/peer";
4
+ export { LixnetServer, LixnetClient, LixnetPeer };
@@ -1,14 +1,11 @@
1
- import type { EventCollection, CallableEvent } from "./types";
2
- export default class LixnetClientConstructor<TEvents extends EventCollection> {
3
- private baseUrl;
1
+ import type { EventCollection, ClientCaller } from "./types";
2
+ export default class LixnetClient<TEvents extends EventCollection> {
3
+ private rpcUrl;
4
4
  private events;
5
- constructor({ events, baseUrl, }: {
5
+ constructor({ events, rpcUrl, }: {
6
6
  events: TEvents;
7
- baseUrl: string;
7
+ rpcUrl: string;
8
8
  });
9
- getClient(): {
10
- [K in keyof TEvents]: TEvents[K] extends {
11
- handler: (input: infer TInput) => Promise<infer TOutput>;
12
- } ? CallableEvent<Omit<TInput, "request">, TOutput> : never;
13
- };
9
+ call: ClientCaller<TEvents>;
10
+ getEventCollection(): TEvents;
14
11
  }
@@ -1,41 +1,24 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- class LixnetClientConstructor {
13
- constructor({ events, baseUrl, }) {
14
- this.baseUrl = baseUrl;
1
+ export default class LixnetClient {
2
+ constructor({ events, rpcUrl, }) {
3
+ this.call = async (event, input) => {
4
+ const response = await fetch(this.rpcUrl, {
5
+ method: "POST",
6
+ headers: {
7
+ "Content-Type": "application/json",
8
+ },
9
+ body: JSON.stringify({ event, input }),
10
+ });
11
+ const json = await response.json();
12
+ if (json.error) {
13
+ throw new Error(json.error);
14
+ }
15
+ return json.data;
16
+ };
17
+ this.rpcUrl = rpcUrl;
15
18
  this.events = events;
16
19
  }
17
- getClient() {
18
- const client = {};
19
- Object.keys(this.events).forEach((key) => {
20
- client[key] = (input) => __awaiter(this, void 0, void 0, function* () {
21
- const response = yield fetch(this.baseUrl, {
22
- method: "POST",
23
- body: JSON.stringify({ event: key, input }),
24
- });
25
- try {
26
- const json = (yield response.json());
27
- if (json.error) {
28
- throw new Error(json.error);
29
- }
30
- return json.data;
31
- }
32
- catch (error) {
33
- console.error(error);
34
- return null;
35
- }
36
- });
37
- });
38
- return client;
20
+ // Keep this for internal use only
21
+ getEventCollection() {
22
+ return this.events;
39
23
  }
40
24
  }
41
- exports.default = LixnetClientConstructor;
package/dist/lib/peer.js CHANGED
@@ -1,24 +1,13 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
1
  function createLixnetId() {
13
2
  return "LX-" + Math.random().toString(36).substring(2, 15);
14
3
  }
15
- class LixnetPeer {
4
+ export default class LixnetPeer {
16
5
  constructor() {
17
6
  this.socket = null;
18
7
  this.rb = {};
19
8
  this.transmissionLimit = -1;
20
9
  this.transmissionChunksLimit = 20;
21
- this.call = (event_1, data_1, ...args_1) => __awaiter(this, [event_1, data_1, ...args_1], void 0, function* (event, data, { callback } = { callback: null }) {
10
+ this.call = async (event, data, { callback } = { callback: null }) => {
22
11
  if (!this.socket)
23
12
  throw new Error("LIXNET - Socket not set");
24
13
  let rf = null;
@@ -65,7 +54,7 @@ class LixnetPeer {
65
54
  return;
66
55
  }
67
56
  this.socket.send(dataToSend);
68
- });
57
+ };
69
58
  this.eventHandlers = {};
70
59
  this.transmissions = {};
71
60
  this.outgoingTransmissions = {};
@@ -239,19 +228,19 @@ class LixnetPeer {
239
228
  socket,
240
229
  });
241
230
  }
242
- handleEvent(_a) {
243
- return __awaiter(this, arguments, void 0, function* ({ eventName, data, rf, socket, }) {
244
- const eventHandler = this.eventHandlers[eventName];
245
- if (!eventHandler)
246
- return;
247
- const result = yield eventHandler(Object.assign(Object.assign({}, (typeof data === "object" ? data : {})), { socket }));
248
- if (rf) {
249
- socket.send(JSON.stringify({
250
- rb: rf,
251
- data: result,
252
- }));
253
- }
231
+ async handleEvent({ eventName, data, rf, socket, }) {
232
+ const eventHandler = this.eventHandlers[eventName];
233
+ if (!eventHandler)
234
+ return;
235
+ const result = await eventHandler({
236
+ ...(typeof data === "object" ? data : {}),
237
+ socket,
254
238
  });
239
+ if (rf) {
240
+ socket.send(JSON.stringify({
241
+ rb: rf,
242
+ data: result,
243
+ }));
244
+ }
255
245
  }
256
246
  }
257
- exports.default = LixnetPeer;
@@ -1,74 +1,58 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- const zod_1 = require("zod");
16
- const log_1 = __importDefault(require("./util/log"));
17
- class LixnetServer {
1
+ import { z } from "zod";
2
+ import LixnetLog from "./util/log";
3
+ export default class LixnetServer {
18
4
  constructor({ debugLog = false, logger, jsonResponseMaker = Response.json, events, }) {
19
- this.logger = log_1.default;
5
+ this.logger = LixnetLog;
20
6
  this.debugLog = false;
21
7
  this.debugLog = debugLog;
22
8
  logger ? (this.logger = logger) : "";
23
9
  this.jsonResponseMaker = jsonResponseMaker;
24
10
  this.eventCollection = events;
25
11
  }
26
- handleRequest(request) {
27
- return __awaiter(this, void 0, void 0, function* () {
28
- let jsonData;
29
- try {
30
- jsonData = (yield request.json());
31
- }
32
- catch (error) {
33
- this.debugLog
34
- ? this.logger({
35
- error: true,
36
- message: "Invalid JSON",
37
- })
38
- : "";
12
+ async handleRequest(request) {
13
+ let jsonData;
14
+ try {
15
+ jsonData = (await request.json());
16
+ }
17
+ catch (error) {
18
+ this.debugLog
19
+ ? this.logger({
20
+ error: true,
21
+ message: "Invalid JSON",
22
+ })
23
+ : "";
24
+ return this.jsonResponseMaker({
25
+ error: "Invalid JSON",
26
+ }, { status: 400 });
27
+ }
28
+ if (!jsonData.action) {
29
+ return this.jsonResponseMaker({ error: "Action not found" }, { status: 400 });
30
+ }
31
+ if (!jsonData.input) {
32
+ return this.jsonResponseMaker({ error: "Input not found" }, { status: 400 });
33
+ }
34
+ const event = this.eventCollection[jsonData.event];
35
+ if (!event) {
36
+ return this.jsonResponseMaker({
37
+ error: "Action not found",
38
+ }, { status: 404 });
39
+ }
40
+ try {
41
+ const validatedInput = event.schema
42
+ ? event.schema.parse(jsonData.input)
43
+ : jsonData.input;
44
+ const result = await event.handler(validatedInput);
45
+ return this.jsonResponseMaker({ data: result });
46
+ }
47
+ catch (error) {
48
+ if (error instanceof z.ZodError) {
39
49
  return this.jsonResponseMaker({
40
- error: "Invalid JSON",
50
+ error: "Invalid input",
51
+ details: error.issues,
41
52
  }, { status: 400 });
42
53
  }
43
- if (!jsonData.action) {
44
- return this.jsonResponseMaker({ error: "Action not found" }, { status: 400 });
45
- }
46
- if (!jsonData.input) {
47
- return this.jsonResponseMaker({ error: "Input not found" }, { status: 400 });
48
- }
49
- const event = this.eventCollection[jsonData.event];
50
- if (!event) {
51
- return this.jsonResponseMaker({
52
- error: "Action not found",
53
- }, { status: 404 });
54
- }
55
- try {
56
- const validatedInput = event.schema
57
- ? event.schema.parse(jsonData.input)
58
- : jsonData.input;
59
- const result = yield event.handler(validatedInput);
60
- return this.jsonResponseMaker({ data: result });
61
- }
62
- catch (error) {
63
- if (error instanceof zod_1.z.ZodError) {
64
- return this.jsonResponseMaker({
65
- error: "Invalid input",
66
- details: error.issues,
67
- }, { status: 400 });
68
- }
69
- throw error;
70
- }
71
- });
54
+ throw error;
55
+ }
72
56
  }
73
57
  // Returns dummy functions that match the type signatures
74
58
  getEventTypes() {
@@ -87,4 +71,3 @@ class LixnetServer {
87
71
  return this.eventCollection;
88
72
  }
89
73
  }
90
- exports.default = LixnetServer;
@@ -14,21 +14,19 @@ export type EventType<TInput = any, TOutput = any> = {
14
14
  output: TOutput;
15
15
  };
16
16
  export type EventCollection = Record<string, Event>;
17
- export type EventTypeCollection = Record<string, EventType>;
18
17
  export type LixnetServerInit<TEvents extends EventCollection> = {
19
18
  debugLog?: boolean;
20
19
  logger?: DebugLogger;
21
20
  jsonResponseMaker?: (data: any, init?: ResponseInit) => Response;
22
21
  events: TEvents;
23
22
  };
24
- export type LixnetClientInit<TEventTypes extends EventTypeCollection> = {
25
- eventTypes: TEventTypes;
26
- baseUrl: string;
27
- };
28
- export type CallableEvent<TInput = any, TOutput = any> = (input: TInput) => Promise<TOutput>;
29
23
  export type ToEventTypes<TEvents extends EventCollection> = {
30
24
  [K in keyof TEvents]: TEvents[K] extends Event<infer TInput, infer TOutput> ? EventType<TInput, TOutput> : never;
31
25
  };
32
- export type ClientEvents<TEventTypes extends EventTypeCollection> = {
33
- [K in keyof TEventTypes]: TEventTypes[K] extends EventType<infer TInput, infer TOutput> ? CallableEvent<TInput, TOutput> : never;
34
- };
26
+ export type ClientEventInput<T> = T extends {
27
+ handler: (input: infer TInput) => any;
28
+ } ? Omit<TInput, "request"> : never;
29
+ export type ClientEventOutput<T> = T extends {
30
+ handler: (input: any) => Promise<infer TOutput>;
31
+ } ? TOutput : never;
32
+ export type ClientCaller<TEvents extends EventCollection> = <K extends keyof TEvents>(event: K, input: ClientEventInput<TEvents[K]>) => Promise<ClientEventOutput<TEvents[K]>>;
package/dist/lib/types.js CHANGED
@@ -1,2 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ export {};
@@ -1,7 +1,4 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.default = default_1;
4
- function default_1({ error = false, message, }) {
1
+ export default function ({ error = false, message, }) {
5
2
  if (error) {
6
3
  return console.error(`[LIXNET]`, message);
7
4
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lixnet",
3
- "version": "1.0.2",
3
+ "version": "1.1.0",
4
4
  "author": "Nitlix",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,111 +0,0 @@
1
- ---
2
- description: Use Bun instead of Node.js, npm, pnpm, or vite.
3
- globs: "*.ts, *.tsx, *.html, *.css, *.js, *.jsx, package.json"
4
- alwaysApply: false
5
- ---
6
-
7
- Default to using Bun instead of Node.js.
8
-
9
- - Use `bun <file>` instead of `node <file>` or `ts-node <file>`
10
- - Use `bun test` instead of `jest` or `vitest`
11
- - Use `bun build <file.html|file.ts|file.css>` instead of `webpack` or `esbuild`
12
- - Use `bun install` instead of `npm install` or `yarn install` or `pnpm install`
13
- - Use `bun run <script>` instead of `npm run <script>` or `yarn run <script>` or `pnpm run <script>`
14
- - Bun automatically loads .env, so don't use dotenv.
15
-
16
- ## APIs
17
-
18
- - `Bun.serve()` supports WebSockets, HTTPS, and routes. Don't use `express`.
19
- - `bun:sqlite` for SQLite. Don't use `better-sqlite3`.
20
- - `Bun.redis` for Redis. Don't use `ioredis`.
21
- - `Bun.sql` for Postgres. Don't use `pg` or `postgres.js`.
22
- - `WebSocket` is built-in. Don't use `ws`.
23
- - Prefer `Bun.file` over `node:fs`'s readFile/writeFile
24
- - Bun.$`ls` instead of execa.
25
-
26
- ## Testing
27
-
28
- Use `bun test` to run tests.
29
-
30
- ```ts#index.test.ts
31
- import { test, expect } from "bun:test";
32
-
33
- test("hello world", () => {
34
- expect(1).toBe(1);
35
- });
36
- ```
37
-
38
- ## Frontend
39
-
40
- Use HTML imports with `Bun.serve()`. Don't use `vite`. HTML imports fully support React, CSS, Tailwind.
41
-
42
- Server:
43
-
44
- ```ts#index.ts
45
- import index from "./index.html"
46
-
47
- Bun.serve({
48
- routes: {
49
- "/": index,
50
- "/api/users/:id": {
51
- GET: (req) => {
52
- return new Response(JSON.stringify({ id: req.params.id }));
53
- },
54
- },
55
- },
56
- // optional websocket support
57
- websocket: {
58
- open: (ws) => {
59
- ws.send("Hello, world!");
60
- },
61
- message: (ws, message) => {
62
- ws.send(message);
63
- },
64
- close: (ws) => {
65
- // handle close
66
- }
67
- },
68
- development: {
69
- hmr: true,
70
- console: true,
71
- }
72
- })
73
- ```
74
-
75
- HTML files can import .tsx, .jsx or .js files directly and Bun's bundler will transpile & bundle automatically. `<link>` tags can point to stylesheets and Bun's CSS bundler will bundle.
76
-
77
- ```html#index.html
78
- <html>
79
- <body>
80
- <h1>Hello, world!</h1>
81
- <script type="module" src="./frontend.tsx"></script>
82
- </body>
83
- </html>
84
- ```
85
-
86
- With the following `frontend.tsx`:
87
-
88
- ```tsx#frontend.tsx
89
- import React from "react";
90
-
91
- // import .css files directly and it works
92
- import './index.css';
93
-
94
- import { createRoot } from "react-dom/client";
95
-
96
- const root = createRoot(document.body);
97
-
98
- export default function Frontend() {
99
- return <h1>Hello, world!</h1>;
100
- }
101
-
102
- root.render(<Frontend />);
103
- ```
104
-
105
- Then, run index.ts
106
-
107
- ```sh
108
- bun --hot ./index.ts
109
- ```
110
-
111
- For more information, read the Bun API docs in `node_modules/bun-types/docs/**.md`.