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,317 +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.createValidator = createValidator;
19
- exports.createReceiveProcessor = createReceiveProcessor;
20
- exports.createSendProcessor = createSendProcessor;
21
- exports.createObjSendProcessor = createObjSendProcessor;
22
- exports.createObjReceiveProcessor = createObjReceiveProcessor;
23
- exports.createObjValidator = createObjValidator;
24
- const BufferUtil_1 = require("../util/BufferUtil");
25
- const CompressionUtil_1 = require("../util/packets/CompressionUtil");
26
- const PacketType_1 = require("./PacketType");
27
- const BufferUtil_2 = require("../util/BufferUtil");
28
- const StringUtil_1 = require("../util/StringUtil");
29
- const JSONUtil_1 = require("../util/packets/JSONUtil");
30
- function BYTE_LEN(cap, min) {
31
- return (data) => data.length >= min && data.length <= cap;
32
- }
33
- function SHORT_LEN(cap, min) {
34
- min *= 2;
35
- cap *= 2;
36
- return (data) => data.length >= min && data.length <= cap && data.length % 2 == 0;
37
- }
38
- function VARINT_VERIF(cap, min) {
39
- return (data) => {
40
- if (data.length == 0)
41
- return min <= 0 ? [] : false;
42
- let sectors = 0, i = 0, computed = [];
43
- while (i < data.length) {
44
- const [off, varint] = (0, CompressionUtil_1.readVarInt)(data, i);
45
- i = off;
46
- computed.push(varint);
47
- if (++sectors > cap)
48
- return false;
49
- }
50
- if (sectors < min)
51
- return false;
52
- return computed;
53
- };
54
- }
55
- ;
56
- function createValidator(type, dataCap, dataMin, packet, gzipCompression) {
57
- function genFunc() {
58
- switch (type) {
59
- case PacketType_1.PacketType.NONE: return (data) => data.length == 0;
60
- case PacketType_1.PacketType.RAW: return () => undefined;
61
- case PacketType_1.PacketType.ENUMS: return (data, index) => {
62
- if (data.length < dataMin || data.length > dataCap || index >= packet.enumData.length)
63
- return false;
64
- const pkg = packet.enumData[index];
65
- for (let i = 0; i < data.length; i++) {
66
- if (pkg.values.length <= data[i])
67
- return false;
68
- }
69
- };
70
- case PacketType_1.PacketType.BYTES: return BYTE_LEN(dataCap, dataMin);
71
- case PacketType_1.PacketType.UBYTES: return BYTE_LEN(dataCap, dataMin);
72
- case PacketType_1.PacketType.HEX: return BYTE_LEN(dataCap, dataMin);
73
- case PacketType_1.PacketType.SHORTS: return SHORT_LEN(dataCap, dataMin);
74
- case PacketType_1.PacketType.USHORTS: return SHORT_LEN(dataCap, dataMin);
75
- case PacketType_1.PacketType.VARINT: return VARINT_VERIF(dataCap, dataMin);
76
- case PacketType_1.PacketType.UVARINT: return VARINT_VERIF(dataCap, dataMin);
77
- case PacketType_1.PacketType.DELTAS: return VARINT_VERIF(dataCap, dataMin);
78
- case PacketType_1.PacketType.FLOATS: return (data) => {
79
- if (data.length % 4 !== 0)
80
- return false;
81
- const sectors = data.length * CompressionUtil_1.ONE_FOURTH;
82
- if (sectors > dataCap || sectors < dataMin)
83
- return false;
84
- return undefined;
85
- };
86
- case PacketType_1.PacketType.DOUBLES: return (data) => {
87
- if (data.length % 8 !== 0)
88
- return false;
89
- const sectors = data.length * CompressionUtil_1.ONE_EIGHT;
90
- if (sectors > dataCap || sectors < dataMin)
91
- return false;
92
- return undefined;
93
- };
94
- case PacketType_1.PacketType.BOOLEANS:
95
- {
96
- const min = Math.ceil(dataMin * CompressionUtil_1.ONE_EIGHT);
97
- const cap = Math.ceil(dataCap * CompressionUtil_1.ONE_EIGHT);
98
- return (data) => data.length >= min && data.length <= cap;
99
- }
100
- ;
101
- case PacketType_1.PacketType.STRINGS_ASCII: return (data) => {
102
- let index = 0;
103
- const [offCount, stringCount] = (0, CompressionUtil_1.readVarInt)(data, index);
104
- index = offCount;
105
- if (stringCount < dataMin || stringCount > dataCap)
106
- return false;
107
- const lengths = [];
108
- let totalLength = 0;
109
- for (let i = 0; i < stringCount; i++) {
110
- const [offLen, strLen] = (0, CompressionUtil_1.readVarInt)(data, index);
111
- index = offLen;
112
- lengths.push(strLen);
113
- totalLength += strLen;
114
- }
115
- if (index + Math.ceil(totalLength / 8) > data.length)
116
- return false;
117
- return [stringCount, lengths, index];
118
- };
119
- case PacketType_1.PacketType.STRINGS_UTF16: return (data) => {
120
- let sectors = 0, index = 0, computed = [];
121
- while (index < data.length) {
122
- sectors++;
123
- if (sectors > dataCap)
124
- return false;
125
- const [off, strLength] = (0, CompressionUtil_1.readVarInt)(data, index);
126
- index = off;
127
- let string = [];
128
- for (let i = 0; i < strLength; i++) {
129
- const [newOff, char] = (0, CompressionUtil_1.readVarInt)(data, index);
130
- index = newOff;
131
- if (index > data.length)
132
- return false;
133
- string.push(char);
134
- }
135
- computed.push(string);
136
- }
137
- if (sectors < dataMin)
138
- return false;
139
- return computed;
140
- };
141
- case PacketType_1.PacketType.JSON: return (data) => {
142
- try {
143
- return (0, JSONUtil_1.decompressJSON)(data);
144
- }
145
- catch {
146
- return false;
147
- }
148
- };
149
- default: throw new Error("Unknown type: " + type);
150
- }
151
- }
152
- const fn = genFunc();
153
- return gzipCompression && packet.dataBatching == 0
154
- ? async (data, index) => {
155
- try {
156
- const dec = await (0, CompressionUtil_1.decompressGzip)(data);
157
- return [dec, fn(dec, index)];
158
- }
159
- catch {
160
- return [data, false];
161
- }
162
- }
163
- : async (data, index) => {
164
- return [data, fn(data, index)];
165
- };
166
- }
167
- function createReceiveProcessor(type, enumData, cap) {
168
- switch (type) {
169
- case PacketType_1.PacketType.NONE: return () => undefined;
170
- case PacketType_1.PacketType.RAW: return (data) => data;
171
- case PacketType_1.PacketType.BYTES: return (data) => Array.from(data).map(CompressionUtil_1.demapZigZag);
172
- case PacketType_1.PacketType.UBYTES: return (data) => Array.from(data);
173
- case PacketType_1.PacketType.HEX: return (data) => (0, CompressionUtil_1.bytesToHex)(data);
174
- case PacketType_1.PacketType.SHORTS: return (data) => (0, BufferUtil_2.splitBuffer)(data, 2).map(v => (0, CompressionUtil_1.demapShort_ZZ)(v));
175
- case PacketType_1.PacketType.USHORTS: return (data) => (0, BufferUtil_2.splitBuffer)(data, 2).map(v => (0, CompressionUtil_1.fromShort)(v));
176
- case PacketType_1.PacketType.VARINT: return (_, computed) => computed.map(CompressionUtil_1.demapZigZag);
177
- case PacketType_1.PacketType.UVARINT: return (_, computed) => computed;
178
- case PacketType_1.PacketType.DELTAS: return (_, computed) => computed.map((x, i) => computed[i] = (computed[i - 1] || 0) + (0, CompressionUtil_1.demapZigZag)(x));
179
- case PacketType_1.PacketType.FLOATS: return (data) => (0, BufferUtil_2.splitBuffer)(data, 4).map(CompressionUtil_1.deconvertFloat);
180
- case PacketType_1.PacketType.DOUBLES: return (data) => (0, BufferUtil_2.splitBuffer)(data, 8).map(CompressionUtil_1.deconvertDouble);
181
- case PacketType_1.PacketType.BOOLEANS: return (data) => Array.from(data).map(d => (0, CompressionUtil_1.decompressBools)(d)).flat().splice(0, cap);
182
- case PacketType_1.PacketType.ENUMS: return (data, _, index) => {
183
- const pkg = enumData[index];
184
- return Array.from(data).map(code => pkg.values[code]);
185
- };
186
- case PacketType_1.PacketType.STRINGS_ASCII: return (data, validationResult) => {
187
- const [stringCount, lengths, dataStart] = validationResult;
188
- const bitString = (0, CompressionUtil_1.bytesToBits)(data.subarray(dataStart));
189
- const decoded = (0, StringUtil_1.decodeHuffman)(bitString);
190
- if (!decoded)
191
- return [];
192
- const strings = [];
193
- let offset = 0;
194
- for (let i = 0; i < stringCount; i++) {
195
- strings.push(decoded.slice(offset, offset + lengths[i]));
196
- offset += lengths[i];
197
- }
198
- return strings;
199
- };
200
- case PacketType_1.PacketType.STRINGS_UTF16: return (_, computed) => {
201
- return computed.map(codes => String.fromCodePoint(...codes));
202
- };
203
- case PacketType_1.PacketType.JSON: return (_, computed) => computed;
204
- default: throw new Error("Unknown type: " + type);
205
- }
206
- }
207
- /** Creates a function that processes a packet type */
208
- function createSendProcessor(type, gzipCompression, batchedData) {
209
- function genFunc() {
210
- switch (type) {
211
- case PacketType_1.PacketType.NONE: return () => [];
212
- case PacketType_1.PacketType.RAW: return (data) => Array.from(data);
213
- case PacketType_1.PacketType.ENUMS: return (enums) => enums;
214
- case PacketType_1.PacketType.BYTES: return (numbers) => numbers.map(CompressionUtil_1.mapZigZag);
215
- case PacketType_1.PacketType.UBYTES: return (numbers) => numbers.map(CompressionUtil_1.toByte);
216
- case PacketType_1.PacketType.HEX: return (hex) => {
217
- if (typeof hex != "string") {
218
- if (hex instanceof Array && hex.length == 1)
219
- return (0, CompressionUtil_1.hexToBytes)(hex[0]);
220
- throw new Error("Cannot send more than 1 hex string; this packet is equivalent to UBYTES: " + JSON.stringify(hex));
221
- }
222
- return (0, CompressionUtil_1.hexToBytes)(hex);
223
- };
224
- case PacketType_1.PacketType.SHORTS: return (numbers) => numbers.map(CompressionUtil_1.mapShort_ZZ).flat();
225
- case PacketType_1.PacketType.USHORTS: return (numbers) => numbers.map(CompressionUtil_1.toShort).flat();
226
- case PacketType_1.PacketType.VARINT: return (numbers) => numbers.map(n => (0, CompressionUtil_1.convertVarInt)((0, CompressionUtil_1.mapZigZag)(n))).flat();
227
- case PacketType_1.PacketType.UVARINT: return (numbers) => numbers.map(CompressionUtil_1.convertVarInt).flat();
228
- case PacketType_1.PacketType.DELTAS: return (numbers) => numbers.map((n, i) => (0, CompressionUtil_1.convertVarInt)((0, CompressionUtil_1.mapZigZag)(n - (numbers[i - 1] || 0)))).flat();
229
- case PacketType_1.PacketType.FLOATS: return (singles) => singles.map(CompressionUtil_1.convertFloat).flat();
230
- case PacketType_1.PacketType.DOUBLES: return (doubles) => doubles.map(CompressionUtil_1.convertDouble).flat();
231
- case PacketType_1.PacketType.BOOLEANS: return (bools) => (0, BufferUtil_1.splitArray)(bools, 8).map((bools) => (0, CompressionUtil_1.compressBools)(bools)).flat();
232
- case PacketType_1.PacketType.STRINGS_ASCII: return (strings) => {
233
- return [
234
- ...(0, CompressionUtil_1.convertVarInt)(strings.length),
235
- ...strings.map(str => (0, CompressionUtil_1.convertVarInt)(str.length)).flat(),
236
- ...(0, StringUtil_1.encodeHuffman)(strings.reduce((a, b) => a + String(b), "")),
237
- ];
238
- };
239
- case PacketType_1.PacketType.STRINGS_UTF16: return (strings) => {
240
- const res = [];
241
- for (const v of strings) {
242
- const string = String(v);
243
- const charCodes = (0, StringUtil_1.processCharCodes)(string);
244
- // hate js man
245
- const length = charCodes.length;
246
- res.push(...(0, CompressionUtil_1.convertVarInt)(length));
247
- res.push(...charCodes.map(CompressionUtil_1.convertVarInt).flat());
248
- }
249
- return res;
250
- };
251
- case PacketType_1.PacketType.JSON: return (value) => Array.from((0, JSONUtil_1.compressJSON)(value));
252
- default: throw new Error("Unknown type: " + type);
253
- }
254
- }
255
- const fn = genFunc();
256
- if (!gzipCompression || batchedData) {
257
- return async (_, data) => {
258
- return new Uint8Array(fn(data));
259
- };
260
- }
261
- return async (ident, data) => {
262
- return (0, CompressionUtil_1.compressGzip)(new Uint8Array(fn(data)), ident);
263
- };
264
- }
265
- function createObjSendProcessor(packet) {
266
- const size = packet.type.length;
267
- // TODO: Add compression and add rereferences[]
268
- const processors = packet.type.map(t => createSendProcessor(t, false, false));
269
- return async (ident, data) => {
270
- let result = [];
271
- for (let i = 0; i < size; i++) {
272
- const sectorData = data[i];
273
- const d = await processors[i](ident, Array.isArray(sectorData) ? sectorData : [sectorData]);
274
- if (d.length > CompressionUtil_1.MAX_UVARINT)
275
- throw new Error(`Cannot send ${d.length}/${CompressionUtil_1.MAX_UVARINT} bytes of data!`);
276
- result.push(...(0, CompressionUtil_1.convertVarInt)(d.length));
277
- d.forEach(val => result.push(val));
278
- }
279
- return new Uint8Array(result);
280
- };
281
- }
282
- function createObjReceiveProcessor(packet) {
283
- const processors = packet.type.map((t, i) => createReceiveProcessor(t, packet.enumData, packet.dataMax[i]));
284
- return (data, validationResult) => {
285
- let index = 0, enums = 0, result = [];
286
- while (index < data.length) {
287
- // TODO: this does not need sector length because objects are actually deterministically sized in each one!!
288
- const [off, sectorLength] = (0, CompressionUtil_1.readVarInt)(data, index);
289
- index = off;
290
- const sector = data.subarray(index, index += sectorLength);
291
- // basically make this return the ending index
292
- // *only works if dataMax=dataMin
293
- result.push(processors[result.length](sector, validationResult[result.length], packet.type[result.length] == PacketType_1.PacketType.ENUMS ? enums++ : 0));
294
- }
295
- return result;
296
- };
297
- }
298
- function createObjValidator(packet) {
299
- const validators = packet.type.map((t, i) => createValidator(t, packet.dataMax[i], packet.dataMin[i], packet, false));
300
- return async (data) => {
301
- let index = 0, enums = 0, computedData = [];
302
- while (index < data.length) {
303
- if (computedData.length > packet.type.length)
304
- return [data, false]; // only types amount of values
305
- const [off, sectorLength] = (0, CompressionUtil_1.readVarInt)(data, index);
306
- index = off;
307
- if (sectorLength + index > data.length)
308
- return [data, false];
309
- const sector = data.subarray(index, index += sectorLength);
310
- const [, result] = await validators[computedData.length](sector, packet.type[computedData.length] == PacketType_1.PacketType.ENUMS ? enums++ : 0);
311
- if (result === false)
312
- return [data, false]; // chat i used === to fix a bug !!!!
313
- computedData.push(result);
314
- }
315
- return [data, computedData];
316
- };
317
- }
@@ -1,61 +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.PacketType = void 0;
19
- // separated file to allow imports
20
- /** All different packet types. Use ENUMS for any constant primitive data */
21
- var PacketType;
22
- (function (PacketType) {
23
- /** No data */
24
- PacketType[PacketType["NONE"] = 0] = "NONE";
25
- /** Raw data */
26
- PacketType[PacketType["RAW"] = 1] = "RAW";
27
- /** 8 byte string data (0-255 codes) */
28
- PacketType[PacketType["STRINGS_ASCII"] = 2] = "STRINGS_ASCII";
29
- /** Code point UTF16 data; up to 0x10FFFF */
30
- PacketType[PacketType["STRINGS_UTF16"] = 3] = "STRINGS_UTF16";
31
- /** Strings; defaults to ASCII (0-255 codes). Use STRINGS_UTF16 for more codes. */
32
- PacketType[PacketType["STRINGS"] = 2] = "STRINGS";
33
- /** Constant primitive data; strings, numbers, booleans, null, undefined */
34
- PacketType[PacketType["ENUMS"] = 4] = "ENUMS";
35
- /** One or more bytes; -128 to 127 | zig-zag encoded */
36
- PacketType[PacketType["BYTES"] = 5] = "BYTES";
37
- /** One or more bytes; 0 to 255 */
38
- PacketType[PacketType["UBYTES"] = 6] = "UBYTES";
39
- /** One or more shorts; -32,768 to 32,767 | zig-zag encoded */
40
- PacketType[PacketType["SHORTS"] = 7] = "SHORTS";
41
- /** One or more shorts; 0 to 65,535 */
42
- PacketType[PacketType["USHORTS"] = 8] = "USHORTS";
43
- /** One or more integers between -281,474,976,710,656 and 281,474,976,710,655 | zig-zag encoded */
44
- PacketType[PacketType["VARINT"] = 9] = "VARINT";
45
- /** One or more integers up to 562,949,953,421,311. */
46
- PacketType[PacketType["UVARINT"] = 10] = "UVARINT";
47
- /** Var ints that use deltas; each value will show the difference from the last value. Good for close numbers */
48
- PacketType[PacketType["DELTAS"] = 11] = "DELTAS";
49
- /** One or more single precision floating point numbers. Only up to 7 digits of accuracy. */
50
- PacketType[PacketType["FLOATS"] = 12] = "FLOATS";
51
- /** One or more double precision floating point numbers. */
52
- PacketType[PacketType["DOUBLES"] = 13] = "DOUBLES";
53
- /** One or more true/false */
54
- PacketType[PacketType["BOOLEANS"] = 14] = "BOOLEANS";
55
- /** Consumes multiple keys to describe the value. E.g. if you want to send a boolean, this could take up 2 keys instead of sending 2 bytes. Currently W.I.P. */
56
- PacketType[PacketType["KEY_EFFECTIVE"] = 15] = "KEY_EFFECTIVE";
57
- /** A more optimized version of JSON for when it's a necessity. However, please try to avoid this; the other types are usually better. */
58
- PacketType[PacketType["JSON"] = 16] = "JSON";
59
- /** Hex bytes, e.g. 0xFFFFFF - the result will always be returned in lowercase. This can only hold 1 hex string, since it's the same as UBYTES but auto-parses. */
60
- PacketType[PacketType["HEX"] = 17] = "HEX";
61
- })(PacketType || (exports.PacketType = PacketType = {}));
@@ -1,277 +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.PacketSchema = exports.Packet = void 0;
19
- const EnumHandler_1 = require("../util/enums/EnumHandler");
20
- const EnumType_1 = require("../util/enums/EnumType");
21
- const CompressionUtil_1 = require("../util/packets/CompressionUtil");
22
- const PacketUtils_1 = require("../util/packets/PacketUtils");
23
- const PacketProcessors_1 = require("./PacketProcessors");
24
- const PacketType_1 = require("./PacketType");
25
- const StringUtil_1 = require("../util/StringUtil");
26
- class Packet {
27
- defaultEnabled;
28
- tag;
29
- maxSize;
30
- minSize;
31
- type;
32
- enumData;
33
- dataMax;
34
- dataMin;
35
- dataBatching;
36
- maxBatchSize;
37
- dontSpread;
38
- autoFlatten;
39
- rateLimit;
40
- async;
41
- rereference;
42
- gzipCompression;
43
- object;
44
- client;
45
- receiveProcessor;
46
- sendProcessor;
47
- validator;
48
- processReceive;
49
- processSend;
50
- validate;
51
- customValidator;
52
- lastReceived = {};
53
- lastSent = {};
54
- constructor(tag, schema, customValidator, enabled, client) {
55
- this.tag = tag;
56
- this.defaultEnabled = enabled;
57
- this.client = client;
58
- this.async = schema.async;
59
- this.enumData = schema.enumData;
60
- this.rateLimit = schema.rateLimit;
61
- this.dontSpread = schema.dontSpread;
62
- this.autoFlatten = schema.autoFlatten;
63
- this.rereference = schema.rereference;
64
- this.dataBatching = schema.dataBatching;
65
- this.maxBatchSize = client ? Infinity : schema.maxBatchSize;
66
- this.gzipCompression = schema.gzipCompression;
67
- this.object = schema.object;
68
- this.type = schema.type;
69
- this.dataMax = schema.dataMax;
70
- this.dataMin = schema.dataMin;
71
- if (schema.testObject(this)) {
72
- this.maxSize = this.minSize = this.type.length;
73
- for (let i = 0; i < this.type.length; i++)
74
- if (this.type[i] == PacketType_1.PacketType.NONE)
75
- this.dataMax[i] = this.dataMin[i] = 0;
76
- this.receiveProcessor = (0, PacketProcessors_1.createObjReceiveProcessor)(this);
77
- this.sendProcessor = (0, PacketProcessors_1.createObjSendProcessor)(this);
78
- this.validator = (0, PacketProcessors_1.createObjValidator)(this);
79
- }
80
- else if (((_) => true)(this)) {
81
- this.maxSize = this.dataMax;
82
- this.minSize = this.dataMin;
83
- if (this.type == PacketType_1.PacketType.NONE)
84
- this.dataMax = this.dataMin = 0;
85
- this.receiveProcessor = (0, PacketProcessors_1.createReceiveProcessor)(this.type, this.enumData, this.dataMax);
86
- this.sendProcessor = (0, PacketProcessors_1.createSendProcessor)(this.type, this.gzipCompression, this.dataBatching != 0);
87
- this.validator = (0, PacketProcessors_1.createValidator)(this.type, this.dataMax, this.dataMin, this, this.gzipCompression);
88
- }
89
- else
90
- throw '';
91
- this.processReceive = (data, validationResult) => this.receiveProcessor(data, validationResult, 0);
92
- this.processSend = async (data) => new Uint8Array(await this.sendProcessor(tag, data));
93
- this.validate = (data) => this.validator(data, 0);
94
- this.customValidator = customValidator;
95
- }
96
- async listen(value, socket) {
97
- try {
98
- const [dcData, validationResult] = await this.validate(value);
99
- // holy shit i used === to fix another bug
100
- if (!this.client && validationResult === false)
101
- return "Invalid packet";
102
- const processed = this.processReceive(dcData, validationResult);
103
- const useableData = this.autoFlatten ? (0, PacketUtils_1.UnFlattenData)(processed) : processed;
104
- if (this.customValidator != null) {
105
- if (!this.dontSpread) {
106
- if (!this.customValidator(socket, ...useableData))
107
- return "Didn't pass custom validator";
108
- }
109
- else {
110
- if (!this.customValidator(socket, useableData))
111
- return "Didn't pass custom validator";
112
- }
113
- }
114
- return [useableData, !this.dontSpread];
115
- }
116
- catch (err) {
117
- console.error("There was an error processing the packet! This is probably my fault... report at https://github.com/liwybloc/sonic-ws", err);
118
- return "Error: " + err;
119
- }
120
- }
121
- serialize() {
122
- // shared values for both
123
- const sharedData = [
124
- this.tag.length, ...(0, StringUtil_1.processCharCodes)(this.tag),
125
- (0, CompressionUtil_1.compressBools)([this.dontSpread, this.async, this.object, this.autoFlatten, this.gzipCompression, this.rereference]),
126
- this.dataBatching,
127
- this.enumData.length, ...this.enumData.map(x => x.serialize()).flat(),
128
- ];
129
- // single-value packet (not an object schema)
130
- if (!this.object) {
131
- return [
132
- ...sharedData, // shared
133
- ...(0, CompressionUtil_1.convertVarInt)(this.dataMax), // the data max
134
- ...(0, CompressionUtil_1.convertVarInt)(this.dataMin), // the data min
135
- this.type,
136
- ];
137
- }
138
- // object packet
139
- return [
140
- ...sharedData,
141
- this.maxSize, // size
142
- ...this.dataMax.map(CompressionUtil_1.convertVarInt).flat(), // all data maxes, serialized
143
- ...this.dataMin.map(CompressionUtil_1.convertVarInt).flat(), // all data mins, serialized
144
- ...this.type, // all types
145
- ];
146
- }
147
- static readVarInts(data, offset, size) {
148
- const res = [];
149
- for (let i = 0; i < size; i++) {
150
- const [off, varint] = (0, CompressionUtil_1.readVarInt)(data, offset);
151
- offset = off;
152
- res.push(varint);
153
- }
154
- return [res, offset];
155
- }
156
- static deserialize(data, offset, client) {
157
- const beginningOffset = offset;
158
- // read length, go up 1
159
- const tagLength = data[offset++];
160
- // read tag as it's up 1, and add offset
161
- const tag = (0, StringUtil_1.as8String)(data.slice(offset, offset += tagLength));
162
- // then read dontSpread and async
163
- const [dontSpread, async, isObject, autoFlatten, gzipCompression, rereference] = (0, CompressionUtil_1.decompressBools)(data[offset++]);
164
- // read batching, up 1
165
- const dataBatching = data[offset++];
166
- // read enum length, up 1
167
- const enumLength = data[offset++];
168
- const enums = [];
169
- for (let i = 0; i < enumLength; i++) {
170
- // read tag length, go up 1
171
- const enumTagLength = data[offset++];
172
- // up 1 so read offset -> offset += tag length, to add tag length and skip over it
173
- const enumTag = (0, StringUtil_1.as8String)(data.slice(offset, offset += enumTagLength));
174
- // read amount of values
175
- const valueCount = data[offset++];
176
- const values = [];
177
- for (let j = 0; j < valueCount; j++) {
178
- // read the length of the value, go up 1
179
- const valueLength = data[offset++];
180
- // then read the type of value, up 1
181
- const valueType = data[offset++];
182
- // now can just read the values, increase offset for later use
183
- const value = (0, StringUtil_1.as8String)(data.slice(offset, offset += valueLength));
184
- // process it
185
- values.push(EnumType_1.TYPE_CONVERSION_MAP[valueType](value));
186
- }
187
- // define the enum with the values
188
- enums.push((0, EnumHandler_1.DefineEnum)(enumTag, values));
189
- }
190
- // objects
191
- if (isObject) {
192
- // read size
193
- const size = data[offset++];
194
- // read var ints for the datamaxes
195
- const [dataMaxes, o1] = this.readVarInts(data, offset, size);
196
- offset = o1;
197
- // read var ints for the datamins
198
- const [dataMins, o2] = this.readVarInts(data, offset, size);
199
- offset = o2;
200
- // get types, skip past size since there'll be size of these
201
- const types = Array.from(data.slice(offset, offset += size));
202
- // convert any enums into their indexed form for best bandwidth
203
- let index = 0;
204
- const finalTypes = types.map(x => x == PacketType_1.PacketType.ENUMS ? enums[index++] : x); // convert enums to their enum packages
205
- // make schema
206
- const schema = new PacketSchema(true, finalTypes, async, dataMins, dataMaxes, -1, dontSpread, autoFlatten, false, dataBatching, -1, gzipCompression);
207
- return [
208
- new Packet(tag, schema, null, false, client),
209
- // +1 to go next
210
- (offset - beginningOffset),
211
- ];
212
- }
213
- // single packet
214
- // read varint for datamax
215
- const [o1, dataMax] = (0, CompressionUtil_1.readVarInt)(data, offset);
216
- offset = o1;
217
- // read varint for datamin
218
- const [o2, dataMin] = (0, CompressionUtil_1.readVarInt)(data, offset);
219
- offset = o2;
220
- // read type
221
- const type = data[offset++];
222
- // do enum stuff
223
- const finalType = type == PacketType_1.PacketType.ENUMS ? enums[0] : type; // convert enum to enum package
224
- // make schema
225
- const schema = new PacketSchema(false, finalType, async, dataMin, dataMax, -1, dontSpread, false, rereference, dataBatching, -1, gzipCompression);
226
- return [
227
- new Packet(tag, schema, null, false, client),
228
- (offset - beginningOffset),
229
- ];
230
- }
231
- static deserializeAll(data, client) {
232
- const arr = [];
233
- let offset = 0;
234
- while (offset < data.length) {
235
- const [packet, len] = this.deserialize(data, offset, client);
236
- arr.push(packet);
237
- offset += len;
238
- }
239
- return arr;
240
- }
241
- }
242
- exports.Packet = Packet;
243
- const convertType = (type, ed) => (type instanceof EnumType_1.EnumPackage ? (ed.push(type), PacketType_1.PacketType.ENUMS) : type);
244
- class PacketSchema {
245
- type;
246
- enumData = [];
247
- dataMax;
248
- dataMin;
249
- dataBatching;
250
- maxBatchSize;
251
- rateLimit;
252
- dontSpread = false;
253
- autoFlatten = false;
254
- async = false;
255
- rereference = false;
256
- gzipCompression = false;
257
- object;
258
- constructor(object, type, async, dataMin, dataMax, rateLimit, dontSpread, autoFlatten, rereference, dataBatching, maxBatchSize, gzipCompression) {
259
- // todo add rereference to objects
260
- this.object = object;
261
- this.async = async;
262
- this.dataMin = dataMin;
263
- this.dataMax = dataMax;
264
- this.rateLimit = rateLimit;
265
- this.dontSpread = dontSpread;
266
- this.autoFlatten = autoFlatten;
267
- this.rereference = rereference;
268
- this.dataBatching = dataBatching;
269
- this.maxBatchSize = maxBatchSize;
270
- this.gzipCompression = gzipCompression;
271
- this.type = (object ? type.map(t => convertType(t, this.enumData)) : convertType(type, this.enumData));
272
- }
273
- testObject(packet) {
274
- return this.object;
275
- }
276
- }
277
- exports.PacketSchema = PacketSchema;