sonic-ws 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -0
- package/bin/sonicws.mjs +159 -0
- package/bundled/bundle.js +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +6 -1
- package/dist/native/wrapper.js +1 -1
- package/dist/ws/Connection.d.ts +14 -3
- package/dist/ws/Connection.js +1 -1
- package/dist/ws/PacketProcessor.js +1 -1
- package/dist/ws/client/core/ClientCore.d.ts +19 -8
- package/dist/ws/client/core/ClientCore.js +1 -1
- package/dist/ws/client/node/ClientNode.d.ts +3 -2
- package/dist/ws/client/node/ClientNode.js +1 -1
- package/dist/ws/debug/PacketLogger.d.ts +30 -0
- package/dist/ws/debug/PacketLogger.js +7 -0
- package/dist/ws/packets/PacketType.d.ts +4 -1
- package/dist/ws/packets/Packets.d.ts +5 -1
- package/dist/ws/packets/Packets.js +1 -1
- package/dist/ws/server/SonicWSConnection.d.ts +13 -2
- package/dist/ws/server/SonicWSConnection.js +1 -1
- package/dist/ws/server/SonicWSServer.d.ts +15 -7
- package/dist/ws/server/SonicWSServer.js +1 -1
- package/dist/ws/util/packets/BatchHelper.js +1 -1
- package/dist/ws/util/packets/PacketHolder.js +1 -1
- package/dist/ws/util/packets/PacketUtils.d.ts +22 -10
- package/dist/ws/util/packets/PacketUtils.js +1 -1
- package/dist/ws/util/packets/SchemaValidation.d.ts +17 -0
- package/dist/ws/util/packets/SchemaValidation.js +7 -0
- package/package.json +10 -4
package/README.md
CHANGED
|
@@ -15,6 +15,8 @@ It is designed for real-time applications such as games, dashboards, collaborati
|
|
|
15
15
|
- Batch, validate, compress, and rate-limit packets with minimal boilerplate.
|
|
16
16
|
- Reconnect with bounded state recovery and opt-in missed-packet replay.
|
|
17
17
|
- Use validated RPC, server-side rooms, and pluggable scaling adapters.
|
|
18
|
+
- Inspect, encode, decode, size, validate, and generate types from packet manifests with the CLI.
|
|
19
|
+
- Drop replaceable updates under backpressure without silently dropping reliable messages.
|
|
18
20
|
- Code is much more readable than every other socket library*
|
|
19
21
|
|
|
20
22
|
<details>
|
|
@@ -149,6 +151,12 @@ Full API documentation:
|
|
|
149
151
|
|
|
150
152
|
- [TypeScript / Node / browser](docs/ts/README.md)
|
|
151
153
|
- [Python](docs/py/README.md)
|
|
154
|
+
- [Protocol version 24](docs/protocol.md)
|
|
155
|
+
- [Production defaults](docs/defaults.md)
|
|
156
|
+
- [Authentication and recovery](docs/authentication.md)
|
|
157
|
+
- [Inspector, generated types, conformance, and benchmarks](docs/tooling.md)
|
|
158
|
+
- [Backpressure and delivery](docs/backpressure.md)
|
|
159
|
+
- [Runnable examples](examples/README.md)
|
|
152
160
|
|
|
153
161
|
Packet schemas can now map the existing single-type wire format directly to application objects:
|
|
154
162
|
|
|
@@ -175,6 +183,10 @@ Clients can opt into capped exponential-backoff reconnect. Packets marked `repla
|
|
|
175
183
|
- Publish the Rust core as a standalone, documented crate
|
|
176
184
|
- Add first-class Go bindings
|
|
177
185
|
|
|
186
|
+
## API AND PROTOCOL STABILITY
|
|
187
|
+
|
|
188
|
+
SonicWS uses semantic package versions and an explicit wire-protocol version. Incompatible wire changes require a protocol-version change and fail during handshake instead of silently decoding with different semantics. Public APIs may still evolve between major package versions; pin the package version for production deployments and run the shared conformance corpus when upgrading.
|
|
189
|
+
|
|
178
190
|
## LICENSE
|
|
179
191
|
This project is source-available.
|
|
180
192
|
|
package/bin/sonicws.mjs
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
readFile,
|
|
5
|
+
writeFile
|
|
6
|
+
} from "node:fs/promises";
|
|
7
|
+
import {
|
|
8
|
+
deflateRawSync
|
|
9
|
+
} from "node:zlib";
|
|
10
|
+
import {
|
|
11
|
+
LoadPacketManifest,
|
|
12
|
+
ValidatePacketSchema
|
|
13
|
+
} from "../dist/index.js";
|
|
14
|
+
import {
|
|
15
|
+
PacketHolder
|
|
16
|
+
} from "../dist/ws/util/packets/PacketHolder.js";
|
|
17
|
+
import {
|
|
18
|
+
processPacket
|
|
19
|
+
} from "../dist/ws/util/packets/PacketUtils.js";
|
|
20
|
+
|
|
21
|
+
function usage(message) {
|
|
22
|
+
if (message) console.error(message);
|
|
23
|
+
console.error(`Usage:
|
|
24
|
+
sonicws inspect <manifest.swsm>
|
|
25
|
+
sonicws validate <manifest.swsm>
|
|
26
|
+
sonicws types <manifest.swsm> [output.d.ts]
|
|
27
|
+
sonicws encode <manifest.swsm> <client|server> <tag> <json>
|
|
28
|
+
sonicws decode <manifest.swsm> <client|server> <tag> <hex>
|
|
29
|
+
sonicws size <manifest.swsm> <client|server> <tag> <json>`);
|
|
30
|
+
process.exit(message ? 2 : 0);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const [, , command, filename, direction, tag, input] = process.argv;
|
|
34
|
+
if (!command || command === "help" || command === "--help") usage();
|
|
35
|
+
if (!filename) usage("A packet manifest is required");
|
|
36
|
+
const manifest = LoadPacketManifest(new Uint8Array(await readFile(filename)));
|
|
37
|
+
const select = name => name === "client" ? manifest.clientPackets : name === "server" ? manifest.serverPackets : usage("Direction must be client or server");
|
|
38
|
+
|
|
39
|
+
if (command === "inspect") {
|
|
40
|
+
const summarize = packets => packets.map((packet, index) => ({
|
|
41
|
+
key: index + 1,
|
|
42
|
+
tag: packet.tag,
|
|
43
|
+
type: packet.type,
|
|
44
|
+
schema: packet.fields,
|
|
45
|
+
dataMin: packet.dataMin,
|
|
46
|
+
dataMax: packet.dataMax,
|
|
47
|
+
batchingMs: packet.dataBatching,
|
|
48
|
+
compressed: packet.gzipCompression,
|
|
49
|
+
replay: packet.replay,
|
|
50
|
+
}));
|
|
51
|
+
console.log(JSON.stringify({
|
|
52
|
+
protocol: 24,
|
|
53
|
+
clientPackets: summarize(manifest.clientPackets),
|
|
54
|
+
serverPackets: summarize(manifest.serverPackets)
|
|
55
|
+
}, null, 2));
|
|
56
|
+
process.exit(0);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (command === "validate") {
|
|
60
|
+
const client = ValidatePacketSchema(manifest.clientPackets, {
|
|
61
|
+
direction: "client",
|
|
62
|
+
warnUnbounded: true
|
|
63
|
+
});
|
|
64
|
+
const server = ValidatePacketSchema(manifest.serverPackets, {
|
|
65
|
+
direction: "server"
|
|
66
|
+
});
|
|
67
|
+
console.log(JSON.stringify({
|
|
68
|
+
client,
|
|
69
|
+
server,
|
|
70
|
+
valid: client.errors.length + server.errors.length === 0
|
|
71
|
+
}, null, 2));
|
|
72
|
+
process.exit(client.errors.length + server.errors.length ? 1 : 0);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (command === "types") {
|
|
76
|
+
const scalar = packetType => ({
|
|
77
|
+
0: "undefined",
|
|
78
|
+
1: "Uint8Array",
|
|
79
|
+
2: "string",
|
|
80
|
+
3: "string",
|
|
81
|
+
4: "unknown",
|
|
82
|
+
5: "number",
|
|
83
|
+
6: "number",
|
|
84
|
+
7: "number",
|
|
85
|
+
8: "number",
|
|
86
|
+
9: "number",
|
|
87
|
+
10: "number",
|
|
88
|
+
11: "number",
|
|
89
|
+
12: "number",
|
|
90
|
+
13: "number",
|
|
91
|
+
14: "boolean",
|
|
92
|
+
16: "unknown",
|
|
93
|
+
17: "string",
|
|
94
|
+
})[packetType] ?? "unknown";
|
|
95
|
+
const payload = (packet, packets, group = true) => {
|
|
96
|
+
if (group && packet.isParent) {
|
|
97
|
+
const variants = packets.filter(child => child.parent === packet.tag && child.variant)
|
|
98
|
+
.map(child => `{ variant: ${JSON.stringify(child.variant)}; payload: ${payload(child, packets, false)} }`);
|
|
99
|
+
return [`{ variant: ""; payload: undefined }`, ...variants].join(" | ");
|
|
100
|
+
}
|
|
101
|
+
const types = Array.isArray(packet.type) ? packet.type : [packet.type];
|
|
102
|
+
if (packet.fields) {
|
|
103
|
+
const record = `{ ${packet.fields.map((field, index) => `${JSON.stringify(field)}: ${scalar(types[Math.min(index, types.length - 1)])}`).join("; ")} }`;
|
|
104
|
+
return packet.autoFlatten ? `${record}[]` : record;
|
|
105
|
+
}
|
|
106
|
+
if (packet.type === 0) return "undefined";
|
|
107
|
+
const value = scalar(types[0]);
|
|
108
|
+
return packet.dataMax === 1 ? value : `${value}[]`;
|
|
109
|
+
};
|
|
110
|
+
const table = (name, packets) => [
|
|
111
|
+
`export interface ${name} {`,
|
|
112
|
+
...packets.map(packet => ` ${JSON.stringify(packet.tag)}: ${payload(packet, packets)};`),
|
|
113
|
+
"}",
|
|
114
|
+
].join("\n");
|
|
115
|
+
const generated = `// Generated by sonicws types; protocol 24.\n${table("ClientPackets", manifest.clientPackets)}\n\n${table("ServerPackets", manifest.serverPackets)}\n\ntype PacketArguments<T> = T extends undefined ? [] : [value: T];\nexport interface TypedSonicWS {\n send<K extends keyof ClientPackets>(tag: K, ...value: PacketArguments<ClientPackets[K]>): Promise<void>;\n sendSafe<K extends keyof ClientPackets>(tag: K, ...value: PacketArguments<ClientPackets[K]>): Promise<boolean>;\n on<K extends keyof ServerPackets>(tag: K, listener: (value: ServerPackets[K]) => void): void;\n}\n`;
|
|
116
|
+
if (direction) await writeFile(direction, generated);
|
|
117
|
+
else process.stdout.write(generated);
|
|
118
|
+
process.exit(0);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (!direction || !tag || input === undefined) usage(`Missing arguments for ${command}`);
|
|
122
|
+
const packets = select(direction);
|
|
123
|
+
const holder = new PacketHolder(packets);
|
|
124
|
+
const packet = holder.getPacket(tag);
|
|
125
|
+
|
|
126
|
+
if (command === "decode") {
|
|
127
|
+
if (!/^(?:[0-9a-fA-F]{2})*$/.test(input)) usage("Encoded data must be even-length hexadecimal");
|
|
128
|
+
let bytes = Uint8Array.from(Buffer.from(input, "hex"));
|
|
129
|
+
if (bytes[0] === holder.getKey(tag)) bytes = bytes.slice(1);
|
|
130
|
+
const decoded = await packet.listen(bytes, null);
|
|
131
|
+
if (typeof decoded === "string") throw new Error(decoded);
|
|
132
|
+
console.log(JSON.stringify(decoded[0], null, 2));
|
|
133
|
+
process.exit(0);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
let value;
|
|
137
|
+
try {
|
|
138
|
+
value = JSON.parse(input);
|
|
139
|
+
} catch {
|
|
140
|
+
usage("Value must be valid JSON");
|
|
141
|
+
}
|
|
142
|
+
const values = packet.fields || packet.autoFlatten ? [value] : Array.isArray(value) ? value : [value];
|
|
143
|
+
const [key, encoded] = await processPacket(holder, tag, values, [false, [], undefined], 0);
|
|
144
|
+
const frame = Buffer.from([key, ...encoded]);
|
|
145
|
+
if (command === "encode") {
|
|
146
|
+
console.log(frame.toString("hex"));
|
|
147
|
+
} else if (command === "size") {
|
|
148
|
+
const json = Buffer.from(JSON.stringify({
|
|
149
|
+
event: tag,
|
|
150
|
+
data: value
|
|
151
|
+
}));
|
|
152
|
+
console.log(JSON.stringify({
|
|
153
|
+
tag,
|
|
154
|
+
sonicBytes: frame.length,
|
|
155
|
+
rawDeflateBytes: 1 + deflateRawSync(encoded).length,
|
|
156
|
+
jsonBytes: json.length,
|
|
157
|
+
reductionPercent: 100 * (1 - frame.length / json.length)
|
|
158
|
+
}, null, 2));
|
|
159
|
+
} else usage(`Unknown command: ${command}`);
|
package/bundled/bundle.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
|
|
4
4
|
* See LICENSE for personal, non-commercial license terms.
|
|
5
5
|
*/
|
|
6
|
-
(()=>{"use strict";var __webpack_modules__={8(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.BatchHelper=void 0;const r=n(950),a=n(351);t.BatchHelper=class{batchInfo={};batchTimeouts={};batchedData={};conn;registerSendPackets(e,t){this.conn=t,e.getTags().forEach(t=>{const n=e.getPacket(t);if(0==n.dataBatching)return;const r=e.getKey(t);this.initiateBatch(r,n.dataBatching,n.gzipCompression)})}initiateBatch(e,t,n){this.batchedData[e]=[],this.batchInfo[e]=[t,n]}startBatch(e){const[t,n]=this.batchInfo[e];this.batchTimeouts[e]=this.conn.setInterval(()=>{if(0==this.batchedData[e].length)return;const t=(0,a.encodeNativeBatch)(this.batchedData[e],n);this.conn.raw_send((0,r.toPacketBuffer)(e,t)),this.batchedData[e]=[],delete this.batchTimeouts[e]},t)}batchPacket(e,t){this.batchedData[e].push(t),this.batchTimeouts[e]||this.startBatch(e)}static async unravelBatch(e,t,n){let r;try{r=(0,a.decodeNativeBatch)(t,e.gzipCompression,e.maxBatchSize)}catch(e){return"Invalid batch: "+e}const s=[];for(const t of r){const r=await e.listen(t,n);if("string"==typeof r)return"Batched packet: "+r;s.push(r)}return s}}},30(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.decompressBools=t.compressBools=t.EMPTY_UINT8=t.MAX_UVARINT=t.MAX_USHORT=t.MAX_BYTE=void 0,t.convertVarInt=function(e){if(!Number.isSafeInteger(e)||e<0||e>t.MAX_UVARINT)throw new Error(`Variable Ints must be within range 0 and ${t.MAX_UVARINT}: ${e}`);const n=[];do{let t=e%128;(e=Math.floor(e/128))>0&&(t|=128),n.push(t)}while(e>0);return n},t.readVarInt=function(e,t){let n=0,r=1;for(let a=0;a<8;a++){if(t>=e.length)throw new Error("Truncated variable integer");const a=e[t++];if(n+=(127&a)*r,!(128&a))return[t,n];r*=128}throw new Error("Variable integer is too long")},t.MAX_BYTE=255,t.MAX_USHORT=65535,t.MAX_UVARINT=128**7-1,t.EMPTY_UINT8=new Uint8Array([]);t.compressBools=e=>e.reduce((e,t,n)=>e|Number(t)<<7-n,0);t.decompressBools=e=>Array.from({length:8},(t,n)=>!!(e&1<<7-n))},72(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.decompressJSON=t.compressJSON=void 0;const r=n(950),a=e=>Array.from({length:8},(t,n)=>!!(e&1<<7-n));function s(e){if(!Number.isInteger(e)||e<0)throw new Error(`Invalid JSON variable integer: ${e}`);const t=[];do{let n=127&e;(e>>>=7)>0&&(n|=128),t.push(n)}while(e>0);return t}function i(e,t){let n=0,r=0;for(;;){if(t>=e.length||r>28)throw new Error("Invalid JSON variable integer");const a=e[t++];if(n+=(127&a)<<r,!(128&a))return[t,n];r+=7}}var o;!function(e){e[e.NULL=0]="NULL",e[e.BOOL=1]="BOOL",e[e.INT=2]="INT",e[e.FLOAT=3]="FLOAT",e[e.STRING=4]="STRING",e[e.ARRAY=5]="ARRAY",e[e.OBJECT=6]="OBJECT"}(o||(o={}));const c=e=>{const t=(new TextEncoder).encode(e);return[...s(t.length),...t]},d=(e,t)=>{const[n,r]=i(e,t);return{value:(new TextDecoder).decode(e.subarray(n,n+r)),length:n+r-t}},l=e=>{let t="";for(const n of e)t+=n.toString(2).padStart(3,"0");return(e=>new Uint8Array(e.match(/.{1,8}/g)?.map(e=>parseInt(e.padEnd(8,"0"),2))??[]))(t)},u=(e,t)=>{const n=(e=>Array.from(e,e=>e.toString(2).padStart(8,"0")).join(""))(e),r=[];for(let e=0;e<t;e++)r.push(parseInt(n.slice(3*e,3*e+3),2));return r};t.compressJSON=e=>{const t=[],n=[],a=[],i=e=>{switch(null===e?"null":Array.isArray(e)?"array":typeof e){case"null":a.push(o.NULL);break;case"boolean":a.push(o.BOOL),t.push(e);break;case"number":Number.isInteger(e)?(a.push(o.INT),n.push(...s((e=>e<<1^e>>31)(e)))):(a.push(o.FLOAT),n.push(...function(e){if(Number.isNaN(e))return[127,128,0,1];const t=e<0?1:0;if(0===(e=Math.abs(e)))return[0,0,0,0];const n=Math.floor(Math.log2(e));if(!Number.isFinite(e)||n>127||n<-126)return[t?255:127,128,0,0];const r=(t<<31|n+127<<23|8388607&Math.round((e/2**n-1)*2**23))>>>0;return[r>>>24,r>>>16&255,r>>>8&255,255&r]}(e)));break;case"string":a.push(o.STRING),n.push(...c(e));break;case"array":a.push(o.ARRAY),n.push(...s(e.length));for(const t of e)i(t);break;case"object":{a.push(o.OBJECT);const t=Object.keys(e);n.push(...s(t.length));for(const r of t)n.push(...c(r)),i(e[r]);break}default:throw new Error("Unsupported type")}};i(e);const d=t.length?(0,r.splitArray)(t,8).map(e=>e.reduce((e,t,n)=>e|Number(t)<<7-n,0)):[],u=l(a),h=[...s(d.length),...s(u.length)];return Uint8Array.from([...h,...d.flat(),...u,...n])};t.decompressJSON=e=>{let t=0;const[n,r]=i(e,t);t=n;const[s,c]=i(e,t);t=s;const l=[];for(let n=0;n<r;n++)l.push(...a(e[t++]));let h=0;const p=e.subarray(t,t+c);t+=c;const f=u(p,8*p.length/3);let w=0;const y=n=>{if(n>500)throw new Error("JSON array too deep.");const r=f[w++];switch(r){case o.NULL:return null;case o.BOOL:return l[h++];case o.INT:{const[n,r]=i(e,t);return t=n,(a=r)>>>1^-(1&a)}case o.FLOAT:{const n=function(e){const t=(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0,n=t>>>23&255,r=(0===n?0:1)+(8388607&t)/2**23,a=255===n?0===r?1/0:NaN:r*2**(0===n?-126:n-127);return t>>>31?-a:a}(Array.from(e.subarray(t,t+4)));return t+=4,n}case o.STRING:{const{value:n,length:r}=d(e,t);return t+=r,n}case o.ARRAY:{const[r,a]=i(e,t);t=r;const s=[];for(let e=0;e<a;e++)s.push(y(n+1));return s}case o.OBJECT:{const[r,a]=i(e,t);t=r;const s={};for(let r=0;r<a;r++){const{value:r,length:a}=d(e,t);t+=a,s[r]=y(n+1)}return s}default:throw new Error(`Unknown type ${r}`)}var a};return y(0)}},98(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.EnumPackage=t.TYPE_CONVERSION_MAP=void 0;const r=n(157),a=n(388),s={string:0,number:1,boolean:2,undefined:3,object:4};function i(e){const t=typeof e;if(!(t in s)&&null!=e)throw new Error(`Cannot serialize type "${t}" in an enum!`);return s[t]}t.TYPE_CONVERSION_MAP={0:e=>e,1:e=>parseFloat(e),2:e=>"true"==e,3:()=>{},4:()=>null};t.EnumPackage=class{tag;values;constructor(e,t){this.tag=e,this.values=t,this.wrap=this.wrap.bind(this)}serialize(){const e=(0,r.processCharCodes)(this.tag);return[this.tag.length,...e,this.values.length,...this.values.map(e=>[String(e).length,i(e),...(0,r.processCharCodes)(String(e))]).flat()]}wrap(e){return(0,a.WrapEnum)(this.tag,e)}}},102(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.PacketSchema=t.Packet=void 0;const r=n(388),a=n(98),s=n(30),i=n(433),o=n(619),c=n(157),d=n(351),l=n(72),u=n(179);class h{defaultEnabled;tag;maxSize;minSize;type;enumData;dataMax;dataMin;dataBatching;maxBatchSize;dontSpread;autoFlatten;fields;quantized;valueMin;valueMax;parent;variant;isParent;constructorName;replay;rateLimit;async;rereference;gzipCompression;object;client;processReceive;processSend;validate;customValidator;lastReceived={};lastSent={};quantizationErrors={};constructor(e,t,n,r,a){if(this.tag=e,this.defaultEnabled=r,this.client=a,this.async=t.async,this.enumData=t.enumData,this.rateLimit=t.rateLimit,this.dontSpread=t.dontSpread,this.autoFlatten=t.autoFlatten,this.rereference=t.rereference,this.dataBatching=t.dataBatching,this.maxBatchSize=a?1/0:t.maxBatchSize,this.gzipCompression=t.gzipCompression,this.fields=t.fields,this.quantized=t.quantized?{...t.quantized,trackError:t.quantized.trackError??!0}:void 0,this.valueMin=t.valueMin,this.valueMax=t.valueMax,this.parent=t.group?.parent,this.variant=t.group?.variant,this.isParent=t.group?.isParent??!1,this.constructorName=t.constructorName,this.replay=t.replay,this.object=t.object,this.type=t.type,this.dataMax=t.dataMax,this.dataMin=t.dataMin,t.testObject(this)){this.maxSize=this.minSize=this.type.length;for(let e=0;e<this.type.length;e++)this.type[e]==o.PacketType.NONE&&(this.dataMax[e]=this.dataMin[e]=0);const e={types:this.type,dataMins:this.dataMin,dataMaxes:this.dataMax,enumData:this.enumData};this.processReceive=t=>(0,d.decodeNativeObject)(e,t).map((e,t)=>this.type[t]===o.PacketType.JSON?(0,l.decompressJSON)(e):e),this.processSend=async t=>{let n=0;const r=t.map((e,t)=>{if(this.type[t]===o.PacketType.JSON)return(0,l.compressJSON)(e);if(this.type[t]!==o.PacketType.ENUMS)return e;const r=this.enumData[n++];return(Array.isArray(e)?e:[e]).map(e=>{if(!Number.isInteger(e)||e<0||e>=r.values.length)throw new Error(`Invalid wrapped enum index: ${e}`);return r.values[e]})});return(0,d.encodeNativeObject)(e,r)},this.validate=async t=>{(0,d.validateNativeObject)(e,t);return(0,d.decodeNativeObject)(e,t).forEach((e,t)=>{if(this.type[t]!==o.PacketType.JSON)return;const n=(0,l.decompressJSON)(e),r=Array.isArray(n)?n.length:1;if(r<this.dataMin[t]||r>this.dataMax[t])throw new Error("JSON value count is outside schema limits")}),[t,!0]}}else{{this.maxSize=this.dataMax,this.minSize=this.dataMin,this.type==o.PacketType.NONE&&(this.dataMax=this.dataMin=0);const e=this.enumData[0];this.processReceive=t=>this.type===o.PacketType.JSON?(0,l.decompressJSON)(t):(0,d.decodeNative)(this.type,t,this.dataMax,e),this.processSend=async t=>{let n;if(this.type===o.PacketType.JSON)n=(0,l.compressJSON)(t);else if(this.type===o.PacketType.ENUMS)n=Uint8Array.from(t);else{const r=this.type===o.PacketType.RAW&&1===t.length&&t[0]instanceof Uint8Array?t[0]:t;n=(0,d.encodeNative)(this.type,r,e)}return this.gzipCompression&&0===this.dataBatching?(0,d.deflateNative)(n):n},this.validate=async t=>{const n=this.gzipCompression&&0===this.dataBatching?(0,d.inflateNative)(t):t;if(this.type===o.PacketType.JSON){const e=(0,l.decompressJSON)(n),t=Array.isArray(e)?e.length:1;if(t<this.dataMin||t>this.dataMax)throw new Error("JSON value count is outside schema limits")}else(0,d.validateNative)(this.type,n,this.dataMin,this.dataMax,{enumData:e});return[n,!0]}}}this.customValidator=n}assertRecord(e,t){if(!this.fields)throw new Error(`Packet "${this.tag}" ${t} requires schema`);if(null===e||"object"!=typeof e||Array.isArray(e))throw new Error(`Packet "${this.tag}" ${t} requires an object record`);const n=this.fields.filter(t=>!Object.prototype.hasOwnProperty.call(e,t));if(n.length)throw new Error(`Packet "${this.tag}" is missing schema field(s): ${n.join(", ")}`);const r=Object.keys(e).filter(e=>!this.fields.includes(e));if(r.length)throw new Error(`Packet "${this.tag}" has unknown schema field(s): ${r.join(", ")}`);return this.fields.map(t=>e[t])}construct(e){return this.constructorName?new((0,u.resolvePacketConstructor)(this.constructorName))(e):e}logical(e,t,n=-1){const r=this.quantized?.scale;return e.map(e=>{if("number"!=typeof e||!Number.isFinite(e))throw new Error(`Packet "${this.tag}" ${t} value must be a finite number`);const a="receive"===t&&r?e/r:e;if(void 0!==this.valueMin&&a<this.valueMin)throw new Error(`Packet "${this.tag}" value ${a} is below minimum ${this.valueMin}`);if(void 0!==this.valueMax&&a>this.valueMax)throw new Error(`Packet "${this.tag}" value ${a} exceeds maximum ${this.valueMax}`);if("send"===t&&r){const e=a*r+(this.quantized?.trackError?this.quantizationErrors[n]??0:0),t=Math.round(e);return this.quantized?.trackError&&(this.quantizationErrors[n]=e-t),t}return a})}prepareSend(e,t=-1){if(this.object){if(this.autoFlatten&&this.fields){if(1!==e.length||!Array.isArray(e[0]))throw new Error(`Packet "${this.tag}" autoTranspose requires one array of records`);const t=e[0].map(e=>this.assertRecord(e,"autoTranspose"));return this.fields.map((e,n)=>t.map(e=>e[n]))}return e}let n=e;if(this.autoFlatten){if(1!==e.length||!Array.isArray(e[0]))throw new Error(`Packet "${this.tag}" autoFlatten requires one array of records`);if(n=e[0].flatMap(e=>this.assertRecord(e,"autoFlatten")),this.fields&&n.length%this.fields.length!==0)throw new Error(`Packet "${this.tag}" flat value count must be divisible by schema length ${this.fields.length}`)}else this.fields&&1===e.length&&null!==e[0]&&"object"==typeof e[0]&&!Array.isArray(e[0])&&(n=this.assertRecord(e[0],"schema mapping"));return this.quantized||void 0!==this.valueMin||void 0!==this.valueMax?this.logical(n,"send",t):n}clearQuantizationState(e){delete this.quantizationErrors[e]}finishReceive(e){if(this.object){if(this.autoFlatten&&this.fields){const t=e,n=t[0]?.length??0;if(t.some(e=>e.length!==n))throw new Error(`Packet "${this.tag}" autoTranspose columns have different lengths`);return Array.from({length:n},(e,n)=>this.construct(Object.fromEntries(this.fields.map((e,r)=>[e,t[r][n]]))))}return this.autoFlatten?(0,i.UnFlattenData)(e):e}let t=Array.isArray(e)?e:[e];if((this.quantized||void 0!==this.valueMin||void 0!==this.valueMax)&&(t=this.logical(t,"receive")),this.autoFlatten){const e=this.fields.length;if(t.length%e!==0)throw new Error(`Packet "${this.tag}" flat value count ${t.length} is not divisible by schema length ${e}`);return Array.from({length:t.length/e},(n,r)=>this.construct(Object.fromEntries(this.fields.map((n,a)=>[n,t[r*e+a]]))))}return this.fields?this.construct(Object.fromEntries(this.fields.map((e,n)=>[e,t[n]]))):e}async listen(e,t){try{const[n,r]=await this.validate(e);if(!this.client&&!1===r)return"Invalid packet";const a=this.processReceive(n,r),s=this.finishReceive(a);if(null!=this.customValidator)if(this.dontSpread||this.fields){if(!this.customValidator(t,s))return"Didn't pass custom validator"}else if(!this.customValidator(t,...s))return"Didn't pass custom validator";return[this.isParent?{variant:"",payload:s}:s,!this.isParent&&!this.fields&&!this.dontSpread]}catch(e){return console.error("There was an error processing the packet! This is probably my fault... report at https://github.com/liwybloc/sonic-ws",e),"Error: "+e}}serialize(){const e=(new TextEncoder).encode(JSON.stringify({schema:this.fields,quantized:this.quantized,min:this.valueMin,max:this.valueMax,group:void 0!==this.parent?{parent:this.parent,variant:this.variant??"",isParent:this.isParent}:void 0,constructor:this.constructorName,replay:this.replay||void 0})),t=[this.tag.length,...(0,c.processCharCodes)(this.tag),(0,s.compressBools)([this.dontSpread,this.async,this.object,this.autoFlatten,this.gzipCompression,this.rereference]),...(0,s.convertVarInt)(e.length),...e,this.dataBatching,this.enumData.length,...this.enumData.map(e=>e.serialize()).flat()];return this.object?[...t,this.maxSize,...this.dataMax.map(s.convertVarInt).flat(),...this.dataMin.map(s.convertVarInt).flat(),...this.type]:[...t,...(0,s.convertVarInt)(this.dataMax),...(0,s.convertVarInt)(this.dataMin),this.type]}static readVarInts(e,t,n){const r=[];for(let a=0;a<n;a++){const[n,a]=(0,s.readVarInt)(e,t);t=n,r.push(a)}return[r,t]}static deserialize(e,t,n){const i=t,d=e[t++],l=(0,c.as8String)(e.slice(t,t+=d)),[u,p,w,y,m,g]=(0,s.decompressBools)(e[t++]),[_,v]=(0,s.readVarInt)(e,t);t=_;const b=JSON.parse((new TextDecoder).decode(e.slice(t,t+=v))),k=Array.isArray(b.schema)?b.schema:void 0,E=b.quantized&&"number"==typeof b.quantized.scale?b.quantized:void 0,S="number"==typeof b.min?b.min:void 0,T="number"==typeof b.max?b.max:void 0,P=b.group&&"string"==typeof b.group.parent?b.group:void 0,N="string"==typeof b.constructor?b.constructor:void 0,O=e[t++],A=e[t++],M=[];for(let n=0;n<A;n++){const n=e[t++],s=(0,c.as8String)(e.slice(t,t+=n)),i=e[t++],o=[];for(let n=0;n<i;n++){const n=e[t++],r=e[t++],s=(0,c.as8String)(e.slice(t,t+=n));o.push(a.TYPE_CONVERSION_MAP[r](s))}M.push((0,r.DefineEnum)(s,o))}if(w){const r=e[t++],[a,s]=this.readVarInts(e,t,r);t=s;const[c,d]=this.readVarInts(e,t,r);t=d;const w=Array.from(e.slice(t,t+=r));let g=0;const _=w.map(e=>e==o.PacketType.ENUMS?M[g++]:e),v=new f(!0,_,p,c,a,-1,u,y,!1,O,-1,m,k,void 0,void 0,void 0,P,N,!0===b.replay);return[new h(l,v,null,!1,n),t-i]}const[x,R]=(0,s.readVarInt)(e,t);t=x;const[C,I]=(0,s.readVarInt)(e,t);t=C;const U=e[t++],L=U==o.PacketType.ENUMS?M[0]:U,B=new f(!1,L,p,I,R,-1,u,y,g,O,-1,m,k,E,S,T,P,N,!0===b.replay);return[new h(l,B,null,!1,n),t-i]}static deserializeAll(e,t){const n=[];let r=0;for(;r<e.length;){const[a,s]=this.deserialize(e,r,t);n.push(a),r+=s}return n}}t.Packet=h;const p=(e,t)=>e instanceof a.EnumPackage?(t.push(e),o.PacketType.ENUMS):e;class f{type;enumData=[];dataMax;dataMin;dataBatching;maxBatchSize;rateLimit;dontSpread=!1;autoFlatten=!1;async=!1;rereference=!1;gzipCompression=!1;object;fields;quantized;valueMin;valueMax;group;constructorName;replay;constructor(e,t,n,r,a,s,i,o,c,d,l,u,h,f,w,y,m,g,_=!1){this.object=e,this.async=n,this.dataMin=r,this.dataMax=a,this.rateLimit=s,this.dontSpread=i,this.autoFlatten=o,this.rereference=c,this.dataBatching=d,this.maxBatchSize=l,this.gzipCompression=u,this.fields=h?[...h]:void 0,this.quantized=f?{...f}:void 0,this.valueMin=w,this.valueMax=y,this.group=m?{...m}:void 0,this.constructorName=g,this.replay=_,this.type=e?t.map(e=>p(e,this.enumData)):p(t,this.enumData)}testObject(e){return this.object}}t.PacketSchema=f},157(e,t){function n(e){return String.fromCodePoint(...e)}Object.defineProperty(t,"__esModule",{value:!0}),t.processCharCodes=function(e){return Array.from(e,e=>e.codePointAt(0))},t.convertCharCodes=n,t.as8String=function(e){return n(Array.from(e))}},179(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.RegisterPacketConstructor=function(e){const t=e.name;if(!t)throw new Error("Packet constructors must have a stable class name");const r=n.get(t);if(r&&r!==e)throw new Error(`A different packet constructor named "${t}" is already registered`);return n.set(t,e),e},t.UnregisterPacketConstructor=function(e){n.delete(e)},t.resolvePacketConstructor=function(e){const t=n.get(e);if(!t)throw new Error(`Packet constructor "${e}" is not registered locally. Call RegisterPacketConstructor(${e}) before decoding.`);return t};const n=new Map},234(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.SERVER_SUFFIX_NUMS=t.SERVER_SUFFIX=t.VERSION=void 0;const r=n(157);t.VERSION=24,t.SERVER_SUFFIX="SWS",t.SERVER_SUFFIX_NUMS=(0,r.processCharCodes)(t.SERVER_SUFFIX)},351(__unused_webpack_module,exports,__webpack_require__){Object.defineProperty(exports,"__esModule",{value:!0}),exports.setNativeCore=setNativeCore,exports.initializeWasmCore=initializeWasmCore,exports.loadNativeCore=loadNativeCore,exports.encodeNative=encodeNative,exports.decodeNative=decodeNative,exports.validateNative=validateNative,exports.encodeNativeObject=encodeNativeObject,exports.decodeNativeObject=decodeNativeObject,exports.validateNativeObject=validateNativeObject,exports.encodeNativeBatch=encodeNativeBatch,exports.decodeNativeBatch=decodeNativeBatch,exports.deflateNative=deflateNative,exports.inflateNative=inflateNative;const PacketType_1=__webpack_require__(619),version_1=__webpack_require__(234),CDN_RELEASE="https://cdn.jsdelivr.net/gh/liwybloc/sonic-ws/release",CDN_WASM=`${CDN_RELEASE}/bundle.wasm`,CDN_VERSION=`${CDN_RELEASE}/version`;let loadedCore,wasmInitialization;function buffer(e){return"undefined"!=typeof Buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function values(e){return Array.isArray(e)?[...e]:[e]}function assertNativeCore(e){const t=["encodeSigned","decodeSigned","encodeUnsigned","decodeUnsigned","encodeFloats","decodeFloats","encodeStrings","decodeStrings","encodeBooleans","decodeBooleans","decodeRaw","encodeHex","decodeHex","frameObject","unframeObject","encodeBatch","decodeBatch","deflateRaw","inflateRaw","validateEncoded","validateEnum","validateObject"].filter(t=>"function"!=typeof e[t]);if(t.length>0)throw new Error(`Invalid SonicWS codec module; missing: ${t.join(", ")}`)}function setNativeCore(e){assertNativeCore(e),loadedCore=e}function fetchUrl(e){return"string"==typeof e?e:e instanceof URL?e.href:e.url}async function isWasm(e){if(!e.ok)return!1;const t=new Uint8Array(await e.clone().arrayBuffer());return t.length>=4&&0===t[0]&&97===t[1]&&115===t[2]&&109===t[3]}async function fetchCdnWasm(e){const t=await e(CDN_VERSION,{cache:"no-store"});if(!t.ok)throw new Error(`Unable to verify SonicWS CDN protocol version (${t.status})`);const n=Number((await t.text()).trim());if(!Number.isInteger(n)||n!==version_1.VERSION)throw new Error(`SonicWS CDN protocol mismatch: expected ${version_1.VERSION}, received ${String(n)}`);const r=await e(CDN_WASM);if(!await isWasm(r))throw new Error("SonicWS CDN returned an invalid WASM module");return r}async function initializeBrowserWasm(){const e=window.fetch.bind(window);window.fetch=async(t,n)=>{const r=fetchUrl(t);if(r===CDN_WASM||!new URL(r,window.location.href).pathname.endsWith("/bundle.wasm"))return e(t,n);try{const r=await e(t,n);if(await isWasm(r))return r}catch{}return fetchCdnWasm(e)};try{return setNativeCore(await Promise.resolve().then(__webpack_require__.bind(__webpack_require__,880))),loadedCore}finally{window.fetch=e}}function initializeWasmCore(){return loadedCore?Promise.resolve(loadedCore):wasmInitialization||(wasmInitialization=(async()=>{if("undefined"!=typeof window)return initializeBrowserWasm();const wasm=eval("require")("./wasm/node/sonic_ws_core.js");return setNativeCore(wasm),loadedCore})().finally(()=>{wasmInitialization=void 0}),wasmInitialization)}function loadNativeCore(){if(loadedCore)return loadedCore;if("undefined"!=typeof window)throw new Error("SonicWS codec is not initialized; await initializeWasmCore() in browsers.");try{const wasm=eval("require")("./wasm/node/sonic_ws_core.js");return assertNativeCore(wasm),loadedCore=wasm,wasm}catch(e){throw new Error(`Unable to load the packaged SonicWS Node WASM codec: ${e instanceof Error?e.message:String(e)}`)}}function enumIndex(e,t){const n=e.values.findIndex(e=>e===t||"number"==typeof e&&"number"==typeof t&&Number.isNaN(e)&&Number.isNaN(t));if(n<0)throw new Error(`Value ${String(t)} does not exist in enum ${e.tag}`);return n}function encodeNative(e,t,n,r=loadNativeCore()){switch(e){case PacketType_1.PacketType.NONE:if(null!=t&&(!Array.isArray(t)||0!==t.length))throw new TypeError("NONE only accepts null, undefined, or an empty array");return new Uint8Array(0);case PacketType_1.PacketType.RAW:case PacketType_1.PacketType.JSON:if(!(t instanceof Uint8Array||Array.isArray(t)))throw new TypeError((e===PacketType_1.PacketType.JSON?"JSON wire data":"RAW")+" requires a Uint8Array or number array");return t instanceof Uint8Array?buffer(t):Uint8Array.from(t);case PacketType_1.PacketType.BYTES:case PacketType_1.PacketType.SHORTS:case PacketType_1.PacketType.VARINT:case PacketType_1.PacketType.DELTAS:return r.encodeSigned(e,values(t));case PacketType_1.PacketType.UBYTES:case PacketType_1.PacketType.USHORTS:case PacketType_1.PacketType.UVARINT:return r.encodeUnsigned(e,values(t));case PacketType_1.PacketType.FLOATS:case PacketType_1.PacketType.DOUBLES:return r.encodeFloats(e,values(t));case PacketType_1.PacketType.STRINGS_ASCII:case PacketType_1.PacketType.STRINGS_UTF16:return r.encodeStrings(e,values(t));case PacketType_1.PacketType.BOOLEANS:return r.encodeBooleans(values(t));case PacketType_1.PacketType.HEX:{const e=Array.isArray(t)?t[0]:t;if("string"!=typeof e)throw new TypeError("HEX requires one string");return r.encodeHex(e)}case PacketType_1.PacketType.ENUMS:if(!n)throw new Error("ENUMS requires an EnumPackage");return Uint8Array.from(values(t).map(e=>enumIndex(n,e)));default:throw new Error(`Unknown packet type: ${e}`)}}function decodeNative(e,t,n=4294967295,r,a=loadNativeCore()){const s=buffer(t);switch(e){case PacketType_1.PacketType.NONE:if(0!==t.byteLength)throw new Error("NONE packet contains data");return;case PacketType_1.PacketType.RAW:case PacketType_1.PacketType.JSON:return a.decodeRaw(s);case PacketType_1.PacketType.BYTES:case PacketType_1.PacketType.SHORTS:case PacketType_1.PacketType.VARINT:case PacketType_1.PacketType.DELTAS:return a.decodeSigned(e,s);case PacketType_1.PacketType.UBYTES:case PacketType_1.PacketType.USHORTS:case PacketType_1.PacketType.UVARINT:return a.decodeUnsigned(e,s);case PacketType_1.PacketType.FLOATS:case PacketType_1.PacketType.DOUBLES:return a.decodeFloats(e,s);case PacketType_1.PacketType.STRINGS_ASCII:case PacketType_1.PacketType.STRINGS_UTF16:return a.decodeStrings(e,s);case PacketType_1.PacketType.BOOLEANS:return a.decodeBooleans(s,n);case PacketType_1.PacketType.HEX:return a.decodeHex(s);case PacketType_1.PacketType.ENUMS:if(!r)throw new Error("ENUMS requires an EnumPackage");return[...t].map(e=>{if(e>=r.values.length)throw new Error(`Enum index ${e} is out of range`);return r.values[e]});default:throw new Error(`Unknown packet type: ${e}`)}}function validateNative(e,t,n,r,a={},s=loadNativeCore()){if(e!==PacketType_1.PacketType.ENUMS)s.validateEncoded(e,buffer(t),n,r,a.compressed??!1,a.batched??!1,a.maxBatchSize);else{if(!a.enumData)throw new Error("ENUMS requires an EnumPackage");s.validateEnum(buffer(t),a.enumData.values.length,n,r)}}function encodeNativeObject(e,t,n=loadNativeCore()){if(t.length!==e.types.length)throw new Error("Object field count does not match schema");let r=0;const a=e.types.map((a,s)=>encodeNative(a,t[s],a===PacketType_1.PacketType.ENUMS?e.enumData?.[r++]:void 0,n));return n.frameObject(a)}function decodeNativeObject(e,t,n=loadNativeCore()){const r=n.unframeObject(buffer(t),e.types.length);let a=0;return r.map((t,r)=>decodeNative(e.types[r],t,e.dataMaxes[r],e.types[r]===PacketType_1.PacketType.ENUMS?e.enumData?.[a++]:void 0,n))}function validateNativeObject(e,t,n=loadNativeCore()){n.validateObject(buffer(t),[...e.types],[...e.dataMins],[...e.dataMaxes],(e.enumData??[]).map(e=>e.values.length))}function encodeNativeBatch(e,t,n=loadNativeCore()){return n.encodeBatch(e.map(buffer),t)}function decodeNativeBatch(e,t,n=0,r,a=loadNativeCore()){const s=Number.isFinite(n)&&n>0?n:0;return a.decodeBatch(buffer(e),t,s,r)}function deflateNative(e,t=loadNativeCore()){return t.deflateRaw(buffer(e))}function inflateNative(e,t,n=loadNativeCore()){return n.inflateRaw(buffer(e),t)}},388(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.SET_PACKAGES=t.ENUM_KEY_TO_TAG=t.ENUM_TAG_TO_KEY=t.MAX_ENUM_SIZE=void 0,t.DefineEnum=function(e,n){const r=t.SET_PACKAGES[e];if(r){if(r.values.find((e,t)=>n[t]!=e))throw new Error(`Pre-existing enum package of tag '${e}' is set and different!`);return r}if(n.length>t.MAX_ENUM_SIZE)throw new Error(`An enum can only hold ${t.MAX_ENUM_SIZE} possible values.`);return t.ENUM_TAG_TO_KEY[e]=Object.fromEntries(n.map((e,t)=>[e,t])),t.ENUM_KEY_TO_TAG[e]=Object.fromEntries(n.map((e,t)=>[t,e])),t.SET_PACKAGES[e]=new a.EnumPackage(e,n)},t.WrapEnum=function(e,n){if(!(n in t.ENUM_TAG_TO_KEY[e]))throw new Error(`Value "${n}" does not exist in enum "${e}"`);return t.ENUM_TAG_TO_KEY[e][n]},t.DeWrapEnum=function(e,n){return t.ENUM_KEY_TO_TAG[e][n]};const r=n(30),a=n(98);t.MAX_ENUM_SIZE=r.MAX_BYTE,t.ENUM_TAG_TO_KEY={},t.ENUM_KEY_TO_TAG={},t.SET_PACKAGES={}},404(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.PacketHolder=void 0;t.PacketHolder=class{key;keys;tags;packetMap;packets;variants={};parents=new Set;constructor(e){this.key=1,this.keys={},this.tags={},this.packetMap={},e&&this.holdPackets(e)}createKey(e){this.keys[e]=this.key,this.tags[this.key]=e,this.key++}holdPackets(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(e){if(!((e=this.resolveTag(e))in this.keys))throw new Error(`Not a valid tag: ${e}`);return this.keys[e]}getTag(e){if(e in this.tags)return this.tags[e]}getPacket(e){if(!((e=this.resolveTag(e))in this.packetMap))throw new Error("Unknown packet tag: "+e);return this.packetMap[e]}hasKey(e){return e in this.tags}hasTag(e){return this.resolveTag(e)in this.keys||this.parents.has(e)}resolveTag(e){return this.variants[e]??e}getVariantTag(e,t){const n=this.variants[`${e}.${t}`];if(!n)throw new Error(`Unknown packet variant: ${e}.${t}`);return n}getKeys(){return this.keys}getTagMap(){return this.tags}getTags(){return Object.values(this.tags)}getPackets(){return this.packets}serialize(){return this.packets.map(e=>e.serialize()).flat()}}},410(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.setHashFunc=function(e){i=e?a:s},t.hashValue=function(e){return i(e)};const n=1099511628211n,r=(1n<<64n)-1n,a=e=>{let t=14695981039346656037n;const a=e=>{if(null===e)return t^=0n,void(t=t*n&r);const s=typeof e;if("number"===s)return t^=BigInt(Math.trunc(e)),void(t=t*n&r);if("string"!==s){if("boolean"===s)return t^=e?1n:0n,void(t=t*n&r);if(Array.isArray(e))for(let t=0;t<e.length;t++)a(e[t]);else if("object"===s){const s=Object.keys(e).sort();for(let i=0;i<s.length;i++){const o=s[i];for(let e=0;e<o.length;e++)t^=BigInt(o.charCodeAt(e)),t=t*n&r;a(e[o])}}}else for(let a=0;a<e.length;a++)t^=BigInt(e.charCodeAt(a)),t=t*n&r};return a(e),t},s=e=>{let t=2166136261;const n=e=>{if(null===e)return void(t^=0);const r=typeof e;if("number"===r)return t^=0|e,void(t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24));if("string"!==r)if("boolean"!==r){if(Array.isArray(e))for(let t=0;t<e.length;t++)n(e[t]);else if("object"===r){const r=Object.keys(e).sort();for(let a=0;a<r.length;a++){const s=r[a];for(let e=0;e<s.length;e++)t^=s.charCodeAt(e),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);n(e[s])}}}else t^=e?1:0;else for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24)};return n(e),t>>>0};let i=a},433(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.processPacket=d,t.listenPacket=async function(e,t,n){if("string"==typeof e)return n(e);const[r,a]=e;try{if(a&&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),n(e)}},t.CreatePacket=w,t.CreateObjPacket=function(e){const t=Object.prototype.hasOwnProperty.call(e,"constructor")?e.constructor:void 0;let{tag:n,types:s=[],dataMaxes:i,dataMins:o,noDataRange:d=!1,dontSpread:w=!1,autoFlatten:m=!1,autoTranspose:g,schema:_,validator:v=null,dataBatching:b=0,maxBatchSize:k=10,rateLimit:E=0,enabled:S=!0,async:T=!1,gzipCompression:P=s&&s.includes(a.PacketType.JSON)}=e;if(!n)throw new Error("Tag not selected!");if(!s||0==s.length)throw new Error("Types is set to 0 length");if(e.replay&&b)throw new Error(`Packet "${n}" cannot combine replay with batching`);if(y(_,n),t&&!_)throw new Error(`Packet "${n}" constructor requires schema`);t&&(0,c.RegisterPacketConstructor)(t);if(_&&_.length!==s.length)throw new Error(`Packet "${n}" schema length must match types length`);if(void 0!==g&&m&&g!==m)throw new Error(`Packet "${n}" has conflicting autoFlatten and autoTranspose options`);const N=g??m;for(const e of s)if(l(e))throw new Error(`Invalid packet type in "${n}" packet: ${e}`);d?(i=Array.from({length:s.length}).map(()=>u),o=Array.from({length:s.length}).map(()=>0)):(null==i?i=Array.from({length:s.length}).map(()=>1):Array.isArray(i)||(i=Array.from({length:s.length}).map(()=>i)),null==o?o=Array.from({length:s.length}).map((e,t)=>i[t]):Array.isArray(o)||(o=Array.from({length:s.length}).map(()=>o)));const O=i.map(h),A=o.map((e,t)=>s[t]==a.PacketType.NONE?0:p(e,O[t])),M=new r.PacketSchema(!0,s,T,A,O,f(E),w,N,!1,b,k,P,_,void 0,void 0,void 0,void 0,t?.name,e.replay??!1);return new r.Packet(n,M,v,S,!1)},t.CreatePacketGroup=function(e){if(!e.tag||e.tag.includes("$"))throw new Error("Packet group tag is required and cannot contain '$'");const t=Object.entries(e.variants);if(!t.length)throw new Error(`Packet group "${e.tag}" requires at least one variant`);const n=w({tag:e.tag,type:a.PacketType.NONE,dataMin:0,dataMax:0,_group:{parent:e.tag,variant:"",isParent:!0}}),r=t.map(([t,n])=>{if(!t||t.includes("$"))throw new Error("Packet variant names cannot be empty or contain '$'");return w({...n,tag:`${e.tag}.${t}`,_group:{parent:e.tag,variant:t,isParent:!1}})});return[n,...r]},t.CreateEnumPacket=function(e){const{tag:t,enumData:n,dataMax:r=1,dataMin:a=0,noDataRange:s=!1,dontSpread:i=!1,validator:o=null,dataBatching:c=0,maxBatchSize:d=10,rateLimit:l=0,enabled:u=!0,async:h=!1}=e;return w({tag:t,type:n,dataMax:r,dataMin:a,noDataRange:s,dontSpread:i,validator:o,dataBatching:c,maxBatchSize:d,rateLimit:l,enabled:u,async:h})},t.FlattenData=g,t.UnFlattenData=function(e){return e[0]?.map((t,n)=>e.map(e=>e[n]))??[]};const r=n(102),a=n(619),s=n(98),i=n(30),o=n(410),c=n(179);async function d(e,t,n,r,s,c=!1){const l=e.getKey(t),u=e.getPacket(t);return async function(e,t,n,r,a,s,i){if(e[0]&&!s)return new Promise(t=>e[1].push([t,r,a]));e[0]=!0;const o=await i();if(e[1].length>0){const[r,a,s]=e[1].shift();queueMicrotask(async()=>{r(await d(t,a,s,e,n,!0))})}else e[0]=!1;return o}(r,e,s,t,n,c,async()=>{if(u.rereference){if(-1===s)throw new Error("Cannot send a re-referenced packet from the server-wide sender!");const e=(0,o.hashValue)(n);if(u.lastSent[s]===e)return[l,i.EMPTY_UINT8,u];u.lastSent[s]=e}if(n=u.prepareSend(n,s),u.autoFlatten&&u.object&&!u.fields)n=g(n[0]);else{if(n.length>u.maxSize)throw new Error(`Packet "${t}" only allows ${u.maxSize} values!`);if(n.length<u.minSize)throw new Error(`Packet "${t}" requires at least ${u.minSize} values!`)}if(u.object){if(n=n.map(e=>Array.isArray(e)?e:[e]),!u.autoFlatten){const e=u.dataMin,r=u.dataMax;for(let a=0;a<e.length;a++){if(n[a].length<e[a])throw new Error(`Section ${a+1} of packet "${t}" requires at least ${e[a]} values!`);if(n[a].length>r[a])throw new Error(`Section ${a+1} of packet "${t}" only allows ${r[a]} values!`)}}}else if(u.type!==a.PacketType.JSON){const e=n.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=n.length>0?await u.processSend(n):i.EMPTY_UINT8;return[l,e,u]})}function l(e){return!("number"==typeof e&&e in a.PacketType||e instanceof s.EnumPackage)}const u=2048383;function h(e){return e<0?(console.warn("Having a data maximum below 0 does not do anything!"),0):e>u?(console.warn("Only 2048383 values can be sent on a type! Uhh make an issue if you want to send more."),u):e}function p(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 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))>i.MAX_USHORT?(console.warn(`A rate limit above ${i.MAX_USHORT} is considered infinite.`),0):e}function w(e){const t=!0===e.autoFlatten&&void 0===e.dataMax&&void 0===e.dataMin,n=Object.prototype.hasOwnProperty.call(e,"constructor")?e.constructor:void 0;let{tag:s,type:i=a.PacketType.NONE,dataMax:o=1,dataMin:d,noDataRange:w=!1,dontSpread:g=!1,validator:_=null,dataBatching:v=0,maxBatchSize:b=10,rateLimit:k=0,enabled:E=!0,async:S=!1,gzipCompression:T=i==a.PacketType.JSON,rereference:P=!1,schema:N,autoFlatten:O=!1,quantized:A,min:M,max:x}=e;if(!s)throw new Error("Tag not selected!");if(w||t?(d=P?1:0,o=u):null==d&&(d=i==a.PacketType.NONE?0:o),P&&0==d)throw new Error("Rereference cannot be true if the dataMin is 0");if(e.replay&&v)throw new Error(`Packet "${s}" cannot combine replay with batching`);if(l(i))throw new Error(`Invalid packet type: ${i}`);if(y(N,s),n&&!N)throw new Error(`Packet "${s}" constructor requires schema`);if(n&&(0,c.RegisterPacketConstructor)(n),O&&(!N||0===N.length))throw new Error(`Packet "${s}" autoFlatten requires schema`);if(N&&!O&&d===o&&N.length!==o)throw new Error(`Packet "${s}" schema length must match its fixed value count (${o})`);!function(e,t,n,r,a){if(void 0!==n&&void 0!==r&&n>r)throw new Error(`Packet "${a}" min cannot exceed max`);if((t||void 0!==n||void 0!==r)&&!m.has(e))throw new Error(`Packet "${a}" numeric options require a numeric packet type`);if(t&&(!Number.isFinite(t.scale)||t.scale<=0))throw new Error(`Packet "${a}" quantization scale must be positive and finite`)}(i,A,M,x,s);const R=new r.PacketSchema(!1,i,S,p(d,o),h(o),f(k),g,O,P,v,b,T,N,A,M,x,e._group,n?.name,e.replay??!1);return new r.Packet(s,R,_,E,!1)}function y(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([a.PacketType.BYTES,a.PacketType.UBYTES,a.PacketType.SHORTS,a.PacketType.USHORTS,a.PacketType.VARINT,a.PacketType.UVARINT,a.PacketType.DELTAS,a.PacketType.FLOATS,a.PacketType.DOUBLES]);function g(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,n)=>e.map(e=>e[n]))??[]}},605(e,t,n){var r=n(804);e.exports=n.v(t,e.id,"12335afce5a51f21a152",{"./sonic_ws_core_bg.js":{__wbg_get_unchecked_6e0ad6d2a41b06f6:r.ss,__wbg_length_370319915dc99107:r.Sg,__wbg_push_d2ae3af0c1217ae6:r.Tb,__wbg_new_32b398fb48b6d94a:r.gV,__wbg_new_cd45aabdf6073e84:r.EW,__wbg_length_1f0964f4a5e2c6d8:r.Pt,__wbg_prototypesetcall_4770620bbe4688a0:r.pe,__wbg_new_from_slice_77cdfb7977362f3c:r.BV,__wbg___wbindgen_string_get_b0ca35b86a603356:r.oF,__wbg___wbindgen_number_get_394265ed1e1b84ee:r.JV,__wbg___wbindgen_throw_344f42d3211c4765:r.F6,__wbg___wbindgen_boolean_get_fa956cfa2d1bd751:r.sL,__wbindgen_init_externref_table:r.bL,__wbindgen_cast_0000000000000001:r.NR,__wbindgen_cast_0000000000000002:r.U_}})},619(e,t){var n;Object.defineProperty(t,"__esModule",{value:!0}),t.PacketType=void 0,function(e){e[e.NONE=0]="NONE",e[e.RAW=1]="RAW",e[e.STRINGS_ASCII=2]="STRINGS_ASCII",e[e.STRINGS_UTF16=3]="STRINGS_UTF16",e[e.STRINGS=2]="STRINGS",e[e.ENUMS=4]="ENUMS",e[e.BYTES=5]="BYTES",e[e.UBYTES=6]="UBYTES",e[e.SHORTS=7]="SHORTS",e[e.USHORTS=8]="USHORTS",e[e.VARINT=9]="VARINT",e[e.UVARINT=10]="UVARINT",e[e.DELTAS=11]="DELTAS",e[e.FLOATS=12]="FLOATS",e[e.DOUBLES=13]="DOUBLES",e[e.BOOLEANS=14]="BOOLEANS",e[e.JSON=16]="JSON",e[e.HEX=17]="HEX"}(n||(t.PacketType=n={}))},804(e,t,n){function r(e,t,n,r){const a=Z.decodeBatch(e,t,n,H(r)?Number.MAX_SAFE_INTEGER:r>>>0);if(a[2])throw Y(a[1]);return Y(a[0])}function a(e,t){const n=Z.decodeBooleans(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function s(e,t){const n=Z.decodeFloats(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function i(e){let t,n;try{const s=Z.decodeHex(e);var r=s[0],a=s[1];if(s[3])throw r=0,a=0,Y(s[2]);return t=r,n=a,F(r,a)}finally{Z.__wbindgen_free(t,n,1)}}function o(e){const t=Z.decodeRaw(e);if(t[2])throw Y(t[1]);return Y(t[0])}function c(e,t){const n=Z.decodeSigned(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function d(e,t){const n=Z.decodeStrings(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function l(e,t){const n=Z.decodeUnsigned(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function u(e){const t=Z.deflateRaw(e);if(t[2])throw Y(t[1]);return Y(t[0])}function h(e,t){const n=Z.encodeBatch(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function p(e){const t=Z.encodeBooleans(e);if(t[2])throw Y(t[1]);return Y(t[0])}function f(e,t){const n=Z.encodeFloats(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function w(e){const t=K(e,Z.__wbindgen_malloc,Z.__wbindgen_realloc),n=ee,r=Z.encodeHex(t,n);if(r[2])throw Y(r[1]);return Y(r[0])}function y(e,t){const n=Z.encodeSigned(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function m(e,t){const n=Z.encodeStrings(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function g(e,t){const n=Z.encodeUnsigned(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function _(e){const t=Z.frameObject(e);if(t[2])throw Y(t[1]);return Y(t[0])}function v(e,t){const n=Z.inflateRaw(e,H(t)?Number.MAX_SAFE_INTEGER:t>>>0);if(n[2])throw Y(n[1]);return Y(n[0])}function b(e,t){const n=Z.unframeObject(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function k(e,t,n,r,a,s,i){const o=Z.validateEncoded(e,t,n,r,a,s,H(i)?Number.MAX_SAFE_INTEGER:i>>>0);if(o[1])throw Y(o[0])}function E(e,t,n,r){const a=Z.validateEnum(e,t,n,r);if(a[1])throw Y(a[0])}function S(e,t,n,r,a){const s=Z.validateObject(e,t,n,r,a);if(s[1])throw Y(s[0])}function T(e){const t="boolean"==typeof e?e:void 0;return H(t)?16777215:t?1:0}function P(e,t){const n="number"==typeof t?t:void 0;q().setFloat64(e+8,H(n)?0:n,!0),q().setInt32(e+0,!H(n),!0)}function N(e,t){const n="string"==typeof t?t:void 0;var r=H(n)?0:K(n,Z.__wbindgen_malloc,Z.__wbindgen_realloc),a=ee;q().setInt32(e+4,a,!0),q().setInt32(e+0,r,!0)}function O(e,t){throw new Error(F(e,t))}function A(e,t){return e[t>>>0]}function M(e){return e.length}function x(e){return e.length}function R(){return new Array}function C(e){return new Uint8Array(e)}function I(e,t){return new Uint8Array($(e,t))}function U(e,t,n){Uint8Array.prototype.set.call($(e,t),n)}function L(e,t){return e.push(t)}function B(e){return e}function D(e,t){return F(e,t)}function j(){const e=Z.__wbindgen_externrefs,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)}function $(e,t){return e>>>=0,W().subarray(e/1,e/1+t)}n.d(t,{B4:()=>h,BV:()=>I,Dq:()=>o,EF:()=>i,EW:()=>C,F6:()=>O,JV:()=>P,NR:()=>B,Pt:()=>M,Q5:()=>S,Sg:()=>x,Tb:()=>L,Ts:()=>y,U_:()=>D,XC:()=>m,_s:()=>f,at:()=>u,bL:()=>j,cv:()=>b,gV:()=>R,hD:()=>k,i1:()=>E,i4:()=>s,iT:()=>p,iX:()=>a,jN:()=>r,lI:()=>te,mU:()=>w,mk:()=>l,nt:()=>_,oF:()=>N,pe:()=>U,qO:()=>g,sL:()=>T,ss:()=>A,tD:()=>c,wS:()=>v,zC:()=>d});let z=null;function q(){return(null===z||!0===z.buffer.detached||void 0===z.buffer.detached&&z.buffer!==Z.memory.buffer)&&(z=new DataView(Z.memory.buffer)),z}function F(e,t){return function(e,t){X+=t,X>=G&&(J=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),J.decode(),X=t);return J.decode(W().subarray(e,e+t))}(e>>>0,t)}let V=null;function W(){return null!==V&&0!==V.byteLength||(V=new Uint8Array(Z.memory.buffer)),V}function H(e){return null==e}function K(e,t,n){if(void 0===n){const n=Q.encode(e),r=t(n.length,1)>>>0;return W().subarray(r,r+n.length).set(n),ee=n.length,r}let r=e.length,a=t(r,1)>>>0;const s=W();let i=0;for(;i<r;i++){const t=e.charCodeAt(i);if(t>127)break;s[a+i]=t}if(i!==r){0!==i&&(e=e.slice(i)),a=n(a,r,r=i+3*e.length,1)>>>0;const t=W().subarray(a+i,a+r);i+=Q.encodeInto(e,t).written,a=n(a,r,i,1)>>>0}return ee=i,a}function Y(e){const t=Z.__wbindgen_externrefs.get(e);return Z.__externref_table_dealloc(e),t}let J=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});J.decode();const G=2146435072;let X=0;const Q=new TextEncoder;"encodeInto"in Q||(Q.encodeInto=function(e,t){const n=Q.encode(e);return t.set(n),{read:e.length,written:n.length}});let Z,ee=0;function te(e){Z=e}},853(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.DebugClient=void 0;t.DebugClient=class{host;constructor(e){this.host=e;const t=document.createElement("sonicws");t.innerHTML="<style>sws-h3{margin:0;color:#fff;font-size:16px;font-weight:600}#sonicws-container{display:flex;flex-direction:column;position:absolute;top:50px;left:50px;width:75vw;min-width:33vw;min-height:25vh;max-height:75vh;max-width:75vw;font-family:Arial,sans-serif;background-color:#2c2c2c;border-radius:10px;box-shadow:0 8px 20px rgba(0,0,0,.4);overflow:hidden;user-select:none;transition:box-shadow .2s ease;z-index:2147483647}#sonicws-container:hover{box-shadow:0 12px 28px rgba(0,0,0,.6)}#sonicws-header{display:flex;justify-content:space-between;align-items:center;cursor:move;background:linear-gradient(90deg,#4a90e2,#357ab7);padding:10px 12px;border-top-left-radius:10px;border-top-right-radius:10px}#sonicws-toggle{font-size:18px;font-weight:700;cursor:pointer;color:#fff;user-select:none}#sonicws-body{flex:1;display:flex;padding:12px;color:#e0e0e0;font-size:14px;min-height:0}#sonicws-stats{display:flex;flex-direction:column;min-width:140px}#sonicws-stats sws-p{margin:4px 0}#sonicws-packets{min-height:0;display:flex;flex-direction:column;flex:1;margin-left:10px;background-color:#1e1e1e;padding:8px;border-radius:8px;overflow-y:scroll}sws-div.packet{background-color:#2a2a2a;border-radius:6px;padding:3px 5px;margin-bottom:2px;cursor:pointer;transition:background .2s ease,transform .1s ease;display:flex;flex-direction:column}sws-div.packet:hover{background-color:#3a3a3a;transform:translateY(-1px)}sws-div.packet-header{display:flex;align-items:flex-start;flex-wrap:wrap;font-size:11px;white-space:normal;word-break:break-word}sws-span.packet-arrow{font-weight:700;margin-right:6px}sws-div.packet-details{margin-top:6px;font-size:10px;color:#aaa;display:none;flex-direction:column}sws-div.packet.expanded sws-div.packet-details{display:flex}#sonicws-resizer{width:12px;height:12px;background:#666;position:absolute;right:0;bottom:0;cursor:se-resize;border-bottom-right-radius:10px;transition:background .2s ease}#sonicws-resizer:hover{background:#888}#sonicws-container.minimized{width:auto!important;height:auto!important;min-width:unset;min-height:unset}#sonicws-container.minimized #sonicws-body,#sonicws-container.minimized #sonicws-resizer{display:none}#sonicws-container.minimized #sonicws-header{padding:8px 12px}#sonicws-container.minimized #sonicws-title{font-size:14px}</style><sws-div id=sonicws-container><sws-div id=sonicws-header><sws-h3 id=sonicws-title>SonicWS Debug Menu</sws-h3><sws-span id=sonicws-toggle>−</sws-span></sws-div><sws-div id=sonicws-body><sws-div id=sonicws-stats><sws-p>Status:<sws-span id=sonicws-status>Connecting</sws-span></sws-p><sws-p>Sent Packets:<sws-span id=sonicws-sent>0</sws-span></sws-p><sws-p>Received Packets:<sws-span id=sonicws-received>0</sws-span></sws-p><sws-p>Total Bytes Sent:<sws-span id=sonicws-sentbytes>0</sws-span></sws-p><sws-p>Total Bytes Received:<sws-span id=sonicws-receivedbytes>0</sws-span></sws-p><sws-p>Total Bytes Saved:<sws-span id=sonicws-savedbytes>0</sws-span></sws-p></sws-div><sws-div id=sonicws-packets></sws-div></sws-div><sws-div id=sonicws-resizer></sws-div></sws-div>",document.body?(document.body.appendChild(t),this._loadDebugScript()):document.addEventListener("DOMContentLoaded",()=>{document.body.appendChild(t),this._loadDebugScript()})}_evalInScope(e){const t=this.host;return new Function("send","WrapEnum","DeWrapEnum","FlattenData","UnFlattenData",`"use strict"; return (${e});`)(t.send.bind(t),t.WrapEnum.bind(t),t.DeWrapEnum.bind(t),t.FlattenData.bind(t),t.UnFlattenData.bind(t))}_loadDebugScript(){const e={},t={},n=this.host;this.host.addMiddleware(new class{onReceive_pre(e,n){t[e]??=[],t[e].push([n,performance.now()])}onReceive_post(e,r){const[a,s]=t[e].shift();T("received",`${e} (0x${n.serverPackets.getKey(e).toString(16).toUpperCase()})`,a,JSON.stringify(r),performance.now()-s)}onSend_pre(t,n){e[t]??=[],e[t].push([n,performance.now()])}onSend_post(t,r){const[a,s]=e[t].shift();T("sent",`${t} (0x${n.clientPackets.getKey(t).toString(16).toUpperCase()})`,r,JSON.stringify(a),performance.now()-s)}onStatusChange(e){E(e)}});const r=e=>document.getElementById(e),a=r("sonicws-container"),s=r("sonicws-header"),i=r("sonicws-resizer"),o=r("sonicws-status"),c=r("sonicws-packets"),d=r("sonicws-sent"),l=r("sonicws-received"),u=r("sonicws-sentbytes"),h=r("sonicws-receivedbytes"),p=r("sonicws-savedbytes"),f=document.getElementById("sonicws-toggle"),w=document.getElementById("sonicws-title");let y=!1;const m=document.createElement("input");m.type="text",m.placeholder='send("tag", 5)',m.style.marginTop="8px",m.style.width="100%",m.style.boxSizing="border-box";const g=document.createElement("button");function _(){const e=a.getBoundingClientRect(),t=window.innerWidth-e.width,n=window.innerHeight-e.height,r=Math.min(Math.max(0,e.left),Math.max(0,t)),s=Math.min(Math.max(0,e.top),Math.max(0,n));a.style.left=r+"px",a.style.top=s+"px"}g.innerText="Run",g.style.marginTop="4px",g.style.width="100%",r("sonicws-stats").appendChild(m),r("sonicws-stats").appendChild(g),g.addEventListener("click",()=>{try{this._evalInScope(m.value)}catch(e){console.error(e)}}),f.addEventListener("click",e=>{e.stopPropagation(),y=!y,y?(a.classList.add("minimized"),w.innerText="SWS",f.innerText="+",a.style.width="",a.style.height=""):(a.classList.remove("minimized"),w.innerText="SonicWS Debug Menu",f.innerText="−"),_()});const v={sentPackets:0,receivedPackets:0,totalBytesSent:0,totalBytesReceived:0,totalBytesSaved:0},b=new Proxy(v,{get(e,t){switch(t){case"sonicws-sent":return v.sentPackets;case"sonicws-received":return v.receivedPackets;case"sonicws-sentbytes":return v.totalBytesSent;case"sonicws-receivedbytes":return v.totalBytesReceived;case"sonicws-savedbytes":return v.totalBytesSaved;default:return}},set(e,t,n){switch(t){case"sonicws-sent":return v.sentPackets=n,d.innerText=n.toLocaleString(),!0;case"sonicws-received":return v.receivedPackets=n,l.innerText=n.toLocaleString(),!0;case"sonicws-sentbytes":{v.totalBytesSent=n;const{amt:e,unit:t}=k(n);return u.innerText=e+t,!0}case"sonicws-receivedbytes":{v.totalBytesReceived=n;const{amt:e,unit:t}=k(n);return h.innerText=e+t,!0}case"sonicws-savedbytes":{v.totalBytesSaved=n;const{amt:e,unit:t}=k(n);return p.innerText=e+t,!0}default:return!1}}}),k=e=>{if(!Number.isFinite(e)||e<0)return{amt:0,unit:"B"};const t=["B","KB","MB","GB","TB"];let n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return{amt:0==r?n.toString():n.toFixed(2),unit:t[r]}};function E(e){switch(e){case WebSocket.CLOSED:o.innerText="Closed",o.style.color="#f00";break;case WebSocket.CLOSING:o.innerText="Closing",o.style.color="#fa0";break;case WebSocket.OPEN:o.innerText="Open",o.style.color="#0f0";break;case WebSocket.CONNECTING:o.innerText="Connecting",o.style.color="#ff0";break;default:o.innerText="Unknown",o.style.color="#777"}}E(WebSocket.CONNECTING);const S=new TextEncoder;function T(e,t,n,r,a){const s=new Date,i=n.length+("sent"==e?1:0),o=S.encode(r).length-i+1,d=document.createElement("sws-div");d.classList.add("packet");const l=document.createElement("sws-div");l.classList.add("packet-header");const u=document.createElement("sws-span");u.classList.add("packet-arrow"),u.innerText="sent"===e?"⬆":"⬇",u.style.color="sent"===e?"#0f0":"#f00";const h=document.createElement("sws-span");h.innerText=t+": "+r,l.appendChild(u),l.appendChild(h);const p=document.createElement("sws-div");p.classList.add("packet-details"),p.innerHTML=`\n <sws-p> Raw Bytes: ${i}b (saved ~${o}b)</sws-p>\n <sws-p> Processed At: ${s.toISOString()} </sws-p>\n <sws-p> Processing Time: <sws-span class="processing-time" > ${a.toFixed(1)} </sws-span> ms</sws-p>\n `,d.appendChild(l),d.appendChild(p),c.append(d),l.addEventListener("click",()=>d.classList.toggle("expanded")),"sent"===e?(b["sonicws-sent"]++,b["sonicws-sentbytes"]+=i):(b["sonicws-received"]++,b["sonicws-receivedbytes"]+=i),b["sonicws-savedbytes"]+=o}let P=!1,N=0,O=0,A=0,M=0,x=!1,R=0,C=0,I=0,U=0;s.addEventListener("mousedown",e=>{P=!0,N=e.clientX,O=e.clientY;const t=a.getBoundingClientRect();A=t.left,M=t.top,e.preventDefault()}),i.addEventListener("mousedown",e=>{x=!0,R=e.clientX,C=e.clientY;const t=a.getBoundingClientRect();I=t.width,U=t.height,e.preventDefault()}),document.addEventListener("mousemove",e=>{P&&(a.style.left=A+e.clientX-N+"px",a.style.top=M+e.clientY-O+"px",_()),x&&!y&&(a.style.width=I+e.clientX-R+"px",a.style.height=U+e.clientY-C+"px",_())}),document.addEventListener("mouseup",()=>{P=!1,x=!1}),_(),window.addEventListener("resize",_)}}},880(e,t,n){n.a(e,async(e,r)=>{try{n.r(t),n.d(t,{decodeBatch:()=>s.jN,decodeBooleans:()=>s.iX,decodeFloats:()=>s.i4,decodeHex:()=>s.EF,decodeRaw:()=>s.Dq,decodeSigned:()=>s.tD,decodeStrings:()=>s.zC,decodeUnsigned:()=>s.mk,deflateRaw:()=>s.at,encodeBatch:()=>s.B4,encodeBooleans:()=>s.iT,encodeFloats:()=>s._s,encodeHex:()=>s.mU,encodeSigned:()=>s.Ts,encodeStrings:()=>s.XC,encodeUnsigned:()=>s.qO,frameObject:()=>s.nt,inflateRaw:()=>s.wS,unframeObject:()=>s.cv,validateEncoded:()=>s.hD,validateEnum:()=>s.i1,validateObject:()=>s.Q5});var a=n(605),s=n(804),i=e([a]);a=(i.then?(await i)():i)[0],(0,s.lI)(a),a.__wbindgen_start(),r()}catch(e){r(e)}})},913(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.CloseCodes=t.Connection=void 0,t.getClosureCause=function(e){if(e>=4e3)return i[e]??"UNKNOWN";switch(e){case 1e3:return"NORMAL_CLOSURE";case 1001:return"GOING_AWAY";case 1002:return"PROTOCOL_ERROR";case 1003:return"UNSUPPORTED_DATA";case 1006:return"ABNORMAL_CLOSURE";default:return"UNKNOWN"}};const r=n(985),a=n(8);class s extends r.MiddlewareHolder{listeners;rawSendListeners=[];name;closed=!1;socket;_timers={};batcher;_on;_off;id;state={};constructor(e,t,n,r,s){super(),this.id=t,this.listeners={},this.name=n,this.socket=e,this.batcher=new a.BatchHelper,this._on=r,this._off=s,this._on("close",()=>{this.callMiddleware("onStatusChange",WebSocket.CLOSED),this.closed=!0;for(const[e,t,n]of Object.values(this._timers))this.clearTimeout(e),n&&t(!0)}),this._on("open",()=>this.callMiddleware("onStatusChange",WebSocket.OPEN))}replaceTransport(e,t,n){this.socket=e,this._on=t,this._off=n,this.closed=!1,this._on("close",()=>{this.callMiddleware("onStatusChange",WebSocket.CLOSED),this.closed=!0}),this._on("open",()=>this.callMiddleware("onStatusChange",WebSocket.OPEN))}setTimeout(e,t,n=!1){const r=setTimeout(()=>{e(),this.clearTimeout(r)},t);return this._timers[r]=[r,e,n],r}setInterval(e,t,n=!1){const r=setInterval(e,t);return this._timers[r]=[r,e,n],r}clearTimeout(e){clearTimeout(e),delete this._timers[e]}clearInterval(e){this.clearTimeout(e)}raw_send(e){this.socket.send(e);for(const t of this.rawSendListeners)t(e)}raw_onmessage(e){this._on("message",e)}raw_onsend(e){this.rawSendListeners.push(e)}close(e=1e3,t){this.closed=!0,this.socket.close(e,t?.toString())}isClosed(){return this.closed||this.socket.readyState==WebSocket.CLOSED}async setName(e){await this.callMiddleware("onNameChange",e)||(this.name=e)}getName(){return this.name}}var i;t.Connection=s,function(e){e[e.RATELIMIT=4e3]="RATELIMIT",e[e.SMALL=4001]="SMALL",e[e.INVALID_KEY=4002]="INVALID_KEY",e[e.INVALID_PACKET=4003]="INVALID_PACKET",e[e.INVALID_DATA=4004]="INVALID_DATA",e[e.REPEATED_HANDSHAKE=4005]="REPEATED_HANDSHAKE",e[e.DISABLED_PACKET=4006]="DISABLED_PACKET",e[e.MIDDLEWARE=4007]="MIDDLEWARE",e[e.MANUAL_SHUTDOWN=4008]="MANUAL_SHUTDOWN"}(i||(t.CloseCodes=i={}))},917(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.encodeResumed=t.encodeReplay=t.ControlType=t.CONTROL_KEY=void 0,t.encodeControlRequest=function(e,n,a){return Uint8Array.from([t.CONTROL_KEY,s.REQUEST,...(0,r.convertVarInt)(e),n,...a])},t.encodeControlResponse=function(e,n,i){return Uint8Array.from([t.CONTROL_KEY,s.RESPONSE,...(0,r.convertVarInt)(e),Number(n),...(0,a.compressJSON)(i)])},t.encodeResume=function(e,n){const a=(new TextEncoder).encode(e);return Uint8Array.from([t.CONTROL_KEY,s.RESUME,...(0,r.convertVarInt)(a.length),...a,...(0,r.convertVarInt)(n)])},t.decodeControl=function(e){if(e[0]!==t.CONTROL_KEY||e.length<3)throw new Error("Invalid SonicWS control frame");const n=e[1];switch(n){case s.REPLAY:{const[t,a]=(0,r.readVarInt)(e,2);return{type:n,sequence:a,payload:e.slice(t)}}case s.RESUME:{const[t,a]=(0,r.readVarInt)(e,2),s=t+a;if(s>e.length)throw new Error("Recovery frame has an invalid session id");const[i,o]=(0,r.readVarInt)(e,s);return{type:n,sessionId:(new TextDecoder).decode(e.slice(t,s)),lastSequence:o}}case s.RESUMED:{if(e.length<4)throw new Error("Invalid recovery result frame");const[t,a]=(0,r.readVarInt)(e,3);return{type:n,recovered:0!==e[2],replayed:a}}case s.REQUEST:{const[t,a]=(0,r.readVarInt)(e,2);if(t>=e.length)throw new Error("RPC request is missing its packet key");return{type:n,id:a,packetKey:e[t],payload:e.slice(t+1)}}case s.RESPONSE:{const[t,s]=(0,r.readVarInt)(e,2);if(t>=e.length)throw new Error("RPC response is missing its status");return{type:n,id:s,ok:0!==e[t],value:(0,a.decompressJSON)(e.slice(t+1))}}default:throw new Error(`Unknown SonicWS control frame type: ${n}`)}};const r=n(30),a=n(72);var s;t.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"}(s||(t.ControlType=s={}));t.encodeReplay=(e,n)=>Uint8Array.from([t.CONTROL_KEY,s.REPLAY,...(0,r.convertVarInt)(e),...n]);t.encodeResumed=(e,n)=>Uint8Array.from([t.CONTROL_KEY,s.RESUMED,Number(e),...(0,r.convertVarInt)(n)])},937(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.SonicWSCore=void 0;const r=n(404),a=n(30),s=n(351),i=n(433),o=n(234),c=n(102),d=n(8),l=n(950),u=n(913),h=n(157),p=n(917);class f extends u.Connection{preListen;clientPackets=new r.PacketHolder;serverPackets=new r.PacketHolder;pastKeys=!1;readyListeners=[];bufferHandler;_timers={};asyncData={};asyncMap={};reconnectFactory;reconnectOptions={enabled:!1,attempts:1/0,minDelayMs:500,maxDelayMs:1e4,jitter:.25};reconnectAttempt=0;reconnectTimer;intentionalClose=!1;connectedOnce=!1;reconnectingListeners=[];reconnectListeners=[];reconnectFailedListeners=[];nextRequestId=1;pendingRequests=new Map;responders=new Map;sessionId;lastReplaySequence=0;recoveredListeners=[];pendingResumeSession;constructor(e,t,n,r){super(e,-1,"LocalSocket",n,r),this.socket=e,this.preListen={},this.invalidPacket=this.invalidPacket.bind(this),this.serverKeyHandler=this.serverKeyHandler.bind(this),this.messageHandler=this.messageHandler.bind(this),this.attachClientTransport(),this.bufferHandler=t}configureReconnect(e,t={}){if(this.reconnectFactory=e,this.reconnectOptions={enabled:t.enabled??!0,attempts:t.attempts??1/0,minDelayMs:t.minDelayMs??500,maxDelayMs:t.maxDelayMs??1e4,jitter:t.jitter??.25},this.reconnectOptions.attempts<0||this.reconnectOptions.minDelayMs<0||this.reconnectOptions.maxDelayMs<this.reconnectOptions.minDelayMs)throw new Error("Invalid reconnect timing options");if(this.reconnectOptions.jitter<0||this.reconnectOptions.jitter>1)throw new Error("Reconnect jitter must be between 0 and 1")}attachClientTransport(){this._on("message",this.serverKeyHandler),this._on("close",(...e)=>{for(const[e,t,n]of Object.values(this._timers))this.clearTimeout(e),n&&t(!0);for(const e of this.clientPackets.getPackets())delete e.lastSent[0],e.clearQuantizationState(0);for(const e of this.serverPackets.getPackets())delete e.lastReceived[0];const t=e[0],n="number"==typeof t?t:t?.code;this.intentionalClose||1e3===n||this.scheduleReconnect()})}scheduleReconnect(){if(!this.reconnectFactory||!this.reconnectOptions.enabled||this.reconnectTimer)return;if(this.reconnectAttempt>=this.reconnectOptions.attempts)return void this.reconnectFailedListeners.forEach(e=>e());const e=++this.reconnectAttempt,t=Math.min(this.reconnectOptions.maxDelayMs,this.reconnectOptions.minDelayMs*2**(e-1)),n=t*this.reconnectOptions.jitter,r=Math.max(0,Math.round(t-n+Math.random()*n*2));this.reconnectingListeners.forEach(t=>t({attempt:e,delayMs:r})),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.beginReconnect()},r)}beginReconnect(){try{const e=this.reconnectFactory();this.clientPackets=new r.PacketHolder,this.serverPackets=new r.PacketHolder,this.asyncData={},this.asyncMap={},this.reading=!1,this.readQueue=[],this.pastKeys=!1,this.preListen={},this.bufferHandler=e.bufferHandler,this.batcher=new d.BatchHelper,this.replaceTransport(e.socket,e.on,e.off),this.attachClientTransport()}catch{this.scheduleReconnect()}}reading=!1;readQueue=[];async serverKeyHandler(e){if(this.reading)return this.readQueue.push(e);this.reading=!0;const t=await this.bufferHandler(e);if(t.length<3||(0,h.as8String)(t.slice(0,3))!=o.SERVER_SUFFIX)throw this.close(1e3),new Error("The server requested is not a Sonic WS server.");const n=t[3];if(n!=o.VERSION)throw this.close(1e3),new Error(`Version mismatch: ${n>o.VERSION?"client":"server"} is outdated (server: ${n}, client: ${o.VERSION})`);const r=(0,s.inflateNative)(t.subarray(4,t.length)),i=this.sessionId,[d,l]=(0,a.readVarInt)(r,0);this.id=l;const[u,f]=(0,a.readVarInt)(r,d);this.sessionId=(new TextDecoder).decode(r.slice(u,u+f));const[w,y]=(0,a.readVarInt)(r,u+f),m=r.subarray(w,w+y);this.clientPackets.holdPackets(c.Packet.deserializeAll(m,!0));const g=r.subarray(w+y,r.length);this.serverPackets.holdPackets(c.Packet.deserializeAll(g,!0)),this.batcher.registerSendPackets(this.clientPackets,this);for(const e of this.serverPackets.getPackets()){const t=this.serverPackets.getKey(e.tag);this.asyncMap[t]=e.async,e.async&&(this.asyncData[t]=[!1,[]])}Object.keys(this.preListen??{}).forEach(e=>this.preListen[e].forEach(t=>{if(!this.serverPackets.hasTag(e))return console.error(new Error(`The server does not send the packet with tag "${e}"!`));this.listen(e,t)})),this.preListen=null,this.pastKeys=!0,this.connectedOnce&&(this.reconnectAttempt=0,this.reconnectListeners.forEach(e=>e())),this.connectedOnce=!0,this.readyListeners?.forEach(e=>e()),this.readyListeners=null,this._off("message",this.serverKeyHandler),this._on("message",this.messageHandler),i&&i!==this.sessionId&&(this.pendingResumeSession=i,this.raw_send((0,p.encodeResume)(i,this.lastReplaySequence))),this.readQueue.forEach(e=>this.messageHandler(e)),this.readQueue=[]}invalidPacket(e){throw console.error(e),new Error("An error occured with data from the server!! This is probably my fault.. make an issue at https://github.com/liwybloc/sonic-ws")}listenLock=!1;packetQueue=[];async listenPacket(e,t,n,r,a){const s=this.listeners[t],o=this.serverPackets.getPacket(t),c=o.parent?this.listeners[o.parent]:void 0;if(!s&&!c)return console.warn("Warn: No listener for packet "+t),void await this.triggerNextPacket(n,r,a);if(s&&await(0,i.listenPacket)(e,s,this.invalidPacket),"string"!=typeof e&&o.parent&&o.variant)for(const t of c??[])await t({variant:o.variant,payload:e[0]});await this.triggerNextPacket(n,r,a),await this.callMiddleware("onReceive_post",t,"string"==typeof e?[e]:e[0])}isAsync(e){return this.asyncMap[e]}async enqueuePacket(e,t,n,r,a){await(0,i.listenPacket)(e,t,this.invalidPacket),await this.triggerNextPacket(n,r,a)}async triggerNextPacket(e,t,n){t?n[0]=!1:this.listenLock=!1,e.length>0&&this.dataHandler(e.shift())}async dataHandler(e){if(0===e[0])return this.handleControl(e);const t=e[0],n=e.slice(1),r=this.isAsync(t);let a,s,i;if(r?(i=this.asyncData[t],a=i[0],s=i[1]):(a=this.listenLock,s=this.packetQueue),a)return void s.push(e);r?i[0]=!0:this.listenLock=!0;const o=this.serverPackets.getTag(t),c=this.serverPackets.getPacket(o);if(await this.callMiddleware("onReceive_pre",c.tag,e,e.length))return;if(c.rereference&&0==n.length)return void 0===c.lastReceived[0]?this.invalidPacket("No previous value to rereference"):void this.listenPacket(c.lastReceived[0],o,s,r,i);if(0==c.dataBatching){const e=c.lastReceived[0]=await c.listen(n,null);return void this.listenPacket(e,o,s,r,i)}const l=await d.BatchHelper.unravelBatch(c,n,null);if("string"==typeof l)return this.invalidPacket(l);l.forEach(e=>this.listenPacket(e,o,s,r,i))}async handleControl(e){const t=(0,p.decodeControl)(e);if(t.type===p.ControlType.REPLAY){if(t.sequence<=this.lastReplaySequence)return;return this.lastReplaySequence=t.sequence,void await this.dataHandler(t.payload)}if(t.type===p.ControlType.RESUMED)return t.recovered&&this.pendingResumeSession&&(this.sessionId=this.pendingResumeSession),this.pendingResumeSession=void 0,this.recoveredListeners.forEach(e=>e({recovered:t.recovered,replayed:t.replayed})),void(t.recovered||(this.lastReplaySequence=0));if(t.type===p.ControlType.RESUME)throw new Error("A client cannot receive a recovery request");if(t.type===p.ControlType.RESPONSE){const e=this.pendingRequests.get(t.id);if(!e)return;return clearTimeout(e.timer),this.pendingRequests.delete(t.id),void(t.ok?e.resolve(t.value):e.reject(new Error(String(t.value))))}try{const e=this.serverPackets.getTag(t.packetKey);if(!e)throw new Error(`Unknown RPC packet key ${t.packetKey}`);const n=this.responders.get(e);if(!n)throw new Error(`No responder registered for packet "${e}"`);const r=await this.serverPackets.getPacket(e).listen(t.payload,null);if("string"==typeof r)throw new Error(r);const[a,s]=r,i=s?await n(...a):await n(a);this.raw_send((0,p.encodeControlResponse)(t.id,!0,i??null))}catch(e){this.raw_send((0,p.encodeControlResponse)(t.id,!1,e instanceof Error?e.message:String(e)))}}async messageHandler(e){const t=await this.bufferHandler(e);t.length<1||await this.dataHandler(t)}listen(e,t){if(!this.serverPackets.hasTag(e))return void console.log("Tag is not available on server: "+e);const n=this.serverPackets.resolveTag(e);(this.listeners[n]??=[]).push(t)}sendQueue=[!1,[],void 0];async send(e,...t){if(await this.callMiddleware("onSend_pre",e,t,Date.now(),performance.now()))return;const[n,r,a]=await(0,i.processPacket)(this.clientPackets,e,t,this.sendQueue,0);0==a.dataBatching?this.raw_send((0,l.toPacketBuffer)(n,r)):this.batcher.batchPacket(n,r),await this.callMiddleware("onSend_post",e,r,r.length)}sendVariant(e,t,...n){return this.send(this.clientPackets.getVariantTag(e,t),...n)}async request(e,...t){const n=t.at(-1),r=t.length>1&&n&&"object"==typeof n&&!Array.isArray(n)&&Object.keys(n).every(e=>"timeoutMs"===e)?t.pop():{},[a,s]=await(0,i.processPacket)(this.clientPackets,e,t,this.sendQueue,0),o=this.nextRequestId++;return this.nextRequestId>2147483647&&(this.nextRequestId=1),new Promise((t,n)=>{const i=setTimeout(()=>{this.pendingRequests.delete(o),n(new Error(`RPC request "${e}" timed out`))},r.timeoutMs??5e3);this.pendingRequests.set(o,{resolve:t,reject:n,timer:i}),this.raw_send((0,p.encodeControlRequest)(o,a,s))})}respond(e,t){const n=this.serverPackets.resolveTag(e);this.responders.set(n,t)}async sendSafe(e,...t){try{return await this.send(e,...t),!0}catch(t){return console.error(`Failed to send packet "${e}"`,t),!1}}on_ready(e){this.pastKeys?e():(this.readyListeners??=[]).push(e)}on_close(e){this._on("close",e)}on_reconnecting(e){this.reconnectingListeners.push(e)}on_reconnect(e){this.reconnectListeners.push(e)}on_reconnect_failed(e){this.reconnectFailedListeners.push(e)}on_recovered(e){this.recoveredListeners.push(e)}close(e=1e3,t){this.intentionalClose=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),super.close(e,t)}on(e,t){if(this.socket.readyState!==WebSocket.OPEN){const n=this.preListen??={};return n[e]||(n[e]=[]),void n[e].push(t)}this.listen(e,t)}}t.SonicWSCore=f},950(e,t){function n(e,t){const n=[];for(let r=0;r<e.length;r+=t){const a=e.slice(r,r+t);n.push(a)}return n}Object.defineProperty(t,"__esModule",{value:!0}),t.splitArray=n,t.toPacketBuffer=function(e,t){const n=new Uint8Array(1+t.length);return n[0]=e,n.set(t,1),n},t.splitBuffer=function(e,t){return n(Array.from(e),t)},t.stringifyBuffer=function(e){return`<Buffer ${Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(" ")}>`}},985(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MiddlewareHolder=void 0;t.MiddlewareHolder=class{middlewares=[];addMiddleware(e){this.middlewares.push(e);const t=e;try{"function"==typeof t.init&&t.init(this)}catch(e){console.warn("Middleware init threw an error:",e)}}async callMiddleware(e,...t){let n=!1;for(const r of this.middlewares){const a=r[e];if(a)try{await a(...t)&&(n=!0)}catch(t){console.warn(`Middleware ${String(e)} threw an error:`,t)}}return n}}}},__webpack_module_cache__={},hasSymbol,webpackQueues,webpackExports,webpackError,resolveQueue;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={id:e,exports:{}};return __webpack_modules__[e](n,n.exports,__webpack_require__),n.exports}hasSymbol="function"==typeof Symbol,webpackQueues=hasSymbol?Symbol("webpack queues"):"__webpack_queues__",webpackExports=hasSymbol?Symbol("webpack exports"):"__webpack_exports__",webpackError=hasSymbol?Symbol("webpack error"):"__webpack_error__",resolveQueue=e=>{e&&e.d<1&&(e.d=1,e.forEach(e=>e.r--),e.forEach(e=>e.r--?e.r++:e()))},__webpack_require__.a=(e,t,n)=>{var r;n&&((r=[]).d=-1);var a,s,i,o=new Set,c=e.exports,d=new Promise((e,t)=>{i=t,s=e});d[webpackExports]=c,d[webpackQueues]=e=>(r&&e(r),o.forEach(e),d.catch(e=>{})),e.exports=d,t(e=>{var t;a=(e=>e.map(e=>{if(null!==e&&"object"==typeof e){if(e[webpackQueues])return e;if(e.then){var t=[];t.d=0,e.then(e=>{n[webpackExports]=e,resolveQueue(t)},e=>{n[webpackError]=e,resolveQueue(t)});var n={};return n[webpackQueues]=e=>e(t),n}}var r={};return r[webpackQueues]=e=>{},r[webpackExports]=e,r}))(e);var n=()=>a.map(e=>{if(e[webpackError])throw e[webpackError];return e[webpackExports]}),s=new Promise(e=>{(t=()=>e(n)).r=0;var s=e=>e!==r&&!o.has(e)&&(o.add(e),e&&!e.d&&(t.r++,e.push(t)));a.map(e=>e[webpackQueues](s))});return t.r?s:n()},e=>(e?i(d[webpackError]=e):s(c),resolveQueue(r))),r&&r.d<0&&(r.d=0)},__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},__webpack_require__.v=(e,t,n,r)=>{var a=fetch(__webpack_require__.p+"bundle.wasm"),s=()=>a.then(e=>e.arrayBuffer()).then(e=>WebAssembly.instantiate(e,r)).then(t=>Object.assign(e,t.instance.exports));return a.then(t=>"function"==typeof WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(t,r).then(t=>Object.assign(e,t.instance.exports),e=>{if("application/wasm"!==t.headers.get("Content-Type"))return console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",e),s();throw e}):s())},(()=>{var e;__webpack_require__.g.importScripts&&(e=__webpack_require__.g.location+"");var t=__webpack_require__.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var n=t.getElementsByTagName("script");if(n.length)for(var r=n.length-1;r>-1&&(!e||!/^http(s?):/.test(e));)e=n[r--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),__webpack_require__.p=e})();var __webpack_exports__={};(()=>{const e=__webpack_require__(853),t=__webpack_require__(388),n=__webpack_require__(433),r=__webpack_require__(937),a=__webpack_require__(351);class s extends r.SonicWSCore{static initialize(){return(0,a.initializeWasmCore)()}static async connect(e,t={}){await s.initialize();const n=new s(e,t.protocols,t.antiTamper??!1,t.reconnect);return await new Promise((e,t)=>{n.on_ready(e),n.on_close(e=>t(new Error(`SonicWS connection closed before ready (${e.code})`)))}),n}antiTamperCall=()=>{};constructor(e,t,n=!1,r){const a=new WebSocket(e,t);if(super(a,async e=>new Uint8Array(await e.data.arrayBuffer()),a.addEventListener.bind(a),a.removeEventListener.bind(a)),r?.enabled){if(n)throw new Error("Reconnect and antiTamper cannot currently be enabled together");this.configureReconnect(()=>{const n=new WebSocket(e,t);return{socket:n,bufferHandler:async e=>new Uint8Array(await e.data.arrayBuffer()),on:n.addEventListener.bind(n),off:n.removeEventListener.bind(n)}},r)}if(n){const e=this,t=a.send.bind(a),n=this.send.bind(this);let r;this.send=async(t,...a)=>(r=e.clientPackets.getKey(t),await n(t,...a)),a.send=n=>n instanceof Uint8Array&&r==n[0]?t(n):(e.antiTamperCall(),void e.close())}}on_tamper(e){this.antiTamperCall=e}WrapEnum(e,n){return(0,t.WrapEnum)(e,n)}DeWrapEnum(e,n){return(0,t.DeWrapEnum)(e,n)}FlattenData(e){return(0,n.FlattenData)(e)}UnFlattenData(e){return(0,n.UnFlattenData)(e)}debugClient=null;OpenDebug(){if(null!=this.debugClient)throw new Error("Debug client has already been opened!");this.debugClient=new e.DebugClient(this)}}window.SonicWS=s})()})();
|
|
6
|
+
(()=>{"use strict";var __webpack_modules__={8(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.BatchHelper=void 0;const r=n(950),a=n(351);t.BatchHelper=class{batchInfo={};batchTimeouts={};batchedData={};conn;registerSendPackets(e,t){this.conn=t,e.getTags().forEach(t=>{const n=e.getPacket(t);if(0===n.dataBatching)return;const r=e.getKey(t);this.initiateBatch(r,n.dataBatching,n.gzipCompression)})}initiateBatch(e,t,n){this.batchedData[e]=[],this.batchInfo[e]=[t,n]}startBatch(e){const[t,n]=this.batchInfo[e];this.batchTimeouts[e]=this.conn.setInterval(()=>{if(0===this.batchedData[e].length)return;const t=(0,a.encodeNativeBatch)(this.batchedData[e],n);this.conn.raw_send((0,r.toPacketBuffer)(e,t)),this.batchedData[e]=[],delete this.batchTimeouts[e]},t)}batchPacket(e,t){this.batchedData[e].push(t),this.batchTimeouts[e]||this.startBatch(e)}static async unravelBatch(e,t,n){let r;try{r=(0,a.decodeNativeBatch)(t,e.gzipCompression,e.maxBatchSize)}catch(e){return`Invalid batch: ${String(e)}`}const s=[];for(const t of r){const r=await e.listen(t,n);if("string"==typeof r)return`Batched packet: ${r}`;s.push(r)}return s}}},30(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.decompressBools=t.compressBools=t.EMPTY_UINT8=t.MAX_UVARINT=t.MAX_USHORT=t.MAX_BYTE=void 0,t.convertVarInt=function(e){if(!Number.isSafeInteger(e)||e<0||e>t.MAX_UVARINT)throw new Error(`Variable Ints must be within range 0 and ${t.MAX_UVARINT}: ${e}`);const n=[];do{let t=e%128;(e=Math.floor(e/128))>0&&(t|=128),n.push(t)}while(e>0);return n},t.readVarInt=function(e,t){let n=0,r=1;for(let a=0;a<8;a++){if(t>=e.length)throw new Error("Truncated variable integer");const a=e[t++];if(n+=(127&a)*r,!(128&a))return[t,n];r*=128}throw new Error("Variable integer is too long")},t.MAX_BYTE=255,t.MAX_USHORT=65535,t.MAX_UVARINT=128**7-1,t.EMPTY_UINT8=new Uint8Array([]);t.compressBools=e=>e.reduce((e,t,n)=>e|Number(t)<<7-n,0);t.decompressBools=e=>Array.from({length:8},(t,n)=>!!(e&1<<7-n))},72(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.decompressJSON=t.compressJSON=void 0;const r=n(950),a=e=>Array.from({length:8},(t,n)=>!!(e&1<<7-n));function s(e){if(!Number.isInteger(e)||e<0)throw new Error(`Invalid JSON variable integer: ${e}`);const t=[];do{let n=127&e;(e>>>=7)>0&&(n|=128),t.push(n)}while(e>0);return t}function i(e,t){let n=0,r=0;for(;;){if(t>=e.length||r>28)throw new Error("Invalid JSON variable integer");const a=e[t++];if(n+=(127&a)<<r,!(128&a))return[t,n];r+=7}}var o;!function(e){e[e.NULL=0]="NULL",e[e.BOOL=1]="BOOL",e[e.INT=2]="INT",e[e.FLOAT=3]="FLOAT",e[e.STRING=4]="STRING",e[e.ARRAY=5]="ARRAY",e[e.OBJECT=6]="OBJECT"}(o||(o={}));const c=e=>{const t=(new TextEncoder).encode(e);return[...s(t.length),...t]},d=(e,t)=>{const[n,r]=i(e,t);return{value:(new TextDecoder).decode(e.subarray(n,n+r)),length:n+r-t}},l=e=>{let t="";for(const n of e)t+=n.toString(2).padStart(3,"0");return(e=>new Uint8Array(e.match(/.{1,8}/g)?.map(e=>parseInt(e.padEnd(8,"0"),2))??[]))(t)},u=(e,t)=>{const n=(e=>Array.from(e,e=>e.toString(2).padStart(8,"0")).join(""))(e),r=[];for(let e=0;e<t;e++)r.push(parseInt(n.slice(3*e,3*e+3),2));return r};t.compressJSON=e=>{const t=[],n=[],a=[],i=e=>{switch(null===e?"null":Array.isArray(e)?"array":typeof e){case"null":a.push(o.NULL);break;case"boolean":a.push(o.BOOL),t.push(e);break;case"number":Number.isInteger(e)?(a.push(o.INT),n.push(...s((e=>e<<1^e>>31)(e)))):(a.push(o.FLOAT),n.push(...function(e){if(Number.isNaN(e))return[127,128,0,1];const t=e<0?1:0;if(0===(e=Math.abs(e)))return[0,0,0,0];const n=Math.floor(Math.log2(e));if(!Number.isFinite(e)||n>127||n<-126)return[t?255:127,128,0,0];const r=(t<<31|n+127<<23|8388607&Math.round((e/2**n-1)*2**23))>>>0;return[r>>>24,r>>>16&255,r>>>8&255,255&r]}(e)));break;case"string":a.push(o.STRING),n.push(...c(e));break;case"array":a.push(o.ARRAY),n.push(...s(e.length));for(const t of e)i(t);break;case"object":{a.push(o.OBJECT);const t=Object.keys(e);n.push(...s(t.length));for(const r of t)n.push(...c(r)),i(e[r]);break}default:throw new Error("Unsupported type")}};i(e);const d=t.length?(0,r.splitArray)(t,8).map(e=>e.reduce((e,t,n)=>e|Number(t)<<7-n,0)):[],u=l(a),h=[...s(d.length),...s(u.length)];return Uint8Array.from([...h,...d.flat(),...u,...n])};t.decompressJSON=e=>{let t=0;const[n,r]=i(e,t);t=n;const[s,c]=i(e,t);t=s;const l=[];for(let n=0;n<r;n++)l.push(...a(e[t++]));let h=0;const p=e.subarray(t,t+c);t+=c;const f=u(p,8*p.length/3);let w=0;const m=n=>{if(n>500)throw new Error("JSON array too deep.");const r=f[w++];switch(r){case o.NULL:return null;case o.BOOL:return l[h++];case o.INT:{const[n,r]=i(e,t);return t=n,(a=r)>>>1^-(1&a)}case o.FLOAT:{const n=function(e){const t=(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0,n=t>>>23&255,r=(0===n?0:1)+(8388607&t)/2**23,a=255===n?0===r?1/0:NaN:r*2**(0===n?-126:n-127);return t>>>31?-a:a}(Array.from(e.subarray(t,t+4)));return t+=4,n}case o.STRING:{const{value:n,length:r}=d(e,t);return t+=r,n}case o.ARRAY:{const[r,a]=i(e,t);t=r;const s=[];for(let e=0;e<a;e++)s.push(m(n+1));return s}case o.OBJECT:{const[r,a]=i(e,t);t=r;const s={};for(let r=0;r<a;r++){const{value:r,length:a}=d(e,t);t+=a,s[r]=m(n+1)}return s}default:throw new Error(`Unknown type ${r}`)}var a};return m(0)}},98(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.EnumPackage=t.TYPE_CONVERSION_MAP=void 0;const r=n(157),a=n(388),s={string:0,number:1,boolean:2,undefined:3,object:4};function i(e){const t=typeof e;if(!(t in s)&&null!=e)throw new Error(`Cannot serialize type "${t}" in an enum!`);return s[t]}t.TYPE_CONVERSION_MAP={0:e=>e,1:e=>parseFloat(e),2:e=>"true"==e,3:()=>{},4:()=>null};t.EnumPackage=class{tag;values;constructor(e,t){this.tag=e,this.values=t,this.wrap=this.wrap.bind(this)}serialize(){const e=(0,r.processCharCodes)(this.tag);return[this.tag.length,...e,this.values.length,...this.values.map(e=>[String(e).length,i(e),...(0,r.processCharCodes)(String(e))]).flat()]}wrap(e){return(0,a.WrapEnum)(this.tag,e)}}},102(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.PacketSchema=t.Packet=void 0;const r=n(388),a=n(98),s=n(30),i=n(433),o=n(619),c=n(157),d=n(351),l=n(72),u=n(179);class h{defaultEnabled;tag;maxSize;minSize;type;enumData;dataMax;dataMin;dataBatching;maxBatchSize;dontSpread;autoFlatten;fields;quantized;valueMin;valueMax;parent;variant;isParent;constructorName;replay;rateLimit;async;rereference;gzipCompression;object;client;processReceive;processSend;validate;customValidator;lastReceived={};lastSent={};quantizationErrors={};recordValues;constructor(e,t,n,r,a){if(this.tag=e,this.defaultEnabled=r,this.client=a,this.async=t.async,this.enumData=t.enumData,this.rateLimit=t.rateLimit,this.dontSpread=t.dontSpread,this.autoFlatten=t.autoFlatten,this.rereference=t.rereference,this.dataBatching=t.dataBatching,this.maxBatchSize=a?1/0:t.maxBatchSize,this.gzipCompression=t.gzipCompression,this.fields=t.fields,this.recordValues=this.fields?h.compileRecordValues(this.fields):void 0,this.quantized=t.quantized?{...t.quantized,trackError:t.quantized.trackError??!0}:void 0,this.valueMin=t.valueMin,this.valueMax=t.valueMax,this.parent=t.group?.parent,this.variant=t.group?.variant,this.isParent=t.group?.isParent??!1,this.constructorName=t.constructorName,this.replay=t.replay,this.object=t.object,this.type=t.type,this.dataMax=t.dataMax,this.dataMin=t.dataMin,t.testObject(this)){this.maxSize=this.minSize=this.type.length;for(let e=0;e<this.type.length;e++)this.type[e]==o.PacketType.NONE&&(this.dataMax[e]=this.dataMin[e]=0);const e={types:this.type,dataMins:this.dataMin,dataMaxes:this.dataMax,enumData:this.enumData};this.processReceive=t=>(0,d.decodeNativeObject)(e,t).map((e,t)=>this.type[t]===o.PacketType.JSON?(0,l.decompressJSON)(e):e),this.processSend=t=>{let n=0;const r=t.map((e,t)=>{if(this.type[t]===o.PacketType.JSON)return(0,l.compressJSON)(e);if(this.type[t]!==o.PacketType.ENUMS)return e;const r=this.enumData[n++];return(Array.isArray(e)?e:[e]).map(e=>{if(!Number.isInteger(e)||e<0||e>=r.values.length)throw new Error(`Invalid wrapped enum index: ${e}`);return r.values[e]})});return(0,d.encodeNativeObject)(e,r)},this.validate=async t=>{(0,d.validateNativeObject)(e,t);return(0,d.decodeNativeObject)(e,t).forEach((e,t)=>{if(this.type[t]!==o.PacketType.JSON)return;const n=(0,l.decompressJSON)(e),r=Array.isArray(n)?n.length:1;if(r<this.dataMin[t]||r>this.dataMax[t])throw new Error("JSON value count is outside schema limits")}),[t,!0]}}else{{this.maxSize=this.dataMax,this.minSize=this.dataMin,this.type==o.PacketType.NONE&&(this.dataMax=this.dataMin=0);const e=this.enumData[0];this.processReceive=t=>this.type===o.PacketType.JSON?(0,l.decompressJSON)(t):(0,d.decodeNative)(this.type,t,this.dataMax,e),this.processSend=t=>{let n;if(this.type===o.PacketType.JSON)n=(0,l.compressJSON)(t);else if(this.type===o.PacketType.ENUMS)n=Uint8Array.from(t);else{const r=this.type===o.PacketType.RAW&&1===t.length&&t[0]instanceof Uint8Array?t[0]:t;n=(0,d.encodeNative)(this.type,r,e)}return this.gzipCompression&&0===this.dataBatching?(0,d.deflateNative)(n):n},this.validate=async t=>{const n=this.gzipCompression&&0===this.dataBatching?(0,d.inflateNative)(t):t;if(this.type===o.PacketType.JSON){const e=(0,l.decompressJSON)(n),t=Array.isArray(e)?e.length:1;if(t<this.dataMin||t>this.dataMax)throw new Error("JSON value count is outside schema limits")}else(0,d.validateNative)(this.type,n,this.dataMin,this.dataMax,{enumData:e});return[n,!0]}}}this.customValidator=n}static compileRecordValues(e){switch(e.length){case 0:return()=>[];case 1:{const[t]=e;return e=>[e[t]]}case 2:{const[t,n]=e;return e=>[e[t],e[n]]}case 3:{const[t,n,r]=e;return e=>[e[t],e[n],e[r]]}case 4:{const[t,n,r,a]=e;return e=>[e[t],e[n],e[r],e[a]]}case 5:{const[t,n,r,a,s]=e;return e=>[e[t],e[n],e[r],e[a],e[s]]}case 6:{const[t,n,r,a,s,i]=e;return e=>[e[t],e[n],e[r],e[a],e[s],e[i]]}case 7:{const[t,n,r,a,s,i,o]=e;return e=>[e[t],e[n],e[r],e[a],e[s],e[i],e[o]]}case 8:{const[t,n,r,a,s,i,o,c]=e;return e=>[e[t],e[n],e[r],e[a],e[s],e[i],e[o],e[c]]}default:return t=>{const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=t[e[r]];return n}}}assertRecord(e,t){if(!this.fields)throw new Error(`Packet "${this.tag}" ${t} requires schema`);if(null===e||"object"!=typeof e||Array.isArray(e))throw new Error(`Packet "${this.tag}" ${t} requires an object record`);for(const t of this.fields)if(!Object.prototype.hasOwnProperty.call(e,t))throw new Error(`Packet "${this.tag}" is missing schema field(s): ${t}`);const n=Object.keys(e);if(n.length!==this.fields.length){const e=n.filter(e=>!this.fields.includes(e));if(e.length)throw new Error(`Packet "${this.tag}" has unknown schema field(s): ${e.join(", ")}`)}return this.recordValues(e)}construct(e){return this.constructorName?new((0,u.resolvePacketConstructor)(this.constructorName))(e):e}logicalValue(e,t,n){const r=this.quantized?.scale;if("number"!=typeof e||!Number.isFinite(e))throw new Error(`Packet "${this.tag}" ${t} value must be a finite number`);const a="receive"===t&&r?e/r:e;if(void 0!==this.valueMin&&a<this.valueMin)throw new Error(`Packet "${this.tag}" value ${a} is below minimum ${this.valueMin}`);if(void 0!==this.valueMax&&a>this.valueMax)throw new Error(`Packet "${this.tag}" value ${a} exceeds maximum ${this.valueMax}`);if("send"===t&&r){const e=a*r+(this.quantized?.trackError?this.quantizationErrors[n]??0:0),t=Math.round(e);return this.quantized?.trackError&&(this.quantizationErrors[n]=e-t),t}return a}logical(e,t,n=-1){const r=new Array(e.length);for(let a=0;a<e.length;a++)r[a]=this.logicalValue(e[a],t,n);return r}prepareSend(e,t=-1){if(this.object){if(this.autoFlatten&&this.fields){if(1!==e.length||!Array.isArray(e[0]))throw new Error(`Packet "${this.tag}" autoTranspose requires one array of records`);const t=e[0].map(e=>this.assertRecord(e,"autoTranspose"));return this.fields.map((e,n)=>t.map(e=>e[n]))}return e}let n=e;if(this.autoFlatten){if(1!==e.length||!Array.isArray(e[0]))throw new Error(`Packet "${this.tag}" autoFlatten requires one array of records`);const r=e[0],a=this.fields.length;n=new Array(r.length*a);let s=0;const i=this.quantized||void 0!==this.valueMin||void 0!==this.valueMax;for(const e of r){const r=this.assertRecord(e,"autoFlatten");for(let e=0;e<a;e++){const a=r[e];n[s++]=i?this.logicalValue(a,"send",t):a}}if(this.fields&&n.length%this.fields.length!==0)throw new Error(`Packet "${this.tag}" flat value count must be divisible by schema length ${this.fields.length}`);if(i)return n}else this.fields&&1===e.length&&null!==e[0]&&"object"==typeof e[0]&&!Array.isArray(e[0])&&(n=this.assertRecord(e[0],"schema mapping"));return this.quantized||void 0!==this.valueMin||void 0!==this.valueMax?this.logical(n,"send",t):n}clearQuantizationState(e){delete this.quantizationErrors[e]}finishReceive(e){if(this.object){if(this.autoFlatten&&this.fields){const t=e,n=t[0]?.length??0;if(t.some(e=>e.length!==n))throw new Error(`Packet "${this.tag}" autoTranspose columns have different lengths`);return Array.from({length:n},(e,n)=>{const r=this.fields.map((e,r)=>[e,t[r][n]]);return this.construct(Object.fromEntries(r))})}return this.autoFlatten?(0,i.UnFlattenData)(e):e}let t=Array.isArray(e)?e:[e];if((this.quantized||void 0!==this.valueMin||void 0!==this.valueMax)&&(t=this.logical(t,"receive")),this.autoFlatten){const e=this.fields.length;if(t.length%e!==0)throw new Error(`Packet "${this.tag}" flat value count ${t.length} is not divisible by schema length ${e}`);return Array.from({length:t.length/e},(n,r)=>this.construct(Object.fromEntries(this.fields.map((n,a)=>[n,t[r*e+a]]))))}if(this.fields){const e=this.fields.map((e,n)=>[e,t[n]]);return this.construct(Object.fromEntries(e))}return e}async listen(e,t){try{const[n,r]=await this.validate(e);if(!this.client&&!1===r)return"Invalid packet";const a=this.processReceive(n,r),s=this.finishReceive(a);if(null!=this.customValidator)if(this.dontSpread||this.fields){if(!this.customValidator(t,s))return"Didn't pass custom validator"}else if(!this.customValidator(t,...s))return"Didn't pass custom validator";return[this.isParent?{variant:"",payload:s}:s,!this.isParent&&!this.fields&&!this.dontSpread]}catch(e){return console.error("SonicWS failed to process a packet. Report reproducible codec failures at https://github.com/liwybloc/sonic-ws",e),`Error: ${String(e)}`}}serialize(){const e=(new TextEncoder).encode(JSON.stringify({schema:this.fields,quantized:this.quantized,min:this.valueMin,max:this.valueMax,group:void 0!==this.parent?{parent:this.parent,variant:this.variant??"",isParent:this.isParent}:void 0,constructor:this.constructorName,replay:this.replay||void 0})),t=[this.tag.length,...(0,c.processCharCodes)(this.tag),(0,s.compressBools)([this.dontSpread,this.async,this.object,this.autoFlatten,this.gzipCompression,this.rereference]),...(0,s.convertVarInt)(e.length),...e,this.dataBatching,this.enumData.length,...this.enumData.flatMap(e=>e.serialize())];return this.object?[...t,this.maxSize,...this.dataMax.flatMap(s.convertVarInt),...this.dataMin.flatMap(s.convertVarInt),...this.type]:[...t,...(0,s.convertVarInt)(this.dataMax),...(0,s.convertVarInt)(this.dataMin),this.type]}static readVarInts(e,t,n){const r=[];for(let a=0;a<n;a++){const[n,a]=(0,s.readVarInt)(e,t);t=n,r.push(a)}return[r,t]}static deserialize(e,t,n){const i=t,d=e[t++],l=(0,c.as8String)(e.slice(t,t+=d)),[u,p,w,m,y,g]=(0,s.decompressBools)(e[t++]),[v,_]=(0,s.readVarInt)(e,t);t=v;const b=e.slice(t,t+=_),k=JSON.parse((new TextDecoder).decode(b)),S=Array.isArray(k.schema)?k.schema:void 0,E=k.quantized&&"number"==typeof k.quantized.scale?k.quantized:void 0,T="number"==typeof k.min?k.min:void 0,P="number"==typeof k.max?k.max:void 0,N=k.group&&"string"==typeof k.group.parent?k.group:void 0,A="string"==typeof k.constructor?k.constructor:void 0,O=e[t++],M=e[t++],R=[];for(let n=0;n<M;n++){const n=e[t++],s=(0,c.as8String)(e.slice(t,t+=n)),i=e[t++],o=[];for(let n=0;n<i;n++){const n=e[t++],r=e[t++],s=(0,c.as8String)(e.slice(t,t+=n));o.push(a.TYPE_CONVERSION_MAP[r](s))}R.push((0,r.DefineEnum)(s,o))}if(w){const r=e[t++],[a,s]=this.readVarInts(e,t,r);t=s;const[c,d]=this.readVarInts(e,t,r);t=d;const w=Array.from(e.slice(t,t+=r));let g=0;const v=w.map(e=>e===o.PacketType.ENUMS?R[g++]:e),_=new f(!0,v,p,c,a,-1,u,m,!1,O,-1,y,S,void 0,void 0,void 0,N,A,!0===k.replay);return[new h(l,_,null,!1,n),t-i]}const[x,C]=(0,s.readVarInt)(e,t);t=x;const[I,U]=(0,s.readVarInt)(e,t);t=I;const B=e[t++],L=B===o.PacketType.ENUMS?R[0]:B,D=new f(!1,L,p,U,C,-1,u,m,g,O,-1,y,S,E,T,P,N,A,!0===k.replay);return[new h(l,D,null,!1,n),t-i]}static deserializeAll(e,t){const n=[];let r=0;for(;r<e.length;){const[a,s]=this.deserialize(e,r,t);n.push(a),r+=s}return n}}function p(e,t){return e instanceof a.EnumPackage?(t.push(e),o.PacketType.ENUMS):e}t.Packet=h;class f{type;enumData=[];dataMax;dataMin;dataBatching;maxBatchSize;rateLimit;dontSpread=!1;autoFlatten=!1;async=!1;rereference=!1;gzipCompression=!1;object;fields;quantized;valueMin;valueMax;group;constructorName;replay;constructor(e,t,n,r,a,s,i,o,c,d,l,u,h,f,w,m,y,g,v=!1){this.object=e,this.async=n,this.dataMin=r,this.dataMax=a,this.rateLimit=s,this.dontSpread=i,this.autoFlatten=o,this.rereference=c,this.dataBatching=d,this.maxBatchSize=l,this.gzipCompression=u,this.fields=h?[...h]:void 0,this.quantized=f?{...f}:void 0,this.valueMin=w,this.valueMax=m,this.group=y?{...y}:void 0,this.constructorName=g,this.replay=v,this.type=e?t.map(e=>p(e,this.enumData)):p(t,this.enumData)}testObject(e){return this.object}}t.PacketSchema=f},157(e,t){function n(e){return String.fromCodePoint(...e)}Object.defineProperty(t,"__esModule",{value:!0}),t.processCharCodes=function(e){return Array.from(e,e=>e.codePointAt(0))},t.convertCharCodes=n,t.as8String=function(e){return n(Array.from(e))}},179(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.RegisterPacketConstructor=function(e){const t=e.name;if(!t)throw new Error("Packet constructors must have a stable class name");const r=n.get(t);if(r&&r!==e)throw new Error(`A different packet constructor named "${t}" is already registered`);return n.set(t,e),e},t.UnregisterPacketConstructor=function(e){n.delete(e)},t.resolvePacketConstructor=function(e){const t=n.get(e);if(!t)throw new Error(`Packet constructor "${e}" is not registered locally. Call RegisterPacketConstructor(${e}) before decoding.`);return t};const n=new Map},234(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.SERVER_SUFFIX_NUMS=t.SERVER_SUFFIX=t.VERSION=void 0;const r=n(157);t.VERSION=24,t.SERVER_SUFFIX="SWS",t.SERVER_SUFFIX_NUMS=(0,r.processCharCodes)(t.SERVER_SUFFIX)},351(__unused_webpack_module,exports,__webpack_require__){Object.defineProperty(exports,"__esModule",{value:!0}),exports.setNativeCore=setNativeCore,exports.initializeWasmCore=initializeWasmCore,exports.loadNativeCore=loadNativeCore,exports.encodeNative=encodeNative,exports.decodeNative=decodeNative,exports.validateNative=validateNative,exports.encodeNativeObject=encodeNativeObject,exports.decodeNativeObject=decodeNativeObject,exports.validateNativeObject=validateNativeObject,exports.encodeNativeBatch=encodeNativeBatch,exports.decodeNativeBatch=decodeNativeBatch,exports.deflateNative=deflateNative,exports.inflateNative=inflateNative;const PacketType_1=__webpack_require__(619),version_1=__webpack_require__(234),CDN_RELEASE="https://cdn.jsdelivr.net/gh/liwybloc/sonic-ws/release",CDN_WASM=`${CDN_RELEASE}/bundle.wasm`,CDN_VERSION=`${CDN_RELEASE}/version`;let loadedCore,wasmInitialization;function buffer(e){return"undefined"!=typeof Buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function values(e){return Array.isArray(e)?[...e]:[e]}function assertNativeCore(e){const t=["encodeSigned","decodeSigned","encodeUnsigned","decodeUnsigned","encodeFloats","decodeFloats","encodeStrings","decodeStrings","encodeBooleans","decodeBooleans","decodeRaw","encodeHex","decodeHex","frameObject","unframeObject","encodeBatch","decodeBatch","deflateRaw","inflateRaw","validateEncoded","validateEnum","validateObject"].filter(t=>"function"!=typeof e[t]);if(t.length>0)throw new Error(`Invalid SonicWS codec module; missing: ${t.join(", ")}`)}function setNativeCore(e){assertNativeCore(e),loadedCore=e}function fetchUrl(e){return"string"==typeof e?e:e instanceof URL?e.href:e.url}async function isWasm(e){if(!e.ok)return!1;const t=new Uint8Array(await e.clone().arrayBuffer());return t.length>=4&&0===t[0]&&97===t[1]&&115===t[2]&&109===t[3]}async function fetchCdnWasm(e){const t=await e(CDN_VERSION,{cache:"no-store"});if(!t.ok)throw new Error(`Unable to verify SonicWS CDN protocol version (${t.status})`);const n=Number((await t.text()).trim());if(!Number.isInteger(n)||n!==version_1.VERSION)throw new Error(`SonicWS CDN protocol mismatch: expected ${version_1.VERSION}, received ${String(n)}`);const r=await e(CDN_WASM);if(!await isWasm(r))throw new Error("SonicWS CDN returned an invalid WASM module");return r}async function initializeBrowserWasm(){const e=window.fetch.bind(window);window.fetch=async(t,n)=>{const r=fetchUrl(t);if(r===CDN_WASM||!new URL(r,window.location.href).pathname.endsWith("/bundle.wasm"))return e(t,n);try{const r=await e(t,n);if(await isWasm(r))return r}catch{}return fetchCdnWasm(e)};try{return setNativeCore(await Promise.resolve().then(__webpack_require__.bind(__webpack_require__,880))),loadedCore}finally{window.fetch=e}}function initializeWasmCore(){return loadedCore?Promise.resolve(loadedCore):wasmInitialization||(wasmInitialization=(async()=>{if("undefined"!=typeof window)return initializeBrowserWasm();const wasm=eval("require")("./wasm/node/sonic_ws_core.js");return setNativeCore(wasm),loadedCore})().finally(()=>{wasmInitialization=void 0}),wasmInitialization)}function loadNativeCore(){if(loadedCore)return loadedCore;if("undefined"!=typeof window)throw new Error("SonicWS codec is not initialized; await initializeWasmCore() in browsers.");try{const wasm=eval("require")("./wasm/node/sonic_ws_core.js");return assertNativeCore(wasm),loadedCore=wasm,wasm}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`Unable to load the packaged SonicWS Node WASM codec: ${t}`)}}function enumIndex(e,t){const n=e.values.findIndex(e=>e===t||"number"==typeof e&&"number"==typeof t&&Number.isNaN(e)&&Number.isNaN(t));if(n<0)throw new Error(`Value ${String(t)} does not exist in enum ${e.tag}`);return n}function encodeIntegerVarints(e,t){const n=values(e),r=new Uint8Array(5*n.length);let a=0;for(let e=0;e<n.length;e++){const s=n[e];if(!Number.isInteger(s)||!Number.isFinite(s))throw new TypeError((t?"VARINT":"UVARINT")+" requires integer values");if(!t&&(s<0||s>4294967295))throw new RangeError("UVARINT value must be between 0 and 4294967295");const i=t?Math.max(-2147483648,Math.min(2147483647,s)):s;let o=t?(i<<1^i>>31)>>>0:i;do{let e=o%128;o=Math.floor(o/128),0!==o&&(e|=128),r[a++]=e}while(0!==o)}return r.slice(0,a)}function encodeNative(e,t,n,r=loadNativeCore()){switch(e){case PacketType_1.PacketType.NONE:if(null!=t&&(!Array.isArray(t)||0!==t.length))throw new TypeError("NONE only accepts null, undefined, or an empty array");return new Uint8Array(0);case PacketType_1.PacketType.RAW:case PacketType_1.PacketType.JSON:if(!(t instanceof Uint8Array||Array.isArray(t))){const t=e===PacketType_1.PacketType.JSON?"JSON wire data":"RAW";throw new TypeError(`${t} requires a Uint8Array or number array`)}return t instanceof Uint8Array?buffer(t):Uint8Array.from(t);case PacketType_1.PacketType.BYTES:case PacketType_1.PacketType.SHORTS:case PacketType_1.PacketType.DELTAS:return r.encodeSigned(e,values(t));case PacketType_1.PacketType.VARINT:return encodeIntegerVarints(t,!0);case PacketType_1.PacketType.UBYTES:case PacketType_1.PacketType.USHORTS:return r.encodeUnsigned(e,values(t));case PacketType_1.PacketType.UVARINT:return encodeIntegerVarints(t,!1);case PacketType_1.PacketType.FLOATS:case PacketType_1.PacketType.DOUBLES:return r.encodeFloats(e,values(t));case PacketType_1.PacketType.STRINGS_ASCII:case PacketType_1.PacketType.STRINGS_UTF16:return r.encodeStrings(e,values(t));case PacketType_1.PacketType.BOOLEANS:return r.encodeBooleans(values(t));case PacketType_1.PacketType.HEX:{const e=Array.isArray(t)?t[0]:t;if("string"!=typeof e)throw new TypeError("HEX requires one string");return r.encodeHex(e)}case PacketType_1.PacketType.ENUMS:if(!n)throw new Error("ENUMS requires an EnumPackage");return Uint8Array.from(values(t).map(e=>enumIndex(n,e)));default:throw new Error(`Unknown packet type: ${e}`)}}function decodeNative(e,t,n=4294967295,r,a=loadNativeCore()){const s=buffer(t);switch(e){case PacketType_1.PacketType.NONE:if(0!==t.byteLength)throw new Error("NONE packet contains data");return;case PacketType_1.PacketType.RAW:case PacketType_1.PacketType.JSON:return a.decodeRaw(s);case PacketType_1.PacketType.BYTES:case PacketType_1.PacketType.SHORTS:case PacketType_1.PacketType.VARINT:case PacketType_1.PacketType.DELTAS:return a.decodeSigned(e,s);case PacketType_1.PacketType.UBYTES:case PacketType_1.PacketType.USHORTS:case PacketType_1.PacketType.UVARINT:return a.decodeUnsigned(e,s);case PacketType_1.PacketType.FLOATS:case PacketType_1.PacketType.DOUBLES:return a.decodeFloats(e,s);case PacketType_1.PacketType.STRINGS_ASCII:case PacketType_1.PacketType.STRINGS_UTF16:return a.decodeStrings(e,s);case PacketType_1.PacketType.BOOLEANS:return a.decodeBooleans(s,n);case PacketType_1.PacketType.HEX:return a.decodeHex(s);case PacketType_1.PacketType.ENUMS:if(!r)throw new Error("ENUMS requires an EnumPackage");return[...t].map(e=>{if(e>=r.values.length)throw new Error(`Enum index ${e} is out of range`);return r.values[e]});default:throw new Error(`Unknown packet type: ${e}`)}}function validateNative(e,t,n,r,a={},s=loadNativeCore()){if(e!==PacketType_1.PacketType.ENUMS)s.validateEncoded(e,buffer(t),n,r,a.compressed??!1,a.batched??!1,a.maxBatchSize);else{if(!a.enumData)throw new Error("ENUMS requires an EnumPackage");s.validateEnum(buffer(t),a.enumData.values.length,n,r)}}function encodeNativeObject(e,t,n=loadNativeCore()){if(t.length!==e.types.length)throw new Error("Object field count does not match schema");let r=0;const a=e.types.map((a,s)=>encodeNative(a,t[s],a===PacketType_1.PacketType.ENUMS?e.enumData?.[r++]:void 0,n));return n.frameObject(a)}function decodeNativeObject(e,t,n=loadNativeCore()){const r=n.unframeObject(buffer(t),e.types.length);let a=0;return r.map((t,r)=>decodeNative(e.types[r],t,e.dataMaxes[r],e.types[r]===PacketType_1.PacketType.ENUMS?e.enumData?.[a++]:void 0,n))}function validateNativeObject(e,t,n=loadNativeCore()){n.validateObject(buffer(t),[...e.types],[...e.dataMins],[...e.dataMaxes],(e.enumData??[]).map(e=>e.values.length))}function encodeNativeBatch(e,t,n=loadNativeCore()){if(!t){let t=0;for(const n of e){let e=n.byteLength;for(t+=e+1;e>=128;)t++,e=Math.floor(e/128)}const n=new Uint8Array(t);let r=0;for(const t of e){let e=t.byteLength;do{let t=e%128;e=Math.floor(e/128),0!==e&&(t|=128),n[r++]=t}while(0!==e);n.set(t,r),r+=t.byteLength}return n}return n.encodeBatch(e.map(buffer),t)}function decodeNativeBatch(e,t,n=0,r,a=loadNativeCore()){const s=Number.isFinite(n)&&n>0?n:0;return a.decodeBatch(buffer(e),t,s,r)}function deflateNative(e,t=loadNativeCore()){return t.deflateRaw(buffer(e))}function inflateNative(e,t,n=loadNativeCore()){return n.inflateRaw(buffer(e),t)}},388(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.SET_PACKAGES=t.ENUM_KEY_TO_TAG=t.ENUM_TAG_TO_KEY=t.MAX_ENUM_SIZE=void 0,t.DefineEnum=function(e,n){const r=t.SET_PACKAGES[e];if(r){if(r.values.find((e,t)=>n[t]!=e))throw new Error(`Pre-existing enum package of tag '${e}' is set and different!`);return r}if(n.length>t.MAX_ENUM_SIZE)throw new Error(`An enum can only hold ${t.MAX_ENUM_SIZE} possible values.`);return t.ENUM_TAG_TO_KEY[e]=Object.fromEntries(n.map((e,t)=>[e,t])),t.ENUM_KEY_TO_TAG[e]=Object.fromEntries(n.map((e,t)=>[t,e])),t.SET_PACKAGES[e]=new a.EnumPackage(e,n)},t.WrapEnum=function(e,n){if(!(n in t.ENUM_TAG_TO_KEY[e]))throw new Error(`Value "${n}" does not exist in enum "${e}"`);return t.ENUM_TAG_TO_KEY[e][n]},t.DeWrapEnum=function(e,n){return t.ENUM_KEY_TO_TAG[e][n]};const r=n(30),a=n(98);t.MAX_ENUM_SIZE=r.MAX_BYTE,t.ENUM_TAG_TO_KEY={},t.ENUM_KEY_TO_TAG={},t.SET_PACKAGES={}},404(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.PacketHolder=void 0;const r=n(954);t.PacketHolder=class{key;keys;tags;packetMap;packets;variants={};parents=new Set;constructor(e){this.key=1,this.keys={},this.tags={},this.packetMap={},e&&this.holdPackets(e)}createKey(e){this.keys[e]=this.key,this.tags[this.key]=e,this.key++}holdPackets(e){(0,r.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(e){if(!((e=this.resolveTag(e))in this.keys))throw new Error(`Not a valid tag: ${e}`);return this.keys[e]}getTag(e){if(e in this.tags)return this.tags[e]}getPacket(e){if(!((e=this.resolveTag(e))in this.packetMap))throw new Error("Unknown packet tag: "+e);return this.packetMap[e]}hasKey(e){return e in this.tags}hasTag(e){return this.resolveTag(e)in this.keys||this.parents.has(e)}resolveTag(e){return this.variants[e]??e}getVariantTag(e,t){const n=this.variants[`${e}.${t}`];if(!n)throw new Error(`Unknown packet variant: ${e}.${t}`);return n}getKeys(){return this.keys}getTagMap(){return this.tags}getTags(){return Object.values(this.tags)}getPackets(){return this.packets}serialize(){return this.packets.map(e=>e.serialize()).flat()}}},410(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.setHashFunc=function(e){i=e?a:s},t.hashValue=function(e){return i(e)};const n=1099511628211n,r=(1n<<64n)-1n,a=e=>{let t=14695981039346656037n;const a=e=>{if(null===e)return t^=0n,void(t=t*n&r);const s=typeof e;if("number"===s)return t^=BigInt(Math.trunc(e)),void(t=t*n&r);if("string"!==s){if("boolean"===s)return t^=e?1n:0n,void(t=t*n&r);if(Array.isArray(e))for(let t=0;t<e.length;t++)a(e[t]);else if("object"===s){const s=Object.keys(e).sort();for(let i=0;i<s.length;i++){const o=s[i];for(let e=0;e<o.length;e++)t^=BigInt(o.charCodeAt(e)),t=t*n&r;a(e[o])}}}else for(let a=0;a<e.length;a++)t^=BigInt(e.charCodeAt(a)),t=t*n&r};return a(e),t},s=e=>{let t=2166136261;const n=e=>{if(null===e)return void(t^=0);const r=typeof e;if("number"===r)return t^=0|e,void(t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24));if("string"!==r)if("boolean"!==r){if(Array.isArray(e))for(let t=0;t<e.length;t++)n(e[t]);else if("object"===r){const r=Object.keys(e).sort();for(let a=0;a<r.length;a++){const s=r[a];for(let e=0;e<s.length;e++)t^=s.charCodeAt(e),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);n(e[s])}}}else t^=e?1:0;else for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24)};return n(e),t>>>0};let i=a},433(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.processPacket=d,t.listenPacket=async function(e,t,n){if("string"==typeof e)return void n(e);const[r,a]=e;try{if(a&&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),n(String(e))}},t.CreatePacket=w,t.CreateObjPacket=function(e){const t=Object.prototype.hasOwnProperty.call(e,"constructor")?e.constructor:void 0;let{tag:n,types:s=[],dataMaxes:i,dataMins:o,noDataRange:d=!1,dontSpread:w=!1,autoFlatten:y=!1,autoTranspose:g,schema:v,validator:_=null,dataBatching:b=0,maxBatchSize:k=10,rateLimit:S=0,enabled:E=!0,async:T=!1,gzipCompression:P=s&&s.includes(a.PacketType.JSON)}=e;if(!n)throw new Error("Packet tag is required");if(!s||0===s.length)throw new Error(`Packet "${n}" requires at least one type`);if(e.replay&&b)throw new Error(`Packet "${n}" cannot combine replay with batching`);if(m(v,n),t&&!v)throw new Error(`Packet "${n}" constructor requires schema`);t&&(0,c.RegisterPacketConstructor)(t);if(v&&v.length!==s.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 N=g??y;for(const e of s)if(l(e))throw new Error(`Invalid packet type in "${n}" packet: ${e}`);if(d)i=Array.from({length:s.length},()=>u),o=Array.from({length:s.length},()=>0);else if(void 0===i?i=Array.from({length:s.length},()=>1):Array.isArray(i)||(i=Array.from({length:s.length},()=>i)),void 0===o){const e=i;o=Array.from({length:s.length},(t,n)=>e[n])}else Array.isArray(o)||(o=Array.from({length:s.length},()=>o));const A=o,O=i.map(h),M=A.map((e,t)=>s[t]===a.PacketType.NONE?0:p(e,O[t])),R=new r.PacketSchema(!0,s,T,M,O,f(S),w,N,!1,b,k,P,v,void 0,void 0,void 0,void 0,t?.name,e.replay??!1);return new r.Packet(n,R,_,E,!1)},t.CreatePacketGroup=function(e){if(!e.tag||e.tag.includes("$"))throw new Error("Packet group tag is required and cannot contain '$'");const t=Object.entries(e.variants);if(!t.length)throw new Error(`Packet group "${e.tag}" requires at least one variant`);const n=w({tag:e.tag,type:a.PacketType.NONE,dataMin:0,dataMax:0,_group:{parent:e.tag,variant:"",isParent:!0}}),r=t.map(([t,n])=>{if(!t||t.includes("$"))throw new Error("Packet variant names cannot be empty or contain '$'");return w({...n,tag:`${e.tag}.${t}`,_group:{parent:e.tag,variant:t,isParent:!1}})});return[n,...r]},t.CreateEnumPacket=function(e){const{tag:t,enumData:n,dataMax:r=1,dataMin:a=0,noDataRange:s=!1,dontSpread:i=!1,validator:o=null,dataBatching:c=0,maxBatchSize:d=10,rateLimit:l=0,enabled:u=!0,async:h=!1}=e;return w({tag:t,type:n,dataMax:r,dataMin:a,noDataRange:s,dontSpread:i,validator:o,dataBatching:c,maxBatchSize:d,rateLimit:l,enabled:u,async:h})},t.FlattenData=g,t.UnFlattenData=function(e){return e[0]?.map((t,n)=>e.map(e=>e[n]))??[]};const r=n(102),a=n(619),s=n(98),i=n(30),o=n(410),c=n(179);async function d(e,t,n,r,s,c=!1){const l=e.getKey(t),u=e.getPacket(t);return async function(e,t,n,r,a,s,i){if(e[0]&&!s)return new Promise(t=>e[1].push([t,r,a]));e[0]=!0;const o=await i();if(e[1].length>0){const[r,a,s]=e[1].shift();queueMicrotask(async()=>{r(await d(t,a,s,e,n,!0))})}else e[0]=!1;return o}(r,e,s,t,n,c,async()=>{if(u.rereference){if(-1===s)throw new Error("Cannot send a re-referenced packet from the server-wide sender");const e=(0,o.hashValue)(n);if(u.lastSent[s]===e)return[l,i.EMPTY_UINT8,u];u.lastSent[s]=e}if(n=u.prepareSend(n,s),u.autoFlatten&&u.object&&!u.fields)n=g(n[0]);else{if(n.length>u.maxSize)throw new Error(`Packet "${t}" only allows ${u.maxSize} values`);if(n.length<u.minSize)throw new Error(`Packet "${t}" requires at least ${u.minSize} values`)}if(u.object||u.type===a.PacketType.JSON){if(u.object&&(n=n.map(e=>Array.isArray(e)?e:[e]),!u.autoFlatten)){const e=u.dataMin,r=u.dataMax;for(let a=0;a<e.length;a++){if(n[a].length<e[a])throw new Error(`Section ${a+1} of packet "${t}" requires at least ${e[a]} values`);if(n[a].length>r[a])throw new Error(`Section ${a+1} of packet "${t}" only allows ${r[a]} values`)}}}else{const e=n.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=i.EMPTY_UINT8;if(n.length>0){const t=u.processSend(n);e=t instanceof Promise?await t:t}return[l,e,u]})}function l(e){return!("number"==typeof e&&e in a.PacketType||e instanceof s.EnumPackage)}const u=2048383;function h(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 2048383 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))>i.MAX_USHORT?(console.warn(`A rate limit above ${i.MAX_USHORT} is considered infinite.`),0):e}function w(e){const t=!0===e.autoFlatten&&void 0===e.dataMax&&void 0===e.dataMin,n=Object.prototype.hasOwnProperty.call(e,"constructor")?e.constructor:void 0;let{tag:s,type:i=a.PacketType.NONE,dataMax:o=1,dataMin:d,noDataRange:w=!1,dontSpread:g=!1,validator:v=null,dataBatching:_=0,maxBatchSize:b=10,rateLimit:k=0,enabled:S=!0,async:E=!1,gzipCompression:T=i===a.PacketType.JSON,rereference:P=!1,schema:N,autoFlatten:A=!1,quantized:O,min:M,max:R}=e;if(!s)throw new Error("Packet tag is required");if(w||t?(d=P?1:0,o=u):void 0===d&&(d=i===a.PacketType.NONE?0:o),P&&0===d)throw new Error("Rereference requires a data minimum above zero");if(e.replay&&_)throw new Error(`Packet "${s}" cannot combine replay with batching`);if(l(i))throw new Error(`Invalid packet type: ${i}`);if(m(N,s),n&&!N)throw new Error(`Packet "${s}" constructor requires schema`);if(n&&(0,c.RegisterPacketConstructor)(n),A&&(!N||0===N.length))throw new Error(`Packet "${s}" autoFlatten requires schema`);if(N&&!A&&d===o&&N.length!==o)throw new Error(`Packet "${s}" schema length must match its fixed value count (${o})`);!function(e,t,n,r,a){if(void 0!==n&&void 0!==r&&n>r)throw new Error(`Packet "${a}" min cannot exceed max`);if((t||void 0!==n||void 0!==r)&&!y.has(e))throw new Error(`Packet "${a}" numeric options require a numeric packet type`);if(t&&(!Number.isFinite(t.scale)||t.scale<=0))throw new Error(`Packet "${a}" quantization scale must be positive and finite`)}(i,O,M,R,s);const x=new r.PacketSchema(!1,i,E,p(d,o),h(o),f(k),g,A,P,_,b,T,N,O,M,R,e._group,n?.name,e.replay??!1);return new r.Packet(s,x,v,S,!1)}function m(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 y=new Set([a.PacketType.BYTES,a.PacketType.UBYTES,a.PacketType.SHORTS,a.PacketType.USHORTS,a.PacketType.VARINT,a.PacketType.UVARINT,a.PacketType.DELTAS,a.PacketType.FLOATS,a.PacketType.DOUBLES]);function g(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,n)=>e.map(e=>e[n]))}},605(e,t,n){var r=n(804);e.exports=n.v(t,e.id,"12335afce5a51f21a152",{"./sonic_ws_core_bg.js":{__wbg_get_unchecked_6e0ad6d2a41b06f6:r.ss,__wbg_length_370319915dc99107:r.Sg,__wbg_push_d2ae3af0c1217ae6:r.Tb,__wbg_new_32b398fb48b6d94a:r.gV,__wbg_new_cd45aabdf6073e84:r.EW,__wbg_length_1f0964f4a5e2c6d8:r.Pt,__wbg_prototypesetcall_4770620bbe4688a0:r.pe,__wbg_new_from_slice_77cdfb7977362f3c:r.BV,__wbg___wbindgen_string_get_b0ca35b86a603356:r.oF,__wbg___wbindgen_number_get_394265ed1e1b84ee:r.JV,__wbg___wbindgen_throw_344f42d3211c4765:r.F6,__wbg___wbindgen_boolean_get_fa956cfa2d1bd751:r.sL,__wbindgen_init_externref_table:r.bL,__wbindgen_cast_0000000000000001:r.NR,__wbindgen_cast_0000000000000002:r.U_}})},619(e,t){var n;Object.defineProperty(t,"__esModule",{value:!0}),t.PacketType=void 0,function(e){e[e.NONE=0]="NONE",e[e.RAW=1]="RAW",e[e.STRINGS_ASCII=2]="STRINGS_ASCII",e[e.STRINGS_UTF16=3]="STRINGS_UTF16",e[e.STRINGS=2]="STRINGS",e[e.ENUMS=4]="ENUMS",e[e.BYTES=5]="BYTES",e[e.UBYTES=6]="UBYTES",e[e.SHORTS=7]="SHORTS",e[e.USHORTS=8]="USHORTS",e[e.VARINT=9]="VARINT",e[e.UVARINT=10]="UVARINT",e[e.DELTAS=11]="DELTAS",e[e.FLOATS=12]="FLOATS",e[e.DOUBLES=13]="DOUBLES",e[e.BOOLEANS=14]="BOOLEANS",e[e.JSON=16]="JSON",e[e.HEX=17]="HEX"}(n||(t.PacketType=n={}))},804(e,t,n){function r(e,t,n,r){const a=Z.decodeBatch(e,t,n,H(r)?Number.MAX_SAFE_INTEGER:r>>>0);if(a[2])throw Y(a[1]);return Y(a[0])}function a(e,t){const n=Z.decodeBooleans(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function s(e,t){const n=Z.decodeFloats(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function i(e){let t,n;try{const s=Z.decodeHex(e);var r=s[0],a=s[1];if(s[3])throw r=0,a=0,Y(s[2]);return t=r,n=a,q(r,a)}finally{Z.__wbindgen_free(t,n,1)}}function o(e){const t=Z.decodeRaw(e);if(t[2])throw Y(t[1]);return Y(t[0])}function c(e,t){const n=Z.decodeSigned(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function d(e,t){const n=Z.decodeStrings(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function l(e,t){const n=Z.decodeUnsigned(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function u(e){const t=Z.deflateRaw(e);if(t[2])throw Y(t[1]);return Y(t[0])}function h(e,t){const n=Z.encodeBatch(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function p(e){const t=Z.encodeBooleans(e);if(t[2])throw Y(t[1]);return Y(t[0])}function f(e,t){const n=Z.encodeFloats(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function w(e){const t=K(e,Z.__wbindgen_malloc,Z.__wbindgen_realloc),n=ee,r=Z.encodeHex(t,n);if(r[2])throw Y(r[1]);return Y(r[0])}function m(e,t){const n=Z.encodeSigned(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function y(e,t){const n=Z.encodeStrings(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function g(e,t){const n=Z.encodeUnsigned(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function v(e){const t=Z.frameObject(e);if(t[2])throw Y(t[1]);return Y(t[0])}function _(e,t){const n=Z.inflateRaw(e,H(t)?Number.MAX_SAFE_INTEGER:t>>>0);if(n[2])throw Y(n[1]);return Y(n[0])}function b(e,t){const n=Z.unframeObject(e,t);if(n[2])throw Y(n[1]);return Y(n[0])}function k(e,t,n,r,a,s,i){const o=Z.validateEncoded(e,t,n,r,a,s,H(i)?Number.MAX_SAFE_INTEGER:i>>>0);if(o[1])throw Y(o[0])}function S(e,t,n,r){const a=Z.validateEnum(e,t,n,r);if(a[1])throw Y(a[0])}function E(e,t,n,r,a){const s=Z.validateObject(e,t,n,r,a);if(s[1])throw Y(s[0])}function T(e){const t="boolean"==typeof e?e:void 0;return H(t)?16777215:t?1:0}function P(e,t){const n="number"==typeof t?t:void 0;V().setFloat64(e+8,H(n)?0:n,!0),V().setInt32(e+0,!H(n),!0)}function N(e,t){const n="string"==typeof t?t:void 0;var r=H(n)?0:K(n,Z.__wbindgen_malloc,Z.__wbindgen_realloc),a=ee;V().setInt32(e+4,a,!0),V().setInt32(e+0,r,!0)}function A(e,t){throw new Error(q(e,t))}function O(e,t){return e[t>>>0]}function M(e){return e.length}function R(e){return e.length}function x(){return new Array}function C(e){return new Uint8Array(e)}function I(e,t){return new Uint8Array(j(e,t))}function U(e,t,n){Uint8Array.prototype.set.call(j(e,t),n)}function B(e,t){return e.push(t)}function L(e){return e}function D(e,t){return q(e,t)}function $(){const e=Z.__wbindgen_externrefs,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)}function j(e,t){return e>>>=0,W().subarray(e/1,e/1+t)}n.d(t,{B4:()=>h,BV:()=>I,Dq:()=>o,EF:()=>i,EW:()=>C,F6:()=>A,JV:()=>P,NR:()=>L,Pt:()=>M,Q5:()=>E,Sg:()=>R,Tb:()=>B,Ts:()=>m,U_:()=>D,XC:()=>y,_s:()=>f,at:()=>u,bL:()=>$,cv:()=>b,gV:()=>x,hD:()=>k,i1:()=>S,i4:()=>s,iT:()=>p,iX:()=>a,jN:()=>r,lI:()=>te,mU:()=>w,mk:()=>l,nt:()=>v,oF:()=>N,pe:()=>U,qO:()=>g,sL:()=>T,ss:()=>O,tD:()=>c,wS:()=>_,zC:()=>d});let z=null;function V(){return(null===z||!0===z.buffer.detached||void 0===z.buffer.detached&&z.buffer!==Z.memory.buffer)&&(z=new DataView(Z.memory.buffer)),z}function q(e,t){return function(e,t){X+=t,X>=G&&(J=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),J.decode(),X=t);return J.decode(W().subarray(e,e+t))}(e>>>0,t)}let F=null;function W(){return null!==F&&0!==F.byteLength||(F=new Uint8Array(Z.memory.buffer)),F}function H(e){return null==e}function K(e,t,n){if(void 0===n){const n=Q.encode(e),r=t(n.length,1)>>>0;return W().subarray(r,r+n.length).set(n),ee=n.length,r}let r=e.length,a=t(r,1)>>>0;const s=W();let i=0;for(;i<r;i++){const t=e.charCodeAt(i);if(t>127)break;s[a+i]=t}if(i!==r){0!==i&&(e=e.slice(i)),a=n(a,r,r=i+3*e.length,1)>>>0;const t=W().subarray(a+i,a+r);i+=Q.encodeInto(e,t).written,a=n(a,r,i,1)>>>0}return ee=i,a}function Y(e){const t=Z.__wbindgen_externrefs.get(e);return Z.__externref_table_dealloc(e),t}let J=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});J.decode();const G=2146435072;let X=0;const Q=new TextEncoder;"encodeInto"in Q||(Q.encodeInto=function(e,t){const n=Q.encode(e);return t.set(n),{read:e.length,written:n.length}});let Z,ee=0;function te(e){Z=e}},853(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.DebugClient=void 0;t.DebugClient=class{host;constructor(e){this.host=e;const t=document.createElement("sonicws");t.innerHTML="<style>sws-h3{margin:0;color:#fff;font-size:16px;font-weight:600}#sonicws-container{display:flex;flex-direction:column;position:absolute;top:50px;left:50px;width:75vw;min-width:33vw;min-height:25vh;max-height:75vh;max-width:75vw;font-family:Arial,sans-serif;background-color:#2c2c2c;border-radius:10px;box-shadow:0 8px 20px rgba(0,0,0,.4);overflow:hidden;user-select:none;transition:box-shadow .2s ease;z-index:2147483647}#sonicws-container:hover{box-shadow:0 12px 28px rgba(0,0,0,.6)}#sonicws-header{display:flex;justify-content:space-between;align-items:center;cursor:move;background:linear-gradient(90deg,#4a90e2,#357ab7);padding:10px 12px;border-top-left-radius:10px;border-top-right-radius:10px}#sonicws-toggle{font-size:18px;font-weight:700;cursor:pointer;color:#fff;user-select:none}#sonicws-body{flex:1;display:flex;padding:12px;color:#e0e0e0;font-size:14px;min-height:0}#sonicws-stats{display:flex;flex-direction:column;min-width:140px}#sonicws-stats sws-p{margin:4px 0}#sonicws-packets{min-height:0;display:flex;flex-direction:column;flex:1;margin-left:10px;background-color:#1e1e1e;padding:8px;border-radius:8px;overflow-y:scroll}sws-div.packet{background-color:#2a2a2a;border-radius:6px;padding:3px 5px;margin-bottom:2px;cursor:pointer;transition:background .2s ease,transform .1s ease;display:flex;flex-direction:column}sws-div.packet:hover{background-color:#3a3a3a;transform:translateY(-1px)}sws-div.packet-header{display:flex;align-items:flex-start;flex-wrap:wrap;font-size:11px;white-space:normal;word-break:break-word}sws-span.packet-arrow{font-weight:700;margin-right:6px}sws-div.packet-details{margin-top:6px;font-size:10px;color:#aaa;display:none;flex-direction:column}sws-div.packet.expanded sws-div.packet-details{display:flex}#sonicws-resizer{width:12px;height:12px;background:#666;position:absolute;right:0;bottom:0;cursor:se-resize;border-bottom-right-radius:10px;transition:background .2s ease}#sonicws-resizer:hover{background:#888}#sonicws-container.minimized{width:auto!important;height:auto!important;min-width:unset;min-height:unset}#sonicws-container.minimized #sonicws-body,#sonicws-container.minimized #sonicws-resizer{display:none}#sonicws-container.minimized #sonicws-header{padding:8px 12px}#sonicws-container.minimized #sonicws-title{font-size:14px}</style><sws-div id=sonicws-container><sws-div id=sonicws-header><sws-h3 id=sonicws-title>SonicWS Debug Menu</sws-h3><sws-span id=sonicws-toggle>−</sws-span></sws-div><sws-div id=sonicws-body><sws-div id=sonicws-stats><sws-p>Status:<sws-span id=sonicws-status>Connecting</sws-span></sws-p><sws-p>Sent Packets:<sws-span id=sonicws-sent>0</sws-span></sws-p><sws-p>Received Packets:<sws-span id=sonicws-received>0</sws-span></sws-p><sws-p>Total Bytes Sent:<sws-span id=sonicws-sentbytes>0</sws-span></sws-p><sws-p>Total Bytes Received:<sws-span id=sonicws-receivedbytes>0</sws-span></sws-p><sws-p>Total Bytes Saved:<sws-span id=sonicws-savedbytes>0</sws-span></sws-p></sws-div><sws-div id=sonicws-packets></sws-div></sws-div><sws-div id=sonicws-resizer></sws-div></sws-div>",document.body?(document.body.appendChild(t),this._loadDebugScript()):document.addEventListener("DOMContentLoaded",()=>{document.body.appendChild(t),this._loadDebugScript()})}_evalInScope(e){const t=this.host;return new Function("send","WrapEnum","DeWrapEnum","FlattenData","UnFlattenData",`"use strict"; return (${e});`)(t.send.bind(t),t.WrapEnum.bind(t),t.DeWrapEnum.bind(t),t.FlattenData.bind(t),t.UnFlattenData.bind(t))}_loadDebugScript(){const e={},t={},n=this.host;this.host.addMiddleware(new class{onReceive_pre(e,n){t[e]??=[],t[e].push([n,performance.now()])}onReceive_post(e,r){const[a,s]=t[e].shift();T("received",`${e} (0x${n.serverPackets.getKey(e).toString(16).toUpperCase()})`,a,JSON.stringify(r),performance.now()-s)}onSend_pre(t,n){e[t]??=[],e[t].push([n,performance.now()])}onSend_post(t,r){const[a,s]=e[t].shift();T("sent",`${t} (0x${n.clientPackets.getKey(t).toString(16).toUpperCase()})`,r,JSON.stringify(a),performance.now()-s)}onStatusChange(e){S(e)}});const r=e=>document.getElementById(e),a=r("sonicws-container"),s=r("sonicws-header"),i=r("sonicws-resizer"),o=r("sonicws-status"),c=r("sonicws-packets"),d=r("sonicws-sent"),l=r("sonicws-received"),u=r("sonicws-sentbytes"),h=r("sonicws-receivedbytes"),p=r("sonicws-savedbytes"),f=document.getElementById("sonicws-toggle"),w=document.getElementById("sonicws-title");let m=!1;const y=document.createElement("input");y.type="text",y.placeholder='send("tag", 5)',y.style.marginTop="8px",y.style.width="100%",y.style.boxSizing="border-box";const g=document.createElement("button");function v(){const e=a.getBoundingClientRect(),t=window.innerWidth-e.width,n=window.innerHeight-e.height,r=Math.min(Math.max(0,e.left),Math.max(0,t)),s=Math.min(Math.max(0,e.top),Math.max(0,n));a.style.left=r+"px",a.style.top=s+"px"}g.innerText="Run",g.style.marginTop="4px",g.style.width="100%",r("sonicws-stats").appendChild(y),r("sonicws-stats").appendChild(g),g.addEventListener("click",()=>{try{this._evalInScope(y.value)}catch(e){console.error(e)}}),f.addEventListener("click",e=>{e.stopPropagation(),m=!m,m?(a.classList.add("minimized"),w.innerText="SWS",f.innerText="+",a.style.width="",a.style.height=""):(a.classList.remove("minimized"),w.innerText="SonicWS Debug Menu",f.innerText="−"),v()});const _={sentPackets:0,receivedPackets:0,totalBytesSent:0,totalBytesReceived:0,totalBytesSaved:0},b=new Proxy(_,{get(e,t){switch(t){case"sonicws-sent":return _.sentPackets;case"sonicws-received":return _.receivedPackets;case"sonicws-sentbytes":return _.totalBytesSent;case"sonicws-receivedbytes":return _.totalBytesReceived;case"sonicws-savedbytes":return _.totalBytesSaved;default:return}},set(e,t,n){switch(t){case"sonicws-sent":return _.sentPackets=n,d.innerText=n.toLocaleString(),!0;case"sonicws-received":return _.receivedPackets=n,l.innerText=n.toLocaleString(),!0;case"sonicws-sentbytes":{_.totalBytesSent=n;const{amt:e,unit:t}=k(n);return u.innerText=e+t,!0}case"sonicws-receivedbytes":{_.totalBytesReceived=n;const{amt:e,unit:t}=k(n);return h.innerText=e+t,!0}case"sonicws-savedbytes":{_.totalBytesSaved=n;const{amt:e,unit:t}=k(n);return p.innerText=e+t,!0}default:return!1}}}),k=e=>{if(!Number.isFinite(e)||e<0)return{amt:0,unit:"B"};const t=["B","KB","MB","GB","TB"];let n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return{amt:0==r?n.toString():n.toFixed(2),unit:t[r]}};function S(e){switch(e){case WebSocket.CLOSED:o.innerText="Closed",o.style.color="#f00";break;case WebSocket.CLOSING:o.innerText="Closing",o.style.color="#fa0";break;case WebSocket.OPEN:o.innerText="Open",o.style.color="#0f0";break;case WebSocket.CONNECTING:o.innerText="Connecting",o.style.color="#ff0";break;default:o.innerText="Unknown",o.style.color="#777"}}S(WebSocket.CONNECTING);const E=new TextEncoder;function T(e,t,n,r,a){const s=new Date,i=n.length+("sent"==e?1:0),o=E.encode(r).length-i+1,d=document.createElement("sws-div");d.classList.add("packet");const l=document.createElement("sws-div");l.classList.add("packet-header");const u=document.createElement("sws-span");u.classList.add("packet-arrow"),u.innerText="sent"===e?"⬆":"⬇",u.style.color="sent"===e?"#0f0":"#f00";const h=document.createElement("sws-span");h.innerText=t+": "+r,l.appendChild(u),l.appendChild(h);const p=document.createElement("sws-div");p.classList.add("packet-details"),p.innerHTML=`\n <sws-p> Raw Bytes: ${i}b (saved ~${o}b)</sws-p>\n <sws-p> Processed At: ${s.toISOString()} </sws-p>\n <sws-p> Processing Time: <sws-span class="processing-time" > ${a.toFixed(1)} </sws-span> ms</sws-p>\n `,d.appendChild(l),d.appendChild(p),c.append(d),l.addEventListener("click",()=>d.classList.toggle("expanded")),"sent"===e?(b["sonicws-sent"]++,b["sonicws-sentbytes"]+=i):(b["sonicws-received"]++,b["sonicws-receivedbytes"]+=i),b["sonicws-savedbytes"]+=o}let P=!1,N=0,A=0,O=0,M=0,R=!1,x=0,C=0,I=0,U=0;s.addEventListener("mousedown",e=>{P=!0,N=e.clientX,A=e.clientY;const t=a.getBoundingClientRect();O=t.left,M=t.top,e.preventDefault()}),i.addEventListener("mousedown",e=>{R=!0,x=e.clientX,C=e.clientY;const t=a.getBoundingClientRect();I=t.width,U=t.height,e.preventDefault()}),document.addEventListener("mousemove",e=>{P&&(a.style.left=O+e.clientX-N+"px",a.style.top=M+e.clientY-A+"px",v()),R&&!m&&(a.style.width=I+e.clientX-x+"px",a.style.height=U+e.clientY-C+"px",v())}),document.addEventListener("mouseup",()=>{P=!1,R=!1}),v(),window.addEventListener("resize",v)}}},880(e,t,n){n.a(e,async(e,r)=>{try{n.r(t),n.d(t,{decodeBatch:()=>s.jN,decodeBooleans:()=>s.iX,decodeFloats:()=>s.i4,decodeHex:()=>s.EF,decodeRaw:()=>s.Dq,decodeSigned:()=>s.tD,decodeStrings:()=>s.zC,decodeUnsigned:()=>s.mk,deflateRaw:()=>s.at,encodeBatch:()=>s.B4,encodeBooleans:()=>s.iT,encodeFloats:()=>s._s,encodeHex:()=>s.mU,encodeSigned:()=>s.Ts,encodeStrings:()=>s.XC,encodeUnsigned:()=>s.qO,frameObject:()=>s.nt,inflateRaw:()=>s.wS,unframeObject:()=>s.cv,validateEncoded:()=>s.hD,validateEnum:()=>s.i1,validateObject:()=>s.Q5});var a=n(605),s=n(804),i=e([a]);a=(i.then?(await i)():i)[0],(0,s.lI)(a),a.__wbindgen_start(),r()}catch(e){r(e)}})},913(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.CloseCodes=t.Connection=void 0,t.getClosureCause=function(e){if(e>=4e3)return i[e]??"UNKNOWN";switch(e){case 1e3:return"NORMAL_CLOSURE";case 1001:return"GOING_AWAY";case 1002:return"PROTOCOL_ERROR";case 1003:return"UNSUPPORTED_DATA";case 1006:return"ABNORMAL_CLOSURE";default:return"UNKNOWN"}};const r=n(985),a=n(8);class s extends r.MiddlewareHolder{listeners;rawSendListeners=[];name;closed=!1;socket;_timers={};batcher;_on;_off;id;state={};volatileAtBytes=1048576;closeAtBytes=16777216;constructor(e,t,n,r,s){super(),this.id=t,this.listeners={},this.name=n,this.socket=e,this.batcher=new a.BatchHelper,this._on=r,this._off=s,this._on("close",()=>{this.callMiddleware("onStatusChange",WebSocket.CLOSED),this.closed=!0;for(const[e,t,n]of Object.values(this._timers))this.clearTimeout(e),n&&t(!0)}),this._on("open",()=>this.callMiddleware("onStatusChange",WebSocket.OPEN))}replaceTransport(e,t,n){this.socket=e,this._on=t,this._off=n,this.closed=!1,this._on("close",()=>{this.callMiddleware("onStatusChange",WebSocket.CLOSED),this.closed=!0}),this._on("open",()=>this.callMiddleware("onStatusChange",WebSocket.OPEN))}setTimeout(e,t,n=!1){const r=setTimeout(()=>{e(),this.clearTimeout(r)},t);return this._timers[r]=[r,e,n],r}setInterval(e,t,n=!1){const r=setInterval(e,t);return this._timers[r]=[r,e,n],r}clearTimeout(e){clearTimeout(e),delete this._timers[e]}clearInterval(e){this.clearTimeout(e)}raw_send(e){if(this.getBufferedAmount()>=this.closeAtBytes)throw this.close(i.BACKPRESSURE,"Outbound buffer exceeded the configured limit"),new Error("SonicWS outbound backpressure limit exceeded");this.socket.send(e);for(const t of this.rawSendListeners)t(e)}getBufferedAmount(){const e=this.socket.bufferedAmount;return"number"==typeof e&&Number.isFinite(e)?e:0}setBackpressureLimits(e){const t=e.volatileAtBytes??this.volatileAtBytes,n=e.closeAtBytes??this.closeAtBytes;if(!Number.isFinite(t)||!Number.isFinite(n)||t<0||n<=0||t>n)throw new Error("Invalid SonicWS backpressure limits");this.volatileAtBytes=t,this.closeAtBytes=n}canSendVolatile(){return this.getBufferedAmount()<this.volatileAtBytes}raw_onmessage(e){this._on("message",e)}raw_onsend(e){this.rawSendListeners.push(e)}close(e=1e3,t){this.closed=!0,this.socket.close(e,t?.toString())}isClosed(){return this.closed||this.socket.readyState===WebSocket.CLOSED}async setName(e){await this.callMiddleware("onNameChange",e)||(this.name=e)}getName(){return this.name}}var i;t.Connection=s,function(e){e[e.RATELIMIT=4e3]="RATELIMIT",e[e.SMALL=4001]="SMALL",e[e.INVALID_KEY=4002]="INVALID_KEY",e[e.INVALID_PACKET=4003]="INVALID_PACKET",e[e.INVALID_DATA=4004]="INVALID_DATA",e[e.REPEATED_HANDSHAKE=4005]="REPEATED_HANDSHAKE",e[e.DISABLED_PACKET=4006]="DISABLED_PACKET",e[e.MIDDLEWARE=4007]="MIDDLEWARE",e[e.MANUAL_SHUTDOWN=4008]="MANUAL_SHUTDOWN",e[e.BACKPRESSURE=4009]="BACKPRESSURE"}(i||(t.CloseCodes=i={}))},917(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.encodeResumed=t.encodeReplay=t.ControlType=t.CONTROL_KEY=void 0,t.encodeControlRequest=function(e,n,a){return Uint8Array.from([t.CONTROL_KEY,s.REQUEST,...(0,r.convertVarInt)(e),n,...a])},t.encodeControlResponse=function(e,n,i){return Uint8Array.from([t.CONTROL_KEY,s.RESPONSE,...(0,r.convertVarInt)(e),Number(n),...(0,a.compressJSON)(i)])},t.encodeResume=function(e,n){const a=(new TextEncoder).encode(e);return Uint8Array.from([t.CONTROL_KEY,s.RESUME,...(0,r.convertVarInt)(a.length),...a,...(0,r.convertVarInt)(n)])},t.decodeControl=function(e){if(e[0]!==t.CONTROL_KEY||e.length<3)throw new Error("Invalid SonicWS control frame");const n=e[1];switch(n){case s.REPLAY:{const[t,a]=(0,r.readVarInt)(e,2);return{type:n,sequence:a,payload:e.slice(t)}}case s.RESUME:{const[t,a]=(0,r.readVarInt)(e,2),s=t+a;if(s>e.length)throw new Error("Recovery frame has an invalid session id");const[i,o]=(0,r.readVarInt)(e,s);return{type:n,sessionId:(new TextDecoder).decode(e.slice(t,s)),lastSequence:o}}case s.RESUMED:{if(e.length<4)throw new Error("Invalid recovery result frame");const[t,a]=(0,r.readVarInt)(e,3);return{type:n,recovered:0!==e[2],replayed:a}}case s.REQUEST:{const[t,a]=(0,r.readVarInt)(e,2);if(t>=e.length)throw new Error("RPC request is missing its packet key");return{type:n,id:a,packetKey:e[t],payload:e.slice(t+1)}}case s.RESPONSE:{const[t,s]=(0,r.readVarInt)(e,2);if(t>=e.length)throw new Error("RPC response is missing its status");return{type:n,id:s,ok:0!==e[t],value:(0,a.decompressJSON)(e.slice(t+1))}}default:throw new Error(`Unknown SonicWS control frame type: ${n}`)}};const r=n(30),a=n(72);var s;t.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"}(s||(t.ControlType=s={}));t.encodeReplay=(e,n)=>Uint8Array.from([t.CONTROL_KEY,s.REPLAY,...(0,r.convertVarInt)(e),...n]);t.encodeResumed=(e,n)=>Uint8Array.from([t.CONTROL_KEY,s.RESUMED,Number(e),...(0,r.convertVarInt)(n)])},937(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.SonicWSCore=void 0;const r=n(404),a=n(30),s=n(351),i=n(433),o=n(234),c=n(102),d=n(8),l=n(950),u=n(913),h=n(157),p=n(917);class f extends u.Connection{preListen;clientPackets=new r.PacketHolder;serverPackets=new r.PacketHolder;pastKeys=!1;readyListeners=[];bufferHandler;_timers={};asyncData={};asyncMap={};reconnectFactory;reconnectOptions={enabled:!1,attempts:1/0,minDelayMs:500,maxDelayMs:1e4,jitter:.25};reconnectAttempt=0;reconnectTimer;intentionalClose=!1;connectedOnce=!1;reconnectingListeners=[];reconnectListeners=[];reconnectFailedListeners=[];nextRequestId=1;pendingRequests=new Map;responders=new Map;sessionId;lastReplaySequence=0;recoveredListeners=[];pendingResumeSession;handshakeTimeoutMs=1e4;handshakeTimer;constructor(e,t,n,r){super(e,-1,"LocalSocket",n,r),this.socket=e,this.preListen={},this.invalidPacket=this.invalidPacket.bind(this),this.serverKeyHandler=this.serverKeyHandler.bind(this),this.messageHandler=this.messageHandler.bind(this),this.attachClientTransport(),this.armHandshakeTimeout(),this.bufferHandler=t}configureHandshakeTimeout(e){if(!Number.isFinite(e)||e<=0)throw new Error("Handshake timeout must be positive");this.handshakeTimeoutMs=e,this.armHandshakeTimeout()}armHandshakeTimeout(){this.handshakeTimer&&clearTimeout(this.handshakeTimer),this.handshakeTimer=setTimeout(()=>{this.pastKeys||this.socket.close(u.CloseCodes.INVALID_DATA,"SonicWS schema handshake timed out")},this.handshakeTimeoutMs)}configureReconnect(e,t={}){if(this.reconnectFactory=e,this.reconnectOptions={enabled:t.enabled??!0,attempts:t.attempts??1/0,minDelayMs:t.minDelayMs??500,maxDelayMs:t.maxDelayMs??1e4,jitter:t.jitter??.25},this.reconnectOptions.attempts<0||this.reconnectOptions.minDelayMs<0||this.reconnectOptions.maxDelayMs<this.reconnectOptions.minDelayMs)throw new Error("Invalid reconnect timing options");if(this.reconnectOptions.jitter<0||this.reconnectOptions.jitter>1)throw new Error("Reconnect jitter must be between 0 and 1")}attachClientTransport(){this._on("message",this.serverKeyHandler),this._on("close",(...e)=>{for(const[e,t,n]of Object.values(this._timers))this.clearTimeout(e),n&&t(!0);for(const e of this.clientPackets.getPackets())delete e.lastSent[0],e.clearQuantizationState(0);for(const e of this.serverPackets.getPackets())delete e.lastReceived[0];const t=e[0],n="number"==typeof t?t:t?.code;this.intentionalClose||1e3===n||this.scheduleReconnect()})}scheduleReconnect(){if(!this.reconnectFactory||!this.reconnectOptions.enabled||this.reconnectTimer)return;if(this.reconnectAttempt>=this.reconnectOptions.attempts)return void this.reconnectFailedListeners.forEach(e=>e());const e=++this.reconnectAttempt,t=Math.min(this.reconnectOptions.maxDelayMs,this.reconnectOptions.minDelayMs*2**(e-1)),n=t*this.reconnectOptions.jitter,r=Math.max(0,Math.round(t-n+Math.random()*n*2));this.reconnectingListeners.forEach(t=>t({attempt:e,delayMs:r})),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.beginReconnect()},r)}beginReconnect(){try{const e=this.reconnectFactory();this.clientPackets=new r.PacketHolder,this.serverPackets=new r.PacketHolder,this.asyncData={},this.asyncMap={},this.reading=!1,this.readQueue=[],this.pastKeys=!1,this.preListen={},this.bufferHandler=e.bufferHandler,this.batcher=new d.BatchHelper,this.replaceTransport(e.socket,e.on,e.off),this.attachClientTransport(),this.armHandshakeTimeout()}catch{this.scheduleReconnect()}}reading=!1;readQueue=[];async serverKeyHandler(e){if(this.reading)return void this.readQueue.push(e);this.reading=!0;const t=await this.bufferHandler(e);if(t.length<3||(0,h.as8String)(t.slice(0,3))!==o.SERVER_SUFFIX)throw this.close(1e3),new Error("The requested server does not use the SonicWS protocol");const n=t[3];if(n!==o.VERSION)throw this.close(1e3),new Error(`Protocol mismatch: ${n>o.VERSION?"client":"server"} is outdated (server: ${n}, client: ${o.VERSION})`);const r=(0,s.inflateNative)(t.subarray(4)),i=this.sessionId,[d,l]=(0,a.readVarInt)(r,0);this.id=l;const[u,f]=(0,a.readVarInt)(r,d);this.sessionId=(new TextDecoder).decode(r.slice(u,u+f));const[w,m]=(0,a.readVarInt)(r,u+f),y=r.subarray(w,w+m);this.clientPackets.holdPackets(c.Packet.deserializeAll(y,!0));const g=r.subarray(w+m);this.serverPackets.holdPackets(c.Packet.deserializeAll(g,!0)),this.batcher.registerSendPackets(this.clientPackets,this);for(const e of this.serverPackets.getPackets()){const t=this.serverPackets.getKey(e.tag);this.asyncMap[t]=e.async,e.async&&(this.asyncData[t]=[!1,[]])}for(const[e,t]of Object.entries(this.preListen??{}))if(this.serverPackets.hasTag(e))for(const n of t)this.listen(e,n);else console.error(new Error(`The server does not define packet tag "${e}"`));this.preListen=null,this.pastKeys=!0,this.handshakeTimer&&clearTimeout(this.handshakeTimer),this.connectedOnce&&(this.reconnectAttempt=0,this.reconnectListeners.forEach(e=>e())),this.connectedOnce=!0,this.readyListeners?.forEach(e=>e()),this.readyListeners=null,this._off("message",this.serverKeyHandler),this._on("message",this.messageHandler),i&&i!==this.sessionId&&(this.pendingResumeSession=i,this.raw_send((0,p.encodeResume)(i,this.lastReplaySequence))),this.readQueue.forEach(e=>{this.messageHandler(e)}),this.readQueue=[]}invalidPacket(e){throw console.error(e),new Error("SonicWS rejected data from the server. Report reproducible codec failures at https://github.com/liwybloc/sonic-ws")}listenLock=!1;packetQueue=[];async deliverPacket(e,t,n,r,a){if(this.closed)return void this.releasePacketLock(n,r,a);const s=this.listeners[t],o=this.serverPackets.getPacket(t),c=o.parent?this.listeners[o.parent]:void 0;if(!s&&!c)return console.warn(`No listener is registered for packet "${t}"`),void this.releasePacketLock(n,r,a);if(s&&await(0,i.listenPacket)(e,s,this.invalidPacket),"string"!=typeof e&&o.parent&&o.variant)for(const t of c??[])await t({variant:o.variant,payload:e[0]});await this.callMiddleware("onReceive_post",t,"string"==typeof e?[e]:e[0]),this.releasePacketLock(n,r,a)}releasePacketLock(e,t,n){t?n[0]=!1:this.listenLock=!1,e.length>0&&this.dataHandler(e.shift())}isAsync(e){return this.asyncMap[e]}async dataHandler(e){if(0===e[0])return void await this.handleControl(e);const t=e[0],n=e.slice(1),r=this.isAsync(t);let a,s,i;if(r?(i=this.asyncData[t],a=i[0],s=i[1]):(a=this.listenLock,s=this.packetQueue),a)return void s.push(e);r?i[0]=!0:this.listenLock=!0;const o=this.serverPackets.getTag(t),c=this.serverPackets.getPacket(o);if(await this.callMiddleware("onReceive_pre",c.tag,e,e.length))return void this.releasePacketLock(s,r,i);if(c.rereference&&0===n.length)return void 0===c.lastReceived[0]&&this.invalidPacket("No previous value to rereference"),void this.deliverPacket(c.lastReceived[0],o,s,r,i);if(0===c.dataBatching){const e=c.lastReceived[0]=await c.listen(n,null);return void this.deliverPacket(e,o,s,r,i)}const l=await d.BatchHelper.unravelBatch(c,n,null);"string"==typeof l&&this.invalidPacket(l),l.forEach(e=>{this.deliverPacket(e,o,s,r,i)})}async handleControl(e){let t;try{t=(0,p.decodeControl)(e)}catch{return void this.close(u.CloseCodes.INVALID_DATA,"Malformed SonicWS control frame")}switch(t.type){case p.ControlType.REPLAY:if(t.sequence<=this.lastReplaySequence)return;return this.lastReplaySequence=t.sequence,void await this.dataHandler(t.payload);case p.ControlType.RESUMED:return t.recovered&&this.pendingResumeSession&&(this.sessionId=this.pendingResumeSession),this.pendingResumeSession=void 0,this.recoveredListeners.forEach(e=>e({recovered:t.recovered,replayed:t.replayed})),void(t.recovered||(this.lastReplaySequence=0));case p.ControlType.RESUME:throw new Error("A client cannot receive a recovery request");case p.ControlType.RESPONSE:{const e=this.pendingRequests.get(t.id);if(!e)return;return clearTimeout(e.timer),this.pendingRequests.delete(t.id),void(t.ok?e.resolve(t.value):e.reject(new Error(String(t.value))))}default:try{const e=this.serverPackets.getTag(t.packetKey);if(!e)throw new Error(`Unknown RPC packet key ${t.packetKey}`);const n=this.responders.get(e);if(!n)throw new Error(`No responder registered for packet "${e}"`);const r=await this.serverPackets.getPacket(e).listen(t.payload,null);if("string"==typeof r)throw new Error(r);const[a,s]=r,i=s?await n(...a):await n(a);this.raw_send((0,p.encodeControlResponse)(t.id,!0,i??null))}catch(e){this.raw_send((0,p.encodeControlResponse)(t.id,!1,e instanceof Error?e.message:String(e)))}}}async messageHandler(e){const t=await this.bufferHandler(e);t.length<1||await this.dataHandler(t)}listen(e,t){if(!this.serverPackets.hasTag(e))return void console.warn(`Packet tag "${e}" is not available on the server`);const n=this.serverPackets.resolveTag(e);(this.listeners[n]??=[]).push(t)}sendQueue=[!1,[],void 0];async send(e,...t){if(await this.callMiddleware("onSend_pre",e,t,Date.now(),performance.now()))return;const[n,r,a]=await(0,i.processPacket)(this.clientPackets,e,t,this.sendQueue,0);0===a.dataBatching?this.raw_send((0,l.toPacketBuffer)(n,r)):this.batcher.batchPacket(n,r),await this.callMiddleware("onSend_post",e,r,r.length)}sendVariant(e,t,...n){return this.send(this.clientPackets.getVariantTag(e,t),...n)}async request(e,...t){const n=t.at(-1),r=t.length>1&&n&&"object"==typeof n&&!Array.isArray(n)&&Object.keys(n).every(e=>"timeoutMs"===e)?t.pop():{},[a,s]=await(0,i.processPacket)(this.clientPackets,e,t,this.sendQueue,0),o=this.nextRequestId++;return this.nextRequestId>2147483647&&(this.nextRequestId=1),new Promise((t,n)=>{const i=setTimeout(()=>{this.pendingRequests.delete(o),n(new Error(`RPC request "${e}" timed out`))},r.timeoutMs??5e3);this.pendingRequests.set(o,{resolve:t,reject:n,timer:i}),this.raw_send((0,p.encodeControlRequest)(o,a,s))})}respond(e,t){const n=this.serverPackets.resolveTag(e);this.responders.set(n,t)}async sendSafe(e,...t){try{return await this.send(e,...t),!0}catch(t){return console.error(`Failed to send packet "${e}"`,t),!1}}async sendVolatile(e,...t){return!!this.canSendVolatile()&&(await this.send(e,...t),!0)}sendReliable(e,...t){return this.send(e,...t)}on_ready(e){this.pastKeys?e():(this.readyListeners??=[]).push(e)}on_close(e){this._on("close",e)}on_reconnecting(e){this.reconnectingListeners.push(e)}on_reconnect(e){this.reconnectListeners.push(e)}on_reconnect_failed(e){this.reconnectFailedListeners.push(e)}on_recovered(e){this.recoveredListeners.push(e)}close(e=1e3,t){this.intentionalClose=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),super.close(e,t)}on(e,t){if(this.socket.readyState!==WebSocket.OPEN){const n=this.preListen??={};return n[e]??=[],void n[e].push(t)}this.listen(e,t)}}t.SonicWSCore=f},950(e,t){function n(e,t){const n=[];for(let r=0;r<e.length;r+=t){const a=e.slice(r,r+t);n.push(a)}return n}Object.defineProperty(t,"__esModule",{value:!0}),t.splitArray=n,t.toPacketBuffer=function(e,t){const n=new Uint8Array(1+t.length);return n[0]=e,n.set(t,1),n},t.splitBuffer=function(e,t){return n(Array.from(e),t)},t.stringifyBuffer=function(e){return`<Buffer ${Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(" ")}>`}},954(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.ValidatePacketSchema=i,t.AssertPacketSchema=function(e,t){const n=i(e,t);if(n.errors.length)throw new Error(`Invalid SonicWS packet schema:\n- ${n.errors.join("\n- ")}`);for(const e of n.warnings)console.warn(`SonicWS schema warning: ${e}`)};const r=n(619),a=new Set([r.PacketType.UBYTES,r.PacketType.USHORTS,r.PacketType.UVARINT]),s=new Set([r.PacketType.BYTES,r.PacketType.UBYTES,r.PacketType.SHORTS,r.PacketType.USHORTS,r.PacketType.VARINT,r.PacketType.UVARINT,r.PacketType.DELTAS,r.PacketType.FLOATS,r.PacketType.DOUBLES]);function i(e,t={}){const n=[],i=[],o=new Set,c=new Map,d=new Set;e.length>254&&n.push(`Packet table contains ${e.length} packets; the maximum is 254`);for(const r of e){o.has(r.tag)&&n.push(`Duplicate packet tag "${r.tag}"`),o.add(r.tag),r.isParent&&c.set(r.tag,r),r.replay&&r.dataBatching&&n.push(`Packet "${r.tag}" combines replay with batching`);const e=Array.isArray(r.type)?r.type:[r.type];r.quantized&&e.some(e=>!s.has(e))&&n.push(`Packet "${r.tag}" quantizes a non-numeric type`),void 0!==r.valueMin&&r.valueMin<0&&e.some(e=>a.has(e))&&n.push(`Packet "${r.tag}" has a negative minimum for an unsigned type`),!r.fields||r.autoFlatten||r.object||r.dataMin!==r.dataMax||r.fields.length===r.dataMax||n.push(`Packet "${r.tag}" schema length does not match its fixed value count`);const l=Array.isArray(r.dataMax)?r.dataMax.some(e=>e>=2048383):r.dataMax>=2048383;if(t.warnUnbounded&&"client"===t.direction&&l&&i.push(`Client packet "${r.tag}" has an effectively unbounded value count`),r.parent&&r.variant){const e=`${r.parent}.${r.variant}`;d.has(e)&&n.push(`Duplicate packet-group variant "${e}"`),d.add(e)}}for(const t of e){if(!t.parent)continue;const e=c.get(t.parent);e?e.type!==r.PacketType.NONE&&n.push(`Packet-group parent "${t.parent}" must use PacketType.NONE`):n.push(`Packet "${t.tag}" references missing group parent "${t.parent}"`)}return{errors:n,warnings:i}}},985(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MiddlewareHolder=void 0;t.MiddlewareHolder=class{middlewares=[];addMiddleware(e){this.middlewares.push(e);const t=e;try{t.init?.(this)}catch(e){console.warn("Middleware init threw an error",e)}}async callMiddleware(e,...t){let n=!1;for(const r of this.middlewares){const a=r[e];if(a)try{await a.call(r,...t)&&(n=!0)}catch(t){console.warn(`Middleware ${String(e)} threw an error`,t)}}return n}}}},__webpack_module_cache__={},hasSymbol,webpackQueues,webpackExports,webpackError,resolveQueue;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={id:e,exports:{}};return __webpack_modules__[e](n,n.exports,__webpack_require__),n.exports}hasSymbol="function"==typeof Symbol,webpackQueues=hasSymbol?Symbol("webpack queues"):"__webpack_queues__",webpackExports=hasSymbol?Symbol("webpack exports"):"__webpack_exports__",webpackError=hasSymbol?Symbol("webpack error"):"__webpack_error__",resolveQueue=e=>{e&&e.d<1&&(e.d=1,e.forEach(e=>e.r--),e.forEach(e=>e.r--?e.r++:e()))},__webpack_require__.a=(e,t,n)=>{var r;n&&((r=[]).d=-1);var a,s,i,o=new Set,c=e.exports,d=new Promise((e,t)=>{i=t,s=e});d[webpackExports]=c,d[webpackQueues]=e=>(r&&e(r),o.forEach(e),d.catch(e=>{})),e.exports=d,t(e=>{var t;a=(e=>e.map(e=>{if(null!==e&&"object"==typeof e){if(e[webpackQueues])return e;if(e.then){var t=[];t.d=0,e.then(e=>{n[webpackExports]=e,resolveQueue(t)},e=>{n[webpackError]=e,resolveQueue(t)});var n={};return n[webpackQueues]=e=>e(t),n}}var r={};return r[webpackQueues]=e=>{},r[webpackExports]=e,r}))(e);var n=()=>a.map(e=>{if(e[webpackError])throw e[webpackError];return e[webpackExports]}),s=new Promise(e=>{(t=()=>e(n)).r=0;var s=e=>e!==r&&!o.has(e)&&(o.add(e),e&&!e.d&&(t.r++,e.push(t)));a.map(e=>e[webpackQueues](s))});return t.r?s:n()},e=>(e?i(d[webpackError]=e):s(c),resolveQueue(r))),r&&r.d<0&&(r.d=0)},__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},__webpack_require__.v=(e,t,n,r)=>{var a=fetch(__webpack_require__.p+"bundle.wasm"),s=()=>a.then(e=>e.arrayBuffer()).then(e=>WebAssembly.instantiate(e,r)).then(t=>Object.assign(e,t.instance.exports));return a.then(t=>"function"==typeof WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(t,r).then(t=>Object.assign(e,t.instance.exports),e=>{if("application/wasm"!==t.headers.get("Content-Type"))return console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",e),s();throw e}):s())},(()=>{var e;__webpack_require__.g.importScripts&&(e=__webpack_require__.g.location+"");var t=__webpack_require__.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var n=t.getElementsByTagName("script");if(n.length)for(var r=n.length-1;r>-1&&(!e||!/^http(s?):/.test(e));)e=n[r--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),__webpack_require__.p=e})();var __webpack_exports__={};(()=>{const e=__webpack_require__(853),t=__webpack_require__(388),n=__webpack_require__(433),r=__webpack_require__(937),a=__webpack_require__(351);class s extends r.SonicWSCore{static initialize(){return(0,a.initializeWasmCore)()}static async connect(e,t={}){await s.initialize();const n=new s(e,t.protocols,t.antiTamper??!1,t.reconnect,t.readyTimeoutMs);return await new Promise((e,t)=>{n.on_ready(e),n.on_close(e=>{t(new Error(`SonicWS connection closed before ready (${e.code})`))})}),n}antiTamperCall=()=>{};constructor(e,t,n=!1,r,a=1e4){const s=new WebSocket(e,t);if(super(s,async e=>new Uint8Array(await e.data.arrayBuffer()),s.addEventListener.bind(s),s.removeEventListener.bind(s)),this.configureHandshakeTimeout(a),r?.enabled){if(n)throw new Error("Reconnect and antiTamper cannot currently be enabled together");this.configureReconnect(()=>{const n=new WebSocket(e,t);return{socket:n,bufferHandler:async e=>new Uint8Array(await e.data.arrayBuffer()),on:n.addEventListener.bind(n),off:n.removeEventListener.bind(n)}},r)}if(n){const e=this,t=s.send.bind(s),n=this.send.bind(this);let r;this.send=async(t,...a)=>{r=e.clientPackets.getKey(t),await n(t,...a)},s.send=n=>n instanceof Uint8Array&&r===n[0]?t(n):(e.antiTamperCall(),void e.close())}}on_tamper(e){this.antiTamperCall=e}WrapEnum(e,n){return(0,t.WrapEnum)(e,n)}DeWrapEnum(e,n){return(0,t.DeWrapEnum)(e,n)}FlattenData(e){return(0,n.FlattenData)(e)}UnFlattenData(e){return(0,n.UnFlattenData)(e)}debugClient=null;OpenDebug(){if(null!=this.debugClient)throw new Error("A debug client is already open");this.debugClient=new e.DebugClient(this)}}window.SonicWS=s})()})();
|
package/dist/index.d.ts
CHANGED
|
@@ -14,6 +14,10 @@ export { BasicMiddleware, ConnectionMiddleware, ServerMiddleware, BCInfo } from
|
|
|
14
14
|
export { CreatePacket, CreateObjPacket, CreateEnumPacket, CreatePacketGroup, FlattenData, UnFlattenData } from './ws/util/packets/PacketUtils';
|
|
15
15
|
export { CreatePacketManifest, LoadPacketManifest } from './ws/util/packets/PacketManifest';
|
|
16
16
|
export type { PacketManifest } from './ws/util/packets/PacketManifest';
|
|
17
|
+
export { ValidatePacketSchema, AssertPacketSchema } from './ws/util/packets/SchemaValidation';
|
|
18
|
+
export type { SchemaValidationResult } from './ws/util/packets/SchemaValidation';
|
|
19
|
+
export { PacketLogger } from './ws/debug/PacketLogger';
|
|
20
|
+
export type { PacketLogEntry, PacketLoggerOptions } from './ws/debug/PacketLogger';
|
|
17
21
|
export { RegisterPacketConstructor, UnregisterPacketConstructor } from './ws/util/packets/ConstructorRegistry';
|
|
18
22
|
export type { PacketConstructor } from './ws/util/packets/ConstructorRegistry';
|
|
19
23
|
export type { SonicWSAdapter, AdapterBroadcast } from './ws/server/Adapter';
|
package/dist/index.js
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
|
|
13
13
|
*/
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
-
exports.initializeWasmCore = exports.WrapEnum = exports.DefineEnum = exports.UnregisterPacketConstructor = exports.RegisterPacketConstructor = exports.LoadPacketManifest = exports.CreatePacketManifest = exports.UnFlattenData = exports.FlattenData = exports.CreatePacketGroup = exports.CreateEnumPacket = exports.CreateObjPacket = exports.CreatePacket = exports.PacketType = exports.SonicWSServer = exports.SonicWSConnection = exports.SonicWS = void 0;
|
|
15
|
+
exports.initializeWasmCore = exports.WrapEnum = exports.DefineEnum = exports.UnregisterPacketConstructor = exports.RegisterPacketConstructor = exports.PacketLogger = exports.AssertPacketSchema = exports.ValidatePacketSchema = exports.LoadPacketManifest = exports.CreatePacketManifest = exports.UnFlattenData = exports.FlattenData = exports.CreatePacketGroup = exports.CreateEnumPacket = exports.CreateObjPacket = exports.CreatePacket = exports.PacketType = exports.SonicWSServer = exports.SonicWSConnection = exports.SonicWS = void 0;
|
|
16
16
|
var ClientNode_1 = require("./ws/client/node/ClientNode");
|
|
17
17
|
Object.defineProperty(exports, "SonicWS", { enumerable: true, get: function () { return ClientNode_1.SonicWS; } });
|
|
18
18
|
var SonicWSConnection_1 = require("./ws/server/SonicWSConnection");
|
|
@@ -31,6 +31,11 @@ Object.defineProperty(exports, "UnFlattenData", { enumerable: true, get: functio
|
|
|
31
31
|
var PacketManifest_1 = require("./ws/util/packets/PacketManifest");
|
|
32
32
|
Object.defineProperty(exports, "CreatePacketManifest", { enumerable: true, get: function () { return PacketManifest_1.CreatePacketManifest; } });
|
|
33
33
|
Object.defineProperty(exports, "LoadPacketManifest", { enumerable: true, get: function () { return PacketManifest_1.LoadPacketManifest; } });
|
|
34
|
+
var SchemaValidation_1 = require("./ws/util/packets/SchemaValidation");
|
|
35
|
+
Object.defineProperty(exports, "ValidatePacketSchema", { enumerable: true, get: function () { return SchemaValidation_1.ValidatePacketSchema; } });
|
|
36
|
+
Object.defineProperty(exports, "AssertPacketSchema", { enumerable: true, get: function () { return SchemaValidation_1.AssertPacketSchema; } });
|
|
37
|
+
var PacketLogger_1 = require("./ws/debug/PacketLogger");
|
|
38
|
+
Object.defineProperty(exports, "PacketLogger", { enumerable: true, get: function () { return PacketLogger_1.PacketLogger; } });
|
|
34
39
|
var ConstructorRegistry_1 = require("./ws/util/packets/ConstructorRegistry");
|
|
35
40
|
Object.defineProperty(exports, "RegisterPacketConstructor", { enumerable: true, get: function () { return ConstructorRegistry_1.RegisterPacketConstructor; } });
|
|
36
41
|
Object.defineProperty(exports, "UnregisterPacketConstructor", { enumerable: true, get: function () { return ConstructorRegistry_1.UnregisterPacketConstructor; } });
|