sonic-ws 2.2.0 → 2.4.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 (42) hide show
  1. package/README.md +28 -4
  2. package/bin/sonicws.mjs +159 -0
  3. package/bundled/bundle.js +1 -1
  4. package/dist/index.d.ts +9 -4
  5. package/dist/index.js +10 -3
  6. package/dist/native/wrapper.js +1 -1
  7. package/dist/version.d.ts +1 -1
  8. package/dist/version.js +1 -1
  9. package/dist/ws/Connection.d.ts +15 -3
  10. package/dist/ws/Connection.js +1 -1
  11. package/dist/ws/PacketProcessor.js +1 -1
  12. package/dist/ws/client/core/ClientCore.d.ts +20 -8
  13. package/dist/ws/client/core/ClientCore.js +1 -1
  14. package/dist/ws/client/node/ClientNode.d.ts +3 -2
  15. package/dist/ws/client/node/ClientNode.js +1 -1
  16. package/dist/ws/debug/PacketLogger.d.ts +30 -0
  17. package/dist/ws/debug/PacketLogger.js +7 -0
  18. package/dist/ws/packets/PacketType.d.ts +4 -1
  19. package/dist/ws/packets/Packets.d.ts +10 -1
  20. package/dist/ws/packets/Packets.js +1 -1
  21. package/dist/ws/server/SonicWSConnection.d.ts +14 -2
  22. package/dist/ws/server/SonicWSConnection.js +1 -1
  23. package/dist/ws/server/SonicWSServer.d.ts +18 -7
  24. package/dist/ws/server/SonicWSServer.js +1 -1
  25. package/dist/ws/util/JSONUtil.js +7 -0
  26. package/dist/ws/util/packets/BatchHelper.js +1 -1
  27. package/dist/ws/util/packets/ControlProtocol.d.ts +7 -1
  28. package/dist/ws/util/packets/ControlProtocol.js +1 -1
  29. package/dist/ws/util/packets/PacketHolder.js +1 -1
  30. package/dist/ws/util/packets/PacketUtils.d.ts +50 -12
  31. package/dist/ws/util/packets/PacketUtils.js +1 -1
  32. package/dist/ws/util/packets/VariantPermutation.d.ts +83 -0
  33. package/dist/ws/util/packets/VariantPermutation.js +7 -0
  34. package/dist/ws/util/packets/{PacketManifest.d.ts → metadata/PacketManifest.d.ts} +1 -1
  35. package/dist/ws/util/packets/{PacketManifest.js → metadata/PacketManifest.js} +1 -1
  36. package/dist/ws/util/packets/metadata/SchemaValidation.d.ts +17 -0
  37. package/dist/ws/util/packets/metadata/SchemaValidation.js +7 -0
  38. package/package.json +10 -4
  39. package/dist/ws/util/packets/JSONUtil.js +0 -7
  40. /package/dist/ws/util/{packets/JSONUtil.d.ts → JSONUtil.d.ts} +0 -0
  41. /package/dist/ws/util/packets/{ConstructorRegistry.d.ts → metadata/ConstructorRegistry.d.ts} +0 -0
  42. /package/dist/ws/util/packets/{ConstructorRegistry.js → metadata/ConstructorRegistry.js} +0 -0
@@ -5,6 +5,7 @@
5
5
  */
6
6
  export declare const CONTROL_KEY = 0;
7
7
  export declare enum ControlType {
8
+ HEARTBEAT = 0,
8
9
  REQUEST = 1,
9
10
  RESPONSE = 2,
10
11
  REPLAY = 3,
@@ -38,7 +39,12 @@ export type ControlResumed = {
38
39
  recovered: boolean;
39
40
  replayed: number;
40
41
  };
41
- export type ControlMessage = ControlRequest | ControlResponse | ControlReplay | ControlResume | ControlResumed;
42
+ export type ControlHeartbeat = {
43
+ type: ControlType.HEARTBEAT;
44
+ };
45
+ export type ControlMessage = ControlHeartbeat | ControlRequest | ControlResponse | ControlReplay | ControlResume | ControlResumed;
46
+ /** Encodes the minimal heartbeat CONTROL frame. */
47
+ export declare const encodeHeartbeat: () => Uint8Array<ArrayBuffer>;
42
48
  export declare function encodeControlRequest(id: number, packetKey: number, payload: Uint8Array): Uint8Array;
43
49
  export declare function encodeControlResponse(id: number, ok: boolean, value: any): Uint8Array;
44
50
  export declare const encodeReplay: (sequence: number, payload: Uint8Array) => Uint8Array<ArrayBuffer>;
@@ -4,4 +4,4 @@
4
4
  * See LICENSE for personal, non-commercial license terms.
5
5
  */
6
6
 
7
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.encodeResumed=exports.encodeReplay=exports.ControlType=exports.CONTROL_KEY=void 0,exports.encodeControlRequest=function(r,o,n){return Uint8Array.from([exports.CONTROL_KEY,t.REQUEST,...(0,e.convertVarInt)(r),o,...n])},exports.encodeControlResponse=function(o,n,s){return Uint8Array.from([exports.CONTROL_KEY,t.RESPONSE,...(0,e.convertVarInt)(o),Number(n),...(0,r.compressJSON)(s)])},exports.encodeResume=function(r,o){const n=(new TextEncoder).encode(r);return Uint8Array.from([exports.CONTROL_KEY,t.RESUME,...(0,e.convertVarInt)(n.length),...n,...(0,e.convertVarInt)(o)])},exports.decodeControl=function(o){if(o[0]!==exports.CONTROL_KEY||o.length<3)throw new Error("Invalid SonicWS control frame");const n=o[1];switch(n){case t.REPLAY:{const[r,t]=(0,e.readVarInt)(o,2);return{type:n,sequence:t,payload:o.slice(r)}}case t.RESUME:{const[r,t]=(0,e.readVarInt)(o,2),s=r+t;if(s>o.length)throw new Error("Recovery frame has an invalid session id");const[c,a]=(0,e.readVarInt)(o,s);return{type:n,sessionId:(new TextDecoder).decode(o.slice(r,s)),lastSequence:a}}case t.RESUMED:{if(o.length<4)throw new Error("Invalid recovery result frame");const[r,t]=(0,e.readVarInt)(o,3);return{type:n,recovered:0!==o[2],replayed:t}}case t.REQUEST:{const[r,t]=(0,e.readVarInt)(o,2);if(r>=o.length)throw new Error("RPC request is missing its packet key");return{type:n,id:t,packetKey:o[r],payload:o.slice(r+1)}}case t.RESPONSE:{const[t,s]=(0,e.readVarInt)(o,2);if(t>=o.length)throw new Error("RPC response is missing its status");return{type:n,id:s,ok:0!==o[t],value:(0,r.decompressJSON)(o.slice(t+1))}}default:throw new Error(`Unknown SonicWS control frame type: ${n}`)}};const e=require("./CompressionUtil"),r=require("./JSONUtil");var t;exports.CONTROL_KEY=0,function(e){e[e.REQUEST=1]="REQUEST",e[e.RESPONSE=2]="RESPONSE",e[e.REPLAY=3]="REPLAY",e[e.RESUME=4]="RESUME",e[e.RESUMED=5]="RESUMED"}(t||(exports.ControlType=t={}));exports.encodeReplay=(r,o)=>Uint8Array.from([exports.CONTROL_KEY,t.REPLAY,...(0,e.convertVarInt)(r),...o]);exports.encodeResumed=(r,o)=>Uint8Array.from([exports.CONTROL_KEY,t.RESUMED,Number(r),...(0,e.convertVarInt)(o)]);
7
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.encodeResumed=exports.encodeReplay=exports.encodeHeartbeat=exports.ControlType=exports.CONTROL_KEY=void 0,exports.encodeControlRequest=function(r,o,n){return Uint8Array.from([exports.CONTROL_KEY,t.REQUEST,...(0,e.convertVarInt)(r),o,...n])},exports.encodeControlResponse=function(o,n,s){return Uint8Array.from([exports.CONTROL_KEY,t.RESPONSE,...(0,e.convertVarInt)(o),Number(n),...(0,r.compressJSON)(s)])},exports.encodeResume=function(r,o){const n=(new TextEncoder).encode(r);return Uint8Array.from([exports.CONTROL_KEY,t.RESUME,...(0,e.convertVarInt)(n.length),...n,...(0,e.convertVarInt)(o)])},exports.decodeControl=function(o){if(1===o.length&&o[0]===exports.CONTROL_KEY)return{type:t.HEARTBEAT};if(o[0]!==exports.CONTROL_KEY||o.length<3)throw new Error("Invalid SonicWS control frame");const n=o[1];switch(n){case t.REPLAY:{const[r,t]=(0,e.readVarInt)(o,2);return{type:n,sequence:t,payload:o.slice(r)}}case t.RESUME:{const[r,t]=(0,e.readVarInt)(o,2),s=r+t;if(s>o.length)throw new Error("Recovery frame has an invalid session id");const[E,c]=(0,e.readVarInt)(o,s);return{type:n,sessionId:(new TextDecoder).decode(o.slice(r,s)),lastSequence:c}}case t.RESUMED:{if(o.length<4)throw new Error("Invalid recovery result frame");const[r,t]=(0,e.readVarInt)(o,3);return{type:n,recovered:0!==o[2],replayed:t}}case t.REQUEST:{const[r,t]=(0,e.readVarInt)(o,2);if(r>=o.length)throw new Error("RPC request is missing its packet key");return{type:n,id:t,packetKey:o[r],payload:o.slice(r+1)}}case t.RESPONSE:{const[t,s]=(0,e.readVarInt)(o,2);if(t>=o.length)throw new Error("RPC response is missing its status");return{type:n,id:s,ok:0!==o[t],value:(0,r.decompressJSON)(o.slice(t+1))}}default:throw new Error(`Unknown SonicWS control frame type: ${n}`)}};const e=require("./CompressionUtil"),r=require("../JSONUtil");var t;exports.CONTROL_KEY=0,function(e){e[e.HEARTBEAT=0]="HEARTBEAT",e[e.REQUEST=1]="REQUEST",e[e.RESPONSE=2]="RESPONSE",e[e.REPLAY=3]="REPLAY",e[e.RESUME=4]="RESUME",e[e.RESUMED=5]="RESUMED"}(t||(exports.ControlType=t={}));exports.encodeHeartbeat=()=>Uint8Array.of(exports.CONTROL_KEY);exports.encodeReplay=(r,o)=>Uint8Array.from([exports.CONTROL_KEY,t.REPLAY,...(0,e.convertVarInt)(r),...o]);exports.encodeResumed=(r,o)=>Uint8Array.from([exports.CONTROL_KEY,t.RESUMED,Number(r),...(0,e.convertVarInt)(o)]);
@@ -4,4 +4,4 @@
4
4
  * See LICENSE for personal, non-commercial license terms.
5
5
  */
6
6
 
7
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.PacketHolder=void 0;exports.PacketHolder=class{key;keys;tags;packetMap;packets;variants={};parents=new Set;constructor(t){this.key=1,this.keys={},this.tags={},this.packetMap={},t&&this.holdPackets(t)}createKey(t){this.keys[t]=this.key,this.tags[this.key]=t,this.key++}holdPackets(t){this.packets=t;for(const e of t)this.createKey(e.tag),this.packetMap[e.tag]=e,e.parent&&e.variant&&(this.variants[`${e.parent}.${e.variant}`]=e.tag,this.parents.add(e.parent)),e.isParent&&this.parents.add(e.tag)}getKey(t){if(!((t=this.resolveTag(t))in this.keys))throw new Error(`Not a valid tag: ${t}`);return this.keys[t]}getTag(t){if(t in this.tags)return this.tags[t]}getPacket(t){if(!((t=this.resolveTag(t))in this.packetMap))throw new Error("Unknown packet tag: "+t);return this.packetMap[t]}hasKey(t){return t in this.tags}hasTag(t){return this.resolveTag(t)in this.keys||this.parents.has(t)}resolveTag(t){return this.variants[t]??t}getVariantTag(t,e){const s=this.variants[`${t}.${e}`];if(!s)throw new Error(`Unknown packet variant: ${t}.${e}`);return s}getKeys(){return this.keys}getTagMap(){return this.tags}getTags(){return Object.values(this.tags)}getPackets(){return this.packets}serialize(){return this.packets.map(t=>t.serialize()).flat()}};
7
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.PacketHolder=void 0;const t=require("./metadata/SchemaValidation");exports.PacketHolder=class{key;keys;tags;packetMap;packets;variants={};parents=new Set;constructor(t){this.key=1,this.keys={},this.tags={},this.packetMap={},t&&this.holdPackets(t)}createKey(t){this.keys[t]=this.key,this.tags[this.key]=t,this.key++}holdPackets(e){(0,t.AssertPacketSchema)(e),this.packets=e;for(const t of e)this.createKey(t.tag),this.packetMap[t.tag]=t,t.parent&&t.variant&&(this.variants[`${t.parent}.${t.variant}`]=t.tag,this.parents.add(t.parent)),t.isParent&&this.parents.add(t.tag)}getKey(t){if(!((t=this.resolveTag(t))in this.keys))throw new Error(`Not a valid tag: ${t}`);return this.keys[t]}getTag(t){if(t in this.tags)return this.tags[t]}getPacket(t){if(!((t=this.resolveTag(t))in this.packetMap))throw new Error("Unknown packet tag: "+t);return this.packetMap[t]}hasKey(t){return t in this.tags}hasTag(t){return this.resolveTag(t)in this.keys||this.parents.has(t)}resolveTag(t){return this.variants[t]??t}getVariantTag(t,e){const a=this.variants[`${t}.${e}`];if(!a)throw new Error(`Unknown packet variant: ${t}.${e}`);return a}getPermutationVariant(t,e){const a=this.getPacket(t).permutationValues;if(!a)throw new Error(`Packet group "${t}" does not define a VariantPermutation`);let r;if(Array.isArray(e)){if(e.length!==a.length||e.some(t=>"boolean"!=typeof t))throw new Error(`Variant permutation requires ${a.length} boolean flags`);r=a.filter((t,a)=>e[a])}else{const t=e,s=Object.keys(t);if(s.length!==a.length||s.some(e=>!a.includes(e)||"boolean"!=typeof t[e]))throw new Error("Variant permutation object must define every known key as a boolean");r=a.filter(e=>t[e])}if(!r.length)return t;const s=Object.keys(this.variants).filter(e=>e.startsWith(`${t}.`)).map(e=>e.slice(t.length+1)).find(t=>{const e=t.split(",");return e.length===r.length&&e.every(t=>r.includes(t))});if(!s)throw new Error("Variant permutation contains an invalid or opposite combination");return this.getVariantTag(t,s)}getKeys(){return this.keys}getTagMap(){return this.tags}getTags(){return Object.values(this.tags)}getPackets(){return this.packets}serialize(){return this.packets.map(t=>t.serialize()).flat()}};
@@ -6,6 +6,7 @@
6
6
  import { ConvertType, Packet, ValidatorFunction } from "../../packets/Packets";
7
7
  import { PacketType } from "../../packets/PacketType";
8
8
  import { EnumPackage } from "../enums/EnumType";
9
+ import { VariantPermutation } from "./VariantPermutation";
9
10
  export type ProcessedPacket = [code: number, data: Uint8Array, packet: Packet<any>];
10
11
  /** Valid packet type */
11
12
  export type ArguableType = PacketType | EnumPackage;
@@ -25,7 +26,10 @@ export type SharedPacketSettings = {
25
26
  * Each batched packet is counted towards the rate limit.
26
27
  */
27
28
  dataBatching?: number;
28
- /** If data batching is on, this will limit the amount of packets that can be batched into one (only effects the client). Defaults to 10. 0 for unlimited. */
29
+ /**
30
+ * Limits packets in one batch on the receiving client.
31
+ * Defaults to 10. Zero disables the limit.
32
+ */
29
33
  maxBatchSize?: number;
30
34
  /** The amount of times this packet can be sent every second, or 0 for infinite. */
31
35
  rateLimit?: number;
@@ -37,7 +41,10 @@ export type SharedPacketSettings = {
37
41
  enabled?: boolean;
38
42
  /** A validation function that is called whenever data is received. Return true for success, return false to kick socket. */
39
43
  validator?: ValidatorFunction;
40
- /** If this is true, other packets will be processed even if this one isn't finished; it'll still prevent it from calling twice before this finishes though. Defaults to false. */
44
+ /**
45
+ * Allows other packet types to run while this packet is processing.
46
+ * Repeated calls for this packet remain serialized.
47
+ */
41
48
  async?: boolean;
42
49
  /** If this is true, the packet will be Gzip compressed. Defaults to false on all types but JSON. */
43
50
  gzipCompression?: boolean;
@@ -52,7 +59,10 @@ export type SinglePacketSettings = SharedPacketSettings & {
52
59
  dataMax?: number;
53
60
  /** The minimum amount of values that can be sent through this packet; defaults to the max */
54
61
  dataMin?: number;
55
- /** If this is true, it will save the last received of this value, and if no data is sent, it'll re-use the previous value. This is not compatible with dataMin: 0. Defaults to false. */
62
+ /**
63
+ * Reuses the previous value when an empty payload arrives.
64
+ * This is incompatible with a zero data minimum.
65
+ */
56
66
  rereference?: boolean;
57
67
  /** Field names used to map positional values to and from an object. */
58
68
  schema?: readonly string[];
@@ -67,18 +77,21 @@ export type SinglePacketSettings = SharedPacketSettings & {
67
77
  min?: number;
68
78
  /** Inclusive application-level numeric maximum. */
69
79
  max?: number;
70
- /** Local class constructed from decoded schema fields. The class name is exchanged; peers must register their own matching class. */
80
+ /**
81
+ * Constructs decoded schema fields with a local class.
82
+ * Peers exchange the class name and register their own matching class.
83
+ */
71
84
  constructor?: Function;
72
85
  };
73
86
  /** Settings for multi-typed packets */
74
87
  export type MultiPacketSettings = SharedPacketSettings & {
75
88
  /** The data types of the packet */
76
89
  readonly types: readonly ArguableType[];
77
- /** The maximum amount of values that can be sent through each type of packet; defaults to 1 for each. Non-array will fill all for that amount */
90
+ /** Sets the maximum value count per field. A scalar applies to every field. */
78
91
  dataMaxes?: number[] | number;
79
- /** The minimum amount of values that can be sent through each type of packet; defaults to the max for each Non-array will fill all for that amount */
92
+ /** Sets the minimum value count per field. A scalar applies to every field. */
80
93
  dataMins?: number[] | number;
81
- /** Will automatically run FlattenData() and UnFlattenData() on values; this will optimize [[x,y,z],[x,y,z]...] for wire transfer */
94
+ /** Transposes repeated rows into columns before encoding. */
82
95
  autoFlatten?: boolean;
83
96
  /** Field names for records transposed into object-packet columns. */
84
97
  schema?: readonly string[];
@@ -87,14 +100,35 @@ export type MultiPacketSettings = SharedPacketSettings & {
87
100
  /** Local class constructed for every decoded schema record. */
88
101
  constructor?: Function;
89
102
  };
103
+ type PacketGroupVariant = Omit<SinglePacketSettings, "tag">;
104
+ type PacketGroupDefaults = {
105
+ /** Settings inherited by every variant. Individual variant settings take precedence. */
106
+ defaults?: PacketGroupVariant;
107
+ /** Deprecated alias for `defaults`. */
108
+ delegate?: PacketGroupVariant;
109
+ };
90
110
  export type PacketGroupSettings = {
91
111
  tag: string;
92
- variants: Record<string, Omit<SinglePacketSettings, "tag">>;
93
- };
112
+ } & PacketGroupDefaults & ({
113
+ variants: Record<string, PacketGroupVariant>;
114
+ } | {
115
+ variants: readonly string[];
116
+ defaults: PacketGroupVariant;
117
+ } | {
118
+ variants: readonly string[];
119
+ delegate: PacketGroupVariant;
120
+ } | {
121
+ variants: VariantPermutation;
122
+ defaults: PacketGroupVariant;
123
+ } | {
124
+ variants: VariantPermutation;
125
+ delegate: PacketGroupVariant;
126
+ });
94
127
  type GroupMetadata = {
95
128
  parent: string;
96
129
  variant: string;
97
130
  isParent: boolean;
131
+ permutation?: string[];
98
132
  };
99
133
  /** Settings for single-typed enum packets */
100
134
  export type EnumPacketSettings = SharedPacketSettings & {
@@ -108,7 +142,7 @@ export type EnumPacketSettings = SharedPacketSettings & {
108
142
  /**
109
143
  * Creates a structure for a simple single-typed packet.
110
144
  * This packet can be sent and received with the specified tag, type, and data cap.
111
- * @param settings The settings object containing `tag`, `type`, `dataMax`, `dataMin`, `noDataRange`, `dontSpread`, `validator`, `dataBatching`, and/or `maxBatchSize`.
145
+ * @param settings Packet type, limits, mapping, validation, and batching settings.
112
146
  * @returns The constructed packet structure data.
113
147
  * @throws {Error} If the `type` is invalid.
114
148
  */
@@ -119,7 +153,7 @@ export declare function CreatePacket<T extends ArguableType>(settings: SinglePac
119
153
  /**
120
154
  * Creates a structure for an object (multi-typed) packet.
121
155
  * This packet allows multiple types and their associated data caps.
122
- * @param settings The settings object containing `tag`, `types`, `dataMaxes`, `dataMins`, `noDataRange`, `dontSpread`, `autoFlatten`, `largePacket`, `validator`, `dataBatching`, and/or `maxBatchSize`.
156
+ * @param settings Field types, limits, transposition, validation, and batching settings.
123
157
  * @returns The constructed packet structure data.
124
158
  * @throws {Error} If any type in `types` is invalid.
125
159
  */
@@ -138,12 +172,16 @@ export declare function CreateObjPacket<T extends readonly ArguableType[], V ext
138
172
  * listeners on `movement.move` receive the child payload, while listeners on
139
173
  * `movement` also receive `{ variant: "move", payload }`. Sending `movement`
140
174
  * directly represents the parent/empty variant (`variant: ""`).
175
+ *
176
+ * `defaults` applies shared settings before each variant override. Array variants
177
+ * require `defaults`, for example `{ variants: ["W", "A"], defaults: { type:
178
+ * PacketType.SHORTS } }`. `delegate` remains accepted as a deprecated alias.
141
179
  */
142
180
  export declare function CreatePacketGroup(settings: PacketGroupSettings): Packet<any>[];
143
181
  /**
144
182
  * Creates and defines an enum packet. This can be used to create an enum-based packet
145
183
  * with a specific tag and possible values.
146
- * @param settings The settings object containing `tag`, `enumTag`, `values`, `dataMax`, `dataMin`, `noDataRange`, `dontSpread`, `validator`, `dataBatching`, and/or `maxBatchSize`.
184
+ * @param settings Enum package, limits, validation, and batching settings.
147
185
  * @returns The constructed packet structure data.
148
186
  */
149
187
  export declare function CreateEnumPacket(settings: EnumPacketSettings): Packet<PacketType.ENUMS>;
@@ -4,4 +4,4 @@
4
4
  * See LICENSE for personal, non-commercial license terms.
5
5
  */
6
6
 
7
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.processPacket=i,exports.listenPacket=async function(e,t,a){if("string"==typeof e)return a(e);const[r,n]=e;try{if(n&&Array.isArray(r))for(const e of t)await e(...r);else for(const e of t)await e(r)}catch(e){console.error(e),a(e)}},exports.CreatePacket=p,exports.CreateObjPacket=function(a){const r=Object.prototype.hasOwnProperty.call(a,"constructor")?a.constructor:void 0;let{tag:n,types:i=[],dataMaxes:p,dataMins:m,noDataRange:w=!1,dontSpread:d=!1,autoFlatten:y=!1,autoTranspose:g,schema:k,validator:P=null,dataBatching:E=0,maxBatchSize:v=10,rateLimit:S=0,enabled:T=!0,async:$=!1,gzipCompression:b=i&&i.includes(t.PacketType.JSON)}=a;if(!n)throw new Error("Tag not selected!");if(!i||0==i.length)throw new Error("Types is set to 0 length");if(a.replay&&E)throw new Error(`Packet "${n}" cannot combine replay with batching`);if(f(k,n),r&&!k)throw new Error(`Packet "${n}" constructor requires schema`);r&&(0,o.RegisterPacketConstructor)(r);if(k&&k.length!==i.length)throw new Error(`Packet "${n}" schema length must match types length`);if(void 0!==g&&y&&g!==y)throw new Error(`Packet "${n}" has conflicting autoFlatten and autoTranspose options`);const x=g??y;for(const e of i)if(c(e))throw new Error(`Invalid packet type in "${n}" packet: ${e}`);w?(p=Array.from({length:i.length}).map(()=>s),m=Array.from({length:i.length}).map(()=>0)):(null==p?p=Array.from({length:i.length}).map(()=>1):Array.isArray(p)||(p=Array.from({length:i.length}).map(()=>p)),null==m?m=Array.from({length:i.length}).map((e,t)=>p[t]):Array.isArray(m)||(m=Array.from({length:i.length}).map(()=>m)));const A=p.map(l),M=m.map((e,a)=>i[a]==t.PacketType.NONE?0:u(e,A[a])),O=new e.PacketSchema(!0,i,$,M,A,h(S),d,x,!1,E,v,b,k,void 0,void 0,void 0,void 0,r?.name,a.replay??!1);return new e.Packet(n,O,P,T,!1)},exports.CreatePacketGroup=function(e){if(!e.tag||e.tag.includes("$"))throw new Error("Packet group tag is required and cannot contain '$'");const a=Object.entries(e.variants);if(!a.length)throw new Error(`Packet group "${e.tag}" requires at least one variant`);const r=p({tag:e.tag,type:t.PacketType.NONE,dataMin:0,dataMax:0,_group:{parent:e.tag,variant:"",isParent:!0}}),n=a.map(([t,a])=>{if(!t||t.includes("$"))throw new Error("Packet variant names cannot be empty or contain '$'");return p({...a,tag:`${e.tag}.${t}`,_group:{parent:e.tag,variant:t,isParent:!1}})});return[r,...n]},exports.CreateEnumPacket=function(e){const{tag:t,enumData:a,dataMax:r=1,dataMin:n=0,noDataRange:o=!1,dontSpread:i=!1,validator:c=null,dataBatching:s=0,maxBatchSize:l=10,rateLimit:u=0,enabled:h=!0,async:f=!1}=e;return p({tag:t,type:a,dataMax:r,dataMin:n,noDataRange:o,dontSpread:i,validator:c,dataBatching:s,maxBatchSize:l,rateLimit:u,enabled:h,async:f})},exports.FlattenData=w,exports.UnFlattenData=function(e){return e[0]?.map((t,a)=>e.map(e=>e[a]))??[]};const e=require("../../packets/Packets"),t=require("../../packets/PacketType"),a=require("../enums/EnumType"),r=require("./CompressionUtil"),n=require("./HashUtil"),o=require("./ConstructorRegistry");async function i(e,a,o,c,s,l=!1){const u=e.getKey(a),h=e.getPacket(a);return async function(e,t,a,r,n,o,c){if(e[0]&&!o)return new Promise(t=>e[1].push([t,r,n]));e[0]=!0;const s=await c();if(e[1].length>0){const[r,n,o]=e[1].shift();queueMicrotask(async()=>{r(await i(t,n,o,e,a,!0))})}else e[0]=!1;return s}(c,e,s,a,o,l,async()=>{if(h.rereference){if(-1===s)throw new Error("Cannot send a re-referenced packet from the server-wide sender!");const e=(0,n.hashValue)(o);if(h.lastSent[s]===e)return[u,r.EMPTY_UINT8,h];h.lastSent[s]=e}if(o=h.prepareSend(o,s),h.autoFlatten&&h.object&&!h.fields)o=w(o[0]);else{if(o.length>h.maxSize)throw new Error(`Packet "${a}" only allows ${h.maxSize} values!`);if(o.length<h.minSize)throw new Error(`Packet "${a}" requires at least ${h.minSize} values!`)}if(h.object){if(o=o.map(e=>Array.isArray(e)?e:[e]),!h.autoFlatten){const e=h.dataMin,t=h.dataMax;for(let r=0;r<e.length;r++){if(o[r].length<e[r])throw new Error(`Section ${r+1} of packet "${a}" requires at least ${e[r]} values!`);if(o[r].length>t[r])throw new Error(`Section ${r+1} of packet "${a}" only allows ${t[r]} values!`)}}}else if(h.type!==t.PacketType.JSON){const e=o.find(e=>"object"==typeof e&&null!=e);e&&console.warn(`Passing an array will result in undefined behavior (${JSON.stringify(e)}). Spread the array with ...arr`)}const e=o.length>0?await h.processSend(o):r.EMPTY_UINT8;return[u,e,h]})}function c(e){return!("number"==typeof e&&e in t.PacketType||e instanceof a.EnumPackage)}const s=2048383;function l(e){return e<0?(console.warn("Having a data maximum below 0 does not do anything!"),0):e>s?(console.warn(`Only ${s} values can be sent on a type! Uhh make an issue if you want to send more.`),s):e}function u(e,t){return e<0?(console.warn("Having a data minimum below 0 does not do anything!"),0):e>t?(console.warn("Data minimum can not be higher than the data maximum!"),t):e}function h(e){if(!Number.isFinite(e)||e<0)throw new Error("Rate limit must be a non-negative finite number");return(e=Math.floor(e))>r.MAX_USHORT?(console.warn(`A rate limit above ${r.MAX_USHORT} is considered infinite.`),0):e}function p(a){const r=!0===a.autoFlatten&&void 0===a.dataMax&&void 0===a.dataMin,n=Object.prototype.hasOwnProperty.call(a,"constructor")?a.constructor:void 0;let{tag:i,type:p=t.PacketType.NONE,dataMax:w=1,dataMin:d,noDataRange:y=!1,dontSpread:g=!1,validator:k=null,dataBatching:P=0,maxBatchSize:E=10,rateLimit:v=0,enabled:S=!0,async:T=!1,gzipCompression:$=p==t.PacketType.JSON,rereference:b=!1,schema:x,autoFlatten:A=!1,quantized:M,min:O,max:q}=a;if(!i)throw new Error("Tag not selected!");if(y||r?(d=b?1:0,w=s):null==d&&(d=p==t.PacketType.NONE?0:w),b&&0==d)throw new Error("Rereference cannot be true if the dataMin is 0");if(a.replay&&P)throw new Error(`Packet "${i}" cannot combine replay with batching`);if(c(p))throw new Error(`Invalid packet type: ${p}`);if(f(x,i),n&&!x)throw new Error(`Packet "${i}" constructor requires schema`);if(n&&(0,o.RegisterPacketConstructor)(n),A&&(!x||0===x.length))throw new Error(`Packet "${i}" autoFlatten requires schema`);if(x&&!A&&d===w&&x.length!==w)throw new Error(`Packet "${i}" schema length must match its fixed value count (${w})`);!function(e,t,a,r,n){if(void 0!==a&&void 0!==r&&a>r)throw new Error(`Packet "${n}" min cannot exceed max`);if((t||void 0!==a||void 0!==r)&&!m.has(e))throw new Error(`Packet "${n}" numeric options require a numeric packet type`);if(t&&(!Number.isFinite(t.scale)||t.scale<=0))throw new Error(`Packet "${n}" quantization scale must be positive and finite`)}(p,M,O,q,i);const N=new e.PacketSchema(!1,p,T,u(d,w),l(w),h(v),g,A,b,P,E,$,x,M,O,q,a._group,n?.name,a.replay??!1);return new e.Packet(i,N,k,S,!1)}function f(e,t){if(e){if(!e.length||e.some(e=>"string"!=typeof e||!e))throw new Error(`Packet "${t}" schema must contain non-empty field names`);if(new Set(e).size!==e.length)throw new Error(`Packet "${t}" schema fields must be unique`)}}const m=new Set([t.PacketType.BYTES,t.PacketType.UBYTES,t.PacketType.SHORTS,t.PacketType.USHORTS,t.PacketType.VARINT,t.PacketType.UVARINT,t.PacketType.DELTAS,t.PacketType.FLOATS,t.PacketType.DOUBLES]);function w(e){if(null==e)return[];const t=e[0];if(null==t)return[];if(!Array.isArray(t))throw new Error(`Cannot flatten array: ${e}`);return t.map((t,a)=>e.map(e=>e[a]))??[]}
7
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.processPacket=c,exports.listenPacket=async function(e,t,a){if("string"==typeof e)return void a(e);const[r,n]=e;try{if(n&&Array.isArray(r))for(const e of t)await e(...r);else for(const e of t)await e(r)}catch(e){console.error(e),a(String(e))}},exports.CreatePacket=m,exports.CreateObjPacket=function(a){const r=Object.prototype.hasOwnProperty.call(a,"constructor")?a.constructor:void 0;let{tag:n,types:i=[],dataMaxes:c,dataMins:m,noDataRange:h=!1,dontSpread:w=!1,autoFlatten:g=!1,autoTranspose:y,schema:k,validator:P=null,dataBatching:v=0,maxBatchSize:E=10,rateLimit:$=0,enabled:S=!0,async:T=!1,gzipCompression:b=i&&i.includes(t.PacketType.JSON)}=a;if(!n)throw new Error("Packet tag is required");if(!i||0===i.length)throw new Error(`Packet "${n}" requires at least one type`);if(a.replay&&v)throw new Error(`Packet "${n}" cannot combine replay with batching`);if(d(k,n),r&&!k)throw new Error(`Packet "${n}" constructor requires schema`);r&&(0,o.RegisterPacketConstructor)(r);if(k&&k.length!==i.length)throw new Error(`Packet "${n}" schema length must match types length`);if(void 0!==y&&g&&y!==g)throw new Error(`Packet "${n}" has conflicting autoFlatten and autoTranspose options`);const A=y??g;for(const e of i)if(s(e))throw new Error(`Invalid packet type in "${n}" packet: ${e}`);if(h)c=Array.from({length:i.length},()=>u),m=Array.from({length:i.length},()=>0);else if(void 0===c?c=Array.from({length:i.length},()=>1):Array.isArray(c)||(c=Array.from({length:i.length},()=>c)),void 0===m){const e=c;m=Array.from({length:i.length},(t,a)=>e[a])}else Array.isArray(m)||(m=Array.from({length:i.length},()=>m));const x=m,q=c.map(l),M=x.map((e,a)=>i[a]===t.PacketType.NONE?0:p(e,q[a])),O=new e.PacketSchema(!0,i,T,M,q,f($),w,A,!1,v,E,b,k,void 0,void 0,void 0,void 0,r?.name,a.replay??!1);return new e.Packet(n,O,P,S,!1)},exports.CreatePacketGroup=function(e){if(!e.tag||e.tag.includes("$"))throw new Error("Packet group tag is required and cannot contain '$'");if(void 0!==e.defaults&&void 0!==e.delegate)throw new Error(`Packet group "${e.tag}" cannot define both defaults and delegate`);const a=e.defaults??e.delegate,r=e.variants instanceof i.VariantPermutation?e.variants:void 0;if((Array.isArray(e.variants)||r)&&void 0===a)throw new Error(`Packet group "${e.tag}" array variants require defaults`);const n=r?r.generate().map(e=>[e,{}]):Array.isArray(e.variants)?e.variants.map(e=>[e,{}]):Object.entries(e.variants);if(!n.length)throw new Error(`Packet group "${e.tag}" requires at least one variant`);if(new Set(n.map(([e])=>e)).size!==n.length)throw new Error(`Packet group "${e.tag}" contains duplicate variant names`);const o=m({tag:e.tag,type:t.PacketType.NONE,dataMin:0,dataMax:0,_group:{parent:e.tag,variant:"",isParent:!0,permutation:r?.getValues()}}),c=n.map(([t,n])=>{if("string"!=typeof t||!t||t.includes("$"))throw new Error("Packet variant names cannot be empty or contain '$'");return m({...a,...n,tag:`${e.tag}.${t}`,_group:{parent:e.tag,variant:t,isParent:!1,permutation:r?.getValues()}})});return[o,...c]},exports.CreateEnumPacket=function(e){const{tag:t,enumData:a,dataMax:r=1,dataMin:n=0,noDataRange:o=!1,dontSpread:i=!1,validator:c=null,dataBatching:s=0,maxBatchSize:u=10,rateLimit:l=0,enabled:p=!0,async:f=!1}=e;return m({tag:t,type:a,dataMax:r,dataMin:n,noDataRange:o,dontSpread:i,validator:c,dataBatching:s,maxBatchSize:u,rateLimit:l,enabled:p,async:f})},exports.FlattenData=w,exports.UnFlattenData=function(e){return e[0]?.map((t,a)=>e.map(e=>e[a]))??[]};const e=require("../../packets/Packets"),t=require("../../packets/PacketType"),a=require("../enums/EnumType"),r=require("./CompressionUtil"),n=require("./HashUtil"),o=require("./metadata/ConstructorRegistry"),i=require("./VariantPermutation");async function c(e,a,o,i,s,u=!1){const l=e.getKey(a),p=e.getPacket(a);return async function(e,t,a,r,n,o,i){if(e[0]&&!o)return new Promise(t=>e[1].push([t,r,n]));e[0]=!0;const s=await i();if(e[1].length>0){const[r,n,o]=e[1].shift();queueMicrotask(async()=>{r(await c(t,n,o,e,a,!0))})}else e[0]=!1;return s}(i,e,s,a,o,u,async()=>{if(p.rereference){if(-1===s)throw new Error("Cannot send a re-referenced packet from the server-wide sender");const e=(0,n.hashValue)(o);if(p.lastSent[s]===e)return[l,r.EMPTY_UINT8,p];p.lastSent[s]=e}if(o=p.prepareSend(o,s),p.autoFlatten&&p.object&&!p.fields)o=w(o[0]);else{if(o.length>p.maxSize)throw new Error(`Packet "${a}" only allows ${p.maxSize} values`);if(o.length<p.minSize)throw new Error(`Packet "${a}" requires at least ${p.minSize} values`)}if(p.object||p.type===t.PacketType.JSON){if(p.object&&(o=o.map(e=>Array.isArray(e)?e:[e]),!p.autoFlatten)){const e=p.dataMin,t=p.dataMax;for(let r=0;r<e.length;r++){if(o[r].length<e[r])throw new Error(`Section ${r+1} of packet "${a}" requires at least ${e[r]} values`);if(o[r].length>t[r])throw new Error(`Section ${r+1} of packet "${a}" only allows ${t[r]} values`)}}}else{const e=o.find(e=>"object"==typeof e&&null!=e);e&&console.warn(`Passing a nested value may produce undefined behavior (${JSON.stringify(e)}). Spread arrays into positional packet arguments`)}let e=r.EMPTY_UINT8;if(o.length>0){const t=p.processSend(o);e=t instanceof Promise?await t:t}return[l,e,p]})}function s(e){return!("number"==typeof e&&e in t.PacketType||e instanceof a.EnumPackage)}const u=2048383;function l(e){return e<0?(console.warn("A data maximum below zero is treated as zero"),0):e>u?(console.warn(`A packet type can contain at most ${u} values`),u):e}function p(e,t){return e<0?(console.warn("A data minimum below zero is treated as zero"),0):e>t?(console.warn("A data minimum above the data maximum is clamped to the maximum"),t):e}function f(e){if(!Number.isFinite(e)||e<0)throw new Error("Rate limit must be a non-negative finite number");return(e=Math.floor(e))>r.MAX_USHORT?(console.warn(`A rate limit above ${r.MAX_USHORT} is considered infinite.`),0):e}function m(a){const r=!0===a.autoFlatten&&void 0===a.dataMax&&void 0===a.dataMin,n=Object.prototype.hasOwnProperty.call(a,"constructor")?a.constructor:void 0;let{tag:i,type:c=t.PacketType.NONE,dataMax:m=1,dataMin:w,noDataRange:g=!1,dontSpread:y=!1,validator:k=null,dataBatching:P=0,maxBatchSize:v=10,rateLimit:E=0,enabled:$=!0,async:S=!1,gzipCompression:T=c===t.PacketType.JSON,rereference:b=!1,schema:A,autoFlatten:x=!1,quantized:q,min:M,max:O}=a;if(!i)throw new Error("Packet tag is required");if(g||r?(w=b?1:0,m=u):void 0===w&&(w=c===t.PacketType.NONE?0:m),b&&0===w)throw new Error("Rereference requires a data minimum above zero");if(a.replay&&P)throw new Error(`Packet "${i}" cannot combine replay with batching`);if(s(c))throw new Error(`Invalid packet type: ${c}`);if(d(A,i),n&&!A)throw new Error(`Packet "${i}" constructor requires schema`);if(n&&(0,o.RegisterPacketConstructor)(n),x&&(!A||0===A.length))throw new Error(`Packet "${i}" autoFlatten requires schema`);if(A&&!x&&w===m&&A.length!==m)throw new Error(`Packet "${i}" schema length must match its fixed value count (${m})`);!function(e,t,a,r,n){if(void 0!==a&&void 0!==r&&a>r)throw new Error(`Packet "${n}" min cannot exceed max`);if((t||void 0!==a||void 0!==r)&&!h.has(e))throw new Error(`Packet "${n}" numeric options require a numeric packet type`);if(t&&(!Number.isFinite(t.scale)||t.scale<=0))throw new Error(`Packet "${n}" quantization scale must be positive and finite`)}(c,q,M,O,i);const z=new e.PacketSchema(!1,c,S,p(w,m),l(m),f(E),y,x,b,P,v,T,A,q,M,O,a._group,n?.name,a.replay??!1);return new e.Packet(i,z,k,$,!1)}function d(e,t){if(e){if(!e.length||e.some(e=>"string"!=typeof e||!e))throw new Error(`Packet "${t}" schema must contain non-empty field names`);if(new Set(e).size!==e.length)throw new Error(`Packet "${t}" schema fields must be unique`)}}const h=new Set([t.PacketType.BYTES,t.PacketType.UBYTES,t.PacketType.SHORTS,t.PacketType.USHORTS,t.PacketType.VARINT,t.PacketType.UVARINT,t.PacketType.DELTAS,t.PacketType.FLOATS,t.PacketType.DOUBLES]);function w(e){if(null==e)return[];const t=e[0];if(null==t)return[];if(!Array.isArray(t))throw new Error(`Cannot flatten array: ${e}`);return t.map((t,a)=>e.map(e=>e[a]))}
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Copyright (c) 2026 Lily (liwybloc)
3
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
4
+ * See LICENSE for personal, non-commercial license terms.
5
+ */
6
+ /**
7
+ * Generates valid permutations/combinations of variant values.
8
+ *
9
+ * Opposite pairs prevent invalid combinations from being generated.
10
+ * For example, with WASD:
11
+ *
12
+ * - W and S are opposites
13
+ * - A and D are opposites
14
+ *
15
+ * So `W,S`, `A,D`, `W,A,S`, etc. are excluded.
16
+ */
17
+ export declare class VariantPermutation {
18
+ private readonly values;
19
+ private readonly opposites;
20
+ private generated?;
21
+ /**
22
+ * Creates a new variant permutation generator.
23
+ *
24
+ * @param values The available variant values.
25
+ * @param opposites Optional pairs of indexes that cannot appear together.
26
+ *
27
+ * @example
28
+ * const variants = new VariantPermutation(
29
+ * ["W", "A", "S", "D"],
30
+ * [[0, 2], [1, 3]]
31
+ * ).generate();
32
+ */
33
+ constructor(values: string[], opposites?: [number, number][]);
34
+ /**
35
+ * Convenience helper for generating variants without manually creating
36
+ * a VariantPermutation instance.
37
+ *
38
+ * @param values The available variant values.
39
+ * @param opposites Optional pairs of indexes that cannot appear together.
40
+ * @returns A variant permutation object.
41
+ */
42
+ static from(values: string[], opposites?: [number, number][]): VariantPermutation;
43
+ /**
44
+ * Generates valid WASD movement combinations.
45
+ *
46
+ * @returns Valid WASD combinations, excluding opposite directions.
47
+ *
48
+ * @example
49
+ * VariantPermutation.WASD();
50
+ * // [
51
+ * // "W", "A", "S", "D",
52
+ * // "W,A", "W,D", "S,A", "S,D"
53
+ * // ]
54
+ */
55
+ static WASD(): VariantPermutation;
56
+ /**
57
+ * Generates valid arrow key movement combinations.
58
+ *
59
+ * @returns Valid arrow key combinations, excluding opposite directions.
60
+ */
61
+ static Arrows(): VariantPermutation;
62
+ /** Returns the ordered boolean keys used by this permutation. */
63
+ getValues(): string[];
64
+ /** Resolves boolean flags or a keyed boolean object to a generated variant. */
65
+ resolve(selection: readonly boolean[] | Record<string, boolean>): string;
66
+ /** Expands a generated variant name into its keyed boolean representation. */
67
+ expand(variant: string): Record<string, boolean>;
68
+ /**
69
+ * Checks whether a combination contains any invalid opposite pair.
70
+ */
71
+ private containsOpposites;
72
+ /**
73
+ * Creates a stable ordering map used for formatting generated combinations.
74
+ *
75
+ * Opposite pairs are treated as directional groups. For WASD:
76
+ *
77
+ * - W/S belong to group 0
78
+ * - A/D belong to group 1
79
+ *
80
+ * This makes diagonals display as `W,A`, `W,D`, `S,A`, `S,D`.
81
+ */
82
+ private createGroupOrder;
83
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Copyright (c) 2026 Lily (liwybloc)
3
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
4
+ * See LICENSE for personal, non-commercial license terms.
5
+ */
6
+
7
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.VariantPermutation=void 0;class e{values;opposites;generated;constructor(e,t){if(!e.length||e.some(e=>"string"!=typeof e||!e||e.includes(",")))throw new Error("Variant permutation values must be non-empty strings without commas");if(new Set(e).size!==e.length)throw new Error("Variant permutation values must be unique");for(const[n,s]of t??[])if(!Number.isInteger(n)||!Number.isInteger(s)||n<0||s<0||n>=e.length||s>=e.length||n===s)throw new Error("Variant permutation opposite indexes are invalid");this.values=e,this.opposites=t??[]}static from(t,n){return new e(t,n)}static WASD(){return new e(["W","A","S","D"],[[0,2],[1,3]])}static Arrows(){return new e(["Up","Left","Down","Right"],[[0,2],[1,3]])}generate(){if(this.generated)return[...this.generated];const e=[],t=1<<this.values.length,n=this.createGroupOrder();for(let s=1;s<t;s++){const t=[];for(let e=0;e<this.values.length;e++)s&1<<e&&t.push(e);if(this.containsOpposites(t))continue;const r=[...t].sort((e,t)=>{const s=n.get(e)-n.get(t);return 0!==s?s:e-t});e.push({indexes:r,value:r.map(e=>this.values[e]).join(",")})}return this.generated=e.sort((e,t)=>{if(e.indexes.length!==t.indexes.length)return e.indexes.length-t.indexes.length;for(let n=0;n<Math.min(e.indexes.length,t.indexes.length);n++)if(e.indexes[n]!==t.indexes[n])return e.indexes[n]-t.indexes[n];return 0}).map(e=>e.value),[...this.generated]}getValues(){return[...this.values]}resolve(e){const t=new Set;if(Array.isArray(e)){if(e.length!==this.values.length||e.some(e=>"boolean"!=typeof e))throw new Error(`Variant permutation requires ${this.values.length} boolean flags`);e.forEach((e,n)=>e&&t.add(this.values[n]))}else{const n=e,s=Object.keys(n);if(s.length!==this.values.length||s.some(e=>!this.values.includes(e)||"boolean"!=typeof n[e]))throw new Error("Variant permutation object must define every known key as a boolean");this.values.forEach(e=>n[e]&&t.add(e))}if(!t.size)return"";const n=this.generate().find(e=>{const n=e.split(",");return n.length===t.size&&n.every(e=>t.has(e))});if(!n)throw new Error("Variant permutation contains an invalid or opposite combination");return n}expand(e){const t=new Set(e?e.split(","):[]);if(t.size&&!this.generate().includes(e))throw new Error(`Unknown generated permutation: ${e}`);return Object.fromEntries(this.values.map(e=>[e,t.has(e)]))}containsOpposites(e){const t=new Set(e);return this.opposites.some(([e,n])=>t.has(e)&&t.has(n))}createGroupOrder(){const e=new Map;this.opposites.forEach(([t,n],s)=>{e.has(t)||e.set(t,s),e.has(n)||e.set(n,s)});let t=this.opposites.length;for(let n=0;n<this.values.length;n++)e.has(n)||e.set(n,t++);return e}}exports.VariantPermutation=e;
@@ -3,7 +3,7 @@
3
3
  * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
4
4
  * See LICENSE for personal, non-commercial license terms.
5
5
  */
6
- import { Packet } from "../../packets/Packets";
6
+ import { Packet } from "../../../packets/Packets";
7
7
  export type PacketManifest = {
8
8
  clientPackets: readonly Packet<any>[];
9
9
  serverPackets: readonly Packet<any>[];
@@ -4,4 +4,4 @@
4
4
  * See LICENSE for personal, non-commercial license terms.
5
5
  */
6
6
 
7
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.CreatePacketManifest=function(t){const i=t.clientPackets.flatMap(e=>e.serialize()),n=t.serverPackets.flatMap(e=>e.serialize());return Uint8Array.from([...a,e.VERSION,...(0,r.convertVarInt)(i.length),...i,...n])},exports.LoadPacketManifest=function(i){if(i.length<6||a.some((e,t)=>i[t]!==e))throw new Error("Invalid SonicWS packet manifest");if(i[4]!==e.VERSION)throw new Error(`Packet manifest protocol mismatch: ${i[4]} != ${e.VERSION}`);const[n,s]=(0,r.readVarInt)(i,5),c=n+s;if(c>i.length)throw new Error("Truncated SonicWS packet manifest");return{clientPackets:t.Packet.deserializeAll(i.slice(n,c),!1),serverPackets:t.Packet.deserializeAll(i.slice(c),!1)}};const e=require("../../../version"),t=require("../../packets/Packets"),r=require("./CompressionUtil"),a=[83,87,83,77];
7
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.CreatePacketManifest=function(t){const i=t.clientPackets.flatMap(e=>e.serialize()),n=t.serverPackets.flatMap(e=>e.serialize());return Uint8Array.from([...a,e.VERSION,...(0,r.convertVarInt)(i.length),...i,...n])},exports.LoadPacketManifest=function(i){if(i.length<6||a.some((e,t)=>i[t]!==e))throw new Error("Invalid SonicWS packet manifest");if(i[4]!==e.VERSION)throw new Error(`Packet manifest protocol mismatch: ${i[4]} != ${e.VERSION}`);const[n,s]=(0,r.readVarInt)(i,5),c=n+s;if(c>i.length)throw new Error("Truncated SonicWS packet manifest");return{clientPackets:t.Packet.deserializeAll(i.slice(n,c),!1),serverPackets:t.Packet.deserializeAll(i.slice(c),!1)}};const e=require("../../../../version"),t=require("../../../packets/Packets"),r=require("../CompressionUtil"),a=[83,87,83,77];
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Copyright (c) 2026 Lily (liwybloc)
3
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
4
+ * See LICENSE for personal, non-commercial license terms.
5
+ */
6
+ import { Packet } from "../../../packets/Packets";
7
+ export type SchemaValidationResult = {
8
+ errors: string[];
9
+ warnings: string[];
10
+ };
11
+ /** Performs whole-table checks that individual CreatePacket calls cannot see. */
12
+ export declare function ValidatePacketSchema(packets: readonly Packet<any>[], options?: {
13
+ direction?: "client" | "server";
14
+ warnUnbounded?: boolean;
15
+ }): SchemaValidationResult;
16
+ /** Throws when a packet table contains structural schema errors. */
17
+ export declare function AssertPacketSchema(packets: readonly Packet<any>[], options?: Parameters<typeof ValidatePacketSchema>[1]): void;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Copyright (c) 2026 Lily (liwybloc)
3
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
4
+ * See LICENSE for personal, non-commercial license terms.
5
+ */
6
+
7
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.ValidatePacketSchema=n,exports.AssertPacketSchema=function(e,a){const t=n(e,a);if(t.errors.length)throw new Error(`Invalid SonicWS packet schema:\n- ${t.errors.join("\n- ")}`);for(const e of t.warnings)console.warn(`SonicWS schema warning: ${e}`)};const e=require("../../../packets/PacketType"),a=new Set([e.PacketType.UBYTES,e.PacketType.USHORTS,e.PacketType.UVARINT]),t=new Set([e.PacketType.BYTES,e.PacketType.UBYTES,e.PacketType.SHORTS,e.PacketType.USHORTS,e.PacketType.VARINT,e.PacketType.UVARINT,e.PacketType.DELTAS,e.PacketType.FLOATS,e.PacketType.DOUBLES]);function n(n,c={}){const s=[],r=[],p=new Set,o=new Map,i=new Set;n.length>254&&s.push(`Packet table contains ${n.length} packets; the maximum is 254`);for(const e of n){p.has(e.tag)&&s.push(`Duplicate packet tag "${e.tag}"`),p.add(e.tag),e.isParent&&o.set(e.tag,e),e.replay&&e.dataBatching&&s.push(`Packet "${e.tag}" combines replay with batching`);const n=Array.isArray(e.type)?e.type:[e.type];e.quantized&&n.some(e=>!t.has(e))&&s.push(`Packet "${e.tag}" quantizes a non-numeric type`),void 0!==e.valueMin&&e.valueMin<0&&n.some(e=>a.has(e))&&s.push(`Packet "${e.tag}" has a negative minimum for an unsigned type`),!e.fields||e.autoFlatten||e.object||e.dataMin!==e.dataMax||e.fields.length===e.dataMax||s.push(`Packet "${e.tag}" schema length does not match its fixed value count`);const u=Array.isArray(e.dataMax)?e.dataMax.some(e=>e>=2048383):e.dataMax>=2048383;if(c.warnUnbounded&&"client"===c.direction&&u&&r.push(`Client packet "${e.tag}" has an effectively unbounded value count`),e.parent&&e.variant){const a=`${e.parent}.${e.variant}`;i.has(a)&&s.push(`Duplicate packet-group variant "${a}"`),i.add(a)}}for(const a of n){if(!a.parent)continue;const t=o.get(a.parent);t?t.type!==e.PacketType.NONE&&s.push(`Packet-group parent "${a.parent}" must use PacketType.NONE`):s.push(`Packet "${a.tag}" references missing group parent "${a.parent}"`)}return{errors:s,warnings:r}}
package/package.json CHANGED
@@ -1,11 +1,15 @@
1
1
  {
2
2
  "name": "sonic-ws",
3
- "version": "2.2.0",
3
+ "version": "2.4.0",
4
4
  "description": "Ultra-lightweight, high-performance, and bandwidth efficient websocket library",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
+ "bin": {
8
+ "sonicws": "bin/sonicws.mjs"
9
+ },
7
10
  "files": [
8
11
  "dist/**/*",
12
+ "bin/sonicws.mjs",
9
13
  "bundled/bundle.js",
10
14
  "bundled/bundle.wasm",
11
15
  "README.md",
@@ -13,18 +17,20 @@
13
17
  ],
14
18
  "scripts": {
15
19
  "webpack": "webpack --mode production",
16
-
20
+
17
21
  "build_wasm_browser": "wasm-pack build --release --target bundler --out-dir ../ts/src/native/wasm/pkg --out-name sonic_ws_core ../core --features wasm --no-default-features",
18
22
  "build_wasm_node": "wasm-pack build --release --target nodejs --out-dir ../ts/src/native/wasm/node --out-name sonic_ws_core ../core --features wasm --no-default-features",
19
23
  "build_wasm": "npm run build_wasm_browser && npm run build_wasm_node",
20
24
  "build_web": "npm run build_wasm_browser && tsc --moduleResolution nodenext --module nodenext --outDir ./dist src/ws/client/browser/ClientBrowser.ts && cpy \"src/native/wasm/pkg/*\" dist/native/wasm/pkg --flat && rimraf ./dist/native/wasm/pkg/.gitignore && npm run webpack && node package-files.mjs",
21
25
  "build_node": "npm run build_wasm_node && rimraf ./dist && tsc -d && cpy \"src/native/wasm/node/*\" dist/native/wasm/node --flat && rimraf ./dist/native/wasm/node/.gitignore",
22
26
  "build": "npm run build_node && npm run build_web && rimraf ./dist/native/wasm/pkg ./dist/ws/client/browser && rimraf ./dist/ws/debug/DebugClient.d.ts && rimraf ./dist/ws/debug/DebugClient.js && node minify.mjs && node package-files.mjs",
23
-
27
+
24
28
  "test_web": "npm run build && node tests/test_web.mjs",
25
29
  "test_node": "npm run build_node && node tests/test_node.mjs",
30
+ "test_conformance": "npm run build_node && node tests/test_conformance.mjs",
31
+ "benchmark": "npm run build_node && node ../../benchmarks/run.mjs && node ../../benchmarks/transport.mjs",
26
32
  "prepack": "npm run build",
27
-
33
+
28
34
  "stage_package": "node package-files.mjs",
29
35
  "publish:assets": "rimraf ../../release/SonicWS_bundle.js ../../release/SonicWS_core.wasm && cp ../../bundled/bundle.js ../../release/bundle.js && cp ../../bundled/bundle.wasm ../../release/bundle.wasm"
30
36
  },
@@ -1,7 +0,0 @@
1
- /**
2
- * Copyright (c) 2026 Lily (liwybloc)
3
- * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
4
- * See LICENSE for personal, non-commercial license terms.
5
- */
6
-
7
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.decompressJSON=exports.compressJSON=void 0;const r=require("../BufferUtil"),e=r=>Array.from({length:8},(e,t)=>!!(r&1<<7-t));function t(r){if(!Number.isInteger(r)||r<0)throw new Error(`Invalid JSON variable integer: ${r}`);const e=[];do{let t=127&r;(r>>>=7)>0&&(t|=128),e.push(t)}while(r>0);return e}function n(r,e){let t=0,n=0;for(;;){if(e>=r.length||n>28)throw new Error("Invalid JSON variable integer");const s=r[e++];if(t+=(127&s)<<n,!(128&s))return[e,t];n+=7}}var s;!function(r){r[r.NULL=0]="NULL",r[r.BOOL=1]="BOOL",r[r.INT=2]="INT",r[r.FLOAT=3]="FLOAT",r[r.STRING=4]="STRING",r[r.ARRAY=5]="ARRAY",r[r.OBJECT=6]="OBJECT"}(s||(s={}));const o=r=>{const e=(new TextEncoder).encode(r);return[...t(e.length),...e]},a=(r,e)=>{const[t,s]=n(r,e);return{value:(new TextDecoder).decode(r.subarray(t,t+s)),length:t+s-e}},u=r=>{let e="";for(const t of r)e+=t.toString(2).padStart(3,"0");return(r=>new Uint8Array(r.match(/.{1,8}/g)?.map(r=>parseInt(r.padEnd(8,"0"),2))??[]))(e)},c=(r,e)=>{const t=(r=>Array.from(r,r=>r.toString(2).padStart(8,"0")).join(""))(r),n=[];for(let r=0;r<e;r++)n.push(parseInt(t.slice(3*r,3*r+3),2));return n};exports.compressJSON=e=>{const n=[],a=[],c=[],l=r=>{switch(null===r?"null":Array.isArray(r)?"array":typeof r){case"null":c.push(s.NULL);break;case"boolean":c.push(s.BOOL),n.push(r);break;case"number":Number.isInteger(r)?(c.push(s.INT),a.push(...t((r=>r<<1^r>>31)(r)))):(c.push(s.FLOAT),a.push(...function(r){if(Number.isNaN(r))return[127,128,0,1];const e=r<0?1:0;if(0===(r=Math.abs(r)))return[0,0,0,0];const t=Math.floor(Math.log2(r));if(!Number.isFinite(r)||t>127||t<-126)return[e?255:127,128,0,0];const n=(e<<31|t+127<<23|8388607&Math.round((r/2**t-1)*2**23))>>>0;return[n>>>24,n>>>16&255,n>>>8&255,255&n]}(r)));break;case"string":c.push(s.STRING),a.push(...o(r));break;case"array":c.push(s.ARRAY),a.push(...t(r.length));for(const e of r)l(e);break;case"object":{c.push(s.OBJECT);const e=Object.keys(r);a.push(...t(e.length));for(const t of e)a.push(...o(t)),l(r[t]);break}default:throw new Error("Unsupported type")}};l(e);const h=n.length?(0,r.splitArray)(n,8).map(r=>r.reduce((r,e,t)=>r|Number(e)<<7-t,0)):[],p=u(c),i=[...t(h.length),...t(p.length)];return Uint8Array.from([...i,...h.flat(),...p,...a])};exports.decompressJSON=r=>{let t=0;const[o,u]=n(r,t);t=o;const[l,h]=n(r,t);t=l;const p=[];for(let n=0;n<u;n++)p.push(...e(r[t++]));let i=0;const f=r.subarray(t,t+h);t+=h;const N=c(f,8*f.length/3);let O=0;const d=e=>{if(e>500)throw new Error("JSON array too deep.");const o=N[O++];switch(o){case s.NULL:return null;case s.BOOL:return p[i++];case s.INT:{const[e,s]=n(r,t);return t=e,(u=s)>>>1^-(1&u)}case s.FLOAT:{const e=function(r){const e=(r[0]<<24|r[1]<<16|r[2]<<8|r[3])>>>0,t=e>>>23&255,n=(0===t?0:1)+(8388607&e)/2**23,s=255===t?0===n?1/0:NaN:n*2**(0===t?-126:t-127);return e>>>31?-s:s}(Array.from(r.subarray(t,t+4)));return t+=4,e}case s.STRING:{const{value:e,length:n}=a(r,t);return t+=n,e}case s.ARRAY:{const[s,o]=n(r,t);t=s;const a=[];for(let r=0;r<o;r++)a.push(d(e+1));return a}case s.OBJECT:{const[s,o]=n(r,t);t=s;const u={};for(let n=0;n<o;n++){const{value:n,length:s}=a(r,t);t+=s,u[n]=d(e+1)}return u}default:throw new Error(`Unknown type ${o}`)}var u};return d(0)};