sonic-ws 1.3.2 → 1.3.3

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.
Files changed (46) hide show
  1. package/dist/index.d.ts +0 -4
  2. package/dist/version.d.ts +1 -5
  3. package/dist/version.js +23 -4
  4. package/dist/ws/Connection.d.ts +0 -4
  5. package/dist/ws/Connection.js +124 -4
  6. package/dist/ws/PacketProcessor.d.ts +0 -4
  7. package/dist/ws/PacketProcessor.js +50 -4
  8. package/dist/ws/client/core/ClientCore.d.ts +0 -4
  9. package/dist/ws/client/core/ClientCore.js +249 -4
  10. package/dist/ws/client/node/ClientNode.d.ts +0 -4
  11. package/dist/ws/client/node/ClientNode.js +34 -4
  12. package/dist/ws/debug/DebugServer.d.ts +0 -4
  13. package/dist/ws/debug/DebugServer.js +605 -4
  14. package/dist/ws/packets/PacketProcessors.d.ts +0 -4
  15. package/dist/ws/packets/PacketProcessors.js +315 -4
  16. package/dist/ws/packets/PacketType.d.ts +0 -4
  17. package/dist/ws/packets/PacketType.js +59 -4
  18. package/dist/ws/packets/Packets.d.ts +0 -4
  19. package/dist/ws/packets/Packets.js +275 -4
  20. package/dist/ws/server/SonicWSConnection.d.ts +0 -4
  21. package/dist/ws/server/SonicWSConnection.js +296 -4
  22. package/dist/ws/server/SonicWSServer.d.ts +1 -5
  23. package/dist/ws/server/SonicWSServer.js +305 -4
  24. package/dist/ws/util/BufferUtil.d.ts +0 -4
  25. package/dist/ws/util/BufferUtil.js +40 -4
  26. package/dist/ws/util/StringUtil.d.ts +0 -4
  27. package/dist/ws/util/StringUtil.js +49 -4
  28. package/dist/ws/util/enums/EnumHandler.d.ts +0 -4
  29. package/dist/ws/util/enums/EnumHandler.js +58 -4
  30. package/dist/ws/util/enums/EnumType.d.ts +0 -4
  31. package/dist/ws/util/enums/EnumType.js +70 -4
  32. package/dist/ws/util/packets/BatchHelper.d.ts +0 -4
  33. package/dist/ws/util/packets/BatchHelper.js +83 -4
  34. package/dist/ws/util/packets/CompressionUtil.d.ts +5 -9
  35. package/dist/ws/util/packets/CompressionUtil.js +275 -4
  36. package/dist/ws/util/packets/HashUtil.d.ts +0 -4
  37. package/dist/ws/util/packets/HashUtil.js +120 -4
  38. package/dist/ws/util/packets/JSONUtil.d.ts +0 -4
  39. package/dist/ws/util/packets/JSONUtil.js +177 -4
  40. package/dist/ws/util/packets/PacketHolder.d.ts +0 -4
  41. package/dist/ws/util/packets/PacketHolder.js +124 -4
  42. package/dist/ws/util/packets/PacketUtils.d.ts +0 -4
  43. package/dist/ws/util/packets/PacketUtils.js +281 -4
  44. package/dist/ws/util/packets/RateHandler.d.ts +0 -4
  45. package/dist/ws/util/packets/RateHandler.js +64 -4
  46. package/package.json +3 -3
package/dist/index.d.ts CHANGED
@@ -1,7 +1,3 @@
1
- /**
2
- * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
4
- */
5
1
  export { SonicWS } from './ws/client/node/ClientNode';
6
2
  export { SonicWSConnection } from './ws/server/SonicWSConnection';
7
3
  export { SonicWSServer } from './ws/server/SonicWSServer';
package/dist/version.d.ts CHANGED
@@ -1,9 +1,5 @@
1
- /**
2
- * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
4
- */
5
1
  /** Current protocol version */
6
- export declare const VERSION = 20;
2
+ export declare const VERSION = 22;
7
3
  /** Server data suffix */
8
4
  export declare const SERVER_SUFFIX = "SWS";
9
5
  /** Server data suffix in array */
package/dist/version.js CHANGED
@@ -1,6 +1,25 @@
1
- /**
1
+ "use strict";
2
+ /*
2
3
  * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
4
16
  */
5
-
6
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.SERVER_SUFFIX_NUMS=exports.SERVER_SUFFIX=exports.VERSION=void 0;const e=require("./ws/util/StringUtil");exports.VERSION=20,exports.SERVER_SUFFIX="SWS",exports.SERVER_SUFFIX_NUMS=(0,e.processCharCodes)(exports.SERVER_SUFFIX);
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.SERVER_SUFFIX_NUMS = exports.SERVER_SUFFIX = exports.VERSION = void 0;
19
+ const StringUtil_1 = require("./ws/util/StringUtil");
20
+ /** Current protocol version */
21
+ exports.VERSION = 22;
22
+ /** Server data suffix */
23
+ exports.SERVER_SUFFIX = "SWS";
24
+ /** Server data suffix in array */
25
+ exports.SERVER_SUFFIX_NUMS = (0, StringUtil_1.processCharCodes)(exports.SERVER_SUFFIX);
@@ -1,7 +1,3 @@
1
- /**
2
- * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
4
- */
5
1
  import { ConnectionMiddleware, IMiddlewareHolder, MiddlewareHolder } from "./PacketProcessor";
6
2
  import { BatchHelper } from "./util/packets/BatchHelper";
7
3
  /**
@@ -1,6 +1,126 @@
1
- /**
1
+ "use strict";
2
+ /*
2
3
  * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
4
16
  */
5
-
6
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.CloseCodes=exports.Connection=void 0,exports.getClosureCause=function(e){if(e>=4e3)return r[e]??"UNKNOWN";switch(e){case 1e3:return"NORMAL_CLOSURE";case 1001:return"GOING_AWAY";case 1002:return"PROTOCOL_ERROR";case 1003:return"UNSUPPORTED_DATA";case 1006:return"ABNORMAL_CLOSURE";default:return"UNKNOWN"}};const e=require("./PacketProcessor"),t=require("./util/packets/BatchHelper");class s extends e.MiddlewareHolder{listeners;name;closed=!1;socket;_timers={};batcher;_on;_off;id;constructor(e,s,r,o,i){super(),this.id=s,this.listeners={},this.name=r,this.socket=e,this.batcher=new t.BatchHelper,this._on=o,this._off=i,this._on("close",()=>{this.callMiddleware("onStatusChange",WebSocket.CLOSED),this.closed=!0;for(const[e,t,s]of Object.values(this._timers))this.clearTimeout(e),s&&t(!0)}),this._on("open",()=>this.callMiddleware("onStatusChange",WebSocket.OPEN))}setTimeout(e,t,s=!1){const r=setTimeout(()=>{e(),this.clearTimeout(r)},t);return this._timers[r]=[r,e,s],r}setInterval(e,t,s=!1){const r=setInterval(e,t);return this._timers[r]=[r,e,s],r}clearTimeout(e){clearTimeout(e),delete this._timers[e]}clearInterval(e){this.clearTimeout(e)}raw_send(e){this.socket.send(e)}raw_onmessage(e){this._on("message",e)}close(e=1e3,t){this.closed=!0,this.socket.close(e,t?.toString())}isClosed(){return this.closed||this.socket.readyState==WebSocket.CLOSED}async setName(e){await this.callMiddleware("onNameChange",e)||(this.name=e)}getName(){return this.name}}var r;exports.Connection=s,function(e){e[e.RATELIMIT=4e3]="RATELIMIT",e[e.SMALL=4001]="SMALL",e[e.INVALID_KEY=4002]="INVALID_KEY",e[e.INVALID_PACKET=4003]="INVALID_PACKET",e[e.INVALID_DATA=4004]="INVALID_DATA",e[e.REPEATED_HANDSHAKE=4005]="REPEATED_HANDSHAKE",e[e.DISABLED_PACKET=4006]="DISABLED_PACKET",e[e.MIDDLEWARE=4007]="MIDDLEWARE",e[e.MANUAL_SHUTDOWN=4008]="MANUAL_SHUTDOWN"}(r||(exports.CloseCodes=r={}));
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.CloseCodes = exports.Connection = void 0;
19
+ exports.getClosureCause = getClosureCause;
20
+ const PacketProcessor_1 = require("./PacketProcessor");
21
+ const BatchHelper_1 = require("./util/packets/BatchHelper");
22
+ class Connection extends PacketProcessor_1.MiddlewareHolder {
23
+ listeners;
24
+ name;
25
+ closed = false;
26
+ socket;
27
+ _timers = {};
28
+ batcher;
29
+ _on;
30
+ _off;
31
+ /** The index of the connection; unique for all connected, not unique after disconnection. */
32
+ id;
33
+ constructor(socket, id, name, addListener, removeListener) {
34
+ super();
35
+ this.id = id;
36
+ this.listeners = {};
37
+ this.name = name;
38
+ this.socket = socket;
39
+ this.batcher = new BatchHelper_1.BatchHelper();
40
+ this._on = addListener;
41
+ this._off = removeListener;
42
+ this._on("close", () => {
43
+ this.callMiddleware('onStatusChange', WebSocket.CLOSED);
44
+ this.closed = true;
45
+ for (const [id, callback, shouldCall] of Object.values(this._timers)) {
46
+ this.clearTimeout(id);
47
+ if (shouldCall)
48
+ callback(true);
49
+ }
50
+ });
51
+ this._on('open', () => this.callMiddleware('onStatusChange', WebSocket.OPEN));
52
+ }
53
+ setTimeout(call, time, callOnClose = false) {
54
+ const timeout = setTimeout(() => {
55
+ call();
56
+ this.clearTimeout(timeout);
57
+ }, time);
58
+ this._timers[timeout] = [timeout, call, callOnClose];
59
+ return timeout;
60
+ }
61
+ setInterval(call, time, callOnClose = false) {
62
+ const interval = setInterval(call, time);
63
+ this._timers[interval] = [interval, call, callOnClose];
64
+ return interval;
65
+ }
66
+ clearTimeout(id) {
67
+ clearTimeout(id);
68
+ delete this._timers[id];
69
+ }
70
+ clearInterval(id) {
71
+ this.clearTimeout(id);
72
+ }
73
+ raw_send(data) {
74
+ this.socket.send(data);
75
+ }
76
+ raw_onmessage(listener) {
77
+ this._on("message", listener);
78
+ }
79
+ close(code = 1000, reason) {
80
+ this.closed = true;
81
+ this.socket.close(code, reason?.toString());
82
+ }
83
+ isClosed() {
84
+ return this.closed || this.socket.readyState == WebSocket.CLOSED;
85
+ }
86
+ async setName(name) {
87
+ if (await this.callMiddleware("onNameChange", name))
88
+ return;
89
+ this.name = name;
90
+ }
91
+ getName() {
92
+ return this.name;
93
+ }
94
+ }
95
+ exports.Connection = Connection;
96
+ var CloseCodes;
97
+ (function (CloseCodes) {
98
+ CloseCodes[CloseCodes["RATELIMIT"] = 4000] = "RATELIMIT";
99
+ CloseCodes[CloseCodes["SMALL"] = 4001] = "SMALL";
100
+ CloseCodes[CloseCodes["INVALID_KEY"] = 4002] = "INVALID_KEY";
101
+ CloseCodes[CloseCodes["INVALID_PACKET"] = 4003] = "INVALID_PACKET";
102
+ CloseCodes[CloseCodes["INVALID_DATA"] = 4004] = "INVALID_DATA";
103
+ CloseCodes[CloseCodes["REPEATED_HANDSHAKE"] = 4005] = "REPEATED_HANDSHAKE";
104
+ CloseCodes[CloseCodes["DISABLED_PACKET"] = 4006] = "DISABLED_PACKET";
105
+ CloseCodes[CloseCodes["MIDDLEWARE"] = 4007] = "MIDDLEWARE";
106
+ CloseCodes[CloseCodes["MANUAL_SHUTDOWN"] = 4008] = "MANUAL_SHUTDOWN";
107
+ })(CloseCodes || (exports.CloseCodes = CloseCodes = {}));
108
+ function getClosureCause(id) {
109
+ if (id >= 4000) {
110
+ return CloseCodes[id] ?? 'UNKNOWN';
111
+ }
112
+ switch (id) {
113
+ case 1000:
114
+ return 'NORMAL_CLOSURE';
115
+ case 1001:
116
+ return 'GOING_AWAY';
117
+ case 1002:
118
+ return 'PROTOCOL_ERROR';
119
+ case 1003:
120
+ return 'UNSUPPORTED_DATA';
121
+ case 1006:
122
+ return 'ABNORMAL_CLOSURE';
123
+ default:
124
+ return 'UNKNOWN';
125
+ }
126
+ }
@@ -1,7 +1,3 @@
1
- /**
2
- * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
4
- */
5
1
  import { SonicWSConnection } from "./server/SonicWSConnection";
6
2
  /**
7
3
  * A basic middleware interface; extended by other middleware types
@@ -1,6 +1,52 @@
1
- /**
1
+ "use strict";
2
+ /*
2
3
  * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
4
16
  */
5
-
6
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.MiddlewareHolder=void 0;exports.MiddlewareHolder=class{middlewares=[];addMiddleware(e){this.middlewares.push(e);const r=e;try{"function"==typeof r.init&&r.init(this)}catch(e){console.warn("Middleware init threw an error:",e)}}async callMiddleware(e,...r){let t=!1;for(const d of this.middlewares){const i=d[e];if(i)try{await i(...r)&&(t=!0)}catch(r){console.warn(`Middleware ${String(e)} threw an error:`,r)}}return t}};
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.MiddlewareHolder = void 0;
19
+ class MiddlewareHolder {
20
+ middlewares = [];
21
+ addMiddleware(middleware) {
22
+ this.middlewares.push(middleware);
23
+ const m = middleware;
24
+ try {
25
+ if (typeof m.init === 'function')
26
+ m.init(this);
27
+ }
28
+ catch (e) {
29
+ console.warn('Middleware init threw an error:', e);
30
+ }
31
+ }
32
+ async callMiddleware(method, ...values) {
33
+ let cancelled = false;
34
+ for (const middleware of this.middlewares) {
35
+ const fn = middleware[method];
36
+ if (!fn)
37
+ continue;
38
+ try {
39
+ if (await fn(...values)) {
40
+ cancelled = true;
41
+ }
42
+ }
43
+ catch (e) {
44
+ console.warn(`Middleware ${String(method)} threw an error:`, e);
45
+ }
46
+ }
47
+ return cancelled;
48
+ }
49
+ }
50
+ exports.MiddlewareHolder = MiddlewareHolder;
51
+ ;
52
+ ;
@@ -1,7 +1,3 @@
1
- /**
2
- * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
4
- */
5
1
  import { PacketHolder } from "../../util/packets/PacketHolder";
6
2
  import { Connection } from "../../Connection";
7
3
  import { AsyncPQ, ClientPQ, PacketQueue } from "../../PacketProcessor";
@@ -1,6 +1,251 @@
1
- /**
1
+ "use strict";
2
+ /*
2
3
  * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
4
16
  */
5
-
6
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.SonicWSCore=void 0;const e=require("../../util/packets/PacketHolder"),t=require("../../util/packets/CompressionUtil"),s=require("../../util/packets/PacketUtils"),i=require("../../../version"),a=require("../../packets/Packets"),r=require("../../util/packets/BatchHelper"),n=require("../../util/BufferUtil"),c=require("../../Connection"),o=require("../../util/StringUtil");class h extends c.Connection{preListen;clientPackets=new e.PacketHolder;serverPackets=new e.PacketHolder;pastKeys=!1;readyListeners=[];bufferHandler;_timers={};asyncData={};asyncMap={};constructor(e,t,s,i){super(e,-1,"LocalSocket",s,i),this.socket=e,this.preListen={},this.invalidPacket=this.invalidPacket.bind(this),this.serverKeyHandler=this.serverKeyHandler.bind(this),this.messageHandler=this.messageHandler.bind(this),this._on("message",this.serverKeyHandler),this._on("close",()=>{this.callMiddleware("onStatusChange",WebSocket.CLOSED);for(const[e,t,s]of Object.values(this._timers))this.clearTimeout(e),s&&t(!0);for(const e of this.clientPackets.getPackets())delete e.lastSent[0];for(const e of this.serverPackets.getPackets())delete e.lastReceived[0]}),this.bufferHandler=t}reading=!1;readQueue=[];async serverKeyHandler(e){if(this.reading)return this.readQueue.push(e);this.reading=!0;const s=await this.bufferHandler(e);if(s.length<3||(0,o.as8String)(s.slice(0,3))!=i.SERVER_SUFFIX)throw this.close(1e3),new Error("The server requested is not a Sonic WS server.");const r=s[3];if(r!=i.VERSION)throw this.close(1e3),new Error(`Version mismatch: ${r>i.VERSION?"client":"server"} is outdated (server: ${r}, client: ${i.VERSION})`);const n=await(0,t.decompressGzip)(s.subarray(4,s.length)),[c,h]=(0,t.readVarInt)(n,0);this.id=h;const[l,d]=(0,t.readVarInt)(n,c),u=n.subarray(l,l+d);this.clientPackets.holdPackets(a.Packet.deserializeAll(u,!0));const k=n.subarray(l+d,n.length);this.serverPackets.holdPackets(a.Packet.deserializeAll(k,!0)),this.batcher.registerSendPackets(this.clientPackets,this);for(const e of this.serverPackets.getPackets()){const t=this.serverPackets.getKey(e.tag);this.asyncMap[t]=e.async,e.async&&(this.asyncData[t]=[!1,[]])}Object.keys(this.preListen).forEach(e=>this.preListen[e].forEach(t=>{if(!this.serverPackets.hasTag(e))return console.error(new Error(`The server does not send the packet with tag "${e}"!`));this.listen(e,t)})),this.preListen=null,this.pastKeys=!0,this.readyListeners.forEach(e=>e()),this.readyListeners=null,this._off("message",this.serverKeyHandler),this._on("message",this.messageHandler),this.readQueue.forEach(e=>this.messageHandler(e)),this.readQueue=[]}invalidPacket(e){throw console.error(e),new Error("An error occured with data from the server!! This is probably my fault.. make an issue at https://github.com/liwybloc/sonic-ws")}listenLock=!1;packetQueue=[];async listenPacket(e,t,s,i,a){const r=this.listeners[t];if(!r)return console.warn("Warn: No listener for packet "+t);await this.enqueuePacket(e,r,s,i,a),await this.callMiddleware("onReceive_post",t,"string"==typeof e?[e]:e[0])}isAsync(e){return this.asyncMap[e]}async enqueuePacket(e,t,i,a,r){await(0,s.listenPacket)(e,t,this.invalidPacket),await this.triggerNextPacket(i,a,r)}async triggerNextPacket(e,t,s){t?s[0]=!1:this.listenLock=!1,e.length>0&&this.dataHandler(e.shift())}async dataHandler(e){const t=e[0],s=e.slice(1),i=this.isAsync(t);let a,n,c;if(i?(c=this.asyncData[t],a=c[0],n=c[1]):(a=this.listenLock,n=this.packetQueue),a)return void n.push(e);i?c[0]=!0:this.listenLock=!0;const o=this.serverPackets.getTag(t),h=this.serverPackets.getPacket(o);if(await this.callMiddleware("onReceive_pre",h.tag,e,e.length))return;if(h.rereference&&0==s.length)return void 0===h.lastReceived[0]?this.invalidPacket("No previous value to rereference"):void this.listenPacket(h.lastReceived[0],o,n,i,c);if(0==h.dataBatching){const e=h.lastReceived[0]=await h.listen(s,null);return void this.listenPacket(e,o,n,i,c)}const l=await r.BatchHelper.unravelBatch(h,s,null);if("string"==typeof l)return this.invalidPacket(l);l.forEach(e=>this.listenPacket(e,o,n,i,c))}async messageHandler(e){const t=await this.bufferHandler(e);t.length<1||await this.dataHandler(t)}listen(e,t){this.serverPackets.hasTag(e)?(this.listeners[e]??=[]).push(t):console.log("Tag is not available on server: "+e)}raw_onsend(e){this.listeners.send.push(e)}sendQueue=[!1,[],void 0];async send(e,...t){if(await this.callMiddleware("onSend_pre",e,t,Date.now(),performance.now()))return;const[i,a,r]=await(0,s.processPacket)(this.clientPackets,e,t,this.sendQueue,0);0==r.dataBatching?this.raw_send((0,n.toPacketBuffer)(i,a)):this.batcher.batchPacket(i,a),await this.callMiddleware("onSend_post",e,a,a.length)}on_ready(e){this.pastKeys?e():this.readyListeners.push(e)}on_close(e){this._on("close",e)}on(e,t){if(this.socket.readyState!==WebSocket.OPEN)return this.preListen[e]||(this.preListen[e]=[]),void this.preListen[e].push(t);this.listen(e,t)}}exports.SonicWSCore=h;
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.SonicWSCore = void 0;
19
+ const PacketHolder_1 = require("../../util/packets/PacketHolder");
20
+ const CompressionUtil_1 = require("../../util/packets/CompressionUtil");
21
+ const PacketUtils_1 = require("../../util/packets/PacketUtils");
22
+ const version_1 = require("../../../version");
23
+ const Packets_1 = require("../../packets/Packets");
24
+ const BatchHelper_1 = require("../../util/packets/BatchHelper");
25
+ const BufferUtil_1 = require("../../util/BufferUtil");
26
+ const Connection_1 = require("../../Connection");
27
+ const StringUtil_1 = require("../../util/StringUtil");
28
+ class SonicWSCore extends Connection_1.Connection {
29
+ preListen;
30
+ clientPackets = new PacketHolder_1.PacketHolder();
31
+ serverPackets = new PacketHolder_1.PacketHolder();
32
+ pastKeys = false;
33
+ readyListeners = [];
34
+ bufferHandler;
35
+ _timers = {};
36
+ asyncData = {};
37
+ asyncMap = {};
38
+ constructor(ws, bufferHandler, on, off) {
39
+ super(ws, -1, "LocalSocket", on, off);
40
+ this.socket = ws;
41
+ this.preListen = {};
42
+ this.invalidPacket = this.invalidPacket.bind(this);
43
+ this.serverKeyHandler = this.serverKeyHandler.bind(this);
44
+ this.messageHandler = this.messageHandler.bind(this);
45
+ this._on('message', this.serverKeyHandler);
46
+ this._on('close', () => {
47
+ this.callMiddleware('onStatusChange', WebSocket.CLOSED);
48
+ for (const [id, callback, shouldCall] of Object.values(this._timers)) {
49
+ this.clearTimeout(id);
50
+ if (shouldCall)
51
+ callback(true);
52
+ }
53
+ for (const packet of this.clientPackets.getPackets()) {
54
+ delete packet.lastSent[0];
55
+ }
56
+ for (const packet of this.serverPackets.getPackets()) {
57
+ delete packet.lastReceived[0];
58
+ }
59
+ });
60
+ this.bufferHandler = bufferHandler;
61
+ }
62
+ reading = false;
63
+ readQueue = [];
64
+ async serverKeyHandler(event) {
65
+ if (this.reading)
66
+ return this.readQueue.push(event);
67
+ this.reading = true;
68
+ const cdata = await this.bufferHandler(event);
69
+ if (cdata.length < 3 || (0, StringUtil_1.as8String)(cdata.slice(0, 3)) != version_1.SERVER_SUFFIX) {
70
+ this.close(1000);
71
+ throw new Error("The server requested is not a Sonic WS server.");
72
+ }
73
+ const version = cdata[3];
74
+ if (version != version_1.VERSION) {
75
+ this.close(1000);
76
+ throw new Error(`Version mismatch: ${version > version_1.VERSION ? "client" : "server"} is outdated (server: ${version}, client: ${version_1.VERSION})`);
77
+ }
78
+ const data = await (0, CompressionUtil_1.decompressGzip)(cdata.subarray(4, cdata.length));
79
+ const [ckOff, id] = (0, CompressionUtil_1.readVarInt)(data, 0);
80
+ this.id = id;
81
+ const [valuesOff, ckLength] = (0, CompressionUtil_1.readVarInt)(data, ckOff);
82
+ const ckData = data.subarray(valuesOff, valuesOff + ckLength);
83
+ this.clientPackets.holdPackets(Packets_1.Packet.deserializeAll(ckData, true));
84
+ const skData = data.subarray(valuesOff + ckLength, data.length);
85
+ this.serverPackets.holdPackets(Packets_1.Packet.deserializeAll(skData, true));
86
+ this.batcher.registerSendPackets(this.clientPackets, this);
87
+ for (const p of this.serverPackets.getPackets()) {
88
+ const key = this.serverPackets.getKey(p.tag);
89
+ this.asyncMap[key] = p.async;
90
+ if (p.async) {
91
+ this.asyncData[key] = [false, []];
92
+ }
93
+ }
94
+ Object.keys(this.preListen).forEach(tag => this.preListen[tag].forEach(listener => {
95
+ // print the error to console without halting execution
96
+ if (!this.serverPackets.hasTag(tag))
97
+ return console.error(new Error(`The server does not send the packet with tag "${tag}"!`));
98
+ this.listen(tag, listener);
99
+ }));
100
+ this.preListen = null; // clear
101
+ this.pastKeys = true;
102
+ this.readyListeners.forEach(l => l());
103
+ this.readyListeners = null; // clear
104
+ this._off('message', this.serverKeyHandler);
105
+ this._on('message', this.messageHandler);
106
+ this.readQueue.forEach(e => this.messageHandler(e));
107
+ this.readQueue = [];
108
+ }
109
+ invalidPacket(listened) {
110
+ console.error(listened);
111
+ throw new Error("An error occured with data from the server!! This is probably my fault.. make an issue at https://github.com/liwybloc/sonic-ws");
112
+ }
113
+ listenLock = false;
114
+ packetQueue = [];
115
+ async listenPacket(data, tag, packetQueue, isAsync, asyncData) {
116
+ const listeners = this.listeners[tag];
117
+ if (!listeners)
118
+ return console.warn("Warn: No listener for packet " + tag);
119
+ await this.enqueuePacket(data, listeners, packetQueue, isAsync, asyncData);
120
+ await this.callMiddleware('onReceive_post', tag, typeof data == 'string' ? [data] : data[0]);
121
+ }
122
+ isAsync(code) {
123
+ return this.asyncMap[code];
124
+ }
125
+ async enqueuePacket(data, listeners, packetQueue, isAsync, asyncData) {
126
+ await (0, PacketUtils_1.listenPacket)(data, listeners, this.invalidPacket);
127
+ await this.triggerNextPacket(packetQueue, isAsync, asyncData);
128
+ }
129
+ async triggerNextPacket(packetQueue, isAsync, asyncData) {
130
+ if (isAsync)
131
+ asyncData[0] = false;
132
+ else
133
+ this.listenLock = false;
134
+ if (packetQueue.length > 0) {
135
+ this.dataHandler(packetQueue.shift());
136
+ return;
137
+ }
138
+ }
139
+ async dataHandler(data) {
140
+ const key = data[0];
141
+ const value = data.slice(1);
142
+ const isAsync = this.isAsync(key);
143
+ let locked;
144
+ let packetQueue;
145
+ let asyncData;
146
+ if (isAsync) {
147
+ asyncData = this.asyncData[key];
148
+ locked = asyncData[0];
149
+ packetQueue = asyncData[1];
150
+ }
151
+ else {
152
+ locked = this.listenLock;
153
+ packetQueue = this.packetQueue;
154
+ }
155
+ if (locked) {
156
+ packetQueue.push(data);
157
+ return;
158
+ }
159
+ if (isAsync)
160
+ asyncData[0] = true;
161
+ else
162
+ this.listenLock = true;
163
+ const tag = this.serverPackets.getTag(key);
164
+ const packet = this.serverPackets.getPacket(tag);
165
+ if (await this.callMiddleware('onReceive_pre', packet.tag, data, data.length))
166
+ return;
167
+ if (packet.rereference && value.length == 0) {
168
+ if (packet.lastReceived[0] === undefined)
169
+ return this.invalidPacket("No previous value to rereference");
170
+ this.listenPacket(packet.lastReceived[0], tag, packetQueue, isAsync, asyncData);
171
+ return;
172
+ }
173
+ if (packet.dataBatching == 0) {
174
+ const res = packet.lastReceived[0] = await packet.listen(value, null);
175
+ this.listenPacket(res, tag, packetQueue, isAsync, asyncData);
176
+ return;
177
+ }
178
+ const batchData = await BatchHelper_1.BatchHelper.unravelBatch(packet, value, null);
179
+ if (typeof batchData == 'string')
180
+ return this.invalidPacket(batchData);
181
+ batchData.forEach(data => this.listenPacket(data, tag, packetQueue, isAsync, asyncData));
182
+ }
183
+ async messageHandler(event) {
184
+ const data = await this.bufferHandler(event);
185
+ if (data.length < 1)
186
+ return;
187
+ await this.dataHandler(data);
188
+ }
189
+ listen(tag, listener) {
190
+ if (!this.serverPackets.hasTag(tag)) {
191
+ console.log("Tag is not available on server: " + tag);
192
+ return;
193
+ }
194
+ (this.listeners[tag] ??= []).push(listener);
195
+ }
196
+ /**
197
+ * Listens for all sent messages rawly
198
+ * @param listener Callback for when data is received
199
+ */
200
+ raw_onsend(listener) {
201
+ this.listeners.send.push(listener);
202
+ }
203
+ sendQueue = [false, [], undefined];
204
+ /**
205
+ * Sends a packet to the server
206
+ * @param tag The tag of the packet
207
+ * @param values The values to send
208
+ */
209
+ async send(tag, ...values) {
210
+ if (await this.callMiddleware('onSend_pre', tag, values, Date.now(), performance.now()))
211
+ return;
212
+ const [code, data, packet] = await (0, PacketUtils_1.processPacket)(this.clientPackets, tag, values, this.sendQueue, 0);
213
+ if (packet.dataBatching == 0)
214
+ this.raw_send((0, BufferUtil_1.toPacketBuffer)(code, data));
215
+ else
216
+ this.batcher.batchPacket(code, data);
217
+ await this.callMiddleware('onSend_post', tag, data, data.length);
218
+ }
219
+ /**
220
+ * Listens for when the client connects
221
+ * @param listener Callback on connection
222
+ */
223
+ on_ready(listener) {
224
+ if (this.pastKeys)
225
+ listener();
226
+ else
227
+ this.readyListeners.push(listener);
228
+ }
229
+ /**
230
+ * Listens for when the client closes
231
+ * @param listener Callback on close with close event
232
+ */
233
+ on_close(listener) {
234
+ this._on("close", listener);
235
+ }
236
+ /**
237
+ * Listens to a packet from the server
238
+ * @param tag The tag to listen for
239
+ * @param listener The callback with the values
240
+ */
241
+ on(tag, listener) {
242
+ if (this.socket.readyState !== WebSocket.OPEN) {
243
+ if (!this.preListen[tag])
244
+ this.preListen[tag] = [];
245
+ this.preListen[tag].push(listener);
246
+ return;
247
+ }
248
+ this.listen(tag, listener);
249
+ }
250
+ }
251
+ exports.SonicWSCore = SonicWSCore;
@@ -1,7 +1,3 @@
1
- /**
2
- * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
4
- */
5
1
  import WS from 'ws';
6
2
  import { SonicWSCore } from "../core/ClientCore";
7
3
  /** Class to connect to a SonicWS server */
@@ -1,6 +1,36 @@
1
- /**
1
+ "use strict";
2
+ /*
2
3
  * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
4
16
  */
5
-
6
- var e=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.SonicWS=void 0;const r=e(require("ws")),o=require("../core/ClientCore");class t extends o.SonicWSCore{constructor(e,o){const t=new r.default.WebSocket(e,o);super(t,e=>Promise.resolve(new Uint8Array(e)),t.on.bind(t),t.removeEventListener.bind(t))}}exports.SonicWS=t;
17
+ var __importDefault = (this && this.__importDefault) || function (mod) {
18
+ return (mod && mod.__esModule) ? mod : { "default": mod };
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.SonicWS = void 0;
22
+ const ws_1 = __importDefault(require("ws"));
23
+ const ClientCore_1 = require("../core/ClientCore");
24
+ /** Class to connect to a SonicWS server */
25
+ class SonicWS extends ClientCore_1.SonicWSCore {
26
+ /**
27
+ * Creates a connection to the url
28
+ * @param url The url to connect to
29
+ * @param options The websocket options
30
+ */
31
+ constructor(url, options) {
32
+ const ws = new ws_1.default.WebSocket(url, options);
33
+ super(ws, (val) => Promise.resolve(new Uint8Array(val)), ws.addEventListener.bind(ws), ws.removeEventListener.bind(ws));
34
+ }
35
+ }
36
+ exports.SonicWS = SonicWS;
@@ -1,7 +1,3 @@
1
- /**
2
- * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
4
- */
5
1
  import { SonicWSServer } from "../server/SonicWSServer";
6
2
  export declare class DebugServer {
7
3
  constructor(host: SonicWSServer, data: {