@napuketto/network 0.5.0 → 0.6.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/index.d.mts CHANGED
@@ -97,9 +97,9 @@ interface HttpClientOptions {
97
97
  /** 上报地址(完整 URL)。 */
98
98
  url: string;
99
99
  headers?: Record<string, string> | undefined;
100
- /** 请求超时(毫秒);缺省不超时。 */
100
+ /** 从提交到投递完成的期限(毫秒);缺省 5 秒。 */
101
101
  timeoutMs?: number | undefined;
102
- /** 上报失败回调(网络错误 / 非 2xx / 超时)。 */
102
+ /** 上报失败回调,含队列拒收和超时。 */
103
103
  onError?: ((err: unknown) => void) | undefined;
104
104
  }
105
105
  interface WsHeartbeatOptions {
@@ -122,6 +122,8 @@ interface WsClientOptions {
122
122
  /** 服务端地址(完整 URL,含 ws:// 或 wss://)。 */
123
123
  url: string;
124
124
  headers?: Record<string, string> | undefined;
125
+ /** 入站单条消息上限(字节);缺省 DEFAULT_MAX_PAYLOAD_BYTES。 */
126
+ maxPayloadBytes?: number | undefined;
125
127
  /** ping/pong 判活,缺省不探测。 */
126
128
  heartbeat?: WsHeartbeatOptions | undefined;
127
129
  /** 发送缓冲上限(字节,含待发送帧);缺省 32 MiB。 */
@@ -162,11 +164,17 @@ export declare class EventBroadcaster {
162
164
  }
163
165
  export declare class HttpClient implements TransportAdapter {
164
166
  private readonly opts;
167
+ private readonly timeoutMs;
168
+ private readonly queue;
169
+ private pendingBytes;
170
+ private shutdown;
171
+ private active;
165
172
  constructor(opts: HttpClientOptions);
166
173
  send<T>(payload: T): void;
167
- /** 正向上报无连接管理。 */
168
174
  open(): void | Promise<void>;
169
175
  close(): void | Promise<void>;
176
+ private drain;
177
+ private reportError;
170
178
  private post;
171
179
  }
172
180
  export declare class HttpServer implements TransportAdapter {
@@ -269,7 +277,6 @@ export declare class WsClient implements TransportAdapter {
269
277
  private cancelReconnect;
270
278
  /** 关闭连接并停止重连 / 心跳。 */
271
279
  close(): void | Promise<void>;
272
- /** 构造 WebSocket 选项(headers / 证书校验按配置透传,缺省由 ws 库决定)。 */
273
280
  private buildSocketOptions;
274
281
  private bind;
275
282
  private onClose;
@@ -278,7 +285,9 @@ export declare class WsClient implements TransportAdapter {
278
285
  export declare function sendWsText(sockets: Iterable<WsSocket>, data: string | undefined, maxBufferedBytes?: number): void;
279
286
  export declare class WsServer implements TransportAdapter {
280
287
  private readonly opts;
281
- private wss;
288
+ private listener;
289
+ private opening;
290
+ private closing;
282
291
  private readonly heartbeats;
283
292
  /**
284
293
  * 请求分发注入点:协议层实现「请求 → 响应」(status 参数 WS 下忽略)。
@@ -293,7 +302,10 @@ export declare class WsServer implements TransportAdapter {
293
302
  /** 广播给所有已连接客户端(序列化后发送)。 */
294
303
  send<T>(payload: T): void;
295
304
  open(): Promise<void>;
305
+ private start;
296
306
  close(): Promise<void>;
307
+ private stop;
308
+ private dispose;
297
309
  private handleConnection;
298
310
  }
299
311
  export type { AuthorizeHook, HttpClientOptions, HttpRouteContext, HttpServerOptions, RawRequestHook, RequestContext, Respond, ServerOptions, SseClient, SseHandler, TransportAdapter, WsClientOptions, WsHeartbeatOptions, WsServerOptions, WsSocket, WsUpgradeHook };
package/dist/index.mjs CHANGED
@@ -5,6 +5,7 @@ import { Hono } from "hono";
5
5
  import { bodyLimit } from "hono/body-limit";
6
6
  import { WebSocket, WebSocketServer } from "ws";
7
7
  import { randomBytes } from "node:crypto";
8
+ import { once } from "node:events";
8
9
  // src/broadcaster.ts
9
10
  var EventBroadcaster = class {
10
11
  adapters = /* @__PURE__ */ new Set();
@@ -40,38 +41,134 @@ var EventBroadcaster = class {
40
41
  }
41
42
  };
42
43
  // src/http-client.ts
44
+ const DEFAULT_TIMEOUT_MS = 5e3;
45
+ const MAX_TIMER_DELAY_MS$1 = 2147483647;
46
+ const MAX_QUEUED_DELIVERIES = 64;
47
+ const MAX_PENDING_BYTES = 33554432;
43
48
  var HttpClient = class {
44
49
  opts;
50
+ timeoutMs;
51
+ queue = [];
52
+ pendingBytes = 0;
53
+ shutdown = new AbortController();
54
+ active;
45
55
  constructor(opts) {
46
56
  this.opts = opts;
57
+ const timeout = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
58
+ this.timeoutMs = Number.isInteger(timeout) && timeout > 0 && timeout <= MAX_TIMER_DELAY_MS$1 ? timeout : DEFAULT_TIMEOUT_MS;
47
59
  }
48
60
  send(payload) {
49
- const { url, headers, timeoutMs, onError } = this.opts;
50
- this.post(url, payload, headers, timeoutMs).catch((err) => onError?.(err));
51
- }
52
- /** 正向上报无连接管理。 */
53
- open() {}
54
- close() {}
55
- async post(url, payload, headers, timeoutMs) {
56
- const controller = new AbortController();
57
- let timer;
58
- if (timeoutMs !== void 0) timer = setTimeout(() => controller.abort(), timeoutMs);
61
+ const deadline = performance.now() + this.timeoutMs;
62
+ const { signal } = this.shutdown;
63
+ if (signal.aborted) {
64
+ this.reportError(/* @__PURE__ */ new Error("HTTP 上报已关闭"));
65
+ return;
66
+ }
67
+ let body;
68
+ try {
69
+ body = JSON.stringify(payload);
70
+ } catch (err) {
71
+ this.reportError(err);
72
+ return;
73
+ }
74
+ if (signal.aborted) {
75
+ this.reportError(/* @__PURE__ */ new Error("HTTP 上报已关闭"));
76
+ return;
77
+ }
78
+ if (this.queue.length >= MAX_QUEUED_DELIVERIES) {
79
+ this.reportError(/* @__PURE__ */ new Error("HTTP 上报队列已满"));
80
+ return;
81
+ }
82
+ const bytes = body === void 0 ? 0 : Buffer.byteLength(body);
83
+ if (this.pendingBytes + bytes > MAX_PENDING_BYTES) {
84
+ this.reportError(/* @__PURE__ */ new Error("HTTP 上报待发送正文超限"));
85
+ return;
86
+ }
87
+ this.queue.push({
88
+ body,
89
+ bytes,
90
+ deadline
91
+ });
92
+ this.pendingBytes += bytes;
93
+ this.active ??= this.drain(signal);
94
+ }
95
+ open() {
96
+ if (!this.shutdown.signal.aborted) return;
97
+ if (this.active) return this.active.then(() => this.open());
98
+ this.shutdown = new AbortController();
99
+ }
100
+ close() {
101
+ this.shutdown.abort();
102
+ this.queue.length = 0;
103
+ this.pendingBytes = 0;
104
+ return this.active;
105
+ }
106
+ async drain(signal) {
107
+ try {
108
+ let delivery = this.queue.shift();
109
+ while (delivery !== void 0) {
110
+ const failure = await this.post(delivery, signal).catch((err) => ({ err }));
111
+ if (signal.aborted) return;
112
+ this.pendingBytes -= delivery.bytes;
113
+ if (failure) this.reportError(failure.err);
114
+ delivery = this.queue.shift();
115
+ }
116
+ } finally {
117
+ this.active = void 0;
118
+ }
119
+ }
120
+ reportError(err) {
59
121
  try {
60
- const res = await fetch(url, {
122
+ this.opts.onError?.(err);
123
+ } catch {}
124
+ }
125
+ async post(delivery, shutdown) {
126
+ const remaining = Math.ceil(delivery.deadline - performance.now());
127
+ const timeoutError = new DOMException("HTTP 上报超时", "TimeoutError");
128
+ if (remaining <= 0) throw timeoutError;
129
+ const timeout = new AbortController();
130
+ const signal = AbortSignal.any([shutdown, timeout.signal]);
131
+ const timer = setTimeout(() => timeout.abort(timeoutError), remaining).unref();
132
+ try {
133
+ const res = await fetch(this.opts.url, {
61
134
  method: "POST",
62
135
  headers: {
63
136
  "content-type": "application/json",
64
- ...headers
137
+ ...this.opts.headers
65
138
  },
66
- body: JSON.stringify(payload),
67
- signal: controller.signal
139
+ ...delivery.body === void 0 ? {} : { body: delivery.body },
140
+ signal
68
141
  });
142
+ await res.body?.cancel().catch(() => void 0);
143
+ signal.throwIfAborted();
69
144
  if (!res.ok) throw new Error(`HTTP 上报失败: ${res.status} ${res.statusText}`);
70
145
  } finally {
71
- if (timer !== void 0) clearTimeout(timer);
146
+ clearTimeout(timer);
72
147
  }
73
148
  }
74
149
  };
150
+ // src/server-lifecycle.ts
151
+ const CLOSE_GRACE_MS = 250;
152
+ /** HTTP server.close 不等待已升级的 TCP 连接,必须单独等待它们释放。 */
153
+ async function closeServerConnections(server, sockets, wss) {
154
+ const httpClosed = new Promise((resolve) => server.close(() => resolve()));
155
+ const socketsClosed = Array.from(sockets, (socket) => new Promise((resolve) => socket.once("close", () => resolve())));
156
+ const wsClosed = wss && new Promise((resolve) => wss.close(() => resolve()));
157
+ if (wss) for (const client of wss.clients) client.close(1001, "server shutdown");
158
+ const timer = setTimeout(() => {
159
+ if (wss) for (const client of wss.clients) client.terminate();
160
+ for (const socket of sockets) socket.destroy();
161
+ }, CLOSE_GRACE_MS).unref();
162
+ try {
163
+ await Promise.all([
164
+ httpClosed,
165
+ wsClosed,
166
+ ...socketsClosed
167
+ ]);
168
+ } finally {
169
+ clearTimeout(timer);
170
+ }
171
+ }
75
172
  // src/types.ts
76
173
  /**
77
174
  * Node 原生 IncomingMessage → RequestContext(headers 展平,url 含查询串)。
@@ -101,6 +198,58 @@ const DEFAULT_MAX_BODY_BYTES = 16777216;
101
198
  * 从 ws 的缺省 100 MiB 收紧,仍可容纳约 24 MB 的 base64 编码前媒体。
102
199
  */
103
200
  const DEFAULT_MAX_PAYLOAD_BYTES = 33554432;
201
+ // src/ws-flow.ts
202
+ const DEFAULT_MAX_BUFFERED_BYTES = 33554432;
203
+ const MAX_FRAME_HEADER_BYTES = 14;
204
+ function wsPayloadLimit(bytes) {
205
+ return bytes !== void 0 && Number.isInteger(bytes) && bytes > 0 && bytes <= 2147483647 ? bytes : DEFAULT_MAX_PAYLOAD_BYTES;
206
+ }
207
+ /** 向选定连接发送文本,超出发送预算时立即断开对应连接。 */
208
+ function sendWsText(sockets, data, maxBufferedBytes = DEFAULT_MAX_BUFFERED_BYTES) {
209
+ const limit = Number.isSafeInteger(maxBufferedBytes) && maxBufferedBytes > 0 ? maxBufferedBytes : DEFAULT_MAX_BUFFERED_BYTES;
210
+ const text = data ?? "";
211
+ const frameBytes = Buffer.byteLength(text) + MAX_FRAME_HEADER_BYTES;
212
+ for (const socket of sockets) {
213
+ if (!isWsOpen(socket)) continue;
214
+ if (socket.bufferedAmount + frameBytes > limit) {
215
+ socket.terminate();
216
+ continue;
217
+ }
218
+ socket.send(text);
219
+ }
220
+ }
221
+ /** 串行探测,每条连接最多等待一个 pong。返回幂等的停止函数。 */
222
+ function startWsHeartbeat(socket, opts) {
223
+ const pongTimeoutMs = opts.pongTimeoutMs ?? Math.max(opts.intervalMs, 1e3);
224
+ let expectedPong;
225
+ let timer = setTimeout(ping, opts.intervalMs).unref();
226
+ socket.on("pong", onPong);
227
+ socket.once("close", stop);
228
+ function ping() {
229
+ if (!isWsOpen(socket)) {
230
+ stop();
231
+ return;
232
+ }
233
+ expectedPong = randomBytes(8);
234
+ timer = setTimeout(() => {
235
+ stop();
236
+ if (isWsOpen(socket)) socket.terminate();
237
+ }, pongTimeoutMs).unref();
238
+ socket.ping(expectedPong);
239
+ }
240
+ function onPong(pong) {
241
+ if (!expectedPong?.equals(pong)) return;
242
+ expectedPong = void 0;
243
+ clearTimeout(timer);
244
+ timer = setTimeout(ping, opts.intervalMs).unref();
245
+ }
246
+ function stop() {
247
+ clearTimeout(timer);
248
+ socket.off("pong", onPong);
249
+ socket.off("close", stop);
250
+ }
251
+ return stop;
252
+ }
104
253
  // src/http-server.ts
105
254
  /**
106
255
  * 反向 HTTP server(hono + @hono/node-server)
@@ -117,8 +266,6 @@ const HTTP_STATUS = {
117
266
  unavailable: 503,
118
267
  timeout: 504
119
268
  };
120
- /** 关闭握手宽限期;之后强断所有剩余 TCP 连接,包括升级后的 WS。 */
121
- const CLOSE_GRACE_MS = 250;
122
269
  const STATUS_REASON = /^[ -~]{1,128}$/;
123
270
  function decideUpgrade(hook, req) {
124
271
  let decision;
@@ -334,7 +481,7 @@ var HttpServer = class {
334
481
  attachUpgrade(server) {
335
482
  const wss = new WebSocketServer({
336
483
  noServer: true,
337
- maxPayload: this.opts.wsMaxPayloadBytes ?? 33554432,
484
+ maxPayload: wsPayloadLimit(this.opts.wsMaxPayloadBytes),
338
485
  skipUTF8Validation: false
339
486
  });
340
487
  this.wss = wss;
@@ -378,31 +525,10 @@ var HttpServer = class {
378
525
  }
379
526
  async dispose(server) {
380
527
  server.removeAllListeners("upgrade");
381
- const httpClosed = new Promise((resolve) => server.close(() => resolve()));
382
- const socketsClosed = [...this.sockets].map((socket) => new Promise((resolve) => socket.once("close", () => resolve())));
383
528
  for (const finish of this.pending) finish();
384
- const wss = this.wss;
385
- const wsClosed = new Promise((resolve) => {
386
- if (!wss) {
387
- resolve();
388
- return;
389
- }
390
- wss.close(() => resolve());
391
- for (const client of wss.clients) client.close(1001, "server shutdown");
392
- });
393
- const timer = setTimeout(() => {
394
- if (wss) for (const client of wss.clients) client.terminate();
395
- for (const socket of this.sockets) socket.destroy();
396
- }, CLOSE_GRACE_MS);
397
- timer.unref();
398
529
  try {
399
- await Promise.all([
400
- httpClosed,
401
- wsClosed,
402
- ...socketsClosed
403
- ]);
530
+ await closeServerConnections(server, this.sockets, this.wss);
404
531
  } finally {
405
- clearTimeout(timer);
406
532
  this.wss = void 0;
407
533
  server.removeAllListeners();
408
534
  }
@@ -455,55 +581,6 @@ function createSseResponse(handler) {
455
581
  });
456
582
  return new Response(stream, { headers: { ...SSE_HEADERS } });
457
583
  }
458
- // src/ws-flow.ts
459
- const DEFAULT_MAX_BUFFERED_BYTES = 33554432;
460
- const MAX_FRAME_HEADER_BYTES = 14;
461
- /** 向选定连接发送文本,超出发送预算时立即断开对应连接。 */
462
- function sendWsText(sockets, data, maxBufferedBytes = DEFAULT_MAX_BUFFERED_BYTES) {
463
- const limit = Number.isSafeInteger(maxBufferedBytes) && maxBufferedBytes > 0 ? maxBufferedBytes : DEFAULT_MAX_BUFFERED_BYTES;
464
- const text = data ?? "";
465
- const frameBytes = Buffer.byteLength(text) + MAX_FRAME_HEADER_BYTES;
466
- for (const socket of sockets) {
467
- if (!isWsOpen(socket)) continue;
468
- if (socket.bufferedAmount + frameBytes > limit) {
469
- socket.terminate();
470
- continue;
471
- }
472
- socket.send(text);
473
- }
474
- }
475
- /** 串行探测,每条连接最多等待一个 pong。返回幂等的停止函数。 */
476
- function startWsHeartbeat(socket, opts) {
477
- const pongTimeoutMs = opts.pongTimeoutMs ?? Math.max(opts.intervalMs, 1e3);
478
- let expectedPong;
479
- let timer = setTimeout(ping, opts.intervalMs).unref();
480
- socket.on("pong", onPong);
481
- socket.once("close", stop);
482
- function ping() {
483
- if (!isWsOpen(socket)) {
484
- stop();
485
- return;
486
- }
487
- expectedPong = randomBytes(8);
488
- timer = setTimeout(() => {
489
- stop();
490
- if (isWsOpen(socket)) socket.terminate();
491
- }, pongTimeoutMs).unref();
492
- socket.ping(expectedPong);
493
- }
494
- function onPong(pong) {
495
- if (!expectedPong?.equals(pong)) return;
496
- expectedPong = void 0;
497
- clearTimeout(timer);
498
- timer = setTimeout(ping, opts.intervalMs).unref();
499
- }
500
- function stop() {
501
- clearTimeout(timer);
502
- socket.off("pong", onPong);
503
- socket.off("close", stop);
504
- }
505
- return stop;
506
- }
507
584
  // src/ws-client.ts
508
585
  /**
509
586
  * 正向 WS 客户端(主动连接 / 反向连接)
@@ -588,13 +665,14 @@ var WsClient = class {
588
665
  this.ws = void 0;
589
666
  if (ws) ws.close();
590
667
  }
591
- /** 构造 WebSocket 选项(headers / 证书校验按配置透传,缺省由 ws 库决定)。 */
592
668
  buildSocketOptions() {
593
- const { headers, rejectUnauthorized } = this.opts;
594
- const out = {};
595
- if (headers !== void 0) out.headers = headers;
596
- if (rejectUnauthorized !== void 0) out.rejectUnauthorized = rejectUnauthorized;
597
- return out;
669
+ const { headers, rejectUnauthorized, maxPayloadBytes } = this.opts;
670
+ return {
671
+ maxPayload: wsPayloadLimit(maxPayloadBytes),
672
+ skipUTF8Validation: false,
673
+ ...headers === void 0 ? {} : { headers },
674
+ ...rejectUnauthorized === void 0 ? {} : { rejectUnauthorized }
675
+ };
598
676
  }
599
677
  bind(ws) {
600
678
  ws.on("message", (raw) => {
@@ -633,10 +711,18 @@ var WsClient = class {
633
711
  }
634
712
  };
635
713
  // src/ws-server.ts
714
+ /**
715
+ * 反向 WS server(被动,第三方主动连入)
716
+ *
717
+ * 收到消息 → `onRequest` 注入点(协议层分发)→ 响应经 `respond` 回发**同一客户端**。
718
+ * 握手鉴权通过 `authorize` 钩子;调用方也可用 `onConnection` 登记连接以进行带内鉴权。
719
+ */
636
720
  const WS_CLOSE_CODE = { unauthorized: 4401 };
637
721
  var WsServer = class {
638
722
  opts;
639
- wss;
723
+ listener;
724
+ opening;
725
+ closing;
640
726
  heartbeats = /* @__PURE__ */ new Map();
641
727
  /**
642
728
  * 请求分发注入点:协议层实现「请求 → 响应」(status 参数 WS 下忽略)。
@@ -652,56 +738,78 @@ var WsServer = class {
652
738
  }
653
739
  /** 广播给所有已连接客户端(序列化后发送)。 */
654
740
  send(payload) {
655
- const { wss } = this;
656
- if (!wss) return;
657
- sendWsText(wss.clients, JSON.stringify(payload), this.opts.maxBufferedBytes);
741
+ if (!this.listener || this.closing) return;
742
+ sendWsText(this.listener.wss.clients, JSON.stringify(payload), this.opts.maxBufferedBytes);
658
743
  }
659
- async open() {
660
- if (this.wss) return;
744
+ open() {
745
+ if (this.closing) return this.closing.then(() => this.open());
746
+ if (this.opening) return this.opening;
747
+ if (this.listener) return Promise.resolve();
748
+ this.opening = this.start().finally(() => {
749
+ this.opening = void 0;
750
+ });
751
+ return this.opening;
752
+ }
753
+ async start() {
661
754
  const { host, port, path } = this.opts;
662
- const serverOptions = {
663
- host,
664
- port,
665
- maxPayload: this.opts.maxPayloadBytes ?? 33554432,
666
- skipUTF8Validation: false
755
+ const http = createServer((_req, res) => {
756
+ const body = STATUS_CODES[426] ?? "Upgrade Required";
757
+ res.writeHead(426, {
758
+ "Content-Length": body.length,
759
+ "Content-Type": "text/plain"
760
+ });
761
+ res.end(body);
762
+ });
763
+ const wss = new WebSocketServer({
764
+ server: http,
765
+ maxPayload: wsPayloadLimit(this.opts.maxPayloadBytes),
766
+ skipUTF8Validation: false,
767
+ ...path === void 0 ? {} : { path }
768
+ });
769
+ const sockets = /* @__PURE__ */ new Set();
770
+ const listener = {
771
+ http,
772
+ wss,
773
+ sockets
667
774
  };
668
- if (path !== void 0) serverOptions.path = path;
669
- const wss = new WebSocketServer(serverOptions);
670
- const onConnection = (socket, req) => this.handleConnection(socket, req);
671
- wss.on("connection", onConnection);
775
+ http.on("connection", (socket) => {
776
+ sockets.add(socket);
777
+ socket.once("close", () => sockets.delete(socket));
778
+ if (this.closing) socket.destroy();
779
+ });
780
+ wss.on("connection", (socket, req) => this.handleConnection(socket, req));
672
781
  try {
673
- await new Promise((resolve, reject) => {
674
- const onListening = () => {
675
- wss.off("error", onError);
676
- resolve();
677
- };
678
- const onError = (err) => {
679
- wss.off("listening", onListening);
680
- reject(err);
681
- };
682
- wss.once("listening", onListening);
683
- wss.once("error", onError);
684
- });
782
+ http.listen(port, host);
783
+ await once(wss, "listening");
685
784
  } catch (err) {
686
- wss.off("connection", onConnection);
687
- wss.on("error", () => void 0);
688
- wss.close();
785
+ await this.dispose(listener);
689
786
  throw err;
690
787
  }
691
- this.wss = wss;
788
+ this.listener = listener;
692
789
  }
693
- async close() {
790
+ close() {
791
+ if (this.closing) return this.closing;
792
+ this.closing = this.stop().finally(() => {
793
+ this.closing = void 0;
794
+ });
795
+ return this.closing;
796
+ }
797
+ async stop() {
798
+ if (this.opening) await this.opening.catch(() => void 0);
799
+ const { listener } = this;
800
+ if (!listener) return;
801
+ await this.dispose(listener);
802
+ this.listener = void 0;
803
+ }
804
+ async dispose({ http, wss, sockets }) {
694
805
  for (const stop of this.heartbeats.values()) stop();
695
806
  this.heartbeats.clear();
696
- const { wss } = this;
697
- if (!wss) return;
698
- await new Promise((resolve) => {
699
- for (const client of wss.clients) client.close();
700
- wss.close(() => {
701
- this.wss = void 0;
702
- resolve();
703
- });
704
- });
807
+ wss.removeAllListeners("connection");
808
+ try {
809
+ await closeServerConnections(http, sockets, wss);
810
+ } finally {
811
+ http.removeAllListeners();
812
+ }
705
813
  }
706
814
  handleConnection(socket, req) {
707
815
  socket.on("error", () => socket.terminate());
@@ -715,7 +823,8 @@ var WsServer = class {
715
823
  socket.once("close", () => this.heartbeats.delete(socket));
716
824
  }
717
825
  this.onConnection?.(socket, ctx);
718
- socket.on("message", (raw) => {
826
+ const onMessage = (raw) => {
827
+ if (this.closing) return;
719
828
  let reqBody;
720
829
  try {
721
830
  reqBody = JSON.parse(raw.toString());
@@ -725,7 +834,9 @@ var WsServer = class {
725
834
  this.onRequest?.(reqBody, (res) => {
726
835
  if (isWsOpen(socket)) sendWsText([socket], JSON.stringify(res), this.opts.maxBufferedBytes);
727
836
  }, socket);
728
- });
837
+ };
838
+ socket.on("message", onMessage);
839
+ socket.once("close", () => socket.off("message", onMessage));
729
840
  }
730
841
  };
731
842
  export { DEFAULT_MAX_BODY_BYTES, DEFAULT_MAX_PAYLOAD_BYTES, EventBroadcaster, HttpClient, HttpServer, WsClient, WsServer, createSseResponse, isWsOpen, sendWsText };
package/package.json CHANGED
@@ -1,11 +1,10 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@napuketto/network",
4
- "version": "0.5.0",
4
+ "version": "0.6.0",
5
5
  "type": "module",
6
- "description": "Network layer of NapukettoQQ",
6
+ "description": "Network layer of Napuketto",
7
7
  "keywords": [
8
- "qq",
9
8
  "bot",
10
9
  "napuketto",
11
10
  "network",
@@ -13,13 +12,13 @@
13
12
  "http",
14
13
  "hono"
15
14
  ],
16
- "homepage": "https://github.com/NapukettoDev/NapukettoQQ/tree/main/packages/network#readme",
15
+ "homepage": "https://github.com/NapukettoDev/Napuketto/tree/main/packages/network#readme",
17
16
  "bugs": {
18
- "url": "https://github.com/NapukettoDev/NapukettoQQ/issues"
17
+ "url": "https://github.com/NapukettoDev/Napuketto/issues"
19
18
  },
20
19
  "repository": {
21
20
  "type": "git",
22
- "url": "git+https://github.com/NapukettoDev/NapukettoQQ.git",
21
+ "url": "git+https://github.com/NapukettoDev/Napuketto.git",
23
22
  "directory": "packages/network"
24
23
  },
25
24
  "license": "MIT",