sonic-ws 1.3.3 → 2.0.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.
Files changed (78) hide show
  1. package/LICENSE +56 -196
  2. package/README.md +88 -17
  3. package/dist/{index.d.ts → ts/index.d.ts} +6 -0
  4. package/dist/{index.js → ts/index.js} +10 -11
  5. package/dist/ts/native/wrapper.d.ts +59 -0
  6. package/dist/ts/native/wrapper.js +7 -0
  7. package/dist/{version.d.ts → ts/version.d.ts} +5 -0
  8. package/dist/ts/version.js +7 -0
  9. package/dist/{ws → ts/ws}/Connection.d.ts +5 -0
  10. package/dist/ts/ws/Connection.js +7 -0
  11. package/dist/{ws → ts/ws}/PacketProcessor.d.ts +5 -0
  12. package/dist/ts/ws/PacketProcessor.js +7 -0
  13. package/dist/{ws → ts/ws}/client/core/ClientCore.d.ts +5 -0
  14. package/dist/ts/ws/client/core/ClientCore.js +7 -0
  15. package/dist/{ws → ts/ws}/client/node/ClientNode.d.ts +5 -0
  16. package/dist/ts/ws/client/node/ClientNode.js +7 -0
  17. package/dist/{ws → ts/ws}/debug/DebugServer.d.ts +5 -0
  18. package/dist/ts/ws/debug/DebugServer.js +7 -0
  19. package/dist/{ws → ts/ws}/packets/PacketType.d.ts +6 -1
  20. package/dist/ts/ws/packets/PacketType.js +7 -0
  21. package/dist/{ws → ts/ws}/packets/Packets.d.ts +5 -3
  22. package/dist/ts/ws/packets/Packets.js +7 -0
  23. package/dist/{ws → ts/ws}/server/SonicWSConnection.d.ts +5 -0
  24. package/dist/ts/ws/server/SonicWSConnection.js +7 -0
  25. package/dist/{ws → ts/ws}/server/SonicWSServer.d.ts +8 -0
  26. package/dist/ts/ws/server/SonicWSServer.js +7 -0
  27. package/dist/{ws → ts/ws}/util/BufferUtil.d.ts +5 -0
  28. package/dist/ts/ws/util/BufferUtil.js +7 -0
  29. package/dist/{ws → ts/ws}/util/StringUtil.d.ts +5 -2
  30. package/dist/ts/ws/util/StringUtil.js +7 -0
  31. package/dist/{ws → ts/ws}/util/enums/EnumHandler.d.ts +5 -0
  32. package/dist/ts/ws/util/enums/EnumHandler.js +7 -0
  33. package/dist/{ws → ts/ws}/util/enums/EnumType.d.ts +5 -0
  34. package/dist/ts/ws/util/enums/EnumType.js +7 -0
  35. package/dist/ts/ws/util/packets/BatchHelper.d.ts +6 -0
  36. package/dist/ts/ws/util/packets/BatchHelper.js +7 -0
  37. package/dist/ts/ws/util/packets/CompressionUtil.d.ts +13 -0
  38. package/dist/ts/ws/util/packets/CompressionUtil.js +7 -0
  39. package/dist/ts/ws/util/packets/HashUtil.d.ts +7 -0
  40. package/dist/ts/ws/util/packets/HashUtil.js +7 -0
  41. package/dist/ts/ws/util/packets/JSONUtil.d.ts +7 -0
  42. package/dist/ts/ws/util/packets/JSONUtil.js +7 -0
  43. package/dist/ts/ws/util/packets/PacketHolder.d.ts +6 -0
  44. package/dist/ts/ws/util/packets/PacketHolder.js +7 -0
  45. package/dist/{ws → ts/ws}/util/packets/PacketUtils.d.ts +5 -0
  46. package/dist/ts/ws/util/packets/PacketUtils.js +7 -0
  47. package/dist/ts/ws/util/packets/RateHandler.d.ts +6 -0
  48. package/dist/ts/ws/util/packets/RateHandler.js +7 -0
  49. package/package.json +14 -10
  50. package/dist/version.js +0 -25
  51. package/dist/ws/Connection.js +0 -126
  52. package/dist/ws/PacketProcessor.js +0 -52
  53. package/dist/ws/client/core/ClientCore.js +0 -251
  54. package/dist/ws/client/node/ClientNode.js +0 -36
  55. package/dist/ws/debug/DebugServer.js +0 -607
  56. package/dist/ws/packets/PacketProcessors.d.ts +0 -13
  57. package/dist/ws/packets/PacketProcessors.js +0 -317
  58. package/dist/ws/packets/PacketType.js +0 -61
  59. package/dist/ws/packets/Packets.js +0 -277
  60. package/dist/ws/server/SonicWSConnection.js +0 -298
  61. package/dist/ws/server/SonicWSServer.js +0 -307
  62. package/dist/ws/util/BufferUtil.js +0 -42
  63. package/dist/ws/util/StringUtil.js +0 -51
  64. package/dist/ws/util/enums/EnumHandler.js +0 -60
  65. package/dist/ws/util/enums/EnumType.js +0 -72
  66. package/dist/ws/util/packets/BatchHelper.d.ts +0 -1
  67. package/dist/ws/util/packets/BatchHelper.js +0 -85
  68. package/dist/ws/util/packets/CompressionUtil.d.ts +0 -35
  69. package/dist/ws/util/packets/CompressionUtil.js +0 -277
  70. package/dist/ws/util/packets/HashUtil.d.ts +0 -2
  71. package/dist/ws/util/packets/HashUtil.js +0 -122
  72. package/dist/ws/util/packets/JSONUtil.d.ts +0 -2
  73. package/dist/ws/util/packets/JSONUtil.js +0 -179
  74. package/dist/ws/util/packets/PacketHolder.d.ts +0 -1
  75. package/dist/ws/util/packets/PacketHolder.js +0 -126
  76. package/dist/ws/util/packets/PacketUtils.js +0 -283
  77. package/dist/ws/util/packets/RateHandler.d.ts +0 -1
  78. package/dist/ws/util/packets/RateHandler.js +0 -66
@@ -1,283 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright 2026 Lily (liwybloc)
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.
16
- */
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.processPacket = processPacket;
19
- exports.listenPacket = listenPacket;
20
- exports.CreatePacket = CreatePacket;
21
- exports.CreateObjPacket = CreateObjPacket;
22
- exports.CreateEnumPacket = CreateEnumPacket;
23
- exports.CreateKeyEffective = CreateKeyEffective;
24
- exports.FlattenData = FlattenData;
25
- exports.UnFlattenData = UnFlattenData;
26
- const Packets_1 = require("../../packets/Packets");
27
- const PacketType_1 = require("../../packets/PacketType");
28
- const EnumType_1 = require("../enums/EnumType");
29
- const CompressionUtil_1 = require("./CompressionUtil");
30
- const HashUtil_1 = require("./HashUtil");
31
- /**
32
- * Processes and verifies values into a sendable format
33
- * @param packets Packet holder
34
- * @param tag The tag of the packet
35
- * @param values The values
36
- * @returns The indexed code, the data, and the packet schema
37
- * @internal
38
- */
39
- async function processPacket(packets, tag, values, sendQueue, id, force = false) {
40
- const code = packets.getKey(tag);
41
- const packet = packets.getPacket(tag);
42
- return handleQueue(sendQueue, packets, id, tag, values, force, async () => {
43
- if (packet.rereference) {
44
- if (id === -1)
45
- throw new Error("Cannot send a re-referenced packet from the server-wide sender!");
46
- const serialized = (0, HashUtil_1.hashValue)(values);
47
- if (packet.lastSent[id] === serialized) {
48
- return [code, CompressionUtil_1.EMPTY_UINT8, packet];
49
- }
50
- packet.lastSent[id] = serialized;
51
- }
52
- if (packet.autoFlatten) {
53
- values = FlattenData(values[0]);
54
- }
55
- else {
56
- if (values.length > packet.maxSize)
57
- throw new Error(`Packet "${tag}" only allows ${packet.maxSize} values!`);
58
- if (values.length < packet.minSize)
59
- throw new Error(`Packet "${tag}" requires at least ${packet.minSize} values!`);
60
- }
61
- if (!packet.object) {
62
- if (packet.type !== PacketType_1.PacketType.JSON) {
63
- const found = values.find(v => typeof v === 'object' && v != null);
64
- if (found)
65
- console.warn(`Passing an array will result in undefined behavior (${JSON.stringify(found)}). Spread the array with ...arr`);
66
- }
67
- }
68
- else {
69
- values = values.map(x => !Array.isArray(x) ? [x] : x);
70
- if (!packet.autoFlatten) {
71
- const dataMins = packet.dataMin;
72
- const dataMaxes = packet.dataMax;
73
- for (let i = 0; i < dataMins.length; i++) {
74
- if (values[i].length < dataMins[i])
75
- throw new Error(`Section ${i + 1} of packet "${tag}" requires at least ${dataMins[i]} values!`);
76
- if (values[i].length > dataMaxes[i])
77
- throw new Error(`Section ${i + 1} of packet "${tag}" only allows ${dataMaxes[i]} values!`);
78
- }
79
- }
80
- }
81
- const sendData = values.length > 0 ? await packet.processSend(values) : CompressionUtil_1.EMPTY_UINT8;
82
- return [code, sendData, packet];
83
- });
84
- }
85
- /**
86
- * @internal
87
- */
88
- async function handleQueue(sendQueue, packets, id, tag, values, force, fn) {
89
- if (sendQueue[0] && !force) {
90
- return new Promise((resolve) => sendQueue[1].push([resolve, tag, values]));
91
- }
92
- sendQueue[0] = true;
93
- const result = await fn();
94
- if (sendQueue[1].length > 0) {
95
- const [resolve, nextTag, nextValues] = sendQueue[1].shift();
96
- queueMicrotask(async () => {
97
- resolve(await processPacket(packets, nextTag, nextValues, sendQueue, id, true));
98
- });
99
- }
100
- else {
101
- sendQueue[0] = false;
102
- }
103
- return result;
104
- }
105
- /**
106
- * Calls the listener for a packet with error callback
107
- * @param listened The listened data
108
- * @param listeners The listeners to run
109
- * @param errorCB The callback if something goes wrong
110
- * @internal
111
- */
112
- async function listenPacket(listened, listeners, errorCB) {
113
- if (typeof listened === 'string')
114
- return errorCB(listened);
115
- const [processed, flatten] = listened;
116
- try {
117
- if (flatten && Array.isArray(processed)) {
118
- for (const l of listeners) {
119
- await l(...processed);
120
- }
121
- }
122
- else {
123
- for (const l of listeners) {
124
- await l(processed);
125
- }
126
- }
127
- }
128
- catch (err) {
129
- console.error(err);
130
- errorCB(err);
131
- }
132
- }
133
- /**
134
- * Determines if a type is a invalid packet type
135
- * @param type A possible type
136
- * @internal
137
- */
138
- function isInvalidType(type) {
139
- return (!(typeof type == 'number' && type in PacketType_1.PacketType) && !(type instanceof EnumType_1.EnumPackage)) || type == PacketType_1.PacketType.KEY_EFFECTIVE;
140
- }
141
- const MAX_DATA_MAX = 2048383;
142
- /** Clamps data max between 0 and MAX_DATA_MAX @internal */
143
- function clampDataMax(dataMax) {
144
- if (dataMax < 0) {
145
- console.warn(`Having a data maximum below 0 does not do anything!`);
146
- return 0;
147
- }
148
- // dfkjgsdkfgjk
149
- if (dataMax > MAX_DATA_MAX) {
150
- console.warn(`Only ${MAX_DATA_MAX} values can be sent on a type! Uhh make an issue if you want to send more.`);
151
- return MAX_DATA_MAX;
152
- }
153
- return dataMax;
154
- }
155
- /** Clamps data min between 0 and datamax @internal */
156
- function clampDataMin(dataMin, dataMax) {
157
- if (dataMin < 0) {
158
- console.warn(`Having a data minimum below 0 does not do anything!`);
159
- return 0;
160
- }
161
- // also catches >MAX_DATA_MAX
162
- if (dataMin > dataMax) {
163
- console.warn(`Data minimum can not be higher than the data maximum!`);
164
- return dataMax;
165
- }
166
- return dataMin;
167
- }
168
- /**
169
- * Creates a structure for a simple single-typed packet.
170
- * This packet can be sent and received with the specified tag, type, and data cap.
171
- * @param settings The settings object containing `tag`, `type`, `dataMax`, `dataMin`, `noDataRange`, `dontSpread`, `validator`, `dataBatching`, and/or `maxBatchSize`.
172
- * @returns The constructed packet structure data.
173
- * @throws {Error} If the `type` is invalid.
174
- */
175
- function CreatePacket(settings) {
176
- let { tag, type = PacketType_1.PacketType.NONE, dataMax = 1, dataMin = 1, noDataRange = false, dontSpread = false, validator = null, dataBatching = 0, maxBatchSize = 10, rateLimit = 0, enabled = true, async = false, gzipCompression = type == PacketType_1.PacketType.JSON, rereference = false } = settings;
177
- if (!tag)
178
- throw new Error("Tag not selected!");
179
- if (noDataRange) {
180
- dataMin = rereference ? 1 : 0;
181
- dataMax = MAX_DATA_MAX;
182
- }
183
- else if (dataMin == undefined)
184
- dataMin = type == PacketType_1.PacketType.NONE ? 0 : dataMax;
185
- if (rereference && dataMin == 0)
186
- throw new Error("Rereference cannot be true if the dataMin is 0");
187
- if (isInvalidType(type)) {
188
- throw new Error(`Invalid packet type: ${type}`);
189
- }
190
- const schema = new Packets_1.PacketSchema(false, type, async, clampDataMin(dataMin, dataMax), clampDataMax(dataMax), rateLimit, dontSpread, false, rereference, dataBatching, maxBatchSize, gzipCompression);
191
- return new Packets_1.Packet(tag, schema, validator, enabled, false);
192
- }
193
- /**
194
- * Creates a structure for an object (multi-typed) packet.
195
- * This packet allows multiple types and their associated data caps.
196
- * @param settings The settings object containing `tag`, `types`, `dataMaxes`, `dataMins`, `noDataRange`, `dontSpread`, `autoFlatten`, `largePacket`, `validator`, `dataBatching`, and/or `maxBatchSize`.
197
- * @returns The constructed packet structure data.
198
- * @throws {Error} If any type in `types` is invalid.
199
- */
200
- function CreateObjPacket(settings) {
201
- let { tag, types = [], dataMaxes, dataMins, noDataRange = false, dontSpread = false, autoFlatten = false, validator = null, dataBatching = 0, maxBatchSize = 10, rateLimit = 0, enabled = true, async = false, gzipCompression = types && types.includes(PacketType_1.PacketType.JSON) } = settings;
202
- if (!tag)
203
- throw new Error("Tag not selected!");
204
- if (!types || types.length == 0)
205
- throw new Error("Types is set to 0 length");
206
- for (const type of types) {
207
- if (!isInvalidType(type))
208
- continue;
209
- throw new Error(`Invalid packet type in "${tag}" packet: ${type}`);
210
- }
211
- if (noDataRange) {
212
- dataMaxes = Array.from({ length: types.length }).map(() => MAX_DATA_MAX);
213
- dataMins = Array.from({ length: types.length }).map(() => 0);
214
- }
215
- else {
216
- if (dataMaxes == undefined)
217
- dataMaxes = Array.from({ length: types.length }).map(() => 1);
218
- else if (!Array.isArray(dataMaxes))
219
- dataMaxes = Array.from({ length: types.length }).map(() => dataMaxes);
220
- if (dataMins == undefined)
221
- dataMins = Array.from({ length: types.length }).map((_, i) => dataMaxes[i]);
222
- else if (!Array.isArray(dataMins))
223
- dataMins = Array.from({ length: types.length }).map(() => dataMins);
224
- }
225
- const clampedDataMaxes = dataMaxes.map(clampDataMax);
226
- const clampedDataMins = dataMins.map((m, i) => types[i] == PacketType_1.PacketType.NONE ? 0 : clampDataMin(m, clampedDataMaxes[i]));
227
- const schema = new Packets_1.PacketSchema(true, types, async, clampedDataMins, clampedDataMaxes, rateLimit, dontSpread, autoFlatten, false, dataBatching, maxBatchSize, gzipCompression);
228
- return new Packets_1.Packet(tag, schema, validator, enabled, false);
229
- }
230
- /**
231
- * Creates and defines an enum packet. This can be used to create an enum-based packet
232
- * with a specific tag and possible values.
233
- * @param settings The settings object containing `tag`, `enumTag`, `values`, `dataMax`, `dataMin`, `noDataRange`, `dontSpread`, `validator`, `dataBatching`, and/or `maxBatchSize`.
234
- * @returns The constructed packet structure data.
235
- */
236
- function CreateEnumPacket(settings) {
237
- const { tag, enumData, dataMax = 1, dataMin = 0, noDataRange = false, dontSpread = false, validator = null, dataBatching = 0, maxBatchSize = 10, rateLimit = 0, enabled = true, async = false } = settings;
238
- return CreatePacket({
239
- tag: tag,
240
- type: enumData,
241
- dataMax,
242
- dataMin,
243
- noDataRange,
244
- dontSpread,
245
- validator,
246
- dataBatching,
247
- maxBatchSize,
248
- rateLimit,
249
- enabled,
250
- async,
251
- });
252
- }
253
- function CreateKeyEffective(settings) {
254
- const { tag, count = 2, validator = null, async = false } = settings;
255
- if (!tag)
256
- throw new Error("Tag not selected!");
257
- if (count < 2)
258
- throw new Error("Must have at least 2 key consumptions on key effective packet!");
259
- throw new Error("Currently W.I.P.");
260
- }
261
- /**
262
- * Flattens a 2-depth array for efficient wire transfer
263
- * Turns [[x,y,z],[x,y,z]...] to [[x,x...],[y,y...],[z,z...]]
264
- * @param array A 2-depth array of multi-valued
265
- */
266
- function FlattenData(arr) {
267
- if (arr == null)
268
- return [];
269
- const setup = arr[0];
270
- if (setup == null)
271
- return [];
272
- if (!Array.isArray(setup))
273
- throw new Error(`Cannot flatten array: ${arr}`);
274
- return setup.map((_, i) => arr.map(row => row[i])) ?? [];
275
- }
276
- /**
277
- * Unflattens an array into 2-depth; reverse of FlattenData()
278
- * turns [[x,x...],[y,y...],[z,z...]] to [[x,y,z],[x,y,z]...]
279
- * @param array A flattened array
280
- */
281
- function UnFlattenData(arr) {
282
- return arr[0]?.map((_, i) => arr.map(col => col[i])) ?? [];
283
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,66 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright 2026 Lily (liwybloc)
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.
16
- */
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.RateHandler = void 0;
19
- const Connection_1 = require("../../Connection");
20
- /** @internal */
21
- class RateHandler {
22
- rates = {};
23
- limits = {};
24
- setInterval;
25
- socket;
26
- constructor(host) {
27
- // shared values
28
- this.setInterval = host.setInterval;
29
- this.socket = host.socket;
30
- }
31
- start() {
32
- // no rates? don't start an interval
33
- if (Object.keys(this.rates).length == 0)
34
- return;
35
- this.setInterval(() => {
36
- for (const tag in this.rates) {
37
- this.rates[tag] = 0;
38
- }
39
- }, 1000);
40
- }
41
- registerRate(tag, limit) {
42
- // ignore no limits
43
- if (limit == 0)
44
- return;
45
- this.rates[tag] = 0;
46
- this.limits[tag] = limit;
47
- }
48
- registerAll(packetHolder, prefix) {
49
- const packets = packetHolder.getPackets();
50
- for (const packet of packets)
51
- this.registerRate(prefix + packetHolder.getKey(packet.tag), packet.rateLimit);
52
- }
53
- trigger(tag) {
54
- if (tag in this.rates && ++this.rates[tag] > this.limits[tag]) {
55
- this.socket.close(Connection_1.CloseCodes.RATELIMIT);
56
- return true;
57
- }
58
- return false;
59
- }
60
- subtract(tag) {
61
- if (!(tag in this.rates))
62
- return;
63
- this.rates[tag]--;
64
- }
65
- }
66
- exports.RateHandler = RateHandler;