@genex-ai/multiplayer 0.17.1 → 0.17.6
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/PROTOCOL.md +688 -7
- package/README.md +263 -0
- package/dist/authority/fast-udp.d.ts +13 -0
- package/dist/authority/fast-udp.js +52 -0
- package/dist/authority/fast-webtransport.d.ts +45 -0
- package/dist/authority/fast-webtransport.js +124 -0
- package/dist/authority/index.d.ts +2333 -0
- package/dist/authority/index.js +758 -0
- package/dist/authority/module.d.ts +1 -0
- package/dist/authority/module.js +12 -0
- package/dist/bridge-authority.d.ts +100 -0
- package/dist/bridge-authority.global.js +14 -0
- package/dist/bridge-authority.js +286 -0
- package/dist/bridge-core-Dhc73GC8.d.ts +27 -0
- package/dist/bridge.d.ts +26 -20
- package/dist/bridge.global.js +7 -7
- package/dist/bridge.js +17 -48
- package/dist/chunk-4R7C2TLH.js +68 -0
- package/dist/chunk-5JGRFT2N.js +3646 -0
- package/dist/{chunk-3ZUPU3GT.js → chunk-7QVOIHJF.js} +13 -122
- package/dist/chunk-K3SF5VDS.js +27 -0
- package/dist/chunk-UX3F6YTV.js +143 -0
- package/dist/chunk-Y6XHXDIK.js +6617 -0
- package/dist/{chunk-C52XFIB6.js → chunk-ZSWF4VCN.js} +141 -4
- package/dist/fast-client-CZ41v-oB.d.ts +465 -0
- package/dist/index.d.ts +3 -5
- package/dist/index.js +3 -2
- package/dist/join-CGoInvUM.d.ts +6 -0
- package/dist/module-DqtFb5wA.d.ts +1436 -0
- package/dist/physics-predict-49udN3a1.d.ts +1208 -0
- package/dist/protocol.d.ts +137 -2
- package/dist/protocol.js +33 -1
- package/package.json +33 -3
package/dist/bridge.global.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
"use strict";(()=>{var lp=Object.create;var fi=Object.defineProperty;var up=Object.getOwnPropertyDescriptor;var dp=Object.getOwnPropertyNames;var fp=Object.getPrototypeOf,hp=Object.prototype.hasOwnProperty;var Ml=n=>{throw TypeError(n)};var pp=(n,e,t)=>e in n?fi(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Oe=(n,e)=>()=>(n&&(e=n(n=0)),e);var mp=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Dl=(n,e)=>{for(var t in e)fi(n,t,{get:e[t],enumerable:!0})},gp=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of dp(e))!hp.call(n,s)&&s!==t&&fi(n,s,{get:()=>e[s],enumerable:!(r=up(e,s))||r.enumerable});return n};var yp=(n,e,t)=>(t=n!=null?lp(fp(n)):{},gp(e||!n||!n.__esModule?fi(t,"default",{value:n,enumerable:!0}):t,n));var l=(n,e,t)=>pp(n,typeof e!="symbol"?e+"":e,t),ha=(n,e,t)=>e.has(n)||Ml("Cannot "+t);var H=(n,e,t)=>(ha(n,e,"read from private field"),t?t.call(n):e.get(n)),he=(n,e,t)=>e.has(n)?Ml("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),pe=(n,e,t,r)=>(ha(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t),On=(n,e,t)=>(ha(n,e,"access private method"),t);var _e,pr,Ja,Mi,Di,Bn,Ne,Mu=Oe(()=>{"use strict";_e={JOIN_ROOM:10,ERROR:11,LEAVE_ROOM:12,ROOM_DATA:13,ROOM_STATE:14,ROOM_STATE_PATCH:15,ROOM_DATA_SCHEMA:16,ROOM_DATA_BYTES:17,PING:18,ROOM_INPUT_RELIABLE:19,ROOM_INPUT_UNRELIABLE:20,ROOM_REQUEST:21,ROOM_RESPONSE:22},pr={TIMED:128,UNRELIABLE:64},Ja=31,Mi={OK:0,REJECTED:1,ERROR:2},Di={INPUT_REFLECTION:1,INPUT_OPTIONS:2},Bn={RENDER_TIME:1,FIXED_TIMESTEP:2,PATCH_RATE:4,SUB_STEPS:8,RECKON_TIME:16},Ne={NORMAL_CLOSURE:1e3,GOING_AWAY:1001,NO_STATUS_RECEIVED:1005,ABNORMAL_CLOSURE:1006,CONSENTED:4e3,SERVER_SHUTDOWN:4001,WITH_ERROR:4002,FAILED_TO_RECONNECT:4003,MAY_TRY_RECONNECT:4010}});var Yt=Oe(()=>{"use strict";Mu()});function xd(n){Object.defineProperty(n,Symbol.metadata,{value:void 0,writable:!0,configurable:!0,enumerable:!1})}function vd(n,e,t){for(var r=0,s=0,i=e.length;s<i;s++)r=e.charCodeAt(s),r<128?n[t.offset++]=r:r<2048?(n[t.offset]=192|r>>6,n[t.offset+1]=128|r&63,t.offset+=2):r<55296||r>=57344?(n[t.offset]=224|r>>12,n[t.offset+1]=128|r>>6&63,n[t.offset+2]=128|r&63,t.offset+=3):(s++,r=65536+((r&1023)<<10|e.charCodeAt(s)&1023),n[t.offset]=240|r>>18,n[t.offset+1]=128|r>>12&63,n[t.offset+2]=128|r>>6&63,n[t.offset+3]=128|r&63,t.offset+=4)}function Ad(n,e,t){n[t.offset++]=e&255}function Jm(n,e,t){n[t.offset++]=e&255}function Cd(n,e,t){n[t.offset++]=e&255,n[t.offset++]=e>>8&255}function oc(n,e,t){n[t.offset++]=e&255,n[t.offset++]=e>>8&255}function en(n,e,t){n[t.offset++]=e&255,n[t.offset++]=e>>8&255,n[t.offset++]=e>>16&255,n[t.offset++]=e>>24&255}function Un(n,e,t){let r=e>>24,s=e>>16,i=e>>8,o=e;n[t.offset++]=o&255,n[t.offset++]=i&255,n[t.offset++]=s&255,n[t.offset++]=r&255}function Id(n,e,t){let r=Math.floor(e/Math.pow(2,32)),s=e>>>0;Un(n,s,t),Un(n,r,t)}function Pd(n,e,t){let r=e/Math.pow(2,32)>>0,s=e>>>0;Un(n,s,t),Un(n,r,t)}function Km(n,e,t){Td[0]=BigInt.asIntN(64,e),en(n,Fn[0],t),en(n,Fn[1],t)}function Ym(n,e,t){Td[0]=BigInt.asIntN(64,e),en(n,Fn[0],t),en(n,Fn[1],t)}function Od(n,e,t){Za[0]=e,en(n,Fn[0],t)}function Md(n,e,t){zm[0]=e,en(n,Fn[0],t),en(n,Fn[1],t)}function Xm(n,e,t){n[t.offset++]=e?1:0}function Qm(n,e,t){e||(e="");let r=kd(e,"utf8"),s=0;if(r<32)n[t.offset++]=r|160,s=1;else if(r<256)n[t.offset++]=217,n[t.offset++]=r,s=2;else if(r<65536)n[t.offset++]=218,oc(n,r,t),s=3;else if(r<4294967296)n[t.offset++]=219,Un(n,r,t),s=5;else throw new Error("String too long");return vd(n,e,t),s+r}function ec(n,e,t){if(isNaN(e))return ec(n,0,t);if(isFinite(e)){if(e!==(e|0))return Math.abs(e)<=34028235e31&&(Za[0]=e,Math.abs(Math.abs(Za[0])-Math.abs(e))<1e-4)?(n[t.offset++]=202,Od(n,e,t),5):(n[t.offset++]=203,Md(n,e,t),9)}else return ec(n,e>0?Number.MAX_SAFE_INTEGER:-Number.MAX_SAFE_INTEGER,t);return e>=0?e<128?(n[t.offset++]=e&255,1):e<256?(n[t.offset++]=204,n[t.offset++]=e&255,2):e<65536?(n[t.offset++]=205,oc(n,e,t),3):e<4294967296?(n[t.offset++]=206,Un(n,e,t),5):(n[t.offset++]=207,Pd(n,e,t),9):e>=-32?(n[t.offset++]=224|e+32,1):e>=-128?(n[t.offset++]=208,Ad(n,e,t),2):e>=-32768?(n[t.offset++]=209,Cd(n,e,t),3):e>=-2147483648?(n[t.offset++]=210,en(n,e,t),5):(n[t.offset++]=211,Id(n,e,t),9)}function Dd(n,e,t){t>n.length-e.offset&&(t=n.length-e.offset);for(var r="",s=0,i=e.offset,o=e.offset+t;i<o;i++){var a=n[i];if((a&128)===0){r+=String.fromCharCode(a);continue}if((a&224)===192){r+=String.fromCharCode((a&31)<<6|n[++i]&63);continue}if((a&240)===224){r+=String.fromCharCode((a&15)<<12|(n[++i]&63)<<6|(n[++i]&63)<<0);continue}if((a&248)===240){s=(a&7)<<18|(n[++i]&63)<<12|(n[++i]&63)<<6|(n[++i]&63)<<0,s>=65536?(s-=65536,r+=String.fromCharCode((s>>>10)+55296,(s&1023)+56320)):r+=String.fromCharCode(s);continue}console.error("decode.utf8Read(): Invalid byte "+a+" at offset "+i+". Skip to end of string: "+(e.offset+t));break}return e.offset+=t,r}function Nd(n,e){return bs(n,e)<<24>>24}function bs(n,e){return n[e.offset++]}function Bd(n,e){return Qi(n,e)<<16>>16}function Qi(n,e){return n[e.offset++]|n[e.offset++]<<8}function xt(n,e){return n[e.offset++]|n[e.offset++]<<8|n[e.offset++]<<16|n[e.offset++]<<24}function yr(n,e){return xt(n,e)>>>0}function Ld(n,e){return $n[0]=xt(n,e),Zm[0]}function Fd(n,e){return $n[0]=xt(n,e),$n[1]=xt(n,e),eg[0]}function Ud(n,e){let t=yr(n,e);return xt(n,e)*Math.pow(2,32)+t}function $d(n,e){let t=yr(n,e);return yr(n,e)*Math.pow(2,32)+t}function rg(n,e){return $n[0]=xt(n,e),$n[1]=xt(n,e),ng[0]}function sg(n,e){return $n[0]=xt(n,e),$n[1]=xt(n,e),tg[0]}function ig(n,e){return bs(n,e)>0}function og(n,e){let t=n[e.offset++],r;return t<192?r=t&31:t===217?r=bs(n,e):t===218?r=Qi(n,e):t===219&&(r=yr(n,e)),Dd(n,e,r)}function ag(n,e){let t=n[e.offset++];if(t<128)return t;if(t===202)return Ld(n,e);if(t===203)return Fd(n,e);if(t===204)return bs(n,e);if(t===205)return Qi(n,e);if(t===206)return yr(n,e);if(t===207)return $d(n,e);if(t===208)return Nd(n,e);if(t===209)return Bd(n,e);if(t===210)return xt(n,e);if(t===211)return Ud(n,e);if(t>223)return(255-t+1)*-1}function cg(n,e){let t=n[e.offset];return t<192&&t>160||t===217||t===218||t===219}function nn(n,e){e.constructor&&(Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor[Symbol.metadata]==null&&xd(e.constructor),lg.set(e.constructor,n),ac[n]=e),e.encode&&(Q[n]=e.encode),e.decode&&(te[n]=e.decode)}function Vd(n){return ac[n]}function tn(){return{pendingByView:new Map,sentByView:new Map,broadcastPending:new Set,sentBroadcast:new Set,broadcastDeletes:new Set,maxPerTick:32}}function lc(n){return n._stream??(n._stream=tn())}function Zi(n,e,t){e.activeViews.size===0&&lc(n).broadcastPending.add(t)}function eo(n,e,t,r){let s=n._stream;if(s===void 0)return!0;let i=!1;return s.broadcastPending.delete(r)?i=!0:s.sentBroadcast.delete(r)&&s.broadcastDeletes.add(r),e.forEachActiveView(o=>{let a=s.pendingByView.get(o.id);if(a?.has(r)){a.delete(r),i=!0;return}let c=s.sentByView.get(o.id);if(c?.has(r)){c.delete(r);let u=o.changes.get(t);u===void 0&&(u=new Map,o.changes.set(t,u)),u.set(r,R.DELETE)}}),i}function ug(n,e,t){let r=n._stream;if(r!==void 0){r.broadcastPending.clear();for(let s of r.sentBroadcast)r.broadcastDeletes.add(s);r.sentBroadcast.clear(),e.forEachActiveView(s=>{r.pendingByView.get(s.id)?.clear();let i=r.sentByView.get(s.id);if(i!==void 0&&i.size>0){let o=s.changes.get(t);o===void 0&&(o=new Map,s.changes.set(t,o));for(let a of i)o.set(a,R.DELETE);i.clear()}})}}function dg(n,e){let t=n._stream?.pendingByView;if(t===void 0)return!1;for(let[r,s]of t)if(s.size>0&&e.activeViews.get(r)?.deref()!==void 0)return!0;return!1}function fg(n){let e=n._stream;return e!==void 0&&(e.broadcastPending.size>0||e.broadcastDeletes.size>0)}function hg(n,e,t){let r=lc(n),s=r.pendingByView.get(e);s===void 0&&(s=new Set,r.pendingByView.set(e,s)),s.add(t)}function to(n,e){let t=n._stream;t!==void 0&&(t.pendingByView.delete(e),t.sentByView.delete(e),t.priorityByView?.delete(e))}function uc(n){if(n==null||typeof n!="object")throw new Error("t.quantized(): options object with { min, max } is required.");let{min:e,max:t}=n;if(typeof e!="number"||typeof t!="number"||!(t>e)||!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`t.quantized(): require finite min < max (got min=${e}, max=${t}).`);let r=n.bits??16;if(r!==8&&r!==16&&r!==32)throw new Error(`t.quantized(): bits must be 8, 16 or 32 (got ${r}).`);let s=n.mode??"clamp";if(s!=="clamp"&&s!=="wrap")throw new Error(`t.quantized(): mode must be "clamp" or "wrap" (got ${JSON.stringify(s)}).`);let i=s==="wrap",o=Math.pow(2,r);return{min:e,max:t,bits:r,wrap:i,wire:pg[r],range:t-e,span:i?o:e===-t?o-2:o-1}}function Vn(n){return n!==null&&typeof n=="object"&&n.quantized!==void 0}function qd(n,e){if(n.wrap){if(!Number.isFinite(e))return 0;let r=n.range,s=(e-n.min)%r;s<0&&(s+=r);let i=n.span;return Math.floor(s/r*i+.5)%i}if(e!==e)return 0;let t=e<n.min?n.min:e>n.max?n.max:e;return Math.floor((t-n.min)/n.range*n.span+.5)}function Gd(n,e){return n.min+e/n.span*n.range}function mg(n){let e=Q[n.wire];return(t,r,s)=>e(t,qd(n,r),s)}function gg(n,e,t){let r=te[n.wire];return Gd(n,r(e,t))}function yg(n){let e=typeof Object.keys(n)[0]=="string"&&Vd(Object.keys(n)[0]);return{complexTypeKlass:e,childType:e?Object.values(n)[0]:n}}function br(n){if(Array.isArray(n))return{array:br(n[0])};if(Vn(n))return typeof n.quantized.wire=="string"?n:{quantized:uc(n.quantized)};if(typeof n.type<"u")return n.type;if(bg(n))return Object.keys(n).every(e=>typeof n[e]=="string")?"string":"number";if(typeof n=="object"&&n!==null){let e=Object.keys(n).find(t=>ac[t]!==void 0);if(e)return n[e]=br(n[e]),n}return n}function bg(n){if(typeof n=="function"&&n[Symbol.metadata])return!1;let e=Object.keys(n),t=e.filter(r=>/\d+/.test(r));return!!(t.length>0&&t.length===e.length/2&&n[n[t[0]]]==t[0]||e.length>0&&e.every(r=>typeof n[r]=="string"&&n[r]===r))}function Bi(n,e,t){n[e]||Object.defineProperty(n,e,{value:[],enumerable:!1,configurable:!0,writable:!0}),n[e].push(t)}function qi(n){return n=n-(n>>>1&1431655765),n=(n&858993459)+(n>>>2&858993459),(n+(n>>>4)&252645135)*16843009>>>24}function Li(n){if(n===void 0)return 0;let e=0;for(let t=0,r=n.length;t<r;t++){let s=n[t];s<32&&(e|=1<<s)}return e}function _g(n){let e=[],t=[],r=[],s=[],i=n?.[Fe];if(i===void 0)return{names:e,types:t,tags:r,encoders:s};let o=n[Qt];for(let a=0;a<=i;a++){let c=n[a];if(c===void 0){e[a]=void 0,t[a]=void 0,r[a]=void 0,s[a]=void 0;continue}e[a]=c.name,t[a]=c.type,r[a]=c.tag,s[a]=o?.[a]}return{names:e,types:t,tags:r,encoders:s}}function dc(n){let e=n.constructor;if(Object.prototype.hasOwnProperty.call(e,ls))return e[ls];let t=e[Symbol.metadata],r=ce.isValidInstance(n),s=(t?.[bt]?.length??0)>0,i=_g(t),o=r&&!s?void 0:e[qn],a={encoder:e[Nt],filter:o,metadata:t,isSchema:r,filterBitmask:r?Li(t?.[bt]):0,hasAnyFullStateOnly:(t?.[gr]?.length??0)>0,hasAnyUnreliable:(t?.[Ln]?.length??0)>0,hasAnyStream:(t?.[at]?.length??0)>0,hasAnyView:s,fullStateOnlyBitmask:Li(t?.[gr]),unreliableBitmask:Li(t?.[Ln]),streamBitmask:Li(t?.[at]),names:i.names,types:i.types,tags:i.tags,encoders:i.encoders};return Object.defineProperty(e,ls,{value:a,enumerable:!1,writable:!0,configurable:!0}),a}function Eg(n,e,t){if(n.parentRef){if(n.parentRef[_]===e[_]){n._parentIndex=t;return}if(zd(n,(r,s)=>r[_]===e[_])){n._parentIndex=t;return}}n.parentRef===void 0?(n.parentRef=e,n._parentIndex=t):(n.extraParents={ref:n.parentRef,index:n._parentIndex,next:n.extraParents},n.parentRef=e,n._parentIndex=t)}function Rg(n,e,t){if(n.extraParents===void 0){n._parentIndex=t;return}if(n.parentRef[_]===e[_]){n._parentIndex=t;return}for(let r=n.extraParents;r!==void 0;r=r.next)if(r.ref[_]===e[_]){r.index=t;return}}function xg(n,e){if(n.parentRef&&n.parentRef[_]===e[_])return n.extraParents?(n.parentRef=n.extraParents.ref,n._parentIndex=n.extraParents.index,n.extraParents=n.extraParents.next):(n.parentRef=void 0,n._parentIndex=void 0),!0;let t=n.extraParents,r=null;for(;t;){if(t.ref[_]===e[_])return r?r.next=t.next:n.extraParents=t.next,!0;r=t,t=t.next}return n.parentRef===void 0}function Sg(n,e){if(n.parentRef!==void 0&&e(n.parentRef,n._parentIndex))return{ref:n.parentRef,index:n._parentIndex};for(let t=n.extraParents;t!==void 0;t=t.next)if(e(t.ref,t.index))return{ref:t.ref,index:t.index}}function zd(n,e){if(n.parentRef!==void 0&&e(n.parentRef,n._parentIndex))return!0;for(let t=n.extraParents;t!==void 0;t=t.next)if(e(t.ref,t.index))return!0;return!1}function Tg(n,e){if(n.parentRef&&n.parentRef[_]===e[_])return n._parentIndex;for(let t=n.extraParents;t!==void 0;t=t.next)if(t.ref[_]===e[_])return t.index}function kg(n){let e=[];n.parentRef&&e.push({ref:n.parentRef,index:n._parentIndex});let t=n.extraParents;for(;t;)e.push({ref:t.ref,index:t.index}),t=t.next;return e}function vg(n,e,t){let r=e.refTarget;if(e.isArray){let i=r.items,o=i[t];if(o!==void 0&&o[_]===n)return!0;for(let a=0,c=i.length;a<c;a++){let u=i[a];if(u!==void 0&&u[_]===n)return!0}return!1}let s=e.getValue(t);return s!==void 0&&s[_]===n}function Cg(n,e){fc(n,e,Ag)}function fc(n,e,t){let r=n.refTarget;if(r[X]!==void 0){if(n.isPatchOnly)return;if(Array.isArray(r.items)){let s=r.items;for(let i=0,o=s.length;i<o;i++)s[i]!==void 0&&t(e,i)}else if(r.journal!==void 0)for(let[s,i]of r.journal.keyByIndex)r.$items.has(i)&&t(e,s);else if(r.$items!==void 0)for(let s of r.$items.keys())t(e,s)}else{let s=n.metadata;if(!s)return;let i=s[Fe]??-1,o=s[ji],a=n.encDescriptor.names;for(let c=0;c<=i;c++){let u=a[c];if(u===void 0||o&&o.includes(c))continue;let d=r[u];d!=null&&t(e,c)}}}function Jd(n,e,t,r){Ig(n,e,t),!n.isFullStateOnly&&(n.has()&&n.root?.enqueueChangeTree(n),n.unreliableRecorder?.has()&&n.root?.enqueueUnreliable(n),!n.has()&&!n.unreliableRecorder?.has()&&n.root?.enqueueChangeTree(n))}function Ig(n,e,t){if(!e)return;let r=e[_],s=!r._isSchema,i;s?(e=r.parent,t=r.parentIndex,i=e?.[_].metadata):i=r.metadata;let o=(i?.[ds]?.includes(t)?us:0)|(i?.[gr]?.includes(t)?mr:0),a=r.flags&jg|o,c=n.flags;if(n.flags=c|a,a&~c&mr&&(n.reset(),n.unreliableRecorder?.reset()),!n.root?.types?.hasFilters)return;let h=i?.[bt]?.includes(t)??!1,m=i?.[at]?.includes(t)??!1,g=r.isFiltered||h||m;if(n.isFiltered=g,m&&!s){n.isStreamCollection=!0;let p=lc(n.ref);if(p.priority===void 0){let y=ce.getStreamPriority(i,t);y!==void 0&&(p.priority=y)}n.root?.registerStream(n.ref)}if(g){let p=Kd(n);n.isVisibilitySharedWithParent=r.isFiltered&&p&&!m&&(!h||s&&i[t].tag!==io)}}function Bu(n){let e=n.pendingFilterRefresh;for(let t=0;t<e.length;t++){let r=e[t];(r.flags&fs)!==0&&hc(r)}e.length=0}function Kd(n){return n._isSchema||typeof n.refTarget[X]!="string"}function hc(n){n.flags&=~fs;let e=n.root;if(e===void 0||n.parentRef===void 0)return;let t=Kd(n),r=Lu(n,n.parentRef,n._parentIndex,t);for(let i=n.extraParents;i!==void 0&&r!==Pg;i=i.next)r|=Lu(n,i.ref,i.index,t);if(r===0)return;n.isVisibilitySharedWithParent=(r&Hi)!==0;let s=(r&Gi)===0;s!==n.isFiltered&&(n.isFiltered=s,!s&&!n.isFullStateOnly&&(n.forEachLiveWithCtx(n,Wd),n.has()&&e.enqueueChangeTree(n),n.unreliableRecorder?.has()&&e.enqueueUnreliable(n)),n.forEachChildWithCtx(n,Og))}function Lu(n,e,t,r){let s=e[_];if(s.root!==n.root||!vg(n,s,t))return 0;s.flags&fs&&hc(s);let i=Yd;if(s._isSchema)s.encDescriptor.tags[t]!==void 0||s.isFieldStream(t)||(s.isFiltered?r&&(i|=Hi):i|=Gi);else if(!s.isFiltered)i|=Gi;else if(r&&!s.isStreamCollection){let o=s.parent?.[_];(o?._isSchema?o.encDescriptor.tags[s.parentIndex]:void 0)!==io&&(i|=Hi)}return i}function Mg(n,e,t,r){let s=n.subscribedViews;if(s===void 0)return;let i=n.isStreamCollection,o=i?n.ref:void 0,a=i?void 0:t[_];for(let c=0,u=s.length;c<u;c++){let d=s[c];for(;d!==0;){let h=d&-d;d^=h;let m=c*32+(31-Math.clz32(h)),p=r.activeViews.get(m)?.deref();if(p===void 0){s[c]&=~h;continue}i?hg(o,m,e):a!==void 0&&p.markVisible(a)}}}function Dg(n,e){n.root=e;let t=e.add(n);Jd(n,n.parent,n.parentIndex),t&&ws(n,e,Fg)}function Ng(n,e,t,r){if(n.addParent(e,r),!t)return;let s=t.add(n);t!==n.root&&(n.root=t,Jd(n,e,r));let i=e?.[_];if(i!==void 0&&i.subscribedViews!==void 0&&e[X]!==void 0&&Mg(i,r,n.ref,t),s){let o=Fu[Fi];o===void 0&&(o={parentRef:void 0,root:void 0},Fu[Fi]=o),o.parentRef=n.ref,o.root=t,Fi++,ws(n,o,Ug),Fi--}}function Bg(n,e){ws(n,e,Lg)}function Lg(n,e,t){n(e,t)}function ws(n,e,t){let r=n.refTarget;if(r[X]){if(typeof r[X]!="string"){let s=r.items;if(s!==void 0)for(let i=0,o=s.length;i<o;i++){let a=s[i];a&&t(e,a[_],i)}else{let i=r.$items,o=r._collectionIndexes;for(let a of i.keys()){let c=i.get(a);c&&t(e,c[_],o?.[a]??a)}}}}else{let i=n.metadata?.[bn];if(!i)return;let o=n.encDescriptor.names;for(let a=0,c=i.length;a<c;a++){let u=i[a],d=r[o[u]];d&&t(e,d[_],u)}}}function Fg(n,e,t){e.root!==n?e.setRoot(n):n.add(e)}function Ug(n,e,t){if(e.root===n.root){n.root.add(e),n.root.moveNextToParent(e);return}e.setParent(n.parentRef,n.root,t)}function $g(n,e,t){let r=(t&3)<<3;return t<4?n>>>r&255:e>>>r&255}function Uu(){return{next:void 0,tail:void 0,nextPosition:0}}function qg(n){return new rc(n)}function _r(n,e=n){Object.defineProperty(n,_,{value:qg(e),enumerable:!1,writable:!0})}function no(n,e,t,r,s,i,o){o!==void 0?o(e,r,i):typeof t=="string"?Q[t]?.(e,r,i):t[Symbol.metadata]!=null?(Q.number(e,r[$],i),(s&R.ADD)===R.ADD&&n.tryEncodeTypeId(e,t,r.constructor,i)):Q.number(e,r[$],i)}function Xd(n,e,t,r,s,i,o){let a=n.resyncVisited,c=a.get(n.currentRefId);if(c===void 0&&a.set(n.currentRefId,c=new Set),c.add(r),s!==void 0&&t===R.ADD&&s!==i){let u=s[$];u!==void 0&&(n.root.removeRef(u),o?.push({ref:e,refId:n.currentRefId,op:R.DELETE,dynamicIndex:r,value:void 0,previousValue:s}))}}function Wg(n,e){let t=n.resyncVisited;t.has(e)||t.set(e,new Set)}function Jg(n,e){if(n.resyncDamaged){console.warn("@colyseus/schema: resync sweep skipped \u2014 parts of the payload could not be decoded. Stale entries may persist until the next resync.");return}gc(n,n.state,new Set,e)}function gc(n,e,t,r){let s=e[$];if(s===void 0||t.has(s))return;t.add(s);let i=e.constructor[Symbol.metadata],o=i?.[bn];if(o===void 0)return;let a=i[ds];for(let c=0;c<o.length;c++){let u=o[c];if(a!==void 0&&a.includes(u))continue;let d=i[u],h=e[d.name];h&&(Ee.is(d.type)?gc(n,h,t,r):Kg(n,h,t,r))}}function Kg(n,e,t,r){let s=e[Ce]??e,i=s[$];if(i===void 0||t.has(i))return;t.add(i);let o=n.resyncVisited.get(i);if(o===void 0)return;let a=n.root;s[wr](o,(c,u)=>{r?.push({ref:e,refId:i,op:R.DELETE,dynamicIndex:u,value:void 0,previousValue:c});let d=c?.[$];d!==void 0&&a.removeRef(d)},c=>{Ee.isSchema(c)&&gc(n,c,t,r)})}function yc(n,e,t,r,s,i,o,a,c){let u=n.root,d;if((e&R.DELETE)===R.DELETE){let h=s?.[$];h!==void 0&&u.removeRef(h),e!==R.DELETE_AND_ADD&&t[Rt](r),d=void 0}if(e!==R.DELETE)if(typeof i=="string")d=te[i](o,a);else if(Vn(i))d=gg(i.quantized,o,a);else if(Ee.is(i)){let h=te.number(o,a);if(d=u.refs.get(h),(e&R.ADD)===R.ADD){let m=n.getInstanceType(o,a,i);d||(d=n.createInstanceOfType(m)),u.addRef(h,d,d!==s||e===R.DELETE_AND_ADD&&d===s)}}else{let h=Vd(Object.keys(i)[0]),m=te.number(o,a);n.resyncVisited!==null&&Wg(n,m);let g=u.refs.has(m)?s||u.refs.get(m):h.constructor.initializeForDecoder();if(d=g.clone(!0),d[X]=Object.values(i)[0],s){let p=s[$];if(p!==void 0&&m!==p){(e&R.DELETE)!==R.DELETE&&u.removeRef(p);let y=s.entries(),x;for(;(x=y.next())&&!x.done;){let[k,I]=x.value;typeof I=="object"&&(p=I[$]),c?.push({ref:s,refId:p,op:R.DELETE,field:k,value:void 0,previousValue:I})}}}u.addRef(m,d,g!==s||e===R.DELETE_AND_ADD&&g===s)}return d}function so(n,e,t,r){if(!(n instanceof e))throw new hs(`a '${e.name}' was expected, but '${n&&n.constructor.name}' was provided in ${t.constructor.name}#${r}`)}function Zd(n){return n!=null&&n[Sd]===!0}function Ge(n){return(()=>new Bt(n))}function _s(n){if(Zd(n)){let e=n._type,t=typeof e=="string"?`use the type name instead: t.array("${e}")`:'collections accept a Schema class or a primitive type name ("string", "number", \u2026)';throw new Error(`t.array/map/set/collection(): a t.* builder is not a valid element type \u2014 ${t}.`)}return n}function Vu(n){return new Bt({quantized:uc(n)})}function iy(n=io){return function(e,t){let r=ce.initialize(e.constructor);ce.setTag(r,t,n)}}function oy(n,e){let t=ce.initialize(n.constructor);ce.setUnreliable(t,e)}function ay(n,e){let t=ce.initialize(n.constructor);ce.setPatchOnly(t,e)}function ly(n,e,t){let r=cy[t],s=t==="string",i=t==="boolean";return function(o){let a=this[Ue],c=a[e];if(o!==c){if(o!=null){if(!i&&r!==void 0&&typeof o!==r&&!(s&&o===null)){let u=o&&o.constructor?` (${o.constructor.name})`:"";throw new hs(`a '${r}' was expected, but '${JSON.stringify(o)}'${u} was provided in ${this.constructor.name}#${n}`)}this.constructor[Dt](this[_],e,R.ADD)}else c!=null&&this[_].delete(e);a[e]=o}}}function uy(n,e,t){return function(r){let s=this[Ue],i=s[e];if(r!==i){if(r!=null){so(r,t,this,n);let o=this[_],a=this.constructor;i!=null&&i[_]?(o.root?.remove(i[_]),a[Dt](o,e,R.DELETE_AND_ADD)):a[Dt](o,e,R.ADD),r[_]?.setParent(this,o.root,e)}else i!=null&&this[_].delete(e);s[e]=r}}}function dy(n,e,t,r){let s=r.constructor===wn,i=r.constructor===_n;return function(o){let a=this[Ue],c=a[e];if(o!==c){if(o!=null){if(s&&!(o instanceof wn)){let h=new wn;h[X]=t,h.push(...o),o=h}else if(i&&!(o instanceof _n)){let h=new _n;if(h[X]=t,o instanceof Map)o.forEach((m,g)=>h.set(g,m));else for(let m in o)h.set(m,o[m]);o=h}else o[X]=t;let u=this[_],d=this.constructor;c!=null&&c[_]?(u.root?.remove(c[_]),d[Dt](u,e,R.DELETE_AND_ADD)):d[Dt](u,e,R.ADD),o[_]?.setParent(this,u.root,e)}else c!=null&&this[_].delete(e);a[e]=o}}}function fy(n,e,t){return function(r){let s=this[Ue],i=s[e];if(r!=null){if(typeof r!="number")throw new hs(`a 'number' was expected, but '${JSON.stringify(r)}' was provided in ${this.constructor.name}#${n}`);if(r=Gd(t,qd(t,r)),r===i)return;this.constructor[Dt](this[_],e,R.ADD)}else{if(r===i)return;i!=null&&this[_].delete(e)}s[e]=r}}function hy(n,e,t,r){let s;return r?s=dy(n,e,t,r):typeof t=="string"?s=ly(n,e,t):Vn(t)?s=fy(n,e,t.quantized):s=uy(n,e,t),{get:function(){return this[Ue][e]},set:s,enumerable:!0,configurable:!0}}function py(n=!0){return function(e,t){let r=ce.initialize(e.constructor);ce.setDeprecated(r,t),n&&(r[ot]??(r[ot]={}),r[ot][t]={get:function(){throw new Error(`${t} is deprecated.`)},set:function(s){},enumerable:!1,configurable:!0},Object.defineProperty(e,t,r[ot][t]))}}function my(n){if(n&&typeof n=="object"){if(n.array!==void 0)return()=>new wn;if(n.map!==void 0)return()=>new _n;if(n.set!==void 0)return()=>new ms;if(n.collection!==void 0)return()=>new ps;if(n.stream!==void 0)return()=>new Wi}else if(typeof n=="function"&&Ee.is(n)&&(!n.prototype.initialize||n.prototype.initialize.length===0))return()=>new n}function Es(n,e,t=Ee){if(n==null||typeof n!="object")throw new Error(`schema(): first argument must be a fields object (got ${typeof n}).`);let r={},s={},i={},o={},a=(A,P)=>{typeof P=="function"?o[A]=P:P&&typeof P.clone=="function"?o[A]=()=>P.clone():i[A]=P},c=(A,P)=>{if(P.hasDefault)a(A,P.default);else if(!P.optional){let V=my(P.type);V&&(o[A]=V)}},u={},d=[],h=[],m={},g=[],p=[],y={},x=[];for(let A in n){let P=n[A];if(Zd(P)){let V=P.toDefinition();if(V.noSync){if(V.view!==void 0||V.unreliable||V.patchOnly||V.fullStateOnly||V.stream)throw new Error(`schema(${e?`'${e}'`:""}): field '${A}' uses .noSync() together with a sync-only modifier (.view/.unreliable/.patchOnly/.fullStateOnly/.stream). A local-only field cannot be synchronized.`);c(A,V);continue}if(V.patchOnly&&V.fullStateOnly)throw new Error(`schema(${e?`'${e}'`:""}): field '${A}' uses .patchOnly() together with .fullStateOnly(). Those are the only two delivery channels, so the field would never reach a client \u2014 use .noSync() if that is intended.`);let Z=br(V.type);if(typeof Z=="function"&&!Ee.is(Z))throw new Error(`schema(${e?`'${e}'`:""}): field '${A}' is a synced ref to non-Schema class '${Z.name||"(anonymous)"}' \u2014 use .noSync(), or Metadata.setFields().`);r[A]=Z,V.view!==void 0&&(u[A]=V.view),V.unreliable&&d.push(A),V.patchOnly&&h.push(A),V.deprecated&&(m[A]=V.deprecatedThrows),V.fullStateOnly&&g.push(A),V.stream&&p.push(A),V.streamPriority!==void 0&&(y[A]=V.streamPriority),V.optional&&x.push(A),c(A,V)}else if(typeof P=="function")Ee.is(P)?(r[A]=br(P),(!P.prototype.initialize||P.prototype.initialize.length===0)&&(o[A]=()=>new P)):s[A]=P;else throw new Error(`schema(${e?`'${e}'`:""}): field '${A}' must be a t.* builder, Schema subclass, or method (got ${typeof P}).`)}let k=A=>{for(let P in i)A[P]=i[P];for(let P in o)A[P]=o[P]()},I=()=>{let A={};return k(A),A},L=A=>{let P=Object.keys(r),V={};for(let Z in A)P.includes(Z)||(V[Z]=A[Z]);return V},N=typeof s.initialize=="function",C=s.initialize??t._initialize,O=class extends t{constructor(...A){let P=A[0];P===void 0?(super(),k(this)):super(Object.assign(I(),N?L(P):P)),C&&new.target===O&&C.apply(this,A)}};e&&Object.defineProperty(O,"name",{value:e}),ce.setFields(O,r),O._getDefaultValues=I,O._initialize=C,Object.assign(O.prototype,s);for(let A in u)iy(u[A])(O.prototype,A);for(let A of d)oy(O.prototype,A);for(let A of h)ay(O.prototype,A);for(let A in m)py(m[A])(O.prototype,A);if(g.length>0||p.length>0){let A=O[Symbol.metadata];for(let P of g)ce.setFullStateOnly(A,P);for(let P of p)ce.setStream(A,P);for(let P in y)ce.setStreamPriority(A,P,y[P])}if(x.length>0){let A=O[Symbol.metadata];for(let P of x)A[A[P]].optional=!0}return O.extend=(A,P)=>Es(A,P,O),O}function gy(n){return new Array(n).fill(0).map((e,t)=>t===n-1?"\u2514\u2500 ":" ").join("")}function yy(n,e){if(e===-1||e>=n.length)return!1;let t=n.length-1;for(let r=e;r<t;r++)n[r]=n[r+1];return n.length=t,!0}function by(n,e,t){let r=~t,s=n.changeTrees;for(let i in s){let o=s[i],a=o.visibleViews;a!==void 0&&e<a.length&&(a[e]&=r);let c=o.subscribedViews;c!==void 0&&e<c.length&&(c[e]&=r);let u=o.tagViews;u!==void 0&&u.forEach(d=>{e<d.length&&(d[e]&=r)})}}function qu(n){n.structSwitchEmitted||(n.shouldEmitSwitch&&(n.buffer[n.it.offset++]=255,Q.number(n.buffer,n.ref[$],n.it)),n.structSwitchEmitted=!0)}function _y(n,e){tf(n,e,R.ADD)}function ef(n,e){if(e._fullSyncGen===n.gen)return;if(e._fullSyncGen=n.gen,!n.hasView||n.view.isChangeTreeVisible(e)){let r=e.encDescriptor;n.changeTree=e,n.ref=e.ref,n.encoder=r.encoder,n.filter=r.filter,n.metadata=r.metadata,n.treeIsFiltered=e.isFiltered,n.isSchema=r.isSchema,n.filterBitmask=r.filterBitmask,n.tags=r.tags,n.structSwitchEmitted=!1,n.shouldEmitSwitch=n.hasView||n.it.offset>n.initialOffset||e!==n.rootChangeTree,e.isArray&&e.collDirty.size>0&&(e.flags|=pc),fc(e,n,_y)}ws(e,n,Ey)}function Ey(n,e,t){ef(n,e)}function tf(n,e,t){if(e<0){if(n.treeIsFiltered!==n.emitFiltered)return;qu(n),n.buffer[n.it.offset++]=Math.abs(e)&255;return}if((n.isSchema?n.treeIsFiltered||(e<32?(n.filterBitmask&1<<e)!==0:n.tags[e]!==void 0):n.treeIsFiltered)!==n.emitFiltered)return;let s=n.isEncodeAll?R.ADD:t;s!==void 0&&(n.filter!==void 0&&!n.filter(n.ref,e,n.view)||(qu(n),n.encoder(n.self,n.buffer,n.changeTree,e,s,n.it,n.isEncodeAll,n.hasView,n.metadata)))}function Qa(n,e){let t=new Uint8Array(n.length+e.length);return t.set(n,0),t.set(e,n.length),t}function Ki(n){let e=n.root,t=e.callbacks,r=new WeakMap,s;n.triggerChanges=function(a){let c=new Set;for(let u=0,d=a.length;u<d;u++){let h=a[u],m=h.refId,g=h.ref,p=t[m];if(p){if((h.op&R.DELETE)===R.DELETE&&Ee.isSchema(h.previousValue)){let y=t[h.previousValue[$]]?.[R.DELETE];for(let x=y?.length-1;x>=0;x--)y[x]()}if(Ee.isSchema(g)){if(!c.has(m)){let y=p?.[R.REPLACE];for(let x=y?.length-1;x>=0;x--)y[x]()}if(p.hasOwnProperty(h.field)){let y=p[h.field];for(let x=y?.length-1;x>=0;x--)y[x](h.value,h.previousValue)}}else{if((h.op&R.DELETE)===R.DELETE){if(h.previousValue!==void 0){let y=p[R.DELETE];for(let x=y?.length-1;x>=0;x--)y[x](h.previousValue,h.dynamicIndex??h.field)}if((h.op&R.ADD)===R.ADD){let y=p[R.ADD];for(let x=y?.length-1;x>=0;x--)y[x](h.value,h.dynamicIndex??h.field)}}else if((h.op&R.ADD)===R.ADD&&h.previousValue!==h.value){let y=p[R.ADD];for(let x=y?.length-1;x>=0;x--)y[x](h.value,h.dynamicIndex??h.field)}if(h.value!==h.previousValue&&(h.value!==void 0||h.previousValue!==void 0)){let y=p[R.REPLACE];for(let x=y?.length-1;x>=0;x--)y[x](h.value,h.dynamicIndex??h.field)}}c.add(m)}}};function i(a,c){let u=c.instance?.constructor[Symbol.metadata]||a,d=c.instance&&typeof c.instance.forEach=="function"||a&&!Ee.is(a);if(u&&!d){let h=function(m,g,p,y){return y&&c.instance[g]!==void 0&&!r.has(s)&&p(c.instance[g],void 0),e.addCallback(m[$],g,p)};return new Proxy({listen:function(g,p,y=!0){if(c.instance)return h(c.instance,g,p,y);{let x=()=>{};return c.onInstanceAvailable((k,I)=>{x=h(k,g,p,y&&I&&!r.has(s))}),()=>x()}},onChange:function(g){return e.addCallback(c.instance[$],R.REPLACE,g)},bindTo:function(g,p){return p||(p=Object.keys(u).map(y=>u[y].name)),e.addCallback(c.instance[$],R.REPLACE,()=>{p.forEach(y=>g[y]=c.instance[y])})}},{get(m,g){let p=u[u[g]];if(p){let y=c.instance?.[g],x=(k=>{let I=o(c.instance).listen(g,(L,N)=>{k(L,!1),I?.()},!1);y?.[$]!==void 0&&k(y,!0)});return i(p.type,{instance:y?.[$]!==void 0&&y,parentInstance:c.instance,onInstanceAvailable:x})}else return m[g]},has(m,g){return u[g]!==void 0},set(m,g,p){throw new Error("not allowed")},deleteProperty(m,g){throw new Error("not allowed")}})}else{let h=function(p,y,x){return x&&p.forEach((k,I)=>y(k,I)),e.addCallback(p[$],R.ADD,(k,I)=>{r.set(y,!0),s=y,y(k,I),r.delete(y),s=void 0})},m=function(p,y){return e.addCallback(p[$],R.DELETE,y)},g=function(p,y){return e.addCallback(p[$],R.REPLACE,y)};return new Proxy({onAdd:function(p,y=!0){if(c.instance)return h(c.instance,p,y&&!r.has(s));if(c.onInstanceAvailable){let x=()=>{};return c.onInstanceAvailable((k,I)=>{x=h(k,p,y&&I&&!r.has(s))}),()=>x()}},onRemove:function(p){if(c.instance)return m(c.instance,p);if(c.onInstanceAvailable){let y=()=>{};return c.onInstanceAvailable(x=>{y=m(x,p)}),()=>y()}},onChange:function(p){if(c.instance)return g(c.instance,p);if(c.onInstanceAvailable){let y=()=>{};return c.onInstanceAvailable(x=>{y=g(x,p)}),()=>y()}}},{get(p,y){if(!p[y])throw new Error(`Can't access '${y}' through callback proxy. access the instance directly.`);return p[y]},has(p,y){return p[y]!==void 0},set(p,y,x){throw new Error("not allowed")},deleteProperty(p,y){throw new Error("not allowed")}})}}function o(a){return i(void 0,{instance:a})}return o}function Ry(n,e){n.triggerChanges=e}var R,Du,$,Dt,Nt,_t,qn,Te,Rt,wr,_,X,Ce,yn,Et,Vi,Ue,Sd,ot,ls,Qt,Fe,bn,bt,Xt,Ln,ds,ji,gr,at,Ni,Hm,Xi,Fn,Za,zm,Td,Wm,kd,Q,ys,$n,Zm,eg,tg,ng,te,ac,lg,jd,pg,Pt,jn,Nu,wg,ce,Hd,tc,nc,Wd,Ag,Yd,Gi,Hi,Pg,Og,Fu,Fi,Vg,Ka,Ya,cs,Xa,us,mr,$i,Ui,fs,pc,jg,En,rc,Gg,Hg,mc,zg,Qd,wt,Yg,ro,Xg,hs,Qg,$u,Hu,zu,Wu,Ju,Ku,Yu,Xu,it,wn,zi,Qu,Zu,ed,td,nd,Ot,_n,rd,sd,id,od,ad,mn,ps,cd,ld,ud,dd,fd,gn,ms,hd,pd,md,gd,yd,Zt,Wi,bd,Bt,Zg,ey,ty,ny,ry,sy,Je,io,cy,wd,_d,Ed,Rd,yt,Ee,ju,sc,q_,wy,Mt,gs,Ji,Gu,ic,St,nf,rf,sf,Tt,Yi,bc,He=Oe(()=>{"use strict";(function(n){n[n.ADD=128]="ADD",n[n.REPLACE=0]="REPLACE",n[n.DELETE=64]="DELETE",n[n.DELETE_AND_MOVE=96]="DELETE_AND_MOVE",n[n.MOVE_AND_ADD=160]="MOVE_AND_ADD",n[n.DELETE_AND_ADD=192]="DELETE_AND_ADD",n[n.CLEAR=10]="CLEAR",n[n.REVERSE=15]="REVERSE",n[n.MOVE=32]="MOVE",n[n.DELETE_BY_REFID=33]="DELETE_BY_REFID",n[n.ADD_BY_REFID=129]="ADD_BY_REFID"})(R||(R={}));Symbol.metadata??(Symbol.metadata=Symbol.for("Symbol.metadata"));Du=(function(){return typeof globalThis<"u"?globalThis:typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{}})();if(typeof Symbol=="function"&&typeof Symbol.for!="function"){let n="colyseus.symbolRegistry",e=Du[n]||(Du[n]=Object.create(null));Symbol.for=function(t){return e[t]||(e[t]=Symbol(t))},Symbol.keyFor=function(t){for(let r in e)if(e[r]===t)return r}}$=Symbol.for("$refId"),Dt="~track",Nt="~encoder",_t="~decoder",qn="~filter",Te="~getByIndex",Rt="~deleteByIndex",wr="~resyncPrune",_=Symbol.for("$changes"),X=Symbol.for("$childType"),Ce=Symbol.for("$proxyTarget"),yn="~onEncodeEnd",Et="~reset",Vi="~onDecodeEnd",Ue=Symbol.for("$values"),Sd="~builder",ot="~descriptors",ls="~__encodeDescriptor",Qt="~encoders",Fe="~__numFields",bn="~__refTypeFieldIndexes",bt="~__viewFieldIndexes",Xt="$__fieldIndexesByViewTag",Ln="~__unreliableFieldIndexes",ds="~__patchOnlyFieldIndexes",ji="~__fullSyncSkipIndexes",gr="~__fullStateOnlyFieldIndexes",at="~__streamFieldIndexes",Ni="~__streamPriorities";try{Hm=new TextEncoder}catch{}Xi=new ArrayBuffer(8),Fn=new Int32Array(Xi),Za=new Float32Array(Xi),zm=new Float64Array(Xi),Td=new BigInt64Array(Xi),Wm=typeof Buffer<"u"&&Buffer.byteLength,kd=Wm?Buffer.byteLength:function(n,e){for(var t=0,r=0,s=0,i=n.length;s<i;s++)t=n.charCodeAt(s),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(s++,r+=4);return r};Q={int8:Ad,uint8:Jm,int16:Cd,uint16:oc,int32:en,uint32:Un,int64:Id,uint64:Pd,bigint64:Km,biguint64:Ym,float32:Od,float64:Md,boolean:Xm,string:Qm,number:ec,utf8Write:vd,utf8Length:kd},ys=new ArrayBuffer(8),$n=new Int32Array(ys),Zm=new Float32Array(ys),eg=new Float64Array(ys),tg=new BigUint64Array(ys),ng=new BigInt64Array(ys);te={utf8Read:Dd,int8:Nd,uint8:bs,int16:Bd,uint16:Qi,int32:xt,uint32:yr,float32:Ld,float64:Fd,int64:Ud,uint64:$d,bigint64:rg,biguint64:sg,boolean:ig,string:og,number:ag,stringCheck:cg},ac={},lg=new Map;jd="ArraySchema does not support streaming \u2014 positional ops (splice / unshift / reverse) shift subsequent indexes, so holding ADDs back for a later tick under `maxPerTick` would desync the decoder. Use `t.stream(X)` (stable monotonic positions) or `t.map(X).stream()` (stable keys) instead.";pg={8:"uint8",16:"uint16",32:"uint32"};Pt=class Pt{constructor(e){l(this,"types",{});l(this,"schemas",new Map);l(this,"hasFilters",!1);e&&this.discoverTypes(e)}static register(e){let t=Object.getPrototypeOf(e);if(t!==Ee){let r=Pt.inheritedTypes.get(t);r||(r=new Set,Pt.inheritedTypes.set(t,r)),r.add(e)}}static cache(e){let t=Pt.cachedContexts.get(e);return t||(t=new Pt(e),Pt.cachedContexts.set(e,t)),t}has(e){return this.schemas.has(e)}get(e){return this.types[e]}add(e,t=this.schemas.size){return this.schemas.has(e)?!1:(this.types[t]=e,e[Symbol.metadata]==null&&ce.initialize(e),this.schemas.set(e,t),!0)}getTypeId(e){return this.schemas.get(e)}discoverTypes(e){if(!this.add(e))return;Pt.inheritedTypes.get(e)?.forEach(s=>{this.discoverTypes(s)});let t=e;for(;(t=Object.getPrototypeOf(t))&&t!==Ee&&t!==Function.prototype;)this.discoverTypes(t);let r=e[Symbol.metadata];(r[bt]||r[at])&&(this.hasFilters=!0);for(let s in r){let o=r[s].type;if(typeof o!="string"&&!Vn(o))if(typeof o=="function")this.discoverTypes(o);else{let a=Object.values(o)[0];if(typeof a=="string")continue;this.discoverTypes(a)}}}debug(){return`TypeContext ->
|
|
1
|
+
"use strict";(()=>{var yp=Object.create;var gi=Object.defineProperty;var bp=Object.getOwnPropertyDescriptor;var wp=Object.getOwnPropertyNames;var _p=Object.getPrototypeOf,Ep=Object.prototype.hasOwnProperty;var Bl=n=>{throw TypeError(n)};var Rp=(n,e,t)=>e in n?gi(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Pe=(n,e)=>()=>(n&&(e=n(n=0)),e);var xp=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ul=(n,e)=>{for(var t in e)gi(n,t,{get:e[t],enumerable:!0})},Sp=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of wp(e))!Ep.call(n,s)&&s!==t&&gi(n,s,{get:()=>e[s],enumerable:!(r=bp(e,s))||r.enumerable});return n};var Tp=(n,e,t)=>(t=n!=null?yp(_p(n)):{},Sp(e||!n||!n.__esModule?gi(t,"default",{value:n,enumerable:!0}):t,n));var l=(n,e,t)=>Rp(n,typeof e!="symbol"?e+"":e,t),ma=(n,e,t)=>e.has(n)||Bl("Cannot "+t);var q=(n,e,t)=>(ma(n,e,"read from private field"),t?t.call(n):e.get(n)),he=(n,e,t)=>e.has(n)?Bl("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),pe=(n,e,t,r)=>(ma(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t),Pn=(n,e,t)=>(ma(n,e,"access private method"),t);var _e,mr,Xa,Ui,Fi,Ln,Ne,Gu=Pe(()=>{"use strict";_e={JOIN_ROOM:10,ERROR:11,LEAVE_ROOM:12,ROOM_DATA:13,ROOM_STATE:14,ROOM_STATE_PATCH:15,ROOM_DATA_SCHEMA:16,ROOM_DATA_BYTES:17,PING:18,ROOM_INPUT_RELIABLE:19,ROOM_INPUT_UNRELIABLE:20,ROOM_REQUEST:21,ROOM_RESPONSE:22},mr={TIMED:128,UNRELIABLE:64},Xa=31,Ui={OK:0,REJECTED:1,ERROR:2},Fi={INPUT_REFLECTION:1,INPUT_OPTIONS:2},Ln={RENDER_TIME:1,FIXED_TIMESTEP:2,PATCH_RATE:4,SUB_STEPS:8,RECKON_TIME:16},Ne={NORMAL_CLOSURE:1e3,GOING_AWAY:1001,NO_STATUS_RECEIVED:1005,ABNORMAL_CLOSURE:1006,CONSENTED:4e3,SERVER_SHUTDOWN:4001,WITH_ERROR:4002,FAILED_TO_RECONNECT:4003,MAY_TRY_RECONNECT:4010}});var Kt=Pe(()=>{"use strict";Gu()});function Dd(n){Object.defineProperty(n,Symbol.metadata,{value:void 0,writable:!0,configurable:!0,enumerable:!1})}function Ud(n,e,t){for(var r=0,s=0,i=e.length;s<i;s++)r=e.charCodeAt(s),r<128?n[t.offset++]=r:r<2048?(n[t.offset]=192|r>>6,n[t.offset+1]=128|r&63,t.offset+=2):r<55296||r>=57344?(n[t.offset]=224|r>>12,n[t.offset+1]=128|r>>6&63,n[t.offset+2]=128|r&63,t.offset+=3):(s++,r=65536+((r&1023)<<10|e.charCodeAt(s)&1023),n[t.offset]=240|r>>18,n[t.offset+1]=128|r>>12&63,n[t.offset+2]=128|r>>6&63,n[t.offset+3]=128|r&63,t.offset+=4)}function Fd(n,e,t){n[t.offset++]=e&255}function lg(n,e,t){n[t.offset++]=e&255}function $d(n,e,t){n[t.offset++]=e&255,n[t.offset++]=e>>8&255}function uc(n,e,t){n[t.offset++]=e&255,n[t.offset++]=e>>8&255}function en(n,e,t){n[t.offset++]=e&255,n[t.offset++]=e>>8&255,n[t.offset++]=e>>16&255,n[t.offset++]=e>>24&255}function Fn(n,e,t){let r=e>>24,s=e>>16,i=e>>8,o=e;n[t.offset++]=o&255,n[t.offset++]=i&255,n[t.offset++]=s&255,n[t.offset++]=r&255}function Vd(n,e,t){let r=Math.floor(e/Math.pow(2,32)),s=e>>>0;Fn(n,s,t),Fn(n,r,t)}function jd(n,e,t){let r=e/Math.pow(2,32)>>0,s=e>>>0;Fn(n,s,t),Fn(n,r,t)}function ug(n,e,t){Ld[0]=BigInt.asIntN(64,e),en(n,Un[0],t),en(n,Un[1],t)}function dg(n,e,t){Ld[0]=BigInt.asIntN(64,e),en(n,Un[0],t),en(n,Un[1],t)}function Hd(n,e,t){nc[0]=e,en(n,Un[0],t)}function Gd(n,e,t){ag[0]=e,en(n,Un[0],t),en(n,Un[1],t)}function fg(n,e,t){n[t.offset++]=e?1:0}function hg(n,e,t){e||(e="");let r=Bd(e,"utf8"),s=0;if(r<32)n[t.offset++]=r|160,s=1;else if(r<256)n[t.offset++]=217,n[t.offset++]=r,s=2;else if(r<65536)n[t.offset++]=218,uc(n,r,t),s=3;else if(r<4294967296)n[t.offset++]=219,Fn(n,r,t),s=5;else throw new Error("String too long");return Ud(n,e,t),s+r}function rc(n,e,t){if(isNaN(e))return rc(n,0,t);if(isFinite(e)){if(e!==(e|0))return Math.abs(e)<=34028235e31&&(nc[0]=e,Math.abs(Math.abs(nc[0])-Math.abs(e))<1e-4)?(n[t.offset++]=202,Hd(n,e,t),5):(n[t.offset++]=203,Gd(n,e,t),9)}else return rc(n,e>0?Number.MAX_SAFE_INTEGER:-Number.MAX_SAFE_INTEGER,t);return e>=0?e<128?(n[t.offset++]=e&255,1):e<256?(n[t.offset++]=204,n[t.offset++]=e&255,2):e<65536?(n[t.offset++]=205,uc(n,e,t),3):e<4294967296?(n[t.offset++]=206,Fn(n,e,t),5):(n[t.offset++]=207,jd(n,e,t),9):e>=-32?(n[t.offset++]=224|e+32,1):e>=-128?(n[t.offset++]=208,Fd(n,e,t),2):e>=-32768?(n[t.offset++]=209,$d(n,e,t),3):e>=-2147483648?(n[t.offset++]=210,en(n,e,t),5):(n[t.offset++]=211,Vd(n,e,t),9)}function qd(n,e,t){t>n.length-e.offset&&(t=n.length-e.offset);for(var r="",s=0,i=e.offset,o=e.offset+t;i<o;i++){var a=n[i];if((a&128)===0){r+=String.fromCharCode(a);continue}if((a&224)===192){r+=String.fromCharCode((a&31)<<6|n[++i]&63);continue}if((a&240)===224){r+=String.fromCharCode((a&15)<<12|(n[++i]&63)<<6|(n[++i]&63)<<0);continue}if((a&248)===240){s=(a&7)<<18|(n[++i]&63)<<12|(n[++i]&63)<<6|(n[++i]&63)<<0,s>=65536?(s-=65536,r+=String.fromCharCode((s>>>10)+55296,(s&1023)+56320)):r+=String.fromCharCode(s);continue}console.error("decode.utf8Read(): Invalid byte "+a+" at offset "+i+". Skip to end of string: "+(e.offset+t));break}return e.offset+=t,r}function zd(n,e){return Es(n,e)<<24>>24}function Es(n,e){return n[e.offset++]}function Wd(n,e){return ro(n,e)<<16>>16}function ro(n,e){return n[e.offset++]|n[e.offset++]<<8}function St(n,e){return n[e.offset++]|n[e.offset++]<<8|n[e.offset++]<<16|n[e.offset++]<<24}function br(n,e){return St(n,e)>>>0}function Yd(n,e){return $n[0]=St(n,e),pg[0]}function Jd(n,e){return $n[0]=St(n,e),$n[1]=St(n,e),mg[0]}function Kd(n,e){let t=br(n,e);return St(n,e)*Math.pow(2,32)+t}function Xd(n,e){let t=br(n,e);return br(n,e)*Math.pow(2,32)+t}function bg(n,e){return $n[0]=St(n,e),$n[1]=St(n,e),yg[0]}function wg(n,e){return $n[0]=St(n,e),$n[1]=St(n,e),gg[0]}function _g(n,e){return Es(n,e)>0}function Eg(n,e){let t=n[e.offset++],r;return t<192?r=t&31:t===217?r=Es(n,e):t===218?r=ro(n,e):t===219&&(r=br(n,e)),qd(n,e,r)}function Rg(n,e){let t=n[e.offset++];if(t<128)return t;if(t===202)return Yd(n,e);if(t===203)return Jd(n,e);if(t===204)return Es(n,e);if(t===205)return ro(n,e);if(t===206)return br(n,e);if(t===207)return Xd(n,e);if(t===208)return zd(n,e);if(t===209)return Wd(n,e);if(t===210)return St(n,e);if(t===211)return Kd(n,e);if(t>223)return(255-t+1)*-1}function xg(n,e){let t=n[e.offset];return t<192&&t>160||t===217||t===218||t===219}function nn(n,e){e.constructor&&(Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor[Symbol.metadata]==null&&Dd(e.constructor),Sg.set(e.constructor,n),dc[n]=e),e.encode&&(Q[n]=e.encode),e.decode&&(te[n]=e.decode)}function Qd(n){return dc[n]}function tn(){return{pendingByView:new Map,sentByView:new Map,broadcastPending:new Set,sentBroadcast:new Set,broadcastDeletes:new Set,maxPerTick:32}}function fc(n){return n._stream??(n._stream=tn())}function so(n,e,t){e.activeViews.size===0&&fc(n).broadcastPending.add(t)}function io(n,e,t,r){let s=n._stream;if(s===void 0)return!0;let i=!1;return s.broadcastPending.delete(r)?i=!0:s.sentBroadcast.delete(r)&&s.broadcastDeletes.add(r),e.forEachActiveView(o=>{let a=s.pendingByView.get(o.id);if(a?.has(r)){a.delete(r),i=!0;return}let c=s.sentByView.get(o.id);if(c?.has(r)){c.delete(r);let u=o.changes.get(t);u===void 0&&(u=new Map,o.changes.set(t,u)),u.set(r,R.DELETE)}}),i}function Tg(n,e,t){let r=n._stream;if(r!==void 0){r.broadcastPending.clear();for(let s of r.sentBroadcast)r.broadcastDeletes.add(s);r.sentBroadcast.clear(),e.forEachActiveView(s=>{r.pendingByView.get(s.id)?.clear();let i=r.sentByView.get(s.id);if(i!==void 0&&i.size>0){let o=s.changes.get(t);o===void 0&&(o=new Map,s.changes.set(t,o));for(let a of i)o.set(a,R.DELETE);i.clear()}})}}function kg(n,e){let t=n._stream?.pendingByView;if(t===void 0)return!1;for(let[r,s]of t)if(s.size>0&&e.activeViews.get(r)?.deref()!==void 0)return!0;return!1}function Ag(n){let e=n._stream;return e!==void 0&&(e.broadcastPending.size>0||e.broadcastDeletes.size>0)}function vg(n,e,t){let r=fc(n),s=r.pendingByView.get(e);s===void 0&&(s=new Set,r.pendingByView.set(e,s)),s.add(t)}function oo(n,e){let t=n._stream;t!==void 0&&(t.pendingByView.delete(e),t.sentByView.delete(e),t.priorityByView?.delete(e))}function hc(n){if(n==null||typeof n!="object")throw new Error("t.quantized(): options object with { min, max } is required.");let{min:e,max:t}=n;if(typeof e!="number"||typeof t!="number"||!(t>e)||!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`t.quantized(): require finite min < max (got min=${e}, max=${t}).`);let r=n.bits??16;if(r!==8&&r!==16&&r!==32)throw new Error(`t.quantized(): bits must be 8, 16 or 32 (got ${r}).`);let s=n.mode??"clamp";if(s!=="clamp"&&s!=="wrap")throw new Error(`t.quantized(): mode must be "clamp" or "wrap" (got ${JSON.stringify(s)}).`);let i=s==="wrap",o=Math.pow(2,r);return{min:e,max:t,bits:r,wrap:i,wire:Cg[r],range:t-e,span:i?o:e===-t?o-2:o-1}}function Vn(n){return n!==null&&typeof n=="object"&&n.quantized!==void 0}function ef(n,e){if(n.wrap){if(!Number.isFinite(e))return 0;let r=n.range,s=(e-n.min)%r;s<0&&(s+=r);let i=n.span;return Math.floor(s/r*i+.5)%i}if(e!==e)return 0;let t=e<n.min?n.min:e>n.max?n.max:e;return Math.floor((t-n.min)/n.range*n.span+.5)}function tf(n,e){return n.min+e/n.span*n.range}function Ig(n){let e=Q[n.wire];return(t,r,s)=>e(t,ef(n,r),s)}function Og(n,e,t){let r=te[n.wire];return tf(n,r(e,t))}function Pg(n){let e=typeof Object.keys(n)[0]=="string"&&Qd(Object.keys(n)[0]);return{complexTypeKlass:e,childType:e?Object.values(n)[0]:n}}function wr(n){if(Array.isArray(n))return{array:wr(n[0])};if(Vn(n))return typeof n.quantized.wire=="string"?n:{quantized:hc(n.quantized)};if(typeof n.type<"u")return n.type;if(Mg(n))return Object.keys(n).every(e=>typeof n[e]=="string")?"string":"number";if(typeof n=="object"&&n!==null){let e=Object.keys(n).find(t=>dc[t]!==void 0);if(e)return n[e]=wr(n[e]),n}return n}function Mg(n){if(typeof n=="function"&&n[Symbol.metadata])return!1;let e=Object.keys(n),t=e.filter(r=>/\d+/.test(r));return!!(t.length>0&&t.length===e.length/2&&n[n[t[0]]]==t[0]||e.length>0&&e.every(r=>typeof n[r]=="string"&&n[r]===r))}function Vi(n,e,t){n[e]||Object.defineProperty(n,e,{value:[],enumerable:!1,configurable:!0,writable:!0}),n[e].push(t)}function Yi(n){return n=n-(n>>>1&1431655765),n=(n&858993459)+(n>>>2&858993459),(n+(n>>>4)&252645135)*16843009>>>24}function ji(n){if(n===void 0)return 0;let e=0;for(let t=0,r=n.length;t<r;t++){let s=n[t];s<32&&(e|=1<<s)}return e}function Ng(n){let e=[],t=[],r=[],s=[],i=n?.[Ue];if(i===void 0)return{names:e,types:t,tags:r,encoders:s};let o=n[Qt];for(let a=0;a<=i;a++){let c=n[a];if(c===void 0){e[a]=void 0,t[a]=void 0,r[a]=void 0,s[a]=void 0;continue}e[a]=c.name,t[a]=c.type,r[a]=c.tag,s[a]=o?.[a]}return{names:e,types:t,tags:r,encoders:s}}function pc(n){let e=n.constructor;if(Object.prototype.hasOwnProperty.call(e,fs))return e[fs];let t=e[Symbol.metadata],r=le.isValidInstance(n),s=(t?.[wt]?.length??0)>0,i=Ng(t),o=r&&!s?void 0:e[Hn],a={encoder:e[Lt],filter:o,metadata:t,isSchema:r,filterBitmask:r?ji(t?.[wt]):0,hasAnyFullStateOnly:(t?.[yr]?.length??0)>0,hasAnyUnreliable:(t?.[Bn]?.length??0)>0,hasAnyStream:(t?.[at]?.length??0)>0,hasAnyView:s,fullStateOnlyBitmask:ji(t?.[yr]),unreliableBitmask:ji(t?.[Bn]),streamBitmask:ji(t?.[at]),names:i.names,types:i.types,tags:i.tags,encoders:i.encoders};return Object.defineProperty(e,fs,{value:a,enumerable:!1,writable:!0,configurable:!0}),a}function Lg(n,e,t){if(n.parentRef){if(n.parentRef[_]===e[_]){n._parentIndex=t;return}if(rf(n,(r,s)=>r[_]===e[_])){n._parentIndex=t;return}}n.parentRef===void 0?(n.parentRef=e,n._parentIndex=t):(n.extraParents={ref:n.parentRef,index:n._parentIndex,next:n.extraParents},n.parentRef=e,n._parentIndex=t)}function Bg(n,e,t){if(n.extraParents===void 0){n._parentIndex=t;return}if(n.parentRef[_]===e[_]){n._parentIndex=t;return}for(let r=n.extraParents;r!==void 0;r=r.next)if(r.ref[_]===e[_]){r.index=t;return}}function Ug(n,e){if(n.parentRef&&n.parentRef[_]===e[_])return n.extraParents?(n.parentRef=n.extraParents.ref,n._parentIndex=n.extraParents.index,n.extraParents=n.extraParents.next):(n.parentRef=void 0,n._parentIndex=void 0),!0;let t=n.extraParents,r=null;for(;t;){if(t.ref[_]===e[_])return r?r.next=t.next:n.extraParents=t.next,!0;r=t,t=t.next}return n.parentRef===void 0}function Fg(n,e){if(n.parentRef!==void 0&&e(n.parentRef,n._parentIndex))return{ref:n.parentRef,index:n._parentIndex};for(let t=n.extraParents;t!==void 0;t=t.next)if(e(t.ref,t.index))return{ref:t.ref,index:t.index}}function rf(n,e){if(n.parentRef!==void 0&&e(n.parentRef,n._parentIndex))return!0;for(let t=n.extraParents;t!==void 0;t=t.next)if(e(t.ref,t.index))return!0;return!1}function $g(n,e){if(n.parentRef&&n.parentRef[_]===e[_])return n._parentIndex;for(let t=n.extraParents;t!==void 0;t=t.next)if(t.ref[_]===e[_])return t.index}function Vg(n){let e=[];n.parentRef&&e.push({ref:n.parentRef,index:n._parentIndex});let t=n.extraParents;for(;t;)e.push({ref:t.ref,index:t.index}),t=t.next;return e}function jg(n,e,t){let r=e.refTarget;if(e.isArray){let i=r.items,o=i[t];if(o!==void 0&&o[_]===n)return!0;for(let a=0,c=i.length;a<c;a++){let u=i[a];if(u!==void 0&&u[_]===n)return!0}return!1}let s=e.getValue(t);return s!==void 0&&s[_]===n}function Gg(n,e){mc(n,e,Hg)}function mc(n,e,t){let r=n.refTarget;if(r[X]!==void 0){if(n.isPatchOnly)return;if(Array.isArray(r.items)){let s=r.items;for(let i=0,o=s.length;i<o;i++)s[i]!==void 0&&t(e,i)}else if(r.journal!==void 0)for(let[s,i]of r.journal.keyByIndex)r.$items.has(i)&&t(e,s);else if(r.$items!==void 0)for(let s of r.$items.keys())t(e,s)}else{let s=n.metadata;if(!s)return;let i=s[Ue]??-1,o=s[Wi],a=n.encDescriptor.names;for(let c=0;c<=i;c++){let u=a[c];if(u===void 0||o&&o.includes(c))continue;let d=r[u];d!=null&&t(e,c)}}}function of(n,e,t,r){qg(n,e,t),!n.isFullStateOnly&&(n.has()&&n.root?.enqueueChangeTree(n),n.unreliableRecorder?.has()&&n.root?.enqueueUnreliable(n),!n.has()&&!n.unreliableRecorder?.has()&&n.root?.enqueueChangeTree(n))}function qg(n,e,t){if(!e)return;let r=e[_],s=!r._isSchema,i;s?(e=r.parent,t=r.parentIndex,i=e?.[_].metadata):i=r.metadata;let o=(i?.[ps]?.includes(t)?hs:0)|(i?.[yr]?.includes(t)?gr:0),a=r.flags&ry|o,c=n.flags;if(n.flags=c|a,a&~c&gr&&(n.reset(),n.unreliableRecorder?.reset()),!n.root?.types?.hasFilters)return;let h=i?.[wt]?.includes(t)??!1,m=i?.[at]?.includes(t)??!1,g=r.isFiltered||h||m;if(n.isFiltered=g,m&&!s){n.isStreamCollection=!0;let p=fc(n.ref);if(p.priority===void 0){let y=le.getStreamPriority(i,t);y!==void 0&&(p.priority=y)}n.root?.registerStream(n.ref)}if(g){let p=af(n);n.isVisibilitySharedWithParent=r.isFiltered&&p&&!m&&(!h||s&&i[t].tag!==uo)}}function Wu(n){let e=n.pendingFilterRefresh;for(let t=0;t<e.length;t++){let r=e[t];(r.flags&ms)!==0&&gc(r)}e.length=0}function af(n){return n._isSchema||typeof n.refTarget[X]!="string"}function gc(n){n.flags&=~ms;let e=n.root;if(e===void 0||n.parentRef===void 0)return;let t=af(n),r=Yu(n,n.parentRef,n._parentIndex,t);for(let i=n.extraParents;i!==void 0&&r!==zg;i=i.next)r|=Yu(n,i.ref,i.index,t);if(r===0)return;n.isVisibilitySharedWithParent=(r&Ki)!==0;let s=(r&Ji)===0;s!==n.isFiltered&&(n.isFiltered=s,!s&&!n.isFullStateOnly&&(n.forEachLiveWithCtx(n,sf),n.has()&&e.enqueueChangeTree(n),n.unreliableRecorder?.has()&&e.enqueueUnreliable(n)),n.forEachChildWithCtx(n,Wg))}function Yu(n,e,t,r){let s=e[_];if(s.root!==n.root||!jg(n,s,t))return 0;s.flags&ms&&gc(s);let i=cf;if(s._isSchema)s.encDescriptor.tags[t]!==void 0||s.isFieldStream(t)||(s.isFiltered?r&&(i|=Ki):i|=Ji);else if(!s.isFiltered)i|=Ji;else if(r&&!s.isStreamCollection){let o=s.parent?.[_];(o?._isSchema?o.encDescriptor.tags[s.parentIndex]:void 0)!==uo&&(i|=Ki)}return i}function Yg(n,e,t,r){let s=n.subscribedViews;if(s===void 0)return;let i=n.isStreamCollection,o=i?n.ref:void 0,a=i?void 0:t[_];for(let c=0,u=s.length;c<u;c++){let d=s[c];for(;d!==0;){let h=d&-d;d^=h;let m=c*32+(31-Math.clz32(h)),p=r.activeViews.get(m)?.deref();if(p===void 0){s[c]&=~h;continue}i?vg(o,m,e):a!==void 0&&p.markVisible(a)}}}function Jg(n,e){n.root=e;let t=e.add(n);of(n,n.parent,n.parentIndex),t&&Rs(n,e,Zg)}function Kg(n,e,t,r){if(n.addParent(e,r),!t)return;let s=t.add(n);t!==n.root&&(n.root=t,of(n,e,r));let i=e?.[_];if(i!==void 0&&i.subscribedViews!==void 0&&e[X]!==void 0&&Yg(i,r,n.ref,t),s){let o=Ju[Hi];o===void 0&&(o={parentRef:void 0,root:void 0},Ju[Hi]=o),o.parentRef=n.ref,o.root=t,Hi++,Rs(n,o,ey),Hi--}}function Xg(n,e){Rs(n,e,Qg)}function Qg(n,e,t){n(e,t)}function Rs(n,e,t){let r=n.refTarget;if(r[X]){if(typeof r[X]!="string"){let s=r.items;if(s!==void 0)for(let i=0,o=s.length;i<o;i++){let a=s[i];a&&t(e,a[_],i)}else{let i=r.$items,o=r._collectionIndexes;for(let a of i.keys()){let c=i.get(a);c&&t(e,c[_],o?.[a]??a)}}}}else{let i=n.metadata?.[bn];if(!i)return;let o=n.encDescriptor.names;for(let a=0,c=i.length;a<c;a++){let u=i[a],d=r[o[u]];d&&t(e,d[_],u)}}}function Zg(n,e,t){e.root!==n?e.setRoot(n):n.add(e)}function ey(n,e,t){if(e.root===n.root){n.root.add(e),n.root.moveNextToParent(e);return}e.setParent(n.parentRef,n.root,t)}function ty(n,e,t){let r=(t&3)<<3;return t<4?n>>>r&255:e>>>r&255}function Ku(){return{next:void 0,tail:void 0,nextPosition:0}}function sy(n){return new oc(n)}function Er(n,e=n){Object.defineProperty(n,_,{value:sy(e),enumerable:!1,writable:!0})}function ao(n,e,t,r,s,i,o){o!==void 0?o(e,r,i):typeof t=="string"?Q[t]?.(e,r,i):t[Symbol.metadata]!=null?(Q.number(e,r[$],i),(s&R.ADD)===R.ADD&&n.tryEncodeTypeId(e,t,r.constructor,i)):Q.number(e,r[$],i)}function lf(n,e,t,r,s,i,o){let a=n.resyncVisited,c=a.get(n.currentRefId);if(c===void 0&&a.set(n.currentRefId,c=new Set),c.add(r),s!==void 0&&t===R.ADD&&s!==i){let u=s[$];u!==void 0&&(n.root.removeRef(u),o?.push({ref:e,refId:n.currentRefId,op:R.DELETE,dynamicIndex:r,value:void 0,previousValue:s}))}}function cy(n,e){let t=n.resyncVisited;t.has(e)||t.set(e,new Set)}function ly(n,e){if(n.resyncDamaged){console.warn("@colyseus/schema: resync sweep skipped \u2014 parts of the payload could not be decoded. Stale entries may persist until the next resync.");return}wc(n,n.state,new Set,e)}function wc(n,e,t,r){let s=e[$];if(s===void 0||t.has(s))return;t.add(s);let i=e.constructor[Symbol.metadata],o=i?.[bn];if(o===void 0)return;let a=i[ps];for(let c=0;c<o.length;c++){let u=o[c];if(a!==void 0&&a.includes(u))continue;let d=i[u],h=e[d.name];h&&(Ee.is(d.type)?wc(n,h,t,r):uy(n,h,t,r))}}function uy(n,e,t,r){let s=e[Ce]??e,i=s[$];if(i===void 0||t.has(i))return;t.add(i);let o=n.resyncVisited.get(i);if(o===void 0)return;let a=n.root;s[_r](o,(c,u)=>{r?.push({ref:e,refId:i,op:R.DELETE,dynamicIndex:u,value:void 0,previousValue:c});let d=c?.[$];d!==void 0&&a.removeRef(d)},c=>{Ee.isSchema(c)&&wc(n,c,t,r)})}function _c(n,e,t,r,s,i,o,a,c){let u=n.root,d;if((e&R.DELETE)===R.DELETE){let h=s?.[$];h!==void 0&&u.removeRef(h),e!==R.DELETE_AND_ADD&&t[xt](r),d=void 0}if(e!==R.DELETE)if(typeof i=="string")d=te[i](o,a);else if(Vn(i))d=Og(i.quantized,o,a);else if(Ee.is(i)){let h=te.number(o,a);if(d=u.refs.get(h),(e&R.ADD)===R.ADD){let m=n.getInstanceType(o,a,i);d||(d=n.createInstanceOfType(m)),u.addRef(h,d,d!==s||e===R.DELETE_AND_ADD&&d===s)}}else{let h=Qd(Object.keys(i)[0]),m=te.number(o,a);n.resyncVisited!==null&&cy(n,m);let g=u.refs.has(m)?s||u.refs.get(m):h.constructor.initializeForDecoder();if(d=g.clone(!0),d[X]=Object.values(i)[0],s){let p=s[$];if(p!==void 0&&m!==p){(e&R.DELETE)!==R.DELETE&&u.removeRef(p);let y=s.entries(),x;for(;(x=y.next())&&!x.done;){let[k,I]=x.value;typeof I=="object"&&(p=I[$]),c?.push({ref:s,refId:p,op:R.DELETE,field:k,value:void 0,previousValue:I})}}}u.addRef(m,d,g!==s||e===R.DELETE_AND_ADD&&g===s)}return d}function lo(n,e,t,r){if(!(n instanceof e))throw new gs(`a '${e.name}' was expected, but '${n&&n.constructor.name}' was provided in ${t.constructor.name}#${r}`)}function df(n){return n!=null&&n[Nd]===!0}function Ge(n){return(()=>new Bt(n))}function xs(n){if(df(n)){let e=n._type,t=typeof e=="string"?`use the type name instead: t.array("${e}")`:'collections accept a Schema class or a primitive type name ("string", "number", \u2026)';throw new Error(`t.array/map/set/collection(): a t.* builder is not a valid element type \u2014 ${t}.`)}return n}function Qu(n){return new Bt({quantized:hc(n)})}function _y(n=uo){return function(e,t){let r=le.initialize(e.constructor);le.setTag(r,t,n)}}function Ey(n,e){let t=le.initialize(n.constructor);le.setUnreliable(t,e)}function Ry(n,e){let t=le.initialize(n.constructor);le.setPatchOnly(t,e)}function Sy(n,e,t){let r=xy[t],s=t==="string",i=t==="boolean";return function(o){let a=this[Fe],c=a[e];if(o!==c){if(o!=null){if(!i&&r!==void 0&&typeof o!==r&&!(s&&o===null)){let u=o&&o.constructor?` (${o.constructor.name})`:"";throw new gs(`a '${r}' was expected, but '${JSON.stringify(o)}'${u} was provided in ${this.constructor.name}#${n}`)}this.constructor[Nt](this[_],e,R.ADD)}else c!=null&&this[_].delete(e);a[e]=o}}}function Ty(n,e,t){return function(r){let s=this[Fe],i=s[e];if(r!==i){if(r!=null){lo(r,t,this,n);let o=this[_],a=this.constructor;i!=null&&i[_]?(o.root?.remove(i[_]),a[Nt](o,e,R.DELETE_AND_ADD)):a[Nt](o,e,R.ADD),r[_]?.setParent(this,o.root,e)}else i!=null&&this[_].delete(e);s[e]=r}}}function ky(n,e,t,r){let s=r.constructor===wn,i=r.constructor===_n;return function(o){let a=this[Fe],c=a[e];if(o!==c){if(o!=null){if(s&&!(o instanceof wn)){let h=new wn;h[X]=t,h.push(...o),o=h}else if(i&&!(o instanceof _n)){let h=new _n;if(h[X]=t,o instanceof Map)o.forEach((m,g)=>h.set(g,m));else for(let m in o)h.set(m,o[m]);o=h}else o[X]=t;let u=this[_],d=this.constructor;c!=null&&c[_]?(u.root?.remove(c[_]),d[Nt](u,e,R.DELETE_AND_ADD)):d[Nt](u,e,R.ADD),o[_]?.setParent(this,u.root,e)}else c!=null&&this[_].delete(e);a[e]=o}}}function Ay(n,e,t){return function(r){let s=this[Fe],i=s[e];if(r!=null){if(typeof r!="number")throw new gs(`a 'number' was expected, but '${JSON.stringify(r)}' was provided in ${this.constructor.name}#${n}`);if(r=tf(t,ef(t,r)),r===i)return;this.constructor[Nt](this[_],e,R.ADD)}else{if(r===i)return;i!=null&&this[_].delete(e)}s[e]=r}}function vy(n,e,t,r){let s;return r?s=ky(n,e,t,r):typeof t=="string"?s=Sy(n,e,t):Vn(t)?s=Ay(n,e,t.quantized):s=Ty(n,e,t),{get:function(){return this[Fe][e]},set:s,enumerable:!0,configurable:!0}}function Cy(n=!0){return function(e,t){let r=le.initialize(e.constructor);le.setDeprecated(r,t),n&&(r[ot]??(r[ot]={}),r[ot][t]={get:function(){throw new Error(`${t} is deprecated.`)},set:function(s){},enumerable:!1,configurable:!0},Object.defineProperty(e,t,r[ot][t]))}}function Iy(n){if(n&&typeof n=="object"){if(n.array!==void 0)return()=>new wn;if(n.map!==void 0)return()=>new _n;if(n.set!==void 0)return()=>new bs;if(n.collection!==void 0)return()=>new ys;if(n.stream!==void 0)return()=>new Qi}else if(typeof n=="function"&&Ee.is(n)&&(!n.prototype.initialize||n.prototype.initialize.length===0))return()=>new n}function Ss(n,e,t=Ee){if(n==null||typeof n!="object")throw new Error(`schema(): first argument must be a fields object (got ${typeof n}).`);let r={},s={},i={},o={},a=(v,O)=>{typeof O=="function"?o[v]=O:O&&typeof O.clone=="function"?o[v]=()=>O.clone():i[v]=O},c=(v,O)=>{if(O.hasDefault)a(v,O.default);else if(!O.optional){let V=Iy(O.type);V&&(o[v]=V)}},u={},d=[],h=[],m={},g=[],p=[],y={},x=[];for(let v in n){let O=n[v];if(df(O)){let V=O.toDefinition();if(V.noSync){if(V.view!==void 0||V.unreliable||V.patchOnly||V.fullStateOnly||V.stream)throw new Error(`schema(${e?`'${e}'`:""}): field '${v}' uses .noSync() together with a sync-only modifier (.view/.unreliable/.patchOnly/.fullStateOnly/.stream). A local-only field cannot be synchronized.`);c(v,V);continue}if(V.patchOnly&&V.fullStateOnly)throw new Error(`schema(${e?`'${e}'`:""}): field '${v}' uses .patchOnly() together with .fullStateOnly(). Those are the only two delivery channels, so the field would never reach a client \u2014 use .noSync() if that is intended.`);let Z=wr(V.type);if(typeof Z=="function"&&!Ee.is(Z))throw new Error(`schema(${e?`'${e}'`:""}): field '${v}' is a synced ref to non-Schema class '${Z.name||"(anonymous)"}' \u2014 use .noSync(), or Metadata.setFields().`);r[v]=Z,V.view!==void 0&&(u[v]=V.view),V.unreliable&&d.push(v),V.patchOnly&&h.push(v),V.deprecated&&(m[v]=V.deprecatedThrows),V.fullStateOnly&&g.push(v),V.stream&&p.push(v),V.streamPriority!==void 0&&(y[v]=V.streamPriority),V.optional&&x.push(v),c(v,V)}else if(typeof O=="function")Ee.is(O)?(r[v]=wr(O),(!O.prototype.initialize||O.prototype.initialize.length===0)&&(o[v]=()=>new O)):s[v]=O;else throw new Error(`schema(${e?`'${e}'`:""}): field '${v}' must be a t.* builder, Schema subclass, or method (got ${typeof O}).`)}let k=v=>{for(let O in i)v[O]=i[O];for(let O in o)v[O]=o[O]()},I=()=>{let v={};return k(v),v},B=v=>{let O=Object.keys(r),V={};for(let Z in v)O.includes(Z)||(V[Z]=v[Z]);return V},N=typeof s.initialize=="function",C=s.initialize??t._initialize,P=class extends t{constructor(...v){let O=v[0];O===void 0?(super(),k(this)):super(Object.assign(I(),N?B(O):O)),C&&new.target===P&&C.apply(this,v)}};e&&Object.defineProperty(P,"name",{value:e}),le.setFields(P,r),P._getDefaultValues=I,P._initialize=C,Object.assign(P.prototype,s);for(let v in u)_y(u[v])(P.prototype,v);for(let v of d)Ey(P.prototype,v);for(let v of h)Ry(P.prototype,v);for(let v in m)Cy(m[v])(P.prototype,v);if(g.length>0||p.length>0){let v=P[Symbol.metadata];for(let O of g)le.setFullStateOnly(v,O);for(let O of p)le.setStream(v,O);for(let O in y)le.setStreamPriority(v,O,y[O])}if(x.length>0){let v=P[Symbol.metadata];for(let O of x)v[v[O]].optional=!0}return P.extend=(v,O)=>Ss(v,O,P),P}function Oy(n){return new Array(n).fill(0).map((e,t)=>t===n-1?"\u2514\u2500 ":" ").join("")}function Py(n,e){if(e===-1||e>=n.length)return!1;let t=n.length-1;for(let r=e;r<t;r++)n[r]=n[r+1];return n.length=t,!0}function My(n,e,t){let r=~t,s=n.changeTrees;for(let i in s){let o=s[i],a=o.visibleViews;a!==void 0&&e<a.length&&(a[e]&=r);let c=o.subscribedViews;c!==void 0&&e<c.length&&(c[e]&=r);let u=o.tagViews;u!==void 0&&u.forEach(d=>{e<d.length&&(d[e]&=r)})}}function ed(n){n.structSwitchEmitted||(n.shouldEmitSwitch&&(n.buffer[n.it.offset++]=255,Q.number(n.buffer,n.ref[$],n.it)),n.structSwitchEmitted=!0)}function Ny(n,e){hf(n,e,R.ADD)}function ff(n,e){if(e._fullSyncGen===n.gen)return;if(e._fullSyncGen=n.gen,!n.hasView||n.view.isChangeTreeVisible(e)){let r=e.encDescriptor;n.changeTree=e,n.ref=e.ref,n.encoder=r.encoder,n.filter=r.filter,n.metadata=r.metadata,n.treeIsFiltered=e.isFiltered,n.isSchema=r.isSchema,n.filterBitmask=r.filterBitmask,n.tags=r.tags,n.structSwitchEmitted=!1,n.shouldEmitSwitch=n.hasView||n.it.offset>n.initialOffset||e!==n.rootChangeTree,e.isArray&&e.collDirty.size>0&&(e.flags|=yc),mc(e,n,Ny)}Rs(e,n,Ly)}function Ly(n,e,t){ff(n,e)}function hf(n,e,t){if(e<0){if(n.treeIsFiltered!==n.emitFiltered)return;ed(n),n.buffer[n.it.offset++]=Math.abs(e)&255;return}if((n.isSchema?n.treeIsFiltered||(e<32?(n.filterBitmask&1<<e)!==0:n.tags[e]!==void 0):n.treeIsFiltered)!==n.emitFiltered)return;let s=n.isEncodeAll?R.ADD:t;s!==void 0&&(n.filter!==void 0&&!n.filter(n.ref,e,n.view)||(ed(n),n.encoder(n.self,n.buffer,n.changeTree,e,s,n.it,n.isEncodeAll,n.hasView,n.metadata)))}function tc(n,e){let t=new Uint8Array(n.length+e.length);return t.set(n,0),t.set(e,n.length),t}function eo(n){let e=n.root,t=e.callbacks,r=new WeakMap,s;n.triggerChanges=function(a){let c=new Set;for(let u=0,d=a.length;u<d;u++){let h=a[u],m=h.refId,g=h.ref,p=t[m];if(p){if((h.op&R.DELETE)===R.DELETE&&Ee.isSchema(h.previousValue)){let y=t[h.previousValue[$]]?.[R.DELETE];for(let x=y?.length-1;x>=0;x--)y[x]()}if(Ee.isSchema(g)){if(!c.has(m)){let y=p?.[R.REPLACE];for(let x=y?.length-1;x>=0;x--)y[x]()}if(p.hasOwnProperty(h.field)){let y=p[h.field];for(let x=y?.length-1;x>=0;x--)y[x](h.value,h.previousValue)}}else{if((h.op&R.DELETE)===R.DELETE){if(h.previousValue!==void 0){let y=p[R.DELETE];for(let x=y?.length-1;x>=0;x--)y[x](h.previousValue,h.dynamicIndex??h.field)}if((h.op&R.ADD)===R.ADD){let y=p[R.ADD];for(let x=y?.length-1;x>=0;x--)y[x](h.value,h.dynamicIndex??h.field)}}else if((h.op&R.ADD)===R.ADD&&h.previousValue!==h.value){let y=p[R.ADD];for(let x=y?.length-1;x>=0;x--)y[x](h.value,h.dynamicIndex??h.field)}if(h.value!==h.previousValue&&(h.value!==void 0||h.previousValue!==void 0)){let y=p[R.REPLACE];for(let x=y?.length-1;x>=0;x--)y[x](h.value,h.dynamicIndex??h.field)}}c.add(m)}}};function i(a,c){let u=c.instance?.constructor[Symbol.metadata]||a,d=c.instance&&typeof c.instance.forEach=="function"||a&&!Ee.is(a);if(u&&!d){let h=function(m,g,p,y){return y&&c.instance[g]!==void 0&&!r.has(s)&&p(c.instance[g],void 0),e.addCallback(m[$],g,p)};return new Proxy({listen:function(g,p,y=!0){if(c.instance)return h(c.instance,g,p,y);{let x=()=>{};return c.onInstanceAvailable((k,I)=>{x=h(k,g,p,y&&I&&!r.has(s))}),()=>x()}},onChange:function(g){return e.addCallback(c.instance[$],R.REPLACE,g)},bindTo:function(g,p){return p||(p=Object.keys(u).map(y=>u[y].name)),e.addCallback(c.instance[$],R.REPLACE,()=>{p.forEach(y=>g[y]=c.instance[y])})}},{get(m,g){let p=u[u[g]];if(p){let y=c.instance?.[g],x=(k=>{let I=o(c.instance).listen(g,(B,N)=>{k(B,!1),I?.()},!1);y?.[$]!==void 0&&k(y,!0)});return i(p.type,{instance:y?.[$]!==void 0&&y,parentInstance:c.instance,onInstanceAvailable:x})}else return m[g]},has(m,g){return u[g]!==void 0},set(m,g,p){throw new Error("not allowed")},deleteProperty(m,g){throw new Error("not allowed")}})}else{let h=function(p,y,x){return x&&p.forEach((k,I)=>y(k,I)),e.addCallback(p[$],R.ADD,(k,I)=>{r.set(y,!0),s=y,y(k,I),r.delete(y),s=void 0})},m=function(p,y){return e.addCallback(p[$],R.DELETE,y)},g=function(p,y){return e.addCallback(p[$],R.REPLACE,y)};return new Proxy({onAdd:function(p,y=!0){if(c.instance)return h(c.instance,p,y&&!r.has(s));if(c.onInstanceAvailable){let x=()=>{};return c.onInstanceAvailable((k,I)=>{x=h(k,p,y&&I&&!r.has(s))}),()=>x()}},onRemove:function(p){if(c.instance)return m(c.instance,p);if(c.onInstanceAvailable){let y=()=>{};return c.onInstanceAvailable(x=>{y=m(x,p)}),()=>y()}},onChange:function(p){if(c.instance)return g(c.instance,p);if(c.onInstanceAvailable){let y=()=>{};return c.onInstanceAvailable(x=>{y=g(x,p)}),()=>y()}}},{get(p,y){if(!p[y])throw new Error(`Can't access '${y}' through callback proxy. access the instance directly.`);return p[y]},has(p,y){return p[y]!==void 0},set(p,y,x){throw new Error("not allowed")},deleteProperty(p,y){throw new Error("not allowed")}})}}function o(a){return i(void 0,{instance:a})}return o}function By(n,e){n.triggerChanges=e}var R,qu,$,Nt,Lt,Et,Hn,Te,xt,_r,_,X,Ce,yn,Rt,zi,Fe,Nd,ot,fs,Qt,Ue,bn,wt,Xt,Bn,ps,Wi,yr,at,$i,og,no,Un,nc,ag,Ld,cg,Bd,Q,_s,$n,pg,mg,gg,yg,te,dc,Sg,Zd,Cg,Pt,jn,zu,Dg,le,nf,sc,ic,sf,Hg,cf,Ji,Ki,zg,Wg,Ju,Hi,ny,Qa,Za,ds,ec,hs,gr,qi,Gi,ms,yc,ry,En,oc,iy,oy,bc,ay,uf,_t,dy,co,fy,gs,hy,Xu,nd,rd,sd,id,od,ad,cd,it,wn,Xi,ld,ud,dd,fd,hd,Mt,_n,pd,md,gd,yd,bd,mn,ys,wd,_d,Ed,Rd,xd,gn,bs,Sd,Td,kd,Ad,vd,Zt,Qi,Cd,Bt,py,my,gy,yy,by,wy,Ye,uo,xy,Id,Od,Pd,Md,bt,Ee,Zu,ac,oE,Dy,Dt,ws,Zi,td,lc,Tt,pf,mf,gf,kt,to,Ec,qe=Pe(()=>{"use strict";(function(n){n[n.ADD=128]="ADD",n[n.REPLACE=0]="REPLACE",n[n.DELETE=64]="DELETE",n[n.DELETE_AND_MOVE=96]="DELETE_AND_MOVE",n[n.MOVE_AND_ADD=160]="MOVE_AND_ADD",n[n.DELETE_AND_ADD=192]="DELETE_AND_ADD",n[n.CLEAR=10]="CLEAR",n[n.REVERSE=15]="REVERSE",n[n.MOVE=32]="MOVE",n[n.DELETE_BY_REFID=33]="DELETE_BY_REFID",n[n.ADD_BY_REFID=129]="ADD_BY_REFID"})(R||(R={}));Symbol.metadata??(Symbol.metadata=Symbol.for("Symbol.metadata"));qu=(function(){return typeof globalThis<"u"?globalThis:typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{}})();if(typeof Symbol=="function"&&typeof Symbol.for!="function"){let n="colyseus.symbolRegistry",e=qu[n]||(qu[n]=Object.create(null));Symbol.for=function(t){return e[t]||(e[t]=Symbol(t))},Symbol.keyFor=function(t){for(let r in e)if(e[r]===t)return r}}$=Symbol.for("$refId"),Nt="~track",Lt="~encoder",Et="~decoder",Hn="~filter",Te="~getByIndex",xt="~deleteByIndex",_r="~resyncPrune",_=Symbol.for("$changes"),X=Symbol.for("$childType"),Ce=Symbol.for("$proxyTarget"),yn="~onEncodeEnd",Rt="~reset",zi="~onDecodeEnd",Fe=Symbol.for("$values"),Nd="~builder",ot="~descriptors",fs="~__encodeDescriptor",Qt="~encoders",Ue="~__numFields",bn="~__refTypeFieldIndexes",wt="~__viewFieldIndexes",Xt="$__fieldIndexesByViewTag",Bn="~__unreliableFieldIndexes",ps="~__patchOnlyFieldIndexes",Wi="~__fullSyncSkipIndexes",yr="~__fullStateOnlyFieldIndexes",at="~__streamFieldIndexes",$i="~__streamPriorities";try{og=new TextEncoder}catch{}no=new ArrayBuffer(8),Un=new Int32Array(no),nc=new Float32Array(no),ag=new Float64Array(no),Ld=new BigInt64Array(no),cg=typeof Buffer<"u"&&Buffer.byteLength,Bd=cg?Buffer.byteLength:function(n,e){for(var t=0,r=0,s=0,i=n.length;s<i;s++)t=n.charCodeAt(s),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(s++,r+=4);return r};Q={int8:Fd,uint8:lg,int16:$d,uint16:uc,int32:en,uint32:Fn,int64:Vd,uint64:jd,bigint64:ug,biguint64:dg,float32:Hd,float64:Gd,boolean:fg,string:hg,number:rc,utf8Write:Ud,utf8Length:Bd},_s=new ArrayBuffer(8),$n=new Int32Array(_s),pg=new Float32Array(_s),mg=new Float64Array(_s),gg=new BigUint64Array(_s),yg=new BigInt64Array(_s);te={utf8Read:qd,int8:zd,uint8:Es,int16:Wd,uint16:ro,int32:St,uint32:br,float32:Yd,float64:Jd,int64:Kd,uint64:Xd,bigint64:bg,biguint64:wg,boolean:_g,string:Eg,number:Rg,stringCheck:xg},dc={},Sg=new Map;Zd="ArraySchema does not support streaming \u2014 positional ops (splice / unshift / reverse) shift subsequent indexes, so holding ADDs back for a later tick under `maxPerTick` would desync the decoder. Use `t.stream(X)` (stable monotonic positions) or `t.map(X).stream()` (stable keys) instead.";Cg={8:"uint8",16:"uint16",32:"uint32"};Pt=class Pt{constructor(e){l(this,"types",{});l(this,"schemas",new Map);l(this,"hasFilters",!1);e&&this.discoverTypes(e)}static register(e){let t=Object.getPrototypeOf(e);if(t!==Ee){let r=Pt.inheritedTypes.get(t);r||(r=new Set,Pt.inheritedTypes.set(t,r)),r.add(e)}}static cache(e){let t=Pt.cachedContexts.get(e);return t||(t=new Pt(e),Pt.cachedContexts.set(e,t)),t}has(e){return this.schemas.has(e)}get(e){return this.types[e]}add(e,t=this.schemas.size){return this.schemas.has(e)?!1:(this.types[t]=e,e[Symbol.metadata]==null&&le.initialize(e),this.schemas.set(e,t),!0)}getTypeId(e){return this.schemas.get(e)}discoverTypes(e){if(!this.add(e))return;Pt.inheritedTypes.get(e)?.forEach(s=>{this.discoverTypes(s)});let t=e;for(;(t=Object.getPrototypeOf(t))&&t!==Ee&&t!==Function.prototype;)this.discoverTypes(t);let r=e[Symbol.metadata];(r[wt]||r[at])&&(this.hasFilters=!0);for(let s in r){let o=r[s].type;if(typeof o!="string"&&!Vn(o))if(typeof o=="function")this.discoverTypes(o);else{let a=Object.values(o)[0];if(typeof a=="string")continue;this.discoverTypes(a)}}}debug(){return`TypeContext ->
|
|
2
2
|
Schema types: ${this.schemas.size}
|
|
3
|
-
hasFilters: ${this.hasFilters}`}};l(Pt,"inheritedTypes",new WeakMap),l(Pt,"cachedContexts",new WeakMap);jn=Pt,
|
|
4
|
-
Schema instances may only have up to ${Nu} fields.`);n[e]=Object.assign(n[e]||{},{type:br(r),index:e,name:t}),Object.defineProperty(n,ot,{value:n[ot]||{},enumerable:!1,configurable:!0}),s?n[ot][t]=s:n[ot][t]={value:void 0,writable:!0,enumerable:!0,configurable:!0},Object.defineProperty(n,Fe,{value:e,enumerable:!1,configurable:!0}),Object.defineProperty(n,t,{value:e,enumerable:!1,configurable:!0}),typeof n[e].type!="string"&&!Vn(n[e].type)&&(n[bn]===void 0&&Object.defineProperty(n,bn,{value:[],enumerable:!1,configurable:!0}),n[bn].push(e));let i=n[e].type;if(i&&typeof i=="object"&&i.stream!==void 0){if(i.array!==void 0)throw new Error(jd);n[e].stream=!0,n[at]||Object.defineProperty(n,at,{value:[],enumerable:!1,configurable:!0,writable:!0}),n[at].includes(e)||n[at].push(e);let o=r?.priority;typeof o=="function"&&ce.setStreamPriority(n,t,o)}},setTag(n,e,t){let r=n[e],s=n[r];if(s.tag=t,n[bt]||(Object.defineProperty(n,bt,{value:[],enumerable:!1,configurable:!0}),Object.defineProperty(n,Xt,{value:{},enumerable:!1,configurable:!0})),n[bt].push(r),t<0)n[Xt][t]||(n[Xt][t]=[]),n[Xt][t].push(r);else for(let i=t;i>0;i&=i-1){let o=i&-i;n[Xt][o]||(n[Xt][o]=[]),n[Xt][o].push(r)}},setUnreliable(n,e){let t=n[e];if(typeof n[t].type!="string")throw new Error(`@unreliable cannot be applied to ref-type field "${e}". For ref-type fields, mark each primitive sub-field with @unreliable instead. See README "Limitations and best practices".`);n[t].unreliable=!0,n[Ln]||Object.defineProperty(n,Ln,{value:[],enumerable:!1,configurable:!0,writable:!0}),n[Ln].push(t)},setPatchOnly(n,e){let t=n[e];if(n[t].fullStateOnly)throw new Error(`field "${e}" cannot be both patchOnly and fullStateOnly \u2014 those are the only two delivery channels, so the field would never reach a client.`);n[t].patchOnly=!0,Bi(n,ds,t),Bi(n,ji,t)},setDeprecated(n,e){let t=n[e];n[t].deprecated=!0,Bi(n,ji,t),Object.defineProperty(n,t,{value:n[t],enumerable:!1,configurable:!0})},setFullStateOnly(n,e){let t=n[e];if(n[t].patchOnly)throw new Error(`field "${e}" cannot be both patchOnly and fullStateOnly \u2014 those are the only two delivery channels, so the field would never reach a client.`);n[t].fullStateOnly=!0,Bi(n,gr,t)},setStream(n,e){let t=n[e];n[t].stream=!0,n[at]||Object.defineProperty(n,at,{value:[],enumerable:!1,configurable:!0,writable:!0}),n[at].push(t)},setStreamPriority(n,e,t){let r=n[e];n[Ni]||Object.defineProperty(n,Ni,{value:{},enumerable:!1,configurable:!0,writable:!0}),n[Ni][r]=t},getStreamPriority(n,e){return n?.[Ni]?.[e]},defineField(n,e,t,r,s){let i=br(s),{complexTypeKlass:o,childType:a}=yg(i);ce.addField(e,t,r,i,hy(r,t,a,o)),e[ot][r]&&Object.defineProperty(n.prototype,r,e[ot][r]),(typeof i=="string"||Vn(i))&&(e[Qt]||Object.defineProperty(e,Qt,{value:[],enumerable:!1,configurable:!0,writable:!0}),e[Qt][t]=typeof i=="string"?Q[i]:mg(i.quantized))},setFields(n,e){let t=n.prototype.constructor;jn.register(t);let r=Object.getPrototypeOf(t),s=r&&r[Symbol.metadata],i=ce.initialize(t);t[Dt]||(t[Dt]=Ee[Dt]),t[Nt]||(t[Nt]=Ee[Nt]),t[_t]||(t[_t]=Ee[_t]),t.prototype.toJSON||(t.prototype.toJSON=Ee.prototype.toJSON);let o=i[Fe]??(s&&s[Fe])??-1;o++,i[Qt]||Object.defineProperty(i,Qt,{value:s?.[Qt]?[...s[Qt]]:[],enumerable:!1,configurable:!0,writable:!0});for(let a in e){if(i[a]!==void 0)throw new Error(`@colyseus/schema: Duplicate '${a}' definition on '${t.name||"(anonymous)"}'.`);ce.defineField(t,i,o,a,e[a]),o++}return n},isDeprecated(n,e){return n[e].deprecated===!0},initialize(n){let e=Object.getPrototypeOf(n),t=e[Symbol.metadata],r=n[Symbol.metadata]??Object.create(null);if(e!==Ee&&r===t&&(r=Object.create(null),t)){Object.setPrototypeOf(r,t),Object.defineProperty(r,Fe,{value:t[Fe],enumerable:!1,configurable:!0,writable:!0}),t[bt]!==void 0&&(Object.defineProperty(r,bt,{value:[...t[bt]],enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(r,Xt,{value:{...t[Xt]},enumerable:!1,configurable:!0,writable:!0}));for(let s of wg){let i=t[s];i!==void 0&&Object.defineProperty(r,s,{value:[...i],enumerable:!1,configurable:!0,writable:!0})}Object.defineProperty(r,ot,{value:{...t[ot]},enumerable:!1,configurable:!0,writable:!0})}return Object.defineProperty(n,Symbol.metadata,{value:r,writable:!1,configurable:!0}),r},isValidInstance(n){return n.constructor[Symbol.metadata]&&Object.prototype.hasOwnProperty.call(n.constructor[Symbol.metadata],Fe)},getFields(n){let e=n[Symbol.metadata],t={};for(let r=0;r<=e[Fe];r++)t[e[r].name]=e[r].type;return t},hasViewTagAtIndex(n,e){return n?.[bt]?.includes(e)},hasUnreliableAtIndex(n,e){return n?.[Ln]?.includes(e)},hasPatchOnlyAtIndex(n,e){return n?.[ds]?.includes(e)},hasFullStateOnlyAtIndex(n,e){return n?.[gr]?.includes(e)},hasStreamAtIndex(n,e){return n?.[at]?.includes(e)}},Hd=(n,e,t)=>n(e,t),tc=class{constructor(e){l(this,"dirtyLow",0);l(this,"dirtyHigh",0);l(this,"ops");this.ops=new Uint8Array(Math.max(e+1,1))}record(e,t){let r=this.ops[e];r===0?this.ops[e]=t:r===R.DELETE?this.ops[e]=R.DELETE_AND_ADD:r===R.ADD&&t===R.DELETE_AND_ADD&&(this.ops[e]=R.DELETE_AND_ADD),e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}recordDelete(e,t){this.ops[e]=t,e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}recordRaw(e,t){this.record(e,t)}operationAt(e){let t=this.ops[e];return t===0?void 0:t}setOperationAt(e,t){this.ops[e]=t}forEach(e){this.forEachWithCtx(e,Hd)}forEachWithCtx(e,t){let r=this.dirtyLow,s=this.dirtyHigh,i=this.ops;for(;r!==0;){let o=r&-r,a=31-Math.clz32(o);r^=o,t(e,a,i[a])}for(;s!==0;){let o=s&-s,a=31-Math.clz32(o)+32;s^=o,t(e,a,i[a])}}size(){return qi(this.dirtyLow)+qi(this.dirtyHigh)}has(){return(this.dirtyLow|this.dirtyHigh)!==0}reset(){this.dirtyLow=0,this.dirtyHigh=0,this.ops.fill(0)}},nc=class{constructor(){l(this,"dirty",new Map);l(this,"pureOps",[])}record(e,t){let r=this.dirty.get(e);r===void 0?this.dirty.set(e,t):r===R.DELETE?this.dirty.set(e,R.DELETE_AND_ADD):r===R.ADD&&t===R.DELETE_AND_ADD&&this.dirty.set(e,R.DELETE_AND_ADD)}recordDelete(e,t){this.dirty.set(e,t)}recordRaw(e,t){this.dirty.set(e,t)}recordPure(e){this.pureOps.push([this.dirty.size,e])}operationAt(e){return this.dirty.get(e)}setOperationAt(e,t){this.dirty.has(e)&&this.dirty.set(e,t)}forEach(e){this.forEachWithCtx(e,Hd)}forEachWithCtx(e,t){let r=this.pureOps;if(r.length>0){let s=0,i=0;for(let[o,a]of this.dirty){for(;s<r.length&&r[s][0]<=i;){let c=r[s++][1];t(e,-c,c)}t(e,o,a),i++}for(;s<r.length;){let o=r[s++][1];t(e,-o,o)}}else for(let[s,i]of this.dirty)t(e,s,i)}size(){return this.dirty.size+this.pureOps.length}has(){return this.dirty.size>0||this.pureOps.length>0}reset(){this.dirty.clear(),this.pureOps.length=0}shift(e){let t=new Map;for(let[r,s]of this.dirty)t.set(r+e,s);this.dirty=t}};Wd=(n,e)=>{n.isFieldUnreliable(e)?n.ensureUnreliableRecorder().record(e,R.ADD):n.record(e,R.ADD)},Ag=(n,e)=>n(e);Yd=1,Gi=2,Hi=4,Pg=Yd|Gi|Hi;Og=(n,e,t)=>{hc(e)};Fu=[],Fi=0;Vg=(n,e,t)=>n(e,t);Ka=1,Ya=2,cs=4,Xa=8,us=16,mr=32,$i=64,Ui=128,fs=256,pc=512,jg=us|mr,En=class{constructor(e,t=e){l(this,"ref");l(this,"refTarget");l(this,"metadata");l(this,"encDescriptor");l(this,"root");l(this,"parentRef");l(this,"_parentIndex");l(this,"extraParents");l(this,"flags",cs);l(this,"_fullSyncGen",0);l(this,"_isSchema",!1);l(this,"dirtyLow",0);l(this,"dirtyHigh",0);l(this,"opsLow",0);l(this,"opsHigh",0);l(this,"ops");l(this,"collDirty");l(this,"collPureOps");l(this,"unreliableRecorder");l(this,"paused",!1);l(this,"changesNode");l(this,"unreliableChangesNode");l(this,"visibleViews");l(this,"tagViews");l(this,"subscribedViews");this.ref=e,this.refTarget=t;let r=dc(e);this.encDescriptor=r,this.metadata=r.metadata;let s=r.isSchema;if(this._isSchema=s,this.ops=void 0,this.collDirty=void 0,this.collPureOps=void 0,s){let i=this.metadata?.[Fe]??0;i>7&&(this.ops=new Uint8Array(i+1))}else this.collDirty=new Map}get isArray(){return this.refTarget!==this.ref}get isFiltered(){return(this.flags&Ka)!==0}set isFiltered(e){this.flags=e?this.flags|Ka:this.flags&~Ka}get isVisibilitySharedWithParent(){return(this.flags&Ya)!==0}set isVisibilitySharedWithParent(e){this.flags=e?this.flags|Ya:this.flags&~Ya}get isNew(){return(this.flags&cs)!==0}set isNew(e){this.flags=e?this.flags|cs:this.flags&~cs}get isUnreliable(){return(this.flags&Xa)!==0}set isUnreliable(e){this.flags=e?this.flags|Xa:this.flags&~Xa}get isPatchOnly(){return(this.flags&us)!==0}set isPatchOnly(e){this.flags=e?this.flags|us:this.flags&~us}get isFullStateOnly(){return(this.flags&mr)!==0}set isFullStateOnly(e){this.flags=e?this.flags|mr:this.flags&~mr}get isStreamCollection(){return(this.flags&$i)!==0}set isStreamCollection(e){this.flags=e?this.flags|$i:this.flags&~$i}get needsRestage(){return(this.flags&Ui)!==0}set needsRestage(e){this.flags=e?this.flags|Ui:this.flags&~Ui}get hasFilteredFields(){return this.isFiltered||this.encDescriptor.hasAnyView}ensureUnreliableRecorder(){return this.unreliableRecorder===void 0&&(this.unreliableRecorder=this._isSchema?new tc(this.metadata?.[Fe]??0):new nc),this.unreliableRecorder}isFieldUnreliable(e){let t=this.encDescriptor;return t.hasAnyUnreliable?e<32?(t.unreliableBitmask&1<<e)!==0:ce.hasUnreliableAtIndex(this.metadata,e):!1}isFieldFullStateOnly(e){if(this.isFullStateOnly)return!0;let t=this.encDescriptor;return t.hasAnyFullStateOnly?e<32?(t.fullStateOnlyBitmask&1<<e)!==0:ce.hasFullStateOnlyAtIndex(this.metadata,e):!1}isFieldStream(e){let t=this.encDescriptor;return t.hasAnyStream?e<32?(t.streamBitmask&1<<e)!==0:ce.hasStreamAtIndex(this.metadata,e):!1}_opAt(e){let t=this.ops;if(t!==void 0)return t[e];let r=(e&3)<<3;return e<4?this.opsLow>>>r&255:this.opsHigh>>>r&255}_opPut(e,t){let r=this.ops;if(r!==void 0){r[e]=t;return}let s=(e&3)<<3,i=~(255<<s);e<4?this.opsLow=this.opsLow&i|t<<s:this.opsHigh=this.opsHigh&i|t<<s}_markDirty(e){e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}record(e,t){if(this._isSchema){let r=this._opAt(e);r===0?this._opPut(e,t):r===R.DELETE?this._opPut(e,R.DELETE_AND_ADD):r===R.ADD&&t===R.DELETE_AND_ADD&&this._opPut(e,R.DELETE_AND_ADD),this._markDirty(e)}else{let r=this.collDirty,s=r.get(e),i;s===void 0?i=t:s===R.DELETE||s===R.ADD&&t===R.DELETE_AND_ADD?i=R.DELETE_AND_ADD:i=s,r.set(e,i)}}recordDelete(e,t){this._isSchema?(this._opPut(e,t),this._markDirty(e)):this.collDirty.set(e,t)}recordRaw(e,t){this._isSchema?(this._opPut(e,t),this._markDirty(e)):this.collDirty.set(e,t)}recordPure(e){if(this._isSchema)throw new Error("ChangeTree (Schema): pure operations are not supported");(this.collPureOps??(this.collPureOps=[])).push([this.collDirty.size,e])}operationAt(e){if(this._isSchema){let t=this._opAt(e);return t===0?void 0:t}return this.collDirty.get(e)}setOperationAt(e,t){if(this._isSchema)this._opPut(e,t);else{let r=this.collDirty;r.has(e)&&r.set(e,t)}}forEach(e){this.forEachWithCtx(e,Vg)}forEachWithCtx(e,t){if(this._isSchema){let i=this.dirtyLow,o=this.dirtyHigh,a=this.ops;if(a!==void 0){for(;i!==0;){let c=i&-i,u=31-Math.clz32(c);i^=c,t(e,u,a[u])}for(;o!==0;){let c=o&-o,u=31-Math.clz32(c)+32;o^=c,t(e,u,a[u])}}else{let c=this.opsLow,u=this.opsHigh;for(;i!==0;){let d=i&-i,h=31-Math.clz32(d);i^=d,t(e,h,$g(c,u,h))}}return}let r=this.collDirty,s=this.collPureOps;if(s!==void 0&&s.length>0){let i=0,o=0;for(let[a,c]of r){for(;i<s.length&&s[i][0]<=o;){let u=s[i++][1];t(e,-u,u)}t(e,a,c),o++}for(;i<s.length;){let a=s[i++][1];t(e,-a,a)}}else for(let[i,o]of r)t(e,i,o)}size(){return this._isSchema?qi(this.dirtyLow)+qi(this.dirtyHigh):this.collDirty.size+(this.collPureOps?.length??0)}has(){return this._isSchema?(this.dirtyLow|this.dirtyHigh)!==0:this.collDirty.size>0||this.collPureOps!==void 0&&this.collPureOps.length>0}reset(){if(this._isSchema){this.dirtyLow=0,this.dirtyHigh=0,this.ops!==void 0?this.ops.fill(0):(this.opsLow=0,this.opsHigh=0);return}this.collDirty.clear(),this.collPureOps!==void 0&&(this.collPureOps.length=0),this.flags&=~pc}recycle(){if(this.root!==void 0)throw new Error(`@colyseus/schema: cannot recycle an attached ChangeTree (${this.ref?.constructor?.name}). Remove the instance from its parent collection before releasing it to a pool.`);this.reset(),this.unreliableRecorder?.reset(),this.flags=cs|Ui,this._fullSyncGen=0,this.parentRef=void 0,this._parentIndex=void 0,this.extraParents=void 0,this.changesNode=void 0,this.unreliableChangesNode=void 0,this.paused=!1,this.visibleViews=void 0,this.tagViews=void 0,this.subscribedViews=void 0}insertAt(e,t){if(this._isSchema)throw new Error("ChangeTree (Schema): insertAt is not supported");let r=this.collDirty,s=new Map,i=!this.paused&&!this.isFullStateOnly;if(e>0)for(let[o,a]of r)o<e&&s.set(o,a);if(i)for(let o=0;o<t;o++)s.set(e+o,R.ADD);for(let[o,a]of r)o>=e&&s.set(o+t,a);this.collDirty=s,i&&this.root?.enqueueChangeTree(this)}removeAt(e,t){if(this._isSchema)throw new Error("ChangeTree (Schema): removeAt is not supported");let r=this.collDirty,s=e+t,i=!1;for(let a of r.keys())if(a>=s){i=!0;break}if(!i){for(let a=e;a<s;a++)r.delete(a);return}let o=new Map;for(let[a,c]of r)a<e?o.set(a,c):a>=s&&o.set(a-t,c);this.collDirty=o}unshift(e){this.insertAt(0,e)}setRoot(e){Dg(this,e)}setParent(e,t,r){Ng(this,e,t,r)}forEachChild(e){Bg(this,e)}forEachChildWithCtx(e,t){ws(this,e,t)}forEachLive(e){Cg(this,e)}forEachLiveWithCtx(e,t){fc(this,e,t)}operation(e){this.paused||this.isFullStateOnly||(this.recordPure(e),this.root?.enqueueChangeTree(this))}_routeAndRecord(e,t,r){if(!(this.paused||this.isFieldFullStateOnly(e))){if(this.isFieldUnreliable(e)&&!this.isNew){let s=this.ensureUnreliableRecorder();r?s.recordRaw(e,t):s.record(e,t),this.root?.enqueueUnreliable(this);return}r?this.recordRaw(e,t):this.record(e,t),this.root?.enqueueChangeTree(this)}}change(e,t=R.ADD){this._routeAndRecord(e,t,!1)}indexedOperation(e,t){this._routeAndRecord(e,t,!0)}getChange(e){return this.operationAt(e)}pause(){this.paused=!0}resume(){this.paused=!1}untracked(e){let t=this.paused;this.paused=!0;try{return e()}finally{this.paused=t}}markDirty(e,t=R.ADD){let r=this.paused;this.paused=!1;try{this.change(e,t)}finally{this.paused=r}}getValue(e,t=!1){return this.refTarget[Te](e,t)}delete(e,t){if(e===void 0){try{throw new Error(`@colyseus/schema ${this.ref.constructor.name}: trying to delete non-existing index '${e}'`)}catch(i){console.warn(i)}return}if(this.paused||this.isFieldFullStateOnly(e))return this.getValue(e);let r=this.isFieldUnreliable(e)&&!this.isNew;r?this.ensureUnreliableRecorder().recordDelete(e,t??R.DELETE):this.recordDelete(e,t??R.DELETE);let s=this.getValue(e);return s&&s[_]&&this.root?.remove(s[_]),r?this.root?.enqueueUnreliable(this):this.root?.enqueueChangeTree(this),s}endEncode(){this.reset(),this.changesNode=void 0,this._isSchema||this.refTarget[yn]?.(),this.isNew=!1}endEncodeUnreliable(){this.unreliableRecorder?.reset(),this.unreliableChangesNode=void 0,this._isSchema||this.refTarget[yn]?.()}discard(){this._isSchema||this.refTarget[yn]?.(),this.reset(),this.unreliableRecorder?.reset()}discardAll(){let e=t=>{if(t<0)return;let r=this.getValue(t);r&&r[_]&&r[_].discardAll()};this.forEach(e),this.unreliableRecorder?.forEach(e),this.discard()}get changed(){return this.has()||(this.unreliableRecorder?.has()??!1)}get parent(){return this.parentRef}get parentIndex(){return this._parentIndex}addParent(e,t){Eg(this,e,t)}setParentIndex(e,t){Rg(this,e,t)}removeParent(e=this.parent){return xg(this,e)}findParent(e){return Sg(this,e)}hasParent(e){return zd(this,e)}indexInParent(e){return Tg(this,e)}getAllParents(){return kg(this)}},rc=class{constructor(e){l(this,"ref");l(this,"root");l(this,"parentRef");l(this,"paused",!1);l(this,"isNew",!1);l(this,"flags",0);this.ref=e}change(){}delete(){}indexedOperation(){}operation(){}setParent(){}addParent(){}setParentIndex(){}removeParent(){return!1}getChange(){return 0}discard(){}discardAll(){}pause(){}resume(){}untracked(e){return e()}markDirty(){}forEachChild(e){let t=this.ref;if(t[X]){if(typeof t[X]!="string")for(let[o,a]of t.entries())a&&e(a[_],t._collectionIndexes?.[o]??o);return}let s=t.constructor?.[Symbol.metadata];if(!s)return;let i=s[bn]??[];for(let o=0;o<i.length;o++){let a=i[o],c=t[s[a].name];c&&e(c[_],a)}}forEachChildWithCtx(e,t){this.forEachChild((r,s)=>t(e,r,s))}forEachLive(){}forEachLiveWithCtx(){}forEach(){}};Gg=function(n,e,t,r,s,i,o,a){if(e[i.offset++]=(r|s)&255,s===R.DELETE)return;let c=t.encDescriptor,u=t.ref,d=u[Ue][r]??u[c.names[r]];no(n,e,c.types[r],d,s,i,c.encoders[r])},Hg=function(n,e,t,r,s,i){if(e[i.offset++]=s&255,Q.number(e,r,i),s===R.DELETE)return;let o=t.ref;if((s&R.ADD)===R.ADD){let a=o.$indexes.get(r);Q.string(e,a,i)}no(n,e,o[X],o[Te](r),s,i)},mc=function(n,e,t,r,s,i){if(e[i.offset++]=s&255,Q.number(e,r,i),s===R.DELETE)return;let o=t.ref;no(n,e,o[X],o[Te](r),s,i)},zg=function(n,e,t,r,s,i,o,a){let c=t.refTarget,u=c[X],d=typeof u!="string",h=a&&t.isFiltered&&d,m;if(h){let p=c.tmpItems[r];if(!p)return;if(m=p[$],s===R.DELETE)s=R.DELETE_BY_REFID;else if((s&R.ADD)===R.ADD)s=R.ADD_BY_REFID;else if((s&R.MOVE)===R.MOVE)return}else if(s===R.DELETE&&d){let p=c.tmpItems[r];if(!p)return;m=p[$],s=R.DELETE_BY_REFID}else m=r;if(e[i.offset++]=s&255,Q.number(e,m,i),s===R.DELETE||s===R.DELETE_BY_REFID)return;let g=c[Te](r,o);no(n,e,u,g,s,i)};Qd=-1,wt={Map:1,Array:2,Set:3,Collection:4,Stream:5};Yg=function(n,e,t,r,s){let i=e[t.offset++],o=r.constructor[Symbol.metadata],a=i>>6<<6,c=i%(a||255),u=o[c];if(u===void 0)return console.warn("@colyseus/schema: field not defined at",{index:c,ref:r.constructor.name,metadata:o}),Qd;let d=u.deprecated===!0,h=d?void 0:r[Te](c),m=yc(n,a,r,c,h,u.type,e,t,s);d||(m!=null&&(r[u.name]=m),h!==m&&s?.push({ref:r,refId:n.currentRefId,op:a,field:u.name,value:m,previousValue:h}))},ro=function(n,e,t,r,s){let i=r[Ce]??r,o=e[t.offset++];if(o===R.CLEAR){n.removeChildRefs(i,s),i.clear();return}let a=te.number(e,t),c=i[X],u=i.constructor.COLLECTION_KIND,d;(o&R.ADD)===R.ADD?u===wt.Map?(d=te.string(e,t),i.setIndex(a,d)):d=a:d=i.getIndex(a);let h=i[Te](a),m=yc(n,o,r,a,h,c,e,t,s);if(n.resyncVisited!==null&&Xd(n,r,o,d,h,m,s),m!=null)switch(u){case wt.Map:i.$items.set(d,m);break;case wt.Array:i.$setAt(a,m,n.resyncVisited!==null&&o===R.ADD?R.REPLACE:o);break;case wt.Set:case wt.Collection:case wt.Stream:i.$items.has(a)||(i.$items.set(a,m),typeof i.$refId=="number"&&a>=i.$refId&&(i.$refId=a+1));break;default:console.warn(`@colyseus/schema: missing COLLECTION_KIND on ${i.constructor?.name} \u2014 item at index ${a} was not stored.`);break}h!==m&&s?.push({ref:r,refId:n.currentRefId,op:o,dynamicIndex:d,value:m,previousValue:h})},Xg=function(n,e,t,r,s){let i=r[Ce]??r,o=e[t.offset++],a;if(o===R.CLEAR){n.removeChildRefs(i,s),i.clear();return}else if(o===R.REVERSE){i.items.reverse();return}else if(o===R.DELETE_BY_REFID){let m=te.number(e,t),g=n.root.refs.get(m);if(g===void 0||(n.root.removeRef(m),a=i.findIndex(p=>p===g),a===-1))return;i[Rt](a),s?.push({ref:r,refId:n.currentRefId,op:R.DELETE,dynamicIndex:a,value:void 0,previousValue:g});return}else if(o===R.ADD_BY_REFID){let m=te.number(e,t),g=n.root.refs.get(m);g&&(a=i.findIndex(p=>p===g)),(a===-1||a===void 0)&&(a=i.length)}else a=te.number(e,t);let c=i[X],u=a,d=i.items[a],h=yc(n,o,r,a,d,c,e,t,s);n.resyncVisited!==null&&Xd(n,r,o,a,d,h,s),h!=null&&h!==d&&i.$setAt(a,h,n.resyncVisited!==null&&o===R.ADD?R.REPLACE:o),d!==h&&s?.push({ref:r,refId:n.currentRefId,op:o,dynamicIndex:u,value:h,previousValue:d})},hs=class extends Error{};Qg=(n,e)=>{let t=n.toString(),r=e.toString();return t<r?-1:t>r?1:0},$u={get:(n,e)=>typeof e!="symbol"&&!isNaN(e)?n.items[e]:Reflect.get(n,e),set:(n,e,t)=>{if(typeof e!="symbol"&&!isNaN(e)){if(t==null)n.$deleteAt(e);else{let r;if(t[_]){so(t,n[X],n,e);let s=n.items[e];n.isMovingItems?(r=n.$wireIndex(Number(e)),s!==void 0?t[_].isNew?n[_].indexedOperation(r,R.MOVE_AND_ADD):(n[_].getChange(r)&R.DELETE)===R.DELETE?n[_].indexedOperation(r,R.DELETE_AND_MOVE):n[_].indexedOperation(r,R.MOVE):t[_].isNew&&n[_].indexedOperation(r,R.ADD),t[_].setParent(n,n[_].root,r)):r=n.$changeAt(Number(e),t),s!==void 0&&s[_].root?.remove(s[_])}else r=n.$changeAt(Number(e),t);n.items[e]=t,r!==void 0&&(n.tmpItems[r]=t)}return!0}return Reflect.set(n,e,t)},deleteProperty:(n,e)=>(typeof e=="number"?n.$deleteAt(e):delete n[e],!0),has:(n,e)=>typeof e!="symbol"&&!isNaN(Number(e))?Reflect.has(n.items,e):Reflect.has(n,e)},it=class it{constructor(...e){l(this,Xu);l(this,Yu);l(this,Ku);l(this,Ju);l(this,"items",[]);l(this,"tmpItems",[]);l(this,"deletedIndexes",[]);l(this,"isMovingItems",!1);l(this,"_needsCompaction",!1);l(this,Hu);this[X]=void 0,this[Ce]=this;let t=new Proxy(this,$u);return Object.defineProperty(this,_,{value:new En(t,this),enumerable:!1,writable:!0}),e.length>0&&this.push(...e),t}static[(Xu=_,Yu=$,Ku=Ce,Ju=X,Wu=Nt,zu=_t,qn)](e,t,r){if(!r)return!0;let s=e[Ce]??e;return typeof s[X]=="string"||r.isChangeTreeVisible(s.tmpItems[t]?.[_])}static is(e){return Array.isArray(e)||e.array!==void 0}static from(e){return new it(...Array.from(e))}static initializeForDecoder(){let e=Object.create(it.prototype);e.items=[],e.isMovingItems=!1,e._needsCompaction=!1,e[X]=void 0,e[Ce]=e;let t=new Proxy(e,$u);return _r(e,t),t}set length(e){e===0?this.clear():e<this.items.length?this.splice(e,this.length-e):console.warn("ArraySchema: can't set .length to a higher value than its length.")}get length(){return this.items.length}pauseTracking(){this[_].pause()}resumeTracking(){this[_].resume()}untracked(e){return this[_].untracked(e)}get isTrackingPaused(){return this[_].paused}push(...e){let t=this[Ce],r=t.items,s=t.tmpItems,i=t[_],o=t[X],a=s.length;for(let c=0,u=e.length;c<u;c++,a++){let d=e[c];if(d==null)return;typeof d=="object"&&o&&so(d,o,t,c),i.indexedOperation(a,R.ADD),r.push(d),s.push(d),d[_]?.setParent(this,i.root,a)}return a}pop(){let e=this[Ce],t=e.tmpItems,r=e.deletedIndexes,s=-1;for(let o=t.length-1;o>=0;o--)if(r[o]!==!0){s=o;break}if(s<0)return;let i=e.$isUnsentAdd(s);return e[_].delete(s),i?e.$cancelAdd(s):r[s]=!0,e.items.pop()}at(e){return e<0&&(e+=this.length),this.items[e]}$wireIndex(e){let t=this.deletedIndexes;if(t.length===0)return e;let r=this.tmpItems,s=0;for(let i=0;i<r.length;i++)if(t[i]!==!0){if(s===e)return i;s++}return r.length+(e-s)}$isUnsentAdd(e){let t=this[_];return(t.flags&(pc|$i))===0&&!t.paused&&typeof this[X]!="string"&&t.operationAt(e)===R.ADD}$cancelAdd(e,t=!0){let r=this[_],s=this.tmpItems[e];this.tmpItems.splice(e,1),this.deletedIndexes.length>0&&this.deletedIndexes.splice(e,1),r.removeAt(e,1);let i=s?.[_];i!==void 0&&i.root===void 0&&i.removeParent(this),t&&this.$reindexChildren(e)}$reindexChildren(e,t){if(!this[_].hasFilteredFields||typeof this[X]=="string")return;let r=this.tmpItems,s=r.length;if(t!==void 0)for(;e<s&&r[e]===t[e];)e++;for(let i=e;i<s;i++)r[i]?.[_]?.setParentIndex(this,i)}$changeAt(e,t){if(t==null){console.error("ArraySchema items cannot be null nor undefined; Use `splice(index, 1)` instead.");return}if(this.items[e]===t)return;let r=this.items[e]!==void 0?typeof t=="object"?R.DELETE_AND_ADD:R.REPLACE:R.ADD,s=this.$wireIndex(e),i=this[_];return i.change(s,r),t[_]?.setParent(this,i.root,s),s}$deleteAt(e,t){this[_].delete(this.$wireIndex(e),t)}$setAt(e,t,r){r===R.ADD&&this.items[e]!==void 0?this.items.splice(e,0,t):r===R.DELETE_AND_MOVE?(this.items.splice(e,1),this.items[e]=t):(e>this.items.length&&(this._needsCompaction=!0),this.items[e]=t)}clear(){let e=this[Ce];if(e.items.length===0)return;let t=e[_];t.forEachChild((r,s)=>{t.root?.remove(r)}),t.discard(),t.operation(R.CLEAR),e.items.length=0,e.tmpItems.length=0}[Et](){let e=this[Ce]??this,t=e[_];if(t.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed ArraySchema (pooling not supported).");let r=e.items;for(let s=0;s<r.length;s++)r[s]?.[Et]?.();e.items.length=0,e.tmpItems.length=0,e.deletedIndexes.length=0,t.recycle(),e[$]=void 0}concat(...e){return new it(...this.items.concat(...e))}join(e){return this.items.join(e)}reverse(){let e=this[Ce],t=e[_];if(t.has()||e.deletedIndexes.length>0){let r=e.items.slice().reverse();return this.clear(),this.push(...r),this}return t.operation(R.REVERSE),e.items.reverse(),e.tmpItems.reverse(),e.$reindexChildren(0),this}shift(){let e=this[Ce],t=e.items;if(t.length===0)return;let r=e[_],s=e.deletedIndexes,i=0;for(;s[i]===!0;)i++;let o=e.$isUnsentAdd(i);return r.delete(i,R.DELETE),o?e.$cancelAdd(i):s[i]=!0,t.shift()}slice(e,t){let r=new it;return r.push(...this.items.slice(e,t)),r}sort(e=Qg){let t=this[Ce];t.isMovingItems=!0;let r=t[_];return t.items.sort(e).forEach((i,o)=>r.change(o,R.REPLACE)),t.tmpItems.sort(e),t.$reindexChildren(0),t.isMovingItems=!1,this}splice(e,t,...r){let s=this[Ce],i=s[_],o=s.items,a=s.tmpItems,c=s.deletedIndexes,u=o.length,d=a.length,h=r.length,m=[];for(let p=0;p<d;p++)c[p]!==!0&&m.push(p);let g;if(u>e){t===void 0&&(t=u-e);for(let p=e;p<e+t;p++){let y=m[p],x=s.$isUnsentAdd(y);i.delete(y,R.DELETE),x?(g??(g=[])).push(y):c[y]=!0}}else t=0;if(h>0){let p=m[e]??u,y=Math.min(h,t);for(let k=0;k<y;k++){let I=p+k,L,N=g!==void 0?g.indexOf(I):-1;N!==-1?(g.splice(N,1),L=R.ADD):L=c[I]?R.DELETE_AND_ADD:R.ADD,i.indexedOperation(I,L),a[I]=r[k],c[I]=!1,r[k][_]?.setParent(this,i.root,I)}let x=h-y;if(x>0){let k=p+y;i.insertAt(k,x);for(let I=0;I<x;I++)r[y+I][_]?.setParent(this,i.root,k+I);c.length>0&&c.splice(k,0,...new Array(x).fill(!1)),a.splice(k,0,...r.slice(y)),s.$reindexChildren(k+x)}}if(g!==void 0&&g.length>0){for(let p=g.length-1;p>=0;p--)s.$cancelAdd(g[p],!1);s.$reindexChildren(g[0])}return i.root?.enqueueChangeTree(i),o.splice(e,t,...r)}unshift(...e){let t=this[Ce],r=t[_];r.unshift(e.length);for(let i=0;i<e.length;i++)e[i]?.[_]?.setParent(this,r.root,i);let s=t.deletedIndexes;return s.length>0&&s.unshift(...new Array(e.length).fill(!1)),t.tmpItems.unshift(...e),t.$reindexChildren(e.length),t.items.unshift(...e)}indexOf(e,t){return this.items.indexOf(e,t)}lastIndexOf(e,t=this.length-1){return this.items.lastIndexOf(e,t)}every(e,t){return this.items.every(e,t)}some(e,t){return this.items.some(e,t)}forEach(e,t){return this.items.forEach(e,t)}map(e,t){return this.items.map(e,t)}filter(e,t){return this.items.filter(e,t)}reduce(e,t){return this.items.reduce.apply(this.items,arguments)}reduceRight(e,t){return this.items.reduceRight.apply(this.items,arguments)}find(e,t){return this.items.find(e,t)}findIndex(e,t){return this.items.findIndex(e,t)}fill(e,t,r){throw new Error("ArraySchema#fill() not implemented")}copyWithin(e,t,r){throw new Error("ArraySchema#copyWithin() not implemented")}toString(){return this.items.toString()}toLocaleString(){return this.items.toLocaleString()}[Symbol.iterator](){return this.items[Symbol.iterator]()}static get[Symbol.species](){return it}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}includes(e,t){return this.items.includes(e,t)}flatMap(e,t){throw new Error("ArraySchema#flatMap() is not supported.")}flat(e){throw new Error("ArraySchema#flat() is not supported.")}findLast(){return this.items.findLast.apply(this.items,arguments)}findLastIndex(...e){return this.items.findLastIndex.apply(this.items,arguments)}with(e,t){let r=this.items.slice();return e<0&&(e+=this.length),r[e]=t,new it(...r)}toReversed(){return this.items.slice().reverse()}toSorted(e){return this.items.slice().sort(e)}toSpliced(e,t,...r){let s=this.items.slice();return s.splice.apply(s,arguments),s}shuffle(){return this.move(e=>{let t=this.items.length;for(;t!=0;){let r=Math.floor(Math.random()*t);t--,[this[t],this[r]]=[this[r],this[t]]}})}move(e){return this.isMovingItems=!0,e(this),this.isMovingItems=!1,this}[(Hu=Symbol.unscopables,Te)](e,t=!1){let r=this[Ce]??this;return t||r.deletedIndexes[e]?r.items[e]:r.tmpItems[e]||r.items[e]}[Rt](e){let t=this[Ce]??this;t.items[e]=void 0,t._needsCompaction=!0}[yn](){let e=this.tmpItems;this.tmpItems=this.items.slice(),this.deletedIndexes.length>0&&(this.$reindexChildren(0,e),this.deletedIndexes.length=0)}[Vi](){let e=this[Ce]??this;e._needsCompaction&&(e._needsCompaction=!1,e.items=e.items.filter(t=>t!==void 0))}[wr](e,t,r){let s=this[Ce]??this,i=s.items,o=!1;for(let a=0;a<i.length;a++){let c=i[a];if(e.has(a)){r(c);continue}o=!0,t(c,a),s[Rt](a)}o&&s[Vi]()}toArray(){return this.items.slice(0)}toJSON(){return this.toArray().map(e=>typeof e.toJSON=="function"?e.toJSON():e)}clone(e){let t;return e?(t=new it,t.push(...this.items)):t=new it(...this.map(r=>r[_]?r.clone():r)),t}};l(it,Wu,zg),l(it,zu,Xg),l(it,"COLLECTION_KIND",wt.Array);wn=it;nn("array",{constructor:wn});zi=class{constructor(){l(this,"keyByIndex",new Map);l(this,"indexByKey",Object.create(null));l(this,"nextIndex",0);l(this,"snapshots")}indexOf(e){let t=this.indexByKey[e];return t===void 0?void 0:t}assign(e){let t=this.nextIndex++;return this.indexByKey[e]=t,this.keyByIndex.set(t,e),t}snapshot(e,t){(this.snapshots??(this.snapshots=new Map)).set(e,t)}forgetSnapshot(e){this.snapshots?.delete(e)}snapshotAt(e){return this.snapshots?.get(e)}setIndex(e,t){this.keyByIndex.set(e,t),this.indexByKey[t]=e}keyOf(e){return this.keyByIndex.get(e)}cleanupAfterEncode(){if(this.snapshots!==void 0){for(let[e]of this.snapshots){let t=this.keyByIndex.get(e);t!==void 0&&(delete this.indexByKey[t],this.keyByIndex.delete(e))}this.snapshots.clear()}}reset(){this.indexByKey=Object.create(null),this.keyByIndex.clear(),this.snapshots?.clear(),this.nextIndex=0}},Ot=class Ot{constructor(e){l(this,nd);l(this,td);l(this,"childType");l(this,ed);l(this,"$items",new Map);l(this,"journal",new zi);l(this,"_stream");if(Object.defineProperty(this,_,{value:new En(this),enumerable:!1,writable:!0}),this[X]=void 0,e)if(e instanceof Map||e instanceof Ot)e.forEach((t,r)=>this.set(r,t));else for(let t in e)this.set(t,e[t])}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=tn())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=tn())).priority=e}get $indexes(){return this.journal.keyByIndex}get _collectionIndexes(){return this.journal.indexByKey}static[(nd=_,td=$,ed=X,Zu=Nt,Qu=_t,qn)](e,t,r){if(!r||typeof e[X]=="string")return!0;let s=e[Te](t)??e.journal.snapshotAt(t);return r.isChangeTreeVisible(s[_])}static is(e){return e.map!==void 0}static initializeForDecoder(){let e=Object.create(Ot.prototype);return e.$items=new Map,e.journal=new zi,e[X]=void 0,_r(e),e}[Symbol.iterator](){return this.$items[Symbol.iterator]()}get[Symbol.toStringTag](){return this.$items[Symbol.toStringTag]}static get[Symbol.species](){return Ot}set(e,t){if(t==null)throw new Error(`MapSchema#set('${e}', ${t}): trying to set ${t} value on '${e}'.`);typeof t=="object"&&this[X]&&so(t,this[X],this,e),e=e.toString();let r=this[_],s=t[_]!==void 0,i=this.journal,o=i.indexOf(e),a;if(o!==void 0){a=R.REPLACE;let c=this.$items.get(e);if(c===t)return;s&&(a=R.DELETE_AND_ADD,c!==void 0&&c[_].root?.remove(c[_])),i.snapshotAt(o)!==void 0&&i.forgetSnapshot(o)}else o=i.assign(e),a=R.ADD;return this.$items.set(e,t),a===R.ADD&&r.isStreamCollection?r.root!==void 0&&Zi(this,r.root,o):r.change(o,a),s&&t[_].setParent(this,r.root,o),this}get(e){return this.$items.get(e)}getOrInsert(e,t){return this.$items.has(e)?this.$items.get(e):(this.set(e,t),t)}getOrInsertComputed(e,t){if(this.$items.has(e))return this.$items.get(e);let r=t(e);return this.set(e,r),r}delete(e){if(!this.$items.has(e))return!1;let t=this.journal.indexOf(e),r=this.$items.get(e),s=this[_];if(s.isStreamCollection){let i=s.root,o=!1;return i!==void 0&&(o=eo(this,i,this[$],t)),r?.[_]!==void 0&&i?.remove(r[_]),this.$items.delete(e),o||this.journal.snapshot(t,r),!0}return this.journal.snapshot(t,r),s.delete(t),this.$items.delete(e)}clear(){let e=this[_];e.discard(),e.forEachChild((t,r)=>{e.root?.remove(t)}),this.journal.reset(),this.$items.clear(),e.operation(R.CLEAR)}[Et](){let e=this[_];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed MapSchema (pooling not supported).");this.$items.forEach(t=>t?.[Et]?.()),this.$items.clear(),this.journal.reset(),e.recycle(),this[$]=void 0}has(e){return this.$items.has(e)}forEach(e){this.$items.forEach(e)}entries(){return this.$items.entries()}keys(){return this.$items.keys()}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[_].pause()}resumeTracking(){this[_].resume()}untracked(e){return this[_].untracked(e)}get isTrackingPaused(){return this[_].paused}setIndex(e,t){this.journal.setIndex(e,t)}getIndex(e){return this.journal.keyOf(e)}[Te](e){let t=this.journal.keyOf(e);return t!==void 0?this.$items.get(t):void 0}[Rt](e){let t=this.journal.keyOf(e);t!==void 0&&(this.$items.delete(t),this.journal.keyByIndex.delete(e))}[wr](e,t,r){let s=null;if(this.$items.forEach((i,o)=>{if(e.has(o)){r(i);return}(s??(s=new Set)).add(o),t(i,o)}),s!==null){s.forEach(o=>{this.$items.delete(o),delete this.journal.indexByKey[o]});let i=[];this.journal.keyByIndex.forEach((o,a)=>{s.has(o)&&i.push(a)});for(let o=0;o<i.length;o++)this.journal.keyByIndex.delete(i[o])}}[yn](){this.journal.cleanupAfterEncode()}_dropView(e){to(this,e)}_unregister(){}toJSON(){return Object.fromEntries(Array.from(this,([t,r])=>[t,typeof r.toJSON=="function"?r.toJSON():r]))}clone(e){let t;return e?t=Object.assign(new Ot,this):(t=new Ot,this.forEach((r,s)=>{r[_]?t.set(s,r.clone()):t.set(s,r)})),t}};l(Ot,Zu,Hg),l(Ot,Qu,ro),l(Ot,"COLLECTION_KIND",wt.Map);_n=Ot;nn("map",{constructor:_n});mn=class mn{constructor(e){l(this,ad);l(this,od);l(this,id);l(this,"$items",new Map);l(this,"deletedItems",{});l(this,"$refId",0);l(this,"_stream");Object.defineProperty(this,_,{value:new En(this),enumerable:!1,writable:!0}),this[X]=void 0,e&&e.forEach(t=>this.add(t))}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=tn())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=tn())).priority=e}static[(ad=_,od=$,id=X,sd=Nt,rd=_t,qn)](e,t,r){return!r||typeof e[X]=="string"||r.isChangeTreeVisible((e[Te](t)??e.deletedItems[t])[_])}static is(e){return e.collection!==void 0}static initializeForDecoder(){let e=Object.create(mn.prototype);return e.$items=new Map,e.deletedItems={},e.$refId=0,e[X]=void 0,_r(e),e}add(e){let t=this.$refId++,r=this[_];return this.$items.set(t,e),r.isStreamCollection?r.root!==void 0&&Zi(this,r.root,t):r.change(t),e[_]!==void 0&&e[_].setParent(this,r.root,t),t}at(e){let t=Array.from(this.$items.keys())[e];return this.$items.get(t)}entries(){return this.$items.entries()}delete(e){let t=this.$items.entries(),r,s;for(;(s=t.next())&&!s.done;)if(e===s.value[1]){r=s.value[0];break}if(r===void 0)return!1;let i=this[_];if(i.isStreamCollection){let o=i.root,a=this.$items.get(r);return o!==void 0&&eo(this,o,this[$],r),a?.[_]!==void 0&&o?.remove(a[_]),this.deletedItems[r]=a,this.$items.delete(r)}return this.deletedItems[r]=i.delete(r),this.$items.delete(r)}clear(){let e=this[_];e.discard(),e.forEachChild((t,r)=>{e.root?.remove(t)}),this.$items.clear(),e.operation(R.CLEAR)}[Et](){let e=this[_];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed CollectionSchema (pooling not supported).");this.$items.forEach(t=>t?.[Et]?.()),this.$items.clear(),this.deletedItems={},this.$refId=0,e.recycle(),this[$]=void 0}has(e){return Array.from(this.$items.values()).some(t=>t===e)}forEach(e){this.$items.forEach((t,r,s)=>e(t,r,this))}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[_].pause()}resumeTracking(){this[_].resume()}untracked(e){return this[_].untracked(e)}get isTrackingPaused(){return this[_].paused}[Symbol.iterator](){return this.$items.values()}setIndex(e,t){}getIndex(e){return e}[Te](e){return this.$items.get(e)}[Rt](e){this.$items.delete(e)}[wr](e,t,r){let s=null;if(this.$items.forEach((i,o)=>{if(e.has(o)){r(i);return}(s??(s=[])).push(o),t(i,o)}),s!==null)for(let i=0;i<s.length;i++)this[Rt](s[i])}[yn](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){to(this,e)}_unregister(){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach((t,r)=>{e.push(typeof t.toJSON=="function"?t.toJSON():t)}),e}clone(e){let t;return e?t=Object.assign(new mn,this):(t=new mn,this.forEach(r=>{r[_]?t.add(r.clone()):t.add(r)})),t}};l(mn,sd,mc),l(mn,rd,ro),l(mn,"COLLECTION_KIND",wt.Collection);ps=mn;nn("collection",{constructor:ps});gn=class gn{constructor(e){l(this,fd);l(this,dd);l(this,ud);l(this,"$items",new Map);l(this,"deletedItems",{});l(this,"$refId",0);l(this,"_stream");Object.defineProperty(this,_,{value:new En(this),enumerable:!1,writable:!0}),this[X]=void 0,e&&e.forEach(t=>this.add(t))}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=tn())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=tn())).priority=e}static[(fd=_,dd=$,ud=X,ld=Nt,cd=_t,qn)](e,t,r){return!r||typeof e[X]=="string"||r.isVisible((e[Te](t)??e.deletedItems[t])[_])}static is(e){return e.set!==void 0}static initializeForDecoder(){let e=Object.create(gn.prototype);return e.$items=new Map,e.deletedItems={},e.$refId=0,e[X]=void 0,_r(e),e}add(e){if(this.has(e))return!1;let t=this.$refId++,r=this[_];return this.$items.set(t,e),r.isStreamCollection?r.root!==void 0&&Zi(this,r.root,t):r.change(t,R.ADD),e[_]!==void 0&&e[_].setParent(this,r.root,t),t}entries(){return this.$items.entries()}delete(e){let t=this.$items.entries(),r,s;for(;(s=t.next())&&!s.done;)if(e===s.value[1]){r=s.value[0];break}if(r===void 0)return!1;let i=this[_];if(i.isStreamCollection){let o=i.root,a=this.$items.get(r);return o!==void 0&&eo(this,o,this[$],r),a?.[_]!==void 0&&o?.remove(a[_]),this.deletedItems[r]=a,this.$items.delete(r)}return this.deletedItems[r]=i.delete(r),this.$items.delete(r)}clear(){let e=this[_];e.discard(),this.$items.clear(),e.operation(R.CLEAR)}[Et](){let e=this[_];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed SetSchema (pooling not supported).");this.$items.forEach(t=>t?.[Et]?.()),this.$items.clear(),this.deletedItems={},this.$refId=0,e.recycle(),this[$]=void 0}has(e){let t=this.$items.values(),r=!1,s;for(;(s=t.next())&&!s.done;)if(e===s.value){r=!0;break}return r}forEach(e){this.$items.forEach((t,r,s)=>e(t,r,this))}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[_].pause()}resumeTracking(){this[_].resume()}untracked(e){return this[_].untracked(e)}get isTrackingPaused(){return this[_].paused}[Symbol.iterator](){return this.$items.values()}setIndex(e,t){}getIndex(e){return e}[Te](e){return this.$items.get(e)}[Rt](e){this.$items.delete(e)}[wr](e,t,r){let s=null;if(this.$items.forEach((i,o)=>{if(e.has(o)){r(i);return}(s??(s=[])).push(o),t(i,o)}),s!==null)for(let i=0;i<s.length;i++)this[Rt](s[i])}[yn](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){to(this,e)}_unregister(){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach((t,r)=>{e.push(typeof t.toJSON=="function"?t.toJSON():t)}),e}clone(e){let t;return e?t=Object.assign(new gn,this):(t=new gn,this.forEach(r=>{r[_]?t.add(r.clone()):t.add(r)})),t}};l(gn,ld,mc),l(gn,cd,ro),l(gn,"COLLECTION_KIND",wt.Set);ms=gn;nn("set",{constructor:ms});Zt=class Zt{constructor(){l(this,yd);l(this,gd);l(this,md);l(this,"$items",new Map);l(this,"$nextPosition",0);l(this,"_itemIndex",new Map);l(this,"_stream");Object.defineProperty(this,_,{value:new En(this),enumerable:!1,writable:!0}),this[X]=void 0}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=tn())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=tn())).priority=e}static[(yd=_,gd=$,md=X,pd=Nt,hd=_t,qn)](e,t,r){if(!r)return!0;let s=e[Te](t);return s===void 0?!1:r.isVisible(s[_])}static is(e){return e&&e.stream!==void 0}static initializeForDecoder(){let e=Object.create(Zt.prototype);return e.$items=new Map,e.$nextPosition=0,e._itemIndex=new Map,e[X]=void 0,_r(e),e}add(e){if(this._itemIndex.has(e))return-1;let t=this.$nextPosition++;this.$items.set(t,e),this._itemIndex.set(e,t);let s=this[_].root;return e[_]!==void 0&&e[_].setParent(this,s,t),s!==void 0&&Zi(this,s,t),t}remove(e){let t=this._itemIndex.get(e);if(t===void 0)return!1;this._itemIndex.delete(e),this.$items.delete(t);let r=this[_].root;return r!==void 0&&(eo(this,r,this[$],t),e[_]!==void 0&&r.remove(e[_])),!0}has(e){return this._itemIndex.has(e)}clear(){let e=this[_].root;if(e!==void 0){ug(this,e,this[$]);for(let t of this.$items.values())t[_]!==void 0&&e.remove(t[_])}this.$items.clear(),this._itemIndex.clear()}forEach(e){for(let[t,r]of this.$items)e(r,t,this)}values(){return this.$items.values()}entries(){return this.$items.entries()}[Symbol.iterator](){return this.$items.values()}get size(){return this.$items.size}get length(){return this.$items.size}setIndex(e,t){}getIndex(e){return e}[Te](e){return this.$items.get(e)}[Rt](e){let t=this.$items.get(e);t!==void 0&&(this._itemIndex.delete(t),this.$items.delete(e))}[wr](){}[yn](){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach(t=>{e.push(typeof t?.toJSON=="function"?t.toJSON():t)}),e}clone(e){if(e)return Object.assign(new Zt,this);let t=new Zt;return t.maxPerTick=this.maxPerTick,this.forEach(r=>{t.add(typeof r?.clone=="function"?r.clone():r)}),t}_dropView(e){to(this,e)}_unregister(){}};l(Zt,"$isStream",!0),l(Zt,pd,mc),l(Zt,hd,ro),l(Zt,"COLLECTION_KIND",wt.Stream);Wi=Zt;nn("stream",{constructor:Wi});bd=Sd;Bt=class{constructor(e){l(this,bd,!0);l(this,"_type");l(this,"_default");l(this,"_hasDefault",!1);l(this,"_view");l(this,"_unreliable",!1);l(this,"_patchOnly",!1);l(this,"_deprecated",!1);l(this,"_deprecatedThrows",!0);l(this,"_fullStateOnly",!1);l(this,"_stream",!1);l(this,"_optional",!1);l(this,"_noSync",!1);l(this,"_streamPriority");this._type=e}default(e){return this._default=e,this._hasDefault=!0,this}view(e){return this._view=e??-1,this}unreliable(){return this._unreliable=!0,this}patchOnly(){return this._patchOnly=!0,this}fullStateOnly(){return this._fullStateOnly=!0,this}noSync(){return this._noSync=!0,this}stream(){let e=this._type;if(e&&typeof e=="object"&&e.array!==void 0)throw new Error(jd);return this._stream=!0,this}priority(e){return this._streamPriority=e,this}deprecated(e=!0){return this._deprecated=!0,this._deprecatedThrows=e,this}optional(){return this._optional=!0,this}toDefinition(){return{type:this._type,default:this._default,hasDefault:this._hasDefault,view:this._view,unreliable:this._unreliable,patchOnly:this._patchOnly,deprecated:this._deprecated,deprecatedThrows:this._deprecatedThrows,fullStateOnly:this._fullStateOnly,stream:this._stream,optional:this._optional,noSync:this._noSync,streamPriority:this._streamPriority}}};Zg=(n=>new Bt({array:_s(n)})),ey=(n=>new Bt({map:_s(n)})),ty=(n=>new Bt({set:_s(n)})),ny=(n=>new Bt({collection:_s(n)})),ry=(n=>{let e=new Bt({stream:_s(n)});return e._stream=!0,e}),sy=(n=>new Bt(n));Je=Object.freeze({string:Ge("string"),number:Ge("number"),boolean:Ge("boolean"),int8:Ge("int8"),uint8:Ge("uint8"),int16:Ge("int16"),uint16:Ge("uint16"),int32:Ge("int32"),uint32:Ge("uint32"),int64:Ge("int64"),uint64:Ge("uint64"),float32:Ge("float32"),float64:Ge("float64"),bigint64:Ge("bigint64"),biguint64:Ge("biguint64"),ref:sy,array:Zg,map:ey,set:ty,collection:ny,stream:ry,quantized:Vu,angle:n=>Vu({min:0,max:Math.PI*2,mode:"wrap",bits:n?.bits??16})}),io=-1;cy={number:"number",int8:"number",uint8:"number",int16:"number",uint16:"number",int32:"number",uint32:"number",int64:"number",uint64:"number",float32:"number",float64:"number",bigint64:"bigint",biguint64:"bigint",string:"string",boolean:"boolean"};yt=class yt{constructor(e){l(this,_d);l(this,wd);yt.initialize(this),e&&yt.assignProps(this,e)}static initialize(e){Object.defineProperty(e,_,{value:new En(e),enumerable:!1,writable:!0}),e[Ue]=[]}static initializeForDecoder(){let e=Object.create(this.prototype);return _r(e),e[Ue]=[],e}static reset(e){let t=e?.[_];if(t===void 0||typeof t.recycle!="function")throw new Error("@colyseus/schema: Schema.reset() requires a tracked (encoder-side) instance.");if(t.extraParents!==void 0)throw new Error(`@colyseus/schema: cannot reset a shared instance (${e.constructor.name}) with multiple parents.`);e[Et]()}[(Rd=Nt,Ed=_t,_d=$,wd=Ue,Et)](){let t=this.constructor[Symbol.metadata]?.[bn]??[],r=this[Ue];for(let s=0;s<t.length;s++)r[t[s]]?.[Et]?.();this[_].recycle(),this[$]=void 0}static is(e){let t=e[Symbol.metadata];return typeof t=="object"&&t!==null}static isSchema(e){return typeof e?.assign=="function"}static[Dt](e,t,r=R.ADD){e.change(t,r)}static[qn](e,t,r){let i=e.constructor[Symbol.metadata][t]?.tag;return r===void 0?i===void 0:i===void 0?!0:i===io?r.isChangeTreeVisible(e[_]):r.hasTagOnTree(e[_],i)}assign(e){return yt.assignProps(this,e),this}static assignProps(e,t){let r=e.constructor[Symbol.metadata];if(r&&r[Fe]!==void 0)for(let i=0;i<=r[Fe];i++){let o=r[i];if(!o)continue;let a=t[o.name];a!==void 0&&(e[o.name]=a)}let s=Object.keys(t);for(let i=0;i<s.length;i++){let o=s[i];r&&r[o]!==void 0||(e[o]=t[o])}}restore(e){let t=this.constructor[Symbol.metadata];for(let r in t){let s=t[r],i=s.name,o=s.type,a=e[i];if(a!=null){if(typeof o=="string")this[i]=a;else if(yt.is(o)){let c=new o;c.restore(a),this[i]=c}else if(typeof o=="object"){let c=Object.keys(o)[0],u=o[c];if(c==="map"){let d=this[i];for(let h in a)if(yt.is(u)){let m=new u;m.restore(a[h]),d.set(h,m)}else d.set(h,a[h])}else if(c==="array"){let d=this[i];for(let h=0;h<a.length;h++)if(yt.is(u)){let m=new u;m.restore(a[h]),d.push(m)}else d.push(a[h])}}}}return this}setDirty(e,t){let r=this.constructor[Symbol.metadata];this[_].change(r[r[e]].index,t)}pauseTracking(){this[_].pause()}resumeTracking(){this[_].resume()}untracked(e){return this[_].untracked(e)}get isTrackingPaused(){return this[_].paused}clone(){let e=Object.create(this.constructor.prototype);yt.initialize(e);let t=this.constructor[Symbol.metadata];for(let r in t){let s=t[r].name;typeof this[s]=="object"&&typeof this[s]?.clone=="function"?e[s]=this[s].clone():e[s]=this[s]}return e}toJSON(){let e={},t=this.constructor[Symbol.metadata];for(let r in t){let s=t[r],i=s.name;!s.deprecated&&this[i]!==null&&typeof this[i]<"u"&&(e[i]=typeof this[i].toJSON=="function"?this[i].toJSON():this[i])}return e}discardAllChanges(){this[_].discardAll()}[Te](e){let t=this.constructor[Symbol.metadata];return this[t[e].name]}[Rt](e){let t=this.constructor[Symbol.metadata];this[t[e].name]=void 0}static debugRefIds(e,t=!1,r=0,s,i=""){let o=t?` - ${JSON.stringify(e.toJSON())}`:"",a=e[_],c=e[$],u=s?s.root:a.root,d=u?.refCount?.[c]>1?` [\xD7${u.refCount[c]}]`:"",h=`${gy(r)}${i}${e.constructor.name} (refId: ${c})${d}${o}
|
|
3
|
+
hasFilters: ${this.hasFilters}`}};l(Pt,"inheritedTypes",new WeakMap),l(Pt,"cachedContexts",new WeakMap);jn=Pt,zu=63;Dg=[bn,Bn,ps,Wi,yr,at,Qt];le={addField(n,e,t,r,s){if(e>=zu)throw new Error(`Can't define field '${t}'.
|
|
4
|
+
Schema instances may only have up to ${zu} fields.`);n[e]=Object.assign(n[e]||{},{type:wr(r),index:e,name:t}),Object.defineProperty(n,ot,{value:n[ot]||{},enumerable:!1,configurable:!0}),s?n[ot][t]=s:n[ot][t]={value:void 0,writable:!0,enumerable:!0,configurable:!0},Object.defineProperty(n,Ue,{value:e,enumerable:!1,configurable:!0}),Object.defineProperty(n,t,{value:e,enumerable:!1,configurable:!0}),typeof n[e].type!="string"&&!Vn(n[e].type)&&(n[bn]===void 0&&Object.defineProperty(n,bn,{value:[],enumerable:!1,configurable:!0}),n[bn].push(e));let i=n[e].type;if(i&&typeof i=="object"&&i.stream!==void 0){if(i.array!==void 0)throw new Error(Zd);n[e].stream=!0,n[at]||Object.defineProperty(n,at,{value:[],enumerable:!1,configurable:!0,writable:!0}),n[at].includes(e)||n[at].push(e);let o=r?.priority;typeof o=="function"&&le.setStreamPriority(n,t,o)}},setTag(n,e,t){let r=n[e],s=n[r];if(s.tag=t,n[wt]||(Object.defineProperty(n,wt,{value:[],enumerable:!1,configurable:!0}),Object.defineProperty(n,Xt,{value:{},enumerable:!1,configurable:!0})),n[wt].push(r),t<0)n[Xt][t]||(n[Xt][t]=[]),n[Xt][t].push(r);else for(let i=t;i>0;i&=i-1){let o=i&-i;n[Xt][o]||(n[Xt][o]=[]),n[Xt][o].push(r)}},setUnreliable(n,e){let t=n[e];if(typeof n[t].type!="string")throw new Error(`@unreliable cannot be applied to ref-type field "${e}". For ref-type fields, mark each primitive sub-field with @unreliable instead. See README "Limitations and best practices".`);n[t].unreliable=!0,n[Bn]||Object.defineProperty(n,Bn,{value:[],enumerable:!1,configurable:!0,writable:!0}),n[Bn].push(t)},setPatchOnly(n,e){let t=n[e];if(n[t].fullStateOnly)throw new Error(`field "${e}" cannot be both patchOnly and fullStateOnly \u2014 those are the only two delivery channels, so the field would never reach a client.`);n[t].patchOnly=!0,Vi(n,ps,t),Vi(n,Wi,t)},setDeprecated(n,e){let t=n[e];n[t].deprecated=!0,Vi(n,Wi,t),Object.defineProperty(n,t,{value:n[t],enumerable:!1,configurable:!0})},setFullStateOnly(n,e){let t=n[e];if(n[t].patchOnly)throw new Error(`field "${e}" cannot be both patchOnly and fullStateOnly \u2014 those are the only two delivery channels, so the field would never reach a client.`);n[t].fullStateOnly=!0,Vi(n,yr,t)},setStream(n,e){let t=n[e];n[t].stream=!0,n[at]||Object.defineProperty(n,at,{value:[],enumerable:!1,configurable:!0,writable:!0}),n[at].push(t)},setStreamPriority(n,e,t){let r=n[e];n[$i]||Object.defineProperty(n,$i,{value:{},enumerable:!1,configurable:!0,writable:!0}),n[$i][r]=t},getStreamPriority(n,e){return n?.[$i]?.[e]},defineField(n,e,t,r,s){let i=wr(s),{complexTypeKlass:o,childType:a}=Pg(i);le.addField(e,t,r,i,vy(r,t,a,o)),e[ot][r]&&Object.defineProperty(n.prototype,r,e[ot][r]),(typeof i=="string"||Vn(i))&&(e[Qt]||Object.defineProperty(e,Qt,{value:[],enumerable:!1,configurable:!0,writable:!0}),e[Qt][t]=typeof i=="string"?Q[i]:Ig(i.quantized))},setFields(n,e){let t=n.prototype.constructor;jn.register(t);let r=Object.getPrototypeOf(t),s=r&&r[Symbol.metadata],i=le.initialize(t);t[Nt]||(t[Nt]=Ee[Nt]),t[Lt]||(t[Lt]=Ee[Lt]),t[Et]||(t[Et]=Ee[Et]),t.prototype.toJSON||(t.prototype.toJSON=Ee.prototype.toJSON);let o=i[Ue]??(s&&s[Ue])??-1;o++,i[Qt]||Object.defineProperty(i,Qt,{value:s?.[Qt]?[...s[Qt]]:[],enumerable:!1,configurable:!0,writable:!0});for(let a in e){if(i[a]!==void 0)throw new Error(`@colyseus/schema: Duplicate '${a}' definition on '${t.name||"(anonymous)"}'.`);le.defineField(t,i,o,a,e[a]),o++}return n},isDeprecated(n,e){return n[e].deprecated===!0},initialize(n){let e=Object.getPrototypeOf(n),t=e[Symbol.metadata],r=n[Symbol.metadata]??Object.create(null);if(e!==Ee&&r===t&&(r=Object.create(null),t)){Object.setPrototypeOf(r,t),Object.defineProperty(r,Ue,{value:t[Ue],enumerable:!1,configurable:!0,writable:!0}),t[wt]!==void 0&&(Object.defineProperty(r,wt,{value:[...t[wt]],enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(r,Xt,{value:{...t[Xt]},enumerable:!1,configurable:!0,writable:!0}));for(let s of Dg){let i=t[s];i!==void 0&&Object.defineProperty(r,s,{value:[...i],enumerable:!1,configurable:!0,writable:!0})}Object.defineProperty(r,ot,{value:{...t[ot]},enumerable:!1,configurable:!0,writable:!0})}return Object.defineProperty(n,Symbol.metadata,{value:r,writable:!1,configurable:!0}),r},isValidInstance(n){return n.constructor[Symbol.metadata]&&Object.prototype.hasOwnProperty.call(n.constructor[Symbol.metadata],Ue)},getFields(n){let e=n[Symbol.metadata],t={};for(let r=0;r<=e[Ue];r++)t[e[r].name]=e[r].type;return t},hasViewTagAtIndex(n,e){return n?.[wt]?.includes(e)},hasUnreliableAtIndex(n,e){return n?.[Bn]?.includes(e)},hasPatchOnlyAtIndex(n,e){return n?.[ps]?.includes(e)},hasFullStateOnlyAtIndex(n,e){return n?.[yr]?.includes(e)},hasStreamAtIndex(n,e){return n?.[at]?.includes(e)}},nf=(n,e,t)=>n(e,t),sc=class{constructor(e){l(this,"dirtyLow",0);l(this,"dirtyHigh",0);l(this,"ops");this.ops=new Uint8Array(Math.max(e+1,1))}record(e,t){let r=this.ops[e];r===0?this.ops[e]=t:r===R.DELETE?this.ops[e]=R.DELETE_AND_ADD:r===R.ADD&&t===R.DELETE_AND_ADD&&(this.ops[e]=R.DELETE_AND_ADD),e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}recordDelete(e,t){this.ops[e]=t,e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}recordRaw(e,t){this.record(e,t)}operationAt(e){let t=this.ops[e];return t===0?void 0:t}setOperationAt(e,t){this.ops[e]=t}forEach(e){this.forEachWithCtx(e,nf)}forEachWithCtx(e,t){let r=this.dirtyLow,s=this.dirtyHigh,i=this.ops;for(;r!==0;){let o=r&-r,a=31-Math.clz32(o);r^=o,t(e,a,i[a])}for(;s!==0;){let o=s&-s,a=31-Math.clz32(o)+32;s^=o,t(e,a,i[a])}}size(){return Yi(this.dirtyLow)+Yi(this.dirtyHigh)}has(){return(this.dirtyLow|this.dirtyHigh)!==0}reset(){this.dirtyLow=0,this.dirtyHigh=0,this.ops.fill(0)}},ic=class{constructor(){l(this,"dirty",new Map);l(this,"pureOps",[])}record(e,t){let r=this.dirty.get(e);r===void 0?this.dirty.set(e,t):r===R.DELETE?this.dirty.set(e,R.DELETE_AND_ADD):r===R.ADD&&t===R.DELETE_AND_ADD&&this.dirty.set(e,R.DELETE_AND_ADD)}recordDelete(e,t){this.dirty.set(e,t)}recordRaw(e,t){this.dirty.set(e,t)}recordPure(e){this.pureOps.push([this.dirty.size,e])}operationAt(e){return this.dirty.get(e)}setOperationAt(e,t){this.dirty.has(e)&&this.dirty.set(e,t)}forEach(e){this.forEachWithCtx(e,nf)}forEachWithCtx(e,t){let r=this.pureOps;if(r.length>0){let s=0,i=0;for(let[o,a]of this.dirty){for(;s<r.length&&r[s][0]<=i;){let c=r[s++][1];t(e,-c,c)}t(e,o,a),i++}for(;s<r.length;){let o=r[s++][1];t(e,-o,o)}}else for(let[s,i]of this.dirty)t(e,s,i)}size(){return this.dirty.size+this.pureOps.length}has(){return this.dirty.size>0||this.pureOps.length>0}reset(){this.dirty.clear(),this.pureOps.length=0}shift(e){let t=new Map;for(let[r,s]of this.dirty)t.set(r+e,s);this.dirty=t}};sf=(n,e)=>{n.isFieldUnreliable(e)?n.ensureUnreliableRecorder().record(e,R.ADD):n.record(e,R.ADD)},Hg=(n,e)=>n(e);cf=1,Ji=2,Ki=4,zg=cf|Ji|Ki;Wg=(n,e,t)=>{gc(e)};Ju=[],Hi=0;ny=(n,e,t)=>n(e,t);Qa=1,Za=2,ds=4,ec=8,hs=16,gr=32,qi=64,Gi=128,ms=256,yc=512,ry=hs|gr,En=class{constructor(e,t=e){l(this,"ref");l(this,"refTarget");l(this,"metadata");l(this,"encDescriptor");l(this,"root");l(this,"parentRef");l(this,"_parentIndex");l(this,"extraParents");l(this,"flags",ds);l(this,"_fullSyncGen",0);l(this,"_isSchema",!1);l(this,"dirtyLow",0);l(this,"dirtyHigh",0);l(this,"opsLow",0);l(this,"opsHigh",0);l(this,"ops");l(this,"collDirty");l(this,"collPureOps");l(this,"unreliableRecorder");l(this,"paused",!1);l(this,"changesNode");l(this,"unreliableChangesNode");l(this,"visibleViews");l(this,"tagViews");l(this,"subscribedViews");this.ref=e,this.refTarget=t;let r=pc(e);this.encDescriptor=r,this.metadata=r.metadata;let s=r.isSchema;if(this._isSchema=s,this.ops=void 0,this.collDirty=void 0,this.collPureOps=void 0,s){let i=this.metadata?.[Ue]??0;i>7&&(this.ops=new Uint8Array(i+1))}else this.collDirty=new Map}get isArray(){return this.refTarget!==this.ref}get isFiltered(){return(this.flags&Qa)!==0}set isFiltered(e){this.flags=e?this.flags|Qa:this.flags&~Qa}get isVisibilitySharedWithParent(){return(this.flags&Za)!==0}set isVisibilitySharedWithParent(e){this.flags=e?this.flags|Za:this.flags&~Za}get isNew(){return(this.flags&ds)!==0}set isNew(e){this.flags=e?this.flags|ds:this.flags&~ds}get isUnreliable(){return(this.flags&ec)!==0}set isUnreliable(e){this.flags=e?this.flags|ec:this.flags&~ec}get isPatchOnly(){return(this.flags&hs)!==0}set isPatchOnly(e){this.flags=e?this.flags|hs:this.flags&~hs}get isFullStateOnly(){return(this.flags&gr)!==0}set isFullStateOnly(e){this.flags=e?this.flags|gr:this.flags&~gr}get isStreamCollection(){return(this.flags&qi)!==0}set isStreamCollection(e){this.flags=e?this.flags|qi:this.flags&~qi}get needsRestage(){return(this.flags&Gi)!==0}set needsRestage(e){this.flags=e?this.flags|Gi:this.flags&~Gi}get hasFilteredFields(){return this.isFiltered||this.encDescriptor.hasAnyView}ensureUnreliableRecorder(){return this.unreliableRecorder===void 0&&(this.unreliableRecorder=this._isSchema?new sc(this.metadata?.[Ue]??0):new ic),this.unreliableRecorder}isFieldUnreliable(e){let t=this.encDescriptor;return t.hasAnyUnreliable?e<32?(t.unreliableBitmask&1<<e)!==0:le.hasUnreliableAtIndex(this.metadata,e):!1}isFieldFullStateOnly(e){if(this.isFullStateOnly)return!0;let t=this.encDescriptor;return t.hasAnyFullStateOnly?e<32?(t.fullStateOnlyBitmask&1<<e)!==0:le.hasFullStateOnlyAtIndex(this.metadata,e):!1}isFieldStream(e){let t=this.encDescriptor;return t.hasAnyStream?e<32?(t.streamBitmask&1<<e)!==0:le.hasStreamAtIndex(this.metadata,e):!1}_opAt(e){let t=this.ops;if(t!==void 0)return t[e];let r=(e&3)<<3;return e<4?this.opsLow>>>r&255:this.opsHigh>>>r&255}_opPut(e,t){let r=this.ops;if(r!==void 0){r[e]=t;return}let s=(e&3)<<3,i=~(255<<s);e<4?this.opsLow=this.opsLow&i|t<<s:this.opsHigh=this.opsHigh&i|t<<s}_markDirty(e){e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}record(e,t){if(this._isSchema){let r=this._opAt(e);r===0?this._opPut(e,t):r===R.DELETE?this._opPut(e,R.DELETE_AND_ADD):r===R.ADD&&t===R.DELETE_AND_ADD&&this._opPut(e,R.DELETE_AND_ADD),this._markDirty(e)}else{let r=this.collDirty,s=r.get(e),i;s===void 0?i=t:s===R.DELETE||s===R.ADD&&t===R.DELETE_AND_ADD?i=R.DELETE_AND_ADD:i=s,r.set(e,i)}}recordDelete(e,t){this._isSchema?(this._opPut(e,t),this._markDirty(e)):this.collDirty.set(e,t)}recordRaw(e,t){this._isSchema?(this._opPut(e,t),this._markDirty(e)):this.collDirty.set(e,t)}recordPure(e){if(this._isSchema)throw new Error("ChangeTree (Schema): pure operations are not supported");(this.collPureOps??(this.collPureOps=[])).push([this.collDirty.size,e])}operationAt(e){if(this._isSchema){let t=this._opAt(e);return t===0?void 0:t}return this.collDirty.get(e)}setOperationAt(e,t){if(this._isSchema)this._opPut(e,t);else{let r=this.collDirty;r.has(e)&&r.set(e,t)}}forEach(e){this.forEachWithCtx(e,ny)}forEachWithCtx(e,t){if(this._isSchema){let i=this.dirtyLow,o=this.dirtyHigh,a=this.ops;if(a!==void 0){for(;i!==0;){let c=i&-i,u=31-Math.clz32(c);i^=c,t(e,u,a[u])}for(;o!==0;){let c=o&-o,u=31-Math.clz32(c)+32;o^=c,t(e,u,a[u])}}else{let c=this.opsLow,u=this.opsHigh;for(;i!==0;){let d=i&-i,h=31-Math.clz32(d);i^=d,t(e,h,ty(c,u,h))}}return}let r=this.collDirty,s=this.collPureOps;if(s!==void 0&&s.length>0){let i=0,o=0;for(let[a,c]of r){for(;i<s.length&&s[i][0]<=o;){let u=s[i++][1];t(e,-u,u)}t(e,a,c),o++}for(;i<s.length;){let a=s[i++][1];t(e,-a,a)}}else for(let[i,o]of r)t(e,i,o)}size(){return this._isSchema?Yi(this.dirtyLow)+Yi(this.dirtyHigh):this.collDirty.size+(this.collPureOps?.length??0)}has(){return this._isSchema?(this.dirtyLow|this.dirtyHigh)!==0:this.collDirty.size>0||this.collPureOps!==void 0&&this.collPureOps.length>0}reset(){if(this._isSchema){this.dirtyLow=0,this.dirtyHigh=0,this.ops!==void 0?this.ops.fill(0):(this.opsLow=0,this.opsHigh=0);return}this.collDirty.clear(),this.collPureOps!==void 0&&(this.collPureOps.length=0),this.flags&=~yc}recycle(){if(this.root!==void 0)throw new Error(`@colyseus/schema: cannot recycle an attached ChangeTree (${this.ref?.constructor?.name}). Remove the instance from its parent collection before releasing it to a pool.`);this.reset(),this.unreliableRecorder?.reset(),this.flags=ds|Gi,this._fullSyncGen=0,this.parentRef=void 0,this._parentIndex=void 0,this.extraParents=void 0,this.changesNode=void 0,this.unreliableChangesNode=void 0,this.paused=!1,this.visibleViews=void 0,this.tagViews=void 0,this.subscribedViews=void 0}insertAt(e,t){if(this._isSchema)throw new Error("ChangeTree (Schema): insertAt is not supported");let r=this.collDirty,s=new Map,i=!this.paused&&!this.isFullStateOnly;if(e>0)for(let[o,a]of r)o<e&&s.set(o,a);if(i)for(let o=0;o<t;o++)s.set(e+o,R.ADD);for(let[o,a]of r)o>=e&&s.set(o+t,a);this.collDirty=s,i&&this.root?.enqueueChangeTree(this)}removeAt(e,t){if(this._isSchema)throw new Error("ChangeTree (Schema): removeAt is not supported");let r=this.collDirty,s=e+t,i=!1;for(let a of r.keys())if(a>=s){i=!0;break}if(!i){for(let a=e;a<s;a++)r.delete(a);return}let o=new Map;for(let[a,c]of r)a<e?o.set(a,c):a>=s&&o.set(a-t,c);this.collDirty=o}unshift(e){this.insertAt(0,e)}setRoot(e){Jg(this,e)}setParent(e,t,r){Kg(this,e,t,r)}forEachChild(e){Xg(this,e)}forEachChildWithCtx(e,t){Rs(this,e,t)}forEachLive(e){Gg(this,e)}forEachLiveWithCtx(e,t){mc(this,e,t)}operation(e){this.paused||this.isFullStateOnly||(this.recordPure(e),this.root?.enqueueChangeTree(this))}_routeAndRecord(e,t,r){if(!(this.paused||this.isFieldFullStateOnly(e))){if(this.isFieldUnreliable(e)&&!this.isNew){let s=this.ensureUnreliableRecorder();r?s.recordRaw(e,t):s.record(e,t),this.root?.enqueueUnreliable(this);return}r?this.recordRaw(e,t):this.record(e,t),this.root?.enqueueChangeTree(this)}}change(e,t=R.ADD){this._routeAndRecord(e,t,!1)}indexedOperation(e,t){this._routeAndRecord(e,t,!0)}getChange(e){return this.operationAt(e)}pause(){this.paused=!0}resume(){this.paused=!1}untracked(e){let t=this.paused;this.paused=!0;try{return e()}finally{this.paused=t}}markDirty(e,t=R.ADD){let r=this.paused;this.paused=!1;try{this.change(e,t)}finally{this.paused=r}}getValue(e,t=!1){return this.refTarget[Te](e,t)}delete(e,t){if(e===void 0){try{throw new Error(`@colyseus/schema ${this.ref.constructor.name}: trying to delete non-existing index '${e}'`)}catch(i){console.warn(i)}return}if(this.paused||this.isFieldFullStateOnly(e))return this.getValue(e);let r=this.isFieldUnreliable(e)&&!this.isNew;r?this.ensureUnreliableRecorder().recordDelete(e,t??R.DELETE):this.recordDelete(e,t??R.DELETE);let s=this.getValue(e);return s&&s[_]&&this.root?.remove(s[_]),r?this.root?.enqueueUnreliable(this):this.root?.enqueueChangeTree(this),s}endEncode(){this.reset(),this.changesNode=void 0,this._isSchema||this.refTarget[yn]?.(),this.isNew=!1}endEncodeUnreliable(){this.unreliableRecorder?.reset(),this.unreliableChangesNode=void 0,this._isSchema||this.refTarget[yn]?.()}discard(){this._isSchema||this.refTarget[yn]?.(),this.reset(),this.unreliableRecorder?.reset()}discardAll(){let e=t=>{if(t<0)return;let r=this.getValue(t);r&&r[_]&&r[_].discardAll()};this.forEach(e),this.unreliableRecorder?.forEach(e),this.discard()}get changed(){return this.has()||(this.unreliableRecorder?.has()??!1)}get parent(){return this.parentRef}get parentIndex(){return this._parentIndex}addParent(e,t){Lg(this,e,t)}setParentIndex(e,t){Bg(this,e,t)}removeParent(e=this.parent){return Ug(this,e)}findParent(e){return Fg(this,e)}hasParent(e){return rf(this,e)}indexInParent(e){return $g(this,e)}getAllParents(){return Vg(this)}},oc=class{constructor(e){l(this,"ref");l(this,"root");l(this,"parentRef");l(this,"paused",!1);l(this,"isNew",!1);l(this,"flags",0);this.ref=e}change(){}delete(){}indexedOperation(){}operation(){}setParent(){}addParent(){}setParentIndex(){}removeParent(){return!1}getChange(){return 0}discard(){}discardAll(){}pause(){}resume(){}untracked(e){return e()}markDirty(){}forEachChild(e){let t=this.ref;if(t[X]){if(typeof t[X]!="string")for(let[o,a]of t.entries())a&&e(a[_],t._collectionIndexes?.[o]??o);return}let s=t.constructor?.[Symbol.metadata];if(!s)return;let i=s[bn]??[];for(let o=0;o<i.length;o++){let a=i[o],c=t[s[a].name];c&&e(c[_],a)}}forEachChildWithCtx(e,t){this.forEachChild((r,s)=>t(e,r,s))}forEachLive(){}forEachLiveWithCtx(){}forEach(){}};iy=function(n,e,t,r,s,i,o,a){if(e[i.offset++]=(r|s)&255,s===R.DELETE)return;let c=t.encDescriptor,u=t.ref,d=u[Fe][r]??u[c.names[r]];ao(n,e,c.types[r],d,s,i,c.encoders[r])},oy=function(n,e,t,r,s,i){if(e[i.offset++]=s&255,Q.number(e,r,i),s===R.DELETE)return;let o=t.ref;if((s&R.ADD)===R.ADD){let a=o.$indexes.get(r);Q.string(e,a,i)}ao(n,e,o[X],o[Te](r),s,i)},bc=function(n,e,t,r,s,i){if(e[i.offset++]=s&255,Q.number(e,r,i),s===R.DELETE)return;let o=t.ref;ao(n,e,o[X],o[Te](r),s,i)},ay=function(n,e,t,r,s,i,o,a){let c=t.refTarget,u=c[X],d=typeof u!="string",h=a&&t.isFiltered&&d,m;if(h){let p=c.tmpItems[r];if(!p)return;if(m=p[$],s===R.DELETE)s=R.DELETE_BY_REFID;else if((s&R.ADD)===R.ADD)s=R.ADD_BY_REFID;else if((s&R.MOVE)===R.MOVE)return}else if(s===R.DELETE&&d){let p=c.tmpItems[r];if(!p)return;m=p[$],s=R.DELETE_BY_REFID}else m=r;if(e[i.offset++]=s&255,Q.number(e,m,i),s===R.DELETE||s===R.DELETE_BY_REFID)return;let g=c[Te](r,o);ao(n,e,u,g,s,i)};uf=-1,_t={Map:1,Array:2,Set:3,Collection:4,Stream:5};dy=function(n,e,t,r,s){let i=e[t.offset++],o=r.constructor[Symbol.metadata],a=i>>6<<6,c=i%(a||255),u=o[c];if(u===void 0)return console.warn("@colyseus/schema: field not defined at",{index:c,ref:r.constructor.name,metadata:o}),uf;let d=u.deprecated===!0,h=d?void 0:r[Te](c),m=_c(n,a,r,c,h,u.type,e,t,s);d||(m!=null&&(r[u.name]=m),h!==m&&s?.push({ref:r,refId:n.currentRefId,op:a,field:u.name,value:m,previousValue:h}))},co=function(n,e,t,r,s){let i=r[Ce]??r,o=e[t.offset++];if(o===R.CLEAR){n.removeChildRefs(i,s),i.clear();return}let a=te.number(e,t),c=i[X],u=i.constructor.COLLECTION_KIND,d;(o&R.ADD)===R.ADD?u===_t.Map?(d=te.string(e,t),i.setIndex(a,d)):d=a:d=i.getIndex(a);let h=i[Te](a),m=_c(n,o,r,a,h,c,e,t,s);if(n.resyncVisited!==null&&lf(n,r,o,d,h,m,s),m!=null)switch(u){case _t.Map:i.$items.set(d,m);break;case _t.Array:i.$setAt(a,m,n.resyncVisited!==null&&o===R.ADD?R.REPLACE:o);break;case _t.Set:case _t.Collection:case _t.Stream:i.$items.has(a)||(i.$items.set(a,m),typeof i.$refId=="number"&&a>=i.$refId&&(i.$refId=a+1));break;default:console.warn(`@colyseus/schema: missing COLLECTION_KIND on ${i.constructor?.name} \u2014 item at index ${a} was not stored.`);break}h!==m&&s?.push({ref:r,refId:n.currentRefId,op:o,dynamicIndex:d,value:m,previousValue:h})},fy=function(n,e,t,r,s){let i=r[Ce]??r,o=e[t.offset++],a;if(o===R.CLEAR){n.removeChildRefs(i,s),i.clear();return}else if(o===R.REVERSE){i.items.reverse();return}else if(o===R.DELETE_BY_REFID){let m=te.number(e,t),g=n.root.refs.get(m);if(g===void 0||(n.root.removeRef(m),a=i.findIndex(p=>p===g),a===-1))return;i[xt](a),s?.push({ref:r,refId:n.currentRefId,op:R.DELETE,dynamicIndex:a,value:void 0,previousValue:g});return}else if(o===R.ADD_BY_REFID){let m=te.number(e,t),g=n.root.refs.get(m);g&&(a=i.findIndex(p=>p===g)),(a===-1||a===void 0)&&(a=i.length)}else a=te.number(e,t);let c=i[X],u=a,d=i.items[a],h=_c(n,o,r,a,d,c,e,t,s);n.resyncVisited!==null&&lf(n,r,o,a,d,h,s),h!=null&&h!==d&&i.$setAt(a,h,n.resyncVisited!==null&&o===R.ADD?R.REPLACE:o),d!==h&&s?.push({ref:r,refId:n.currentRefId,op:o,dynamicIndex:u,value:h,previousValue:d})},gs=class extends Error{};hy=(n,e)=>{let t=n.toString(),r=e.toString();return t<r?-1:t>r?1:0},Xu={get:(n,e)=>typeof e!="symbol"&&!isNaN(e)?n.items[e]:Reflect.get(n,e),set:(n,e,t)=>{if(typeof e!="symbol"&&!isNaN(e)){if(t==null)n.$deleteAt(e);else{let r;if(t[_]){lo(t,n[X],n,e);let s=n.items[e];n.isMovingItems?(r=n.$wireIndex(Number(e)),s!==void 0?t[_].isNew?n[_].indexedOperation(r,R.MOVE_AND_ADD):(n[_].getChange(r)&R.DELETE)===R.DELETE?n[_].indexedOperation(r,R.DELETE_AND_MOVE):n[_].indexedOperation(r,R.MOVE):t[_].isNew&&n[_].indexedOperation(r,R.ADD),t[_].setParent(n,n[_].root,r)):r=n.$changeAt(Number(e),t),s!==void 0&&s[_].root?.remove(s[_])}else r=n.$changeAt(Number(e),t);n.items[e]=t,r!==void 0&&(n.tmpItems[r]=t)}return!0}return Reflect.set(n,e,t)},deleteProperty:(n,e)=>(typeof e=="number"?n.$deleteAt(e):delete n[e],!0),has:(n,e)=>typeof e!="symbol"&&!isNaN(Number(e))?Reflect.has(n.items,e):Reflect.has(n,e)},it=class it{constructor(...e){l(this,cd);l(this,ad);l(this,od);l(this,id);l(this,"items",[]);l(this,"tmpItems",[]);l(this,"deletedIndexes",[]);l(this,"isMovingItems",!1);l(this,"_needsCompaction",!1);l(this,nd);this[X]=void 0,this[Ce]=this;let t=new Proxy(this,Xu);return Object.defineProperty(this,_,{value:new En(t,this),enumerable:!1,writable:!0}),e.length>0&&this.push(...e),t}static[(cd=_,ad=$,od=Ce,id=X,sd=Lt,rd=Et,Hn)](e,t,r){if(!r)return!0;let s=e[Ce]??e;return typeof s[X]=="string"||r.isChangeTreeVisible(s.tmpItems[t]?.[_])}static is(e){return Array.isArray(e)||e.array!==void 0}static from(e){return new it(...Array.from(e))}static initializeForDecoder(){let e=Object.create(it.prototype);e.items=[],e.isMovingItems=!1,e._needsCompaction=!1,e[X]=void 0,e[Ce]=e;let t=new Proxy(e,Xu);return Er(e,t),t}set length(e){e===0?this.clear():e<this.items.length?this.splice(e,this.length-e):console.warn("ArraySchema: can't set .length to a higher value than its length.")}get length(){return this.items.length}pauseTracking(){this[_].pause()}resumeTracking(){this[_].resume()}untracked(e){return this[_].untracked(e)}get isTrackingPaused(){return this[_].paused}push(...e){let t=this[Ce],r=t.items,s=t.tmpItems,i=t[_],o=t[X],a=s.length;for(let c=0,u=e.length;c<u;c++,a++){let d=e[c];if(d==null)return;typeof d=="object"&&o&&lo(d,o,t,c),i.indexedOperation(a,R.ADD),r.push(d),s.push(d),d[_]?.setParent(this,i.root,a)}return a}pop(){let e=this[Ce],t=e.tmpItems,r=e.deletedIndexes,s=-1;for(let o=t.length-1;o>=0;o--)if(r[o]!==!0){s=o;break}if(s<0)return;let i=e.$isUnsentAdd(s);return e[_].delete(s),i?e.$cancelAdd(s):r[s]=!0,e.items.pop()}at(e){return e<0&&(e+=this.length),this.items[e]}$wireIndex(e){let t=this.deletedIndexes;if(t.length===0)return e;let r=this.tmpItems,s=0;for(let i=0;i<r.length;i++)if(t[i]!==!0){if(s===e)return i;s++}return r.length+(e-s)}$isUnsentAdd(e){let t=this[_];return(t.flags&(yc|qi))===0&&!t.paused&&typeof this[X]!="string"&&t.operationAt(e)===R.ADD}$cancelAdd(e,t=!0){let r=this[_],s=this.tmpItems[e];this.tmpItems.splice(e,1),this.deletedIndexes.length>0&&this.deletedIndexes.splice(e,1),r.removeAt(e,1);let i=s?.[_];i!==void 0&&i.root===void 0&&i.removeParent(this),t&&this.$reindexChildren(e)}$reindexChildren(e,t){if(!this[_].hasFilteredFields||typeof this[X]=="string")return;let r=this.tmpItems,s=r.length;if(t!==void 0)for(;e<s&&r[e]===t[e];)e++;for(let i=e;i<s;i++)r[i]?.[_]?.setParentIndex(this,i)}$changeAt(e,t){if(t==null){console.error("ArraySchema items cannot be null nor undefined; Use `splice(index, 1)` instead.");return}if(this.items[e]===t)return;let r=this.items[e]!==void 0?typeof t=="object"?R.DELETE_AND_ADD:R.REPLACE:R.ADD,s=this.$wireIndex(e),i=this[_];return i.change(s,r),t[_]?.setParent(this,i.root,s),s}$deleteAt(e,t){this[_].delete(this.$wireIndex(e),t)}$setAt(e,t,r){r===R.ADD&&this.items[e]!==void 0?this.items.splice(e,0,t):r===R.DELETE_AND_MOVE?(this.items.splice(e,1),this.items[e]=t):(e>this.items.length&&(this._needsCompaction=!0),this.items[e]=t)}clear(){let e=this[Ce];if(e.items.length===0)return;let t=e[_];t.forEachChild((r,s)=>{t.root?.remove(r)}),t.discard(),t.operation(R.CLEAR),e.items.length=0,e.tmpItems.length=0}[Rt](){let e=this[Ce]??this,t=e[_];if(t.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed ArraySchema (pooling not supported).");let r=e.items;for(let s=0;s<r.length;s++)r[s]?.[Rt]?.();e.items.length=0,e.tmpItems.length=0,e.deletedIndexes.length=0,t.recycle(),e[$]=void 0}concat(...e){return new it(...this.items.concat(...e))}join(e){return this.items.join(e)}reverse(){let e=this[Ce],t=e[_];if(t.has()||e.deletedIndexes.length>0){let r=e.items.slice().reverse();return this.clear(),this.push(...r),this}return t.operation(R.REVERSE),e.items.reverse(),e.tmpItems.reverse(),e.$reindexChildren(0),this}shift(){let e=this[Ce],t=e.items;if(t.length===0)return;let r=e[_],s=e.deletedIndexes,i=0;for(;s[i]===!0;)i++;let o=e.$isUnsentAdd(i);return r.delete(i,R.DELETE),o?e.$cancelAdd(i):s[i]=!0,t.shift()}slice(e,t){let r=new it;return r.push(...this.items.slice(e,t)),r}sort(e=hy){let t=this[Ce];t.isMovingItems=!0;let r=t[_];return t.items.sort(e).forEach((i,o)=>r.change(o,R.REPLACE)),t.tmpItems.sort(e),t.$reindexChildren(0),t.isMovingItems=!1,this}splice(e,t,...r){let s=this[Ce],i=s[_],o=s.items,a=s.tmpItems,c=s.deletedIndexes,u=o.length,d=a.length,h=r.length,m=[];for(let p=0;p<d;p++)c[p]!==!0&&m.push(p);let g;if(u>e){t===void 0&&(t=u-e);for(let p=e;p<e+t;p++){let y=m[p],x=s.$isUnsentAdd(y);i.delete(y,R.DELETE),x?(g??(g=[])).push(y):c[y]=!0}}else t=0;if(h>0){let p=m[e]??u,y=Math.min(h,t);for(let k=0;k<y;k++){let I=p+k,B,N=g!==void 0?g.indexOf(I):-1;N!==-1?(g.splice(N,1),B=R.ADD):B=c[I]?R.DELETE_AND_ADD:R.ADD,i.indexedOperation(I,B),a[I]=r[k],c[I]=!1,r[k][_]?.setParent(this,i.root,I)}let x=h-y;if(x>0){let k=p+y;i.insertAt(k,x);for(let I=0;I<x;I++)r[y+I][_]?.setParent(this,i.root,k+I);c.length>0&&c.splice(k,0,...new Array(x).fill(!1)),a.splice(k,0,...r.slice(y)),s.$reindexChildren(k+x)}}if(g!==void 0&&g.length>0){for(let p=g.length-1;p>=0;p--)s.$cancelAdd(g[p],!1);s.$reindexChildren(g[0])}return i.root?.enqueueChangeTree(i),o.splice(e,t,...r)}unshift(...e){let t=this[Ce],r=t[_];r.unshift(e.length);for(let i=0;i<e.length;i++)e[i]?.[_]?.setParent(this,r.root,i);let s=t.deletedIndexes;return s.length>0&&s.unshift(...new Array(e.length).fill(!1)),t.tmpItems.unshift(...e),t.$reindexChildren(e.length),t.items.unshift(...e)}indexOf(e,t){return this.items.indexOf(e,t)}lastIndexOf(e,t=this.length-1){return this.items.lastIndexOf(e,t)}every(e,t){return this.items.every(e,t)}some(e,t){return this.items.some(e,t)}forEach(e,t){return this.items.forEach(e,t)}map(e,t){return this.items.map(e,t)}filter(e,t){return this.items.filter(e,t)}reduce(e,t){return this.items.reduce.apply(this.items,arguments)}reduceRight(e,t){return this.items.reduceRight.apply(this.items,arguments)}find(e,t){return this.items.find(e,t)}findIndex(e,t){return this.items.findIndex(e,t)}fill(e,t,r){throw new Error("ArraySchema#fill() not implemented")}copyWithin(e,t,r){throw new Error("ArraySchema#copyWithin() not implemented")}toString(){return this.items.toString()}toLocaleString(){return this.items.toLocaleString()}[Symbol.iterator](){return this.items[Symbol.iterator]()}static get[Symbol.species](){return it}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}includes(e,t){return this.items.includes(e,t)}flatMap(e,t){throw new Error("ArraySchema#flatMap() is not supported.")}flat(e){throw new Error("ArraySchema#flat() is not supported.")}findLast(){return this.items.findLast.apply(this.items,arguments)}findLastIndex(...e){return this.items.findLastIndex.apply(this.items,arguments)}with(e,t){let r=this.items.slice();return e<0&&(e+=this.length),r[e]=t,new it(...r)}toReversed(){return this.items.slice().reverse()}toSorted(e){return this.items.slice().sort(e)}toSpliced(e,t,...r){let s=this.items.slice();return s.splice.apply(s,arguments),s}shuffle(){return this.move(e=>{let t=this.items.length;for(;t!=0;){let r=Math.floor(Math.random()*t);t--,[this[t],this[r]]=[this[r],this[t]]}})}move(e){return this.isMovingItems=!0,e(this),this.isMovingItems=!1,this}[(nd=Symbol.unscopables,Te)](e,t=!1){let r=this[Ce]??this;return t||r.deletedIndexes[e]?r.items[e]:r.tmpItems[e]||r.items[e]}[xt](e){let t=this[Ce]??this;t.items[e]=void 0,t._needsCompaction=!0}[yn](){let e=this.tmpItems;this.tmpItems=this.items.slice(),this.deletedIndexes.length>0&&(this.$reindexChildren(0,e),this.deletedIndexes.length=0)}[zi](){let e=this[Ce]??this;e._needsCompaction&&(e._needsCompaction=!1,e.items=e.items.filter(t=>t!==void 0))}[_r](e,t,r){let s=this[Ce]??this,i=s.items,o=!1;for(let a=0;a<i.length;a++){let c=i[a];if(e.has(a)){r(c);continue}o=!0,t(c,a),s[xt](a)}o&&s[zi]()}toArray(){return this.items.slice(0)}toJSON(){return this.toArray().map(e=>typeof e.toJSON=="function"?e.toJSON():e)}clone(e){let t;return e?(t=new it,t.push(...this.items)):t=new it(...this.map(r=>r[_]?r.clone():r)),t}};l(it,sd,ay),l(it,rd,fy),l(it,"COLLECTION_KIND",_t.Array);wn=it;nn("array",{constructor:wn});Xi=class{constructor(){l(this,"keyByIndex",new Map);l(this,"indexByKey",Object.create(null));l(this,"nextIndex",0);l(this,"snapshots")}indexOf(e){let t=this.indexByKey[e];return t===void 0?void 0:t}assign(e){let t=this.nextIndex++;return this.indexByKey[e]=t,this.keyByIndex.set(t,e),t}snapshot(e,t){(this.snapshots??(this.snapshots=new Map)).set(e,t)}forgetSnapshot(e){this.snapshots?.delete(e)}snapshotAt(e){return this.snapshots?.get(e)}setIndex(e,t){this.keyByIndex.set(e,t),this.indexByKey[t]=e}keyOf(e){return this.keyByIndex.get(e)}cleanupAfterEncode(){if(this.snapshots!==void 0){for(let[e]of this.snapshots){let t=this.keyByIndex.get(e);t!==void 0&&(delete this.indexByKey[t],this.keyByIndex.delete(e))}this.snapshots.clear()}}reset(){this.indexByKey=Object.create(null),this.keyByIndex.clear(),this.snapshots?.clear(),this.nextIndex=0}},Mt=class Mt{constructor(e){l(this,hd);l(this,fd);l(this,"childType");l(this,dd);l(this,"$items",new Map);l(this,"journal",new Xi);l(this,"_stream");if(Object.defineProperty(this,_,{value:new En(this),enumerable:!1,writable:!0}),this[X]=void 0,e)if(e instanceof Map||e instanceof Mt)e.forEach((t,r)=>this.set(r,t));else for(let t in e)this.set(t,e[t])}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=tn())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=tn())).priority=e}get $indexes(){return this.journal.keyByIndex}get _collectionIndexes(){return this.journal.indexByKey}static[(hd=_,fd=$,dd=X,ud=Lt,ld=Et,Hn)](e,t,r){if(!r||typeof e[X]=="string")return!0;let s=e[Te](t)??e.journal.snapshotAt(t);return r.isChangeTreeVisible(s[_])}static is(e){return e.map!==void 0}static initializeForDecoder(){let e=Object.create(Mt.prototype);return e.$items=new Map,e.journal=new Xi,e[X]=void 0,Er(e),e}[Symbol.iterator](){return this.$items[Symbol.iterator]()}get[Symbol.toStringTag](){return this.$items[Symbol.toStringTag]}static get[Symbol.species](){return Mt}set(e,t){if(t==null)throw new Error(`MapSchema#set('${e}', ${t}): trying to set ${t} value on '${e}'.`);typeof t=="object"&&this[X]&&lo(t,this[X],this,e),e=e.toString();let r=this[_],s=t[_]!==void 0,i=this.journal,o=i.indexOf(e),a;if(o!==void 0){a=R.REPLACE;let c=this.$items.get(e);if(c===t)return;s&&(a=R.DELETE_AND_ADD,c!==void 0&&c[_].root?.remove(c[_])),i.snapshotAt(o)!==void 0&&i.forgetSnapshot(o)}else o=i.assign(e),a=R.ADD;return this.$items.set(e,t),a===R.ADD&&r.isStreamCollection?r.root!==void 0&&so(this,r.root,o):r.change(o,a),s&&t[_].setParent(this,r.root,o),this}get(e){return this.$items.get(e)}getOrInsert(e,t){return this.$items.has(e)?this.$items.get(e):(this.set(e,t),t)}getOrInsertComputed(e,t){if(this.$items.has(e))return this.$items.get(e);let r=t(e);return this.set(e,r),r}delete(e){if(!this.$items.has(e))return!1;let t=this.journal.indexOf(e),r=this.$items.get(e),s=this[_];if(s.isStreamCollection){let i=s.root,o=!1;return i!==void 0&&(o=io(this,i,this[$],t)),r?.[_]!==void 0&&i?.remove(r[_]),this.$items.delete(e),o||this.journal.snapshot(t,r),!0}return this.journal.snapshot(t,r),s.delete(t),this.$items.delete(e)}clear(){let e=this[_];e.discard(),e.forEachChild((t,r)=>{e.root?.remove(t)}),this.journal.reset(),this.$items.clear(),e.operation(R.CLEAR)}[Rt](){let e=this[_];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed MapSchema (pooling not supported).");this.$items.forEach(t=>t?.[Rt]?.()),this.$items.clear(),this.journal.reset(),e.recycle(),this[$]=void 0}has(e){return this.$items.has(e)}forEach(e){this.$items.forEach(e)}entries(){return this.$items.entries()}keys(){return this.$items.keys()}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[_].pause()}resumeTracking(){this[_].resume()}untracked(e){return this[_].untracked(e)}get isTrackingPaused(){return this[_].paused}setIndex(e,t){this.journal.setIndex(e,t)}getIndex(e){return this.journal.keyOf(e)}[Te](e){let t=this.journal.keyOf(e);return t!==void 0?this.$items.get(t):void 0}[xt](e){let t=this.journal.keyOf(e);t!==void 0&&(this.$items.delete(t),this.journal.keyByIndex.delete(e))}[_r](e,t,r){let s=null;if(this.$items.forEach((i,o)=>{if(e.has(o)){r(i);return}(s??(s=new Set)).add(o),t(i,o)}),s!==null){s.forEach(o=>{this.$items.delete(o),delete this.journal.indexByKey[o]});let i=[];this.journal.keyByIndex.forEach((o,a)=>{s.has(o)&&i.push(a)});for(let o=0;o<i.length;o++)this.journal.keyByIndex.delete(i[o])}}[yn](){this.journal.cleanupAfterEncode()}_dropView(e){oo(this,e)}_unregister(){}toJSON(){return Object.fromEntries(Array.from(this,([t,r])=>[t,typeof r.toJSON=="function"?r.toJSON():r]))}clone(e){let t;return e?t=Object.assign(new Mt,this):(t=new Mt,this.forEach((r,s)=>{r[_]?t.set(s,r.clone()):t.set(s,r)})),t}};l(Mt,ud,oy),l(Mt,ld,co),l(Mt,"COLLECTION_KIND",_t.Map);_n=Mt;nn("map",{constructor:_n});mn=class mn{constructor(e){l(this,bd);l(this,yd);l(this,gd);l(this,"$items",new Map);l(this,"deletedItems",{});l(this,"$refId",0);l(this,"_stream");Object.defineProperty(this,_,{value:new En(this),enumerable:!1,writable:!0}),this[X]=void 0,e&&e.forEach(t=>this.add(t))}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=tn())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=tn())).priority=e}static[(bd=_,yd=$,gd=X,md=Lt,pd=Et,Hn)](e,t,r){return!r||typeof e[X]=="string"||r.isChangeTreeVisible((e[Te](t)??e.deletedItems[t])[_])}static is(e){return e.collection!==void 0}static initializeForDecoder(){let e=Object.create(mn.prototype);return e.$items=new Map,e.deletedItems={},e.$refId=0,e[X]=void 0,Er(e),e}add(e){let t=this.$refId++,r=this[_];return this.$items.set(t,e),r.isStreamCollection?r.root!==void 0&&so(this,r.root,t):r.change(t),e[_]!==void 0&&e[_].setParent(this,r.root,t),t}at(e){let t=Array.from(this.$items.keys())[e];return this.$items.get(t)}entries(){return this.$items.entries()}delete(e){let t=this.$items.entries(),r,s;for(;(s=t.next())&&!s.done;)if(e===s.value[1]){r=s.value[0];break}if(r===void 0)return!1;let i=this[_];if(i.isStreamCollection){let o=i.root,a=this.$items.get(r);return o!==void 0&&io(this,o,this[$],r),a?.[_]!==void 0&&o?.remove(a[_]),this.deletedItems[r]=a,this.$items.delete(r)}return this.deletedItems[r]=i.delete(r),this.$items.delete(r)}clear(){let e=this[_];e.discard(),e.forEachChild((t,r)=>{e.root?.remove(t)}),this.$items.clear(),e.operation(R.CLEAR)}[Rt](){let e=this[_];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed CollectionSchema (pooling not supported).");this.$items.forEach(t=>t?.[Rt]?.()),this.$items.clear(),this.deletedItems={},this.$refId=0,e.recycle(),this[$]=void 0}has(e){return Array.from(this.$items.values()).some(t=>t===e)}forEach(e){this.$items.forEach((t,r,s)=>e(t,r,this))}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[_].pause()}resumeTracking(){this[_].resume()}untracked(e){return this[_].untracked(e)}get isTrackingPaused(){return this[_].paused}[Symbol.iterator](){return this.$items.values()}setIndex(e,t){}getIndex(e){return e}[Te](e){return this.$items.get(e)}[xt](e){this.$items.delete(e)}[_r](e,t,r){let s=null;if(this.$items.forEach((i,o)=>{if(e.has(o)){r(i);return}(s??(s=[])).push(o),t(i,o)}),s!==null)for(let i=0;i<s.length;i++)this[xt](s[i])}[yn](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){oo(this,e)}_unregister(){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach((t,r)=>{e.push(typeof t.toJSON=="function"?t.toJSON():t)}),e}clone(e){let t;return e?t=Object.assign(new mn,this):(t=new mn,this.forEach(r=>{r[_]?t.add(r.clone()):t.add(r)})),t}};l(mn,md,bc),l(mn,pd,co),l(mn,"COLLECTION_KIND",_t.Collection);ys=mn;nn("collection",{constructor:ys});gn=class gn{constructor(e){l(this,xd);l(this,Rd);l(this,Ed);l(this,"$items",new Map);l(this,"deletedItems",{});l(this,"$refId",0);l(this,"_stream");Object.defineProperty(this,_,{value:new En(this),enumerable:!1,writable:!0}),this[X]=void 0,e&&e.forEach(t=>this.add(t))}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=tn())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=tn())).priority=e}static[(xd=_,Rd=$,Ed=X,_d=Lt,wd=Et,Hn)](e,t,r){return!r||typeof e[X]=="string"||r.isVisible((e[Te](t)??e.deletedItems[t])[_])}static is(e){return e.set!==void 0}static initializeForDecoder(){let e=Object.create(gn.prototype);return e.$items=new Map,e.deletedItems={},e.$refId=0,e[X]=void 0,Er(e),e}add(e){if(this.has(e))return!1;let t=this.$refId++,r=this[_];return this.$items.set(t,e),r.isStreamCollection?r.root!==void 0&&so(this,r.root,t):r.change(t,R.ADD),e[_]!==void 0&&e[_].setParent(this,r.root,t),t}entries(){return this.$items.entries()}delete(e){let t=this.$items.entries(),r,s;for(;(s=t.next())&&!s.done;)if(e===s.value[1]){r=s.value[0];break}if(r===void 0)return!1;let i=this[_];if(i.isStreamCollection){let o=i.root,a=this.$items.get(r);return o!==void 0&&io(this,o,this[$],r),a?.[_]!==void 0&&o?.remove(a[_]),this.deletedItems[r]=a,this.$items.delete(r)}return this.deletedItems[r]=i.delete(r),this.$items.delete(r)}clear(){let e=this[_];e.discard(),this.$items.clear(),e.operation(R.CLEAR)}[Rt](){let e=this[_];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed SetSchema (pooling not supported).");this.$items.forEach(t=>t?.[Rt]?.()),this.$items.clear(),this.deletedItems={},this.$refId=0,e.recycle(),this[$]=void 0}has(e){let t=this.$items.values(),r=!1,s;for(;(s=t.next())&&!s.done;)if(e===s.value){r=!0;break}return r}forEach(e){this.$items.forEach((t,r,s)=>e(t,r,this))}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[_].pause()}resumeTracking(){this[_].resume()}untracked(e){return this[_].untracked(e)}get isTrackingPaused(){return this[_].paused}[Symbol.iterator](){return this.$items.values()}setIndex(e,t){}getIndex(e){return e}[Te](e){return this.$items.get(e)}[xt](e){this.$items.delete(e)}[_r](e,t,r){let s=null;if(this.$items.forEach((i,o)=>{if(e.has(o)){r(i);return}(s??(s=[])).push(o),t(i,o)}),s!==null)for(let i=0;i<s.length;i++)this[xt](s[i])}[yn](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){oo(this,e)}_unregister(){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach((t,r)=>{e.push(typeof t.toJSON=="function"?t.toJSON():t)}),e}clone(e){let t;return e?t=Object.assign(new gn,this):(t=new gn,this.forEach(r=>{r[_]?t.add(r.clone()):t.add(r)})),t}};l(gn,_d,bc),l(gn,wd,co),l(gn,"COLLECTION_KIND",_t.Set);bs=gn;nn("set",{constructor:bs});Zt=class Zt{constructor(){l(this,vd);l(this,Ad);l(this,kd);l(this,"$items",new Map);l(this,"$nextPosition",0);l(this,"_itemIndex",new Map);l(this,"_stream");Object.defineProperty(this,_,{value:new En(this),enumerable:!1,writable:!0}),this[X]=void 0}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=tn())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=tn())).priority=e}static[(vd=_,Ad=$,kd=X,Td=Lt,Sd=Et,Hn)](e,t,r){if(!r)return!0;let s=e[Te](t);return s===void 0?!1:r.isVisible(s[_])}static is(e){return e&&e.stream!==void 0}static initializeForDecoder(){let e=Object.create(Zt.prototype);return e.$items=new Map,e.$nextPosition=0,e._itemIndex=new Map,e[X]=void 0,Er(e),e}add(e){if(this._itemIndex.has(e))return-1;let t=this.$nextPosition++;this.$items.set(t,e),this._itemIndex.set(e,t);let s=this[_].root;return e[_]!==void 0&&e[_].setParent(this,s,t),s!==void 0&&so(this,s,t),t}remove(e){let t=this._itemIndex.get(e);if(t===void 0)return!1;this._itemIndex.delete(e),this.$items.delete(t);let r=this[_].root;return r!==void 0&&(io(this,r,this[$],t),e[_]!==void 0&&r.remove(e[_])),!0}has(e){return this._itemIndex.has(e)}clear(){let e=this[_].root;if(e!==void 0){Tg(this,e,this[$]);for(let t of this.$items.values())t[_]!==void 0&&e.remove(t[_])}this.$items.clear(),this._itemIndex.clear()}forEach(e){for(let[t,r]of this.$items)e(r,t,this)}values(){return this.$items.values()}entries(){return this.$items.entries()}[Symbol.iterator](){return this.$items.values()}get size(){return this.$items.size}get length(){return this.$items.size}setIndex(e,t){}getIndex(e){return e}[Te](e){return this.$items.get(e)}[xt](e){let t=this.$items.get(e);t!==void 0&&(this._itemIndex.delete(t),this.$items.delete(e))}[_r](){}[yn](){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach(t=>{e.push(typeof t?.toJSON=="function"?t.toJSON():t)}),e}clone(e){if(e)return Object.assign(new Zt,this);let t=new Zt;return t.maxPerTick=this.maxPerTick,this.forEach(r=>{t.add(typeof r?.clone=="function"?r.clone():r)}),t}_dropView(e){oo(this,e)}_unregister(){}};l(Zt,"$isStream",!0),l(Zt,Td,bc),l(Zt,Sd,co),l(Zt,"COLLECTION_KIND",_t.Stream);Qi=Zt;nn("stream",{constructor:Qi});Cd=Nd;Bt=class{constructor(e){l(this,Cd,!0);l(this,"_type");l(this,"_default");l(this,"_hasDefault",!1);l(this,"_view");l(this,"_unreliable",!1);l(this,"_patchOnly",!1);l(this,"_deprecated",!1);l(this,"_deprecatedThrows",!0);l(this,"_fullStateOnly",!1);l(this,"_stream",!1);l(this,"_optional",!1);l(this,"_noSync",!1);l(this,"_streamPriority");this._type=e}default(e){return this._default=e,this._hasDefault=!0,this}view(e){return this._view=e??-1,this}unreliable(){return this._unreliable=!0,this}patchOnly(){return this._patchOnly=!0,this}fullStateOnly(){return this._fullStateOnly=!0,this}noSync(){return this._noSync=!0,this}stream(){let e=this._type;if(e&&typeof e=="object"&&e.array!==void 0)throw new Error(Zd);return this._stream=!0,this}priority(e){return this._streamPriority=e,this}deprecated(e=!0){return this._deprecated=!0,this._deprecatedThrows=e,this}optional(){return this._optional=!0,this}toDefinition(){return{type:this._type,default:this._default,hasDefault:this._hasDefault,view:this._view,unreliable:this._unreliable,patchOnly:this._patchOnly,deprecated:this._deprecated,deprecatedThrows:this._deprecatedThrows,fullStateOnly:this._fullStateOnly,stream:this._stream,optional:this._optional,noSync:this._noSync,streamPriority:this._streamPriority}}};py=(n=>new Bt({array:xs(n)})),my=(n=>new Bt({map:xs(n)})),gy=(n=>new Bt({set:xs(n)})),yy=(n=>new Bt({collection:xs(n)})),by=(n=>{let e=new Bt({stream:xs(n)});return e._stream=!0,e}),wy=(n=>new Bt(n));Ye=Object.freeze({string:Ge("string"),number:Ge("number"),boolean:Ge("boolean"),int8:Ge("int8"),uint8:Ge("uint8"),int16:Ge("int16"),uint16:Ge("uint16"),int32:Ge("int32"),uint32:Ge("uint32"),int64:Ge("int64"),uint64:Ge("uint64"),float32:Ge("float32"),float64:Ge("float64"),bigint64:Ge("bigint64"),biguint64:Ge("biguint64"),ref:wy,array:py,map:my,set:gy,collection:yy,stream:by,quantized:Qu,angle:n=>Qu({min:0,max:Math.PI*2,mode:"wrap",bits:n?.bits??16})}),uo=-1;xy={number:"number",int8:"number",uint8:"number",int16:"number",uint16:"number",int32:"number",uint32:"number",int64:"number",uint64:"number",float32:"number",float64:"number",bigint64:"bigint",biguint64:"bigint",string:"string",boolean:"boolean"};bt=class bt{constructor(e){l(this,Od);l(this,Id);bt.initialize(this),e&&bt.assignProps(this,e)}static initialize(e){Object.defineProperty(e,_,{value:new En(e),enumerable:!1,writable:!0}),e[Fe]=[]}static initializeForDecoder(){let e=Object.create(this.prototype);return Er(e),e[Fe]=[],e}static reset(e){let t=e?.[_];if(t===void 0||typeof t.recycle!="function")throw new Error("@colyseus/schema: Schema.reset() requires a tracked (encoder-side) instance.");if(t.extraParents!==void 0)throw new Error(`@colyseus/schema: cannot reset a shared instance (${e.constructor.name}) with multiple parents.`);e[Rt]()}[(Md=Lt,Pd=Et,Od=$,Id=Fe,Rt)](){let t=this.constructor[Symbol.metadata]?.[bn]??[],r=this[Fe];for(let s=0;s<t.length;s++)r[t[s]]?.[Rt]?.();this[_].recycle(),this[$]=void 0}static is(e){let t=e[Symbol.metadata];return typeof t=="object"&&t!==null}static isSchema(e){return typeof e?.assign=="function"}static[Nt](e,t,r=R.ADD){e.change(t,r)}static[Hn](e,t,r){let i=e.constructor[Symbol.metadata][t]?.tag;return r===void 0?i===void 0:i===void 0?!0:i===uo?r.isChangeTreeVisible(e[_]):r.hasTagOnTree(e[_],i)}assign(e){return bt.assignProps(this,e),this}static assignProps(e,t){let r=e.constructor[Symbol.metadata];if(r&&r[Ue]!==void 0)for(let i=0;i<=r[Ue];i++){let o=r[i];if(!o)continue;let a=t[o.name];a!==void 0&&(e[o.name]=a)}let s=Object.keys(t);for(let i=0;i<s.length;i++){let o=s[i];r&&r[o]!==void 0||(e[o]=t[o])}}restore(e){let t=this.constructor[Symbol.metadata];for(let r in t){let s=t[r],i=s.name,o=s.type,a=e[i];if(a!=null){if(typeof o=="string")this[i]=a;else if(bt.is(o)){let c=new o;c.restore(a),this[i]=c}else if(typeof o=="object"){let c=Object.keys(o)[0],u=o[c];if(c==="map"){let d=this[i];for(let h in a)if(bt.is(u)){let m=new u;m.restore(a[h]),d.set(h,m)}else d.set(h,a[h])}else if(c==="array"){let d=this[i];for(let h=0;h<a.length;h++)if(bt.is(u)){let m=new u;m.restore(a[h]),d.push(m)}else d.push(a[h])}}}}return this}setDirty(e,t){let r=this.constructor[Symbol.metadata];this[_].change(r[r[e]].index,t)}pauseTracking(){this[_].pause()}resumeTracking(){this[_].resume()}untracked(e){return this[_].untracked(e)}get isTrackingPaused(){return this[_].paused}clone(){let e=Object.create(this.constructor.prototype);bt.initialize(e);let t=this.constructor[Symbol.metadata];for(let r in t){let s=t[r].name;typeof this[s]=="object"&&typeof this[s]?.clone=="function"?e[s]=this[s].clone():e[s]=this[s]}return e}toJSON(){let e={},t=this.constructor[Symbol.metadata];for(let r in t){let s=t[r],i=s.name;!s.deprecated&&this[i]!==null&&typeof this[i]<"u"&&(e[i]=typeof this[i].toJSON=="function"?this[i].toJSON():this[i])}return e}discardAllChanges(){this[_].discardAll()}[Te](e){let t=this.constructor[Symbol.metadata];return this[t[e].name]}[xt](e){let t=this.constructor[Symbol.metadata];this[t[e].name]=void 0}static debugRefIds(e,t=!1,r=0,s,i=""){let o=t?` - ${JSON.stringify(e.toJSON())}`:"",a=e[_],c=e[$],u=s?s.root:a.root,d=u?.refCount?.[c]>1?` [\xD7${u.refCount[c]}]`:"",h=`${Oy(r)}${i}${e.constructor.name} (refId: ${c})${d}${o}
|
|
5
5
|
`;return a.forEachChild((m,g)=>{let p=g;typeof g=="number"&&e.$indexes&&(p=e.$indexes.get(g)??g);let y=e.forEach!==void 0&&p!==void 0?`["${p}"]: `:"";h+=this.debugRefIds(m.ref,t,r+1,s,y)}),h}static debugRefIdEncodingOrder(e,t="allChanges"){let r=[],s=e[_];if(t==="changes"){let c=s.root.changes?.next;for(;c;)c.changeTree&&r.push(c.changeTree.ref[$]),c=c.next;return r}let i=t==="allFilteredChanges",o=new Set,a=c=>{o.has(c)||(o.add(c),c.isFiltered===i&&r.push(c.ref[$]),c.forEachChild((u,d)=>a(u)))};return a(s),r}static debugRefIdsFromDecoder(e){return this.debugRefIds(e.state,!1,0,e)}static debugChanges(e,t=!1){let r=e[_],s=t?"allChanges":"changes",i=`${e.constructor.name} (${e[$]}) -> .${s}:
|
|
6
6
|
`;return t?r.forEachLive(o=>{i+=`- [${o}]: ADD (${JSON.stringify(r.getValue(Number(o),!0))})
|
|
7
7
|
`}):r.forEach((o,a)=>{o<0||!a||(i+=`- [${o}]: ${R[a]} (${JSON.stringify(r.getValue(Number(o),!1))})
|
|
8
|
-
`)}),i}};l(
|
|
8
|
+
`)}),i}};l(bt,Md,iy),l(bt,Pd,dy);Ee=bt;Dd(Ee);Zu={value:0,enumerable:!1,writable:!0},ac=class{constructor(e,t=0){l(this,"types");l(this,"nextUniqueId",0);l(this,"refCount",{});l(this,"changeTrees",{});l(this,"changes",Ku());l(this,"unreliableChanges",Ku());l(this,"pendingFilterRefresh",[]);l(this,"_nodePool",[]);l(this,"_nextViewId",0);l(this,"_freeViewIds",[]);l(this,"activeViews",new Map);l(this,"streamTrees",new Set);this.types=e,this.nextUniqueId=t}enqueueFilterRefresh(e){this.types.hasFilters&&(e.flags&ms||(e.flags|=ms,this.pendingFilterRefresh.push(e)))}acquireViewId(){return this._freeViewIds.length>0?this._freeViewIds.pop():this._nextViewId++}releaseViewId(e){this._freeViewIds.push(e)}registerView(e){this.activeViews.set(e.id,new WeakRef(e))}unregisterView(e){this.activeViews.delete(e.id);let t=e.id;for(let r of this.streamTrees)r._dropView(t)}forEachActiveView(e){for(let[t,r]of this.activeViews){let s=r.deref();if(s===void 0){this.activeViews.delete(t);for(let i of this.streamTrees)i._dropView(t);continue}e(s)}}registerStream(e){this.streamTrees.add(e)}unregisterStream(e){this.streamTrees.delete(e)}add(e){let t=e.ref;t[$]===void 0&&(Zu.value=this.nextUniqueId++,Object.defineProperty(t,$,Zu));let r=t[$],s=this.changeTrees[r]===void 0;s&&(this.changeTrees[r]=e);let i=this.refCount[r];return(i===0||e.needsRestage)&&(e.needsRestage=!1,e.forEachLiveWithCtx(e,sf)),this.refCount[r]=(i||0)+1,i>0&&this.enqueueFilterRefresh(e),s}remove(e){let t=e.ref[$],r=this.refCount[t]-1;if(r<=0){if(e.root=void 0,delete this.changeTrees[t],e.isStreamCollection){let s=e.ref;s._unregister?.(),this.unregisterStream(s)}this.removeFromQueue(e),this.removeFromUnreliableQueue(e),this.refCount[t]=0,e.forEachChild((s,i)=>{s.removeParent(e.ref)&&(s.parentRef===void 0||s.parentRef&&this.refCount[s.ref[$]]>0?this.remove(s):s.parentRef&&this.moveNextToParent(s))})}else this.refCount[t]=r,this.enqueueFilterRefresh(e),this.recursivelyMoveNextToParent(e);return r}recursivelyMoveNextToParent(e){this.moveNextToParent(e),e.forEachChild((t,r)=>this.recursivelyMoveNextToParent(t))}moveNextToParent(e){e.changesNode&&this._moveNextToParentInList(this.changes,e,e.changesNode,"changesNode"),e.unreliableChangesNode&&this._moveNextToParentInList(this.unreliableChanges,e,e.unreliableChangesNode,"unreliableChangesNode")}_moveNextToParentInList(e,t,r,s){let i=t.parent;if(!i||!i[_])return;let o=i[_][s];!o||o===r||r.position>o.position||(r.prev?r.prev.next=r.next:e.next=r.next,r.next?r.next.prev=r.prev:e.tail=r.prev,r.prev=e.tail,r.next=void 0,e.tail.next=r,e.tail=r,r.position=e.nextPosition++)}enqueueChangeTree(e,t=e.changesNode){t||(e.changesNode=this._appendToList(this.changes,e))}enqueueUnreliable(e,t=e.unreliableChangesNode){t||(e.unreliableChangesNode=this._appendToList(this.unreliableChanges,e))}_appendToList(e,t){let r=this._nodePool,s;return r.length>0?(s=r.pop(),s.changeTree=t,s.next=void 0,s.prev=void 0):s={changeTree:t,next:void 0,prev:void 0,position:0},e.next?(s.prev=e.tail,e.tail.next=s,e.tail=s):(e.nextPosition=0,e.next=s,e.tail=s),s.position=e.nextPosition++,s}releaseNode(e){e.changeTree=void 0,e.prev=void 0,e.next=void 0,this._nodePool.push(e)}removeFromQueue(e){return this._removeNode(this.changes,e,e.changesNode,"changesNode")}removeFromUnreliableQueue(e){return this._removeNode(this.unreliableChanges,e,e.unreliableChangesNode,"unreliableChangesNode")}_removeNode(e,t,r,s){return!r||r.changeTree!==t?!1:(r.prev?r.prev.next=r.next:e.next=r.next,r.next?r.next.prev=r.prev:e.tail=r.prev,t[s]=void 0,this.releaseNode(r),!0)}};oE=new FinalizationRegistry(({root:n,id:e,slot:t,bit:r})=>{My(n,t,r),n.activeViews.delete(e);for(let s of n.streamTrees)s._dropView(e);n.releaseViewId(e)}),Dy=-1;Dt=class Dt{constructor(e,t){l(this,"sharedBuffer",new Uint8Array(Dt.BUFFER_SIZE));l(this,"context");l(this,"state");l(this,"root");l(this,"_encodeCtx",{self:void 0,buffer:void 0,it:void 0,changeTree:void 0,ref:void 0,encoder:void 0,filter:void 0,metadata:void 0,view:void 0,isEncodeAll:!1,hasView:!1,treeIsFiltered:!1,isSchema:!1,emitFiltered:!1,filterBitmask:0,tags:void 0,structSwitchEmitted:!1,isRootTree:!1,shouldEmitSwitch:!1,gen:0,initialOffset:0,rootChangeTree:void 0});l(this,"_fullSyncGen",0);this.context=jn.cache(e.constructor),this.root=t??new ac(this.context),this.setState(e)}setState(e){this.state=e,this.state[_].setRoot(this.root)}encode(e={offset:0},t,r=this.sharedBuffer,s=e.offset){return this._encodeChannel(e,t,r,s,!1)}encodeUnreliable(e={offset:0},t,r=this.sharedBuffer,s=e.offset){return this._encodeChannel(e,t,r,s,!0)}_encodeChannel(e,t,r,s,i){this.root.pendingFilterRefresh.length>0&&Wu(this.root);let o=t!==void 0,a=this.state[_],c=this._encodeCtx;c.self=this,c.buffer=r,c.it=e,c.view=t,c.isEncodeAll=!1,c.hasView=o,c.emitFiltered=o;let d=i?this.root.unreliableChanges:this.root.changes;for(;d=d.next;){let h=d.changeTree;if(o&&!t.isChangeTreeVisible(h))continue;let m=i?h.unreliableRecorder:h;if(!m||!m.has())continue;let g=h.encDescriptor;c.changeTree=h,c.ref=h.ref,c.encoder=g.encoder,c.filter=g.filter,c.metadata=g.metadata,c.treeIsFiltered=h.isFiltered,c.isSchema=g.isSchema,c.filterBitmask=g.filterBitmask,c.tags=g.tags,c.structSwitchEmitted=!1,c.isRootTree=h===a,c.shouldEmitSwitch=o||e.offset>s||!c.isRootTree,m.forEachWithCtx(c,hf)}return!i&&!o&&this._isStreamBroadcastMode&&this._emitStreamBroadcast(r,e),e.offset>r.byteLength?(r=this._resizeBuffer(r,e.offset),e.offset=s,this._encodeChannel(e,t,r,s,i)):r.subarray(0,e.offset)}encodeFullSync(e,t,r,s,i=e.offset){this.root.pendingFilterRefresh.length>0&&Wu(this.root);let o=s!==void 0,a=this.state[_],c=this._encodeCtx;return c.self=this,c.buffer=t,c.it=e,c.view=s,c.isEncodeAll=!0,c.hasView=o,c.emitFiltered=r,c.gen=++this._fullSyncGen,c.initialOffset=i,c.rootChangeTree=a,ff(c,a),e.offset>t.byteLength?(t=this._resizeBuffer(t,e.offset),e.offset=i,this.encodeFullSync(e,t,r,s,i)):t.subarray(0,e.offset)}_resizeBuffer(e,t){let r=Math.ceil(t/Dt.BUFFER_SIZE)*Dt.BUFFER_SIZE;console.warn(`@colyseus/schema buffer overflow. Encoded state is higher than default BUFFER_SIZE. Use the following to increase default BUFFER_SIZE:
|
|
9
9
|
|
|
10
10
|
import { Encoder } from "@colyseus/schema";
|
|
11
11
|
Encoder.BUFFER_SIZE = ${Math.round(r/1024)} * 1024; // ${Math.round(r/1024)} KB
|
|
12
|
-
`);let s=new Uint8Array(r);return s.set(e),e===this.sharedBuffer&&(this.sharedBuffer=s),s}encodeAll(e={offset:0},t=this.sharedBuffer){return this.encodeFullSync(e,t,!1)}encodeAllView(e,t,r,s=this.sharedBuffer){let i=r.offset;return s=this.encodeFullSync(r,s,!0,e,i),Qa(s.subarray(0,t),s.subarray(i,r.offset))}ensureCapacity(e,t){if(t+Mt.BUFFER_SIZE<=e.byteLength)return e;let r=Math.ceil((t+Mt.BUFFER_SIZE)/Mt.BUFFER_SIZE)*Mt.BUFFER_SIZE,s=new Uint8Array(r);return s.set(e.subarray(0,t)),e===this.sharedBuffer&&(this.sharedBuffer=s),s}encodeView(e,t,r,s=this.sharedBuffer){let i=r.offset;this._emitStreamPriority(e);for(let o of e.changes.keys()){let a=e.changes.get(o),c=this.root.changeTrees[o];if(c===void 0){e.changes.delete(o);continue}if(a.size===0)continue;let u=c.encDescriptor,d=u.encoder,h=u.metadata,m=c.ref,g=c.refTarget;s=this.ensureCapacity(s,r.offset),s[r.offset++]=255,Q.number(s,m[$],r);for(let[p,y]of a){let x;if(p===wy){let L=g.tmpItems,N=g.deletedIndexes;for(let C=0;C<L.length;C++)L[C]===void 0||N[C]===!0||d(this,s,c,C,R.ADD,r,!1,!0,h);continue}if(typeof p=="number")x=p;else{let L=p.indexInParent(m);if(L===void 0)continue;if(x=L,y===R.ADD&&c.getChange(x)===R.DELETE){e.changes.delete(p.ref[$]);continue}}let I=g[Te](x)!==void 0&&y||R.DELETE;d(this,s,c,x,I,r,!1,!0,h)}}return e.changes.clear(),s=this.encode(r,e,s),Qa(s.subarray(0,t),s.subarray(i,r.offset))}encodeUnreliableView(e,t,r,s=this.sharedBuffer){let i=r.offset;return s=this.encodeUnreliable(r,e,s,i),Qa(s.subarray(0,t),s.subarray(i,r.offset))}_emitStreamBroadcast(e,t){let r=this.root.streamTrees;for(let s of r){let i=s,o=i[_],a=i[$];if(a===void 0)continue;let c=i._stream,u=c.broadcastDeletes,d=c.broadcastPending,h=c.sentBroadcast,m=u.size>0,g=d.size>0,p=o.encDescriptor,y=p.encoder,x=p.metadata;if(m||g){if(e[t.offset++]=255,Q.number(e,a,t),m){for(let C of u)y(this,e,o,C,R.DELETE,t,!1,!1,x);u.clear()}let k=c.maxPerTick,I=[],L=0,N=[];for(let C of d){if(L>=k)break;let O=i[Te](C);if(O===void 0){N.push(C);continue}y(this,e,o,C,R.ADD,t,!1,!1,x),h.add(C),I.push(O),N.push(C),L++}for(let C of N)d.delete(C);for(let C of I){let O=C[_];if(O===void 0)continue;let A=C[$];if(A===void 0)continue;e[t.offset++]=255,Q.number(e,A,t);let P=O.encDescriptor,V=P.encoder,Z=P.metadata;O.forEachLive(ee=>{ce.hasUnreliableAtIndex(Z,ee)||V(this,e,O,ee,R.ADD,t,!1,!1,Z)})}}for(let k of h){let I=i[Te](k);if(I===void 0)continue;let L=I[_];if(L===void 0||!L.has())continue;let N=I[$];if(N===void 0)continue;e[t.offset++]=255,Q.number(e,N,t);let C=L.encDescriptor,O=C.encoder,A=C.metadata;L.forEach((P,V)=>{P<0||ce.hasUnreliableAtIndex(A,P)||O(this,e,L,P,V,t,!1,!1,A)})}}}_emitStreamPriority(e){let t=this.root.streamTrees;if(t.size===0)return;let r=e.id;for(let s of t){let i=s,o=i._stream,a=o.pendingByView.get(r);if(a===void 0||a.size===0)continue;let c=o.priorityByView?.get(r),u=c!==void 0,d=o.priority,h=o.maxPerTick,m=[],g=[];if(u||d!==void 0){let x=[],k=[],I=0;for(let L of a){let N=i[Te](L);if(N===void 0){g.push(L);continue}let C=u?c(N):d(e,N);if(I<h){let O=I++;for(;O>0&&k[O-1]<C;)k[O]=k[O-1],x[O]=x[O-1],O--;k[O]=C,x[O]=L}else if(C>k[h-1]){let O=h-1;for(;O>0&&k[O-1]<C;)k[O]=k[O-1],x[O]=x[O-1],O--;k[O]=C,x[O]=L}}for(let L=0;L<I;L++)m.push(x[L])}else for(let x of a){if(m.length>=h)break;m.push(x)}for(let x of g)a.delete(x);let p=m.length,y=o.sentByView.get(r);y===void 0&&(y=new Set,o.sentByView.set(r,y));for(let x=0;x<p;x++){let k=m[x],I=i[Te](k);if(I===void 0){a.delete(k);continue}e._addImmediate(I);let L=I[_];if(L!==void 0){let N=I[$],C=e.changes.get(N);C===void 0&&(C=new Map,e.changes.set(N,C));let O=L.metadata;L.forEachLive(A=>{ce.hasUnreliableAtIndex(O,A)||C.set(A,R.ADD)})}a.delete(k),y.add(k)}}}discardChanges(){let e=this.root.changes,t=e.next,r=this.root;for(;t;){let s=t.next;t.changeTree.endEncode(),r.releaseNode(t),t=s}e.next=void 0,e.tail=void 0}discardUnreliableChanges(){let e=this.root.unreliableChanges,t=e.next,r=this.root;for(;t;){let s=t.next;t.changeTree.endEncodeUnreliable(),r.releaseNode(t),t=s}e.next=void 0,e.tail=void 0}tryEncodeTypeId(e,t,r,s){let i=this.context.getTypeId(t),o=this.context.getTypeId(r);if(o===void 0){console.warn(`@colyseus/schema WARNING: Class "${r.name}" is not registered on TypeRegistry - Please either tag the class with @entity or define a @type() field.`);return}i!==o&&(e[s.offset++]=213,Q.number(e,o,s))}get hasChanges(){return this.root.changes.next!==void 0||this._hasStreamBacklog()}get _isStreamBroadcastMode(){return this.root.activeViews.size===0&&this.root.streamTrees.size>0}_hasStreamBacklog(){let e=this.root;if(e.streamTrees.size===0)return!1;let t=e.activeViews.size===0;for(let r of e.streamTrees)if(t?fg(r):dg(r,e))return!0;return!1}get hasUnreliableChanges(){return this.root.unreliableChanges.next!==void 0}};l(Mt,"BUFFER_SIZE",16*1024);gs=Mt,Ji=class extends Error{constructor(e){super(e),this.name="DecodingWarning"}},Gu={value:0,enumerable:!1,writable:!0},ic=class{constructor(){l(this,"refs",new Map);l(this,"refCount",{});l(this,"deletedRefs",new Set);l(this,"callbacks",{});l(this,"nextUniqueId",0)}getNextUniqueId(){return this.nextUniqueId++}addRef(e,t,r=!0){this.refs.set(e,t),t[$]===void 0?(Gu.value=e,Object.defineProperty(t,$,Gu)):t[$]!==e&&(t[$]=e),r&&(this.refCount[e]=(this.refCount[e]||0)+1),this.deletedRefs.has(e)&&this.deletedRefs.delete(e)}removeRef(e){let t=this.refCount[e];if(t===void 0){try{throw new Ji("trying to remove refId that doesn't exist: "+e)}catch(r){console.warn(r)}return}if(t===0){try{let r=this.refs.get(e);throw new Ji(`trying to remove refId '${e}' with 0 refCount (${r.constructor.name}: ${JSON.stringify(r)})`)}catch(r){console.warn(r)}return}(this.refCount[e]=t-1)<=0&&this.deletedRefs.add(e)}clearRefs(){this.refs.clear(),this.deletedRefs.clear(),this.callbacks={},this.refCount={}}garbageCollectDeletedRefs(){this.deletedRefs.forEach(e=>{if(this.refCount[e]>0)return;let t=this.refs.get(e),r=t.constructor[Symbol.metadata];if(r!=null)for(let s in r){let i=r[s].name,o=t[i];if(typeof o=="object"&&o){let a=o[$];a!==void 0&&!this.deletedRefs.has(a)&&this.removeRef(a)}}else typeof t[X]=="function"&&Array.from(t.values()).forEach(s=>{let i=s[$];i!==void 0&&!this.deletedRefs.has(i)&&this.removeRef(i)});this.refs.delete(e),delete this.refCount[e],delete this.callbacks[e]}),this.deletedRefs.clear()}addCallback(e,t,r){if(e===void 0){let s=typeof t=="number"?R[t]:t;throw new Error(`Can't addCallback on '${s}' (refId is undefined)`)}return this.callbacks[e]||(this.callbacks[e]={}),this.callbacks[e][t]||(this.callbacks[e][t]=[]),this.callbacks[e][t].push(r),()=>this.removeCallback(e,t,r)}removeCallback(e,t,r){let s=this.callbacks?.[e]?.[t]?.indexOf(r);s!==void 0&&s!==-1&&yy(this.callbacks[e][t],s)}},St=class{constructor(e,t){l(this,"context");l(this,"state");l(this,"root");l(this,"currentRefId",0);l(this,"triggerChanges");l(this,"resyncVisited",null);l(this,"resyncDamaged",!1);this.setState(e),this.context=t||new jn(e.constructor)}setState(e){this.state=e,this.root=new ic,this.root.addRef(0,e)}decode(e,t={offset:0},r=this.state){let s=this.triggerChanges!==void 0?[]:null,i=this.root,o=e.byteLength,a=r.constructor[_t];for(this.currentRefId=0;t.offset<o;){if(e[t.offset]==255){t.offset++,r[Vi]?.();let u=te.number(e,t),d=i.refs.get(u);d?(r=d,a=r.constructor[_t],this.currentRefId=u):(console.error(`"refId" not found: ${u}`,{previousRef:r,previousRefId:this.currentRefId}),console.warn("Please report this issue to the developers."),this.skipCurrentStructure(e,t,o));continue}if(a(this,e,t,r,s)===Qd){console.warn("@colyseus/schema: definition mismatch"),this.skipCurrentStructure(e,t,o);continue}}return r[Vi]?.(),this.resyncVisited!==null&&Jg(this,s),s!==null&&this.triggerChanges?.(s),i.garbageCollectDeletedRefs(),s}decodeResync(e,t={offset:0}){this.resyncVisited=new Map,this.resyncDamaged=!1;try{return this.decode(e,t)}finally{this.resyncVisited=null}}skipCurrentStructure(e,t,r){this.resyncVisited!==null&&(this.resyncDamaged=!0);let s={offset:t.offset};for(;t.offset<r&&!(e[t.offset]===255&&(s.offset=t.offset+1,this.root.refs.has(te.number(e,s))));)t.offset++}getInstanceType(e,t,r){let s;if(e[t.offset]===213){t.offset++;let i=te.number(e,t);s=this.context.get(i)}return s||r}createInstanceOfType(e){return e.initializeForDecoder()}removeChildRefs(e,t){let r=typeof e[X]!="string",s=e[$];e.forEach((i,o)=>{t?.push({ref:e,refId:s,op:R.DELETE,field:o,value:void 0,previousValue:i}),r&&this.root.removeRef(i[$])})}},nf=Es({min:Je.float64(),max:Je.float64(),bits:Je.uint8(),mode:Je.uint8()},"QuantizedDescriptor"),rf=Es({name:Je.string(),type:Je.string(),referencedType:Je.number(),childPrimitive:Je.string(),quantized:Je.ref(nf).optional()},"ReflectionField"),sf=Es({id:Je.number(),extendsId:Je.number(),fields:Je.array(rf)},"ReflectionType"),Tt=Es({types:Je.array(sf),rootType:Je.number()},"Reflection");Tt.encode=function(n,e={offset:0}){let t=n.context,r=new Tt,s=new gs(r),i=t.schemas.get(n.state.constructor);i>0&&(r.rootType=i);let o=new Set,a={},c=d=>{if(d.extendsId===void 0||o.has(d.extendsId)){o.add(d.id),r.types.push(d);let h=a[d.id];h!==void 0&&(delete a[d.id],h.forEach(m=>c(m)))}else a[d.extendsId]===void 0&&(a[d.extendsId]=[]),a[d.extendsId].push(d)};t.schemas.forEach((d,h)=>{let m=new sf;m.id=Number(d);let g=Object.getPrototypeOf(h);g!==Ee&&(m.extendsId=t.schemas.get(g));let p=h[Symbol.metadata];if(p!==g[Symbol.metadata]){let y=p[Fe]??-1;for(let x=0;x<=y;x++){let k=p[x];if(k===void 0)continue;let I=k.name;if(!Object.prototype.hasOwnProperty.call(p,I))continue;let L=new rf;L.name=I;let N;if(typeof k.type=="string")N=k.type;else if(Vn(k.type)){let C=k.type.quantized;N="quantized";let O=new nf;O.min=C.min,O.max=C.max,O.bits=C.bits,O.mode=C.wrap?1:0,L.quantized=O}else{let C;Ee.is(k.type)?(N="ref",C=k.type):(N=Object.keys(k.type)[0],typeof k.type[N]=="string"?L.childPrimitive=k.type[N]:C=k.type[N]),L.referencedType=C?t.getTypeId(C):-1}L.type=N,m.fields.push(L)}}c(m)});for(let d in a)a[d].forEach(h=>r.types.push(h));return s.encodeAll(e).slice(0,e.offset)};Tt.decode=function(n,e){let t=new Tt;new St(t).decode(n,e);let s=new jn;t.types.forEach(a=>{let c=s.get(a.extendsId)??Ee,u=class extends c{};jn.register(u),s.add(u,a.id)},{});let i=(a,c,u)=>{c.fields.forEach((d,h)=>{let m=u+h;if(d.quantized!==void 0){let g=d.quantized;ce.addField(a,m,d.name,{quantized:uc({min:g.min,max:g.max,bits:g.bits,mode:g.mode===1?"wrap":"clamp"})})}else if(d.referencedType!==void 0){let g=d.type,p=s.get(d.referencedType)??d.childPrimitive;g==="ref"?ce.addField(a,m,d.name,p):ce.addField(a,m,d.name,{[g]:p})}else ce.addField(a,m,d.name,d.type)})};t.types.forEach(a=>{let c=s.get(a.id),u=ce.initialize(c),d=[],h=a;do d.push(h),h=t.types.find(g=>g.id===h.extendsId);while(h);let m=0;d.reverse().forEach(g=>{i(u,g,m),m+=g.fields.length})});let o=new(s.get(t.rootType||0));return new St(o,s)};Tt.makeEncodable=function(n){let e=n[Symbol.metadata];if(!e)return n;let t=e[Fe];if(t===void 0)return n;for(let r=0;r<=t;r++){let s=e[r];s&&ce.defineField(n,e,r,s.name,s.type)}return Object.prototype.hasOwnProperty.call(n,ls)&&delete n[ls],n};Yi=class{constructor(e){l(this,"decoder");l(this,"uniqueRefIds",new Set);l(this,"isTriggering",!1);this.decoder=e,this.decoder.triggerChanges=this.triggerChanges.bind(this)}get callbacks(){return this.decoder.root.callbacks}get state(){return this.decoder.state}addCallback(e,t,r){return this.decoder.root.addCallback(e,t,r)}addCallbackOrWaitCollectionAvailable(e,t,r,s,i=!0){let o=()=>{},a=()=>o(),c=e[t];if(!c||c[$]===void 0){let u;return u=this.addCallback(e[$],t,(d,h)=>{d!=null&&(u(),o=this.addCallback(d[$],r,s))}),o=u,a}else return i=i&&this.isTriggering===!1,r===R.ADD&&i&&c.forEach((u,d)=>{s(u,d)}),this.addCallback(c[$],r,s)}listen(...e){return typeof e[0]=="string"?this.listenInstance(this.state,e[0],e[1],e[2]):this.listenInstance(e[0],e[1],e[2],e[3])}listenInstance(e,t,r,s=!0){s=s&&this.isTriggering===!1;let i=e[t];return s&&i!==null&&i!==void 0&&r(i,void 0),this.addCallback(e[$],t,r)}onChange(...e){if(e.length===2&&typeof e[0]!="string"){let t=e[0],r=e[1];return this.addCallback(t[$],R.REPLACE,r)}return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],R.REPLACE,e[1]):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],R.REPLACE,e[2])}onAdd(...e){return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],R.ADD,e[1],e[2]!==!1):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],R.ADD,e[2],e[3]!==!1)}onRemove(...e){return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],R.DELETE,e[1]):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],R.DELETE,e[2])}bindTo(e,t,r,s=!0){let i=e.constructor[Symbol.metadata];r||(r=Object.keys(i).filter(a=>!isNaN(Number(a))).map(a=>i[a].name));let o=()=>{for(let a of r){let c=e[a];c!==void 0&&(t[a]=c)}};return s&&o(),this.addCallback(e[$],R.REPLACE,o)}triggerChanges(e){this.uniqueRefIds.clear(),this.isTriggering=!0;for(let t=0,r=e.length;t<r;t++){let s=e[t],i=s.refId,o=s.ref,a=this.callbacks[i];if(a){if((s.op&R.DELETE)===R.DELETE&&Ee.isSchema(s.previousValue)){let c=s.previousValue[$],u=this.callbacks[c]?.[R.DELETE];if(u)for(let d=u.length-1;d>=0;d--)try{u[d]()}catch(h){console.error(h)}}if(Ee.isSchema(o)){if(!this.uniqueRefIds.has(i)){let u=a[R.REPLACE];if(u)for(let d=u.length-1;d>=0;d--)try{u[d]()}catch(h){console.error(h)}}let c=a[s.field];if(c)for(let u=c.length-1;u>=0;u--)try{c[u](s.value,s.previousValue)}catch(d){console.error(d)}}else{let c=s.dynamicIndex??s.field;if((s.op&R.DELETE)===R.DELETE){if(s.previousValue!==void 0){let u=a[R.DELETE];if(u)for(let d=u.length-1;d>=0;d--)try{u[d](s.previousValue,c)}catch(h){console.error(h)}}if((s.op&R.ADD)===R.ADD){let u=a[R.ADD];if(u)for(let d=u.length-1;d>=0;d--)try{u[d](s.value,c)}catch(h){console.error(h)}}}else if((s.op&R.ADD)===R.ADD&&s.previousValue!==s.value){let u=a[R.ADD];if(u)for(let d=u.length-1;d>=0;d--)try{u[d](s.value,c)}catch(h){console.error(h)}}if(s.value!==s.previousValue){let u=a[R.REPLACE];if(u)for(let d=u.length-1;d>=0;d--)try{u[d](c,s.value)}catch(h){console.error(h)}}}this.uniqueRefIds.add(i)}}this.isTriggering=!1}},bc={get(n){if(n instanceof St)return new Yi(n);if("decoder"in n.serializer)return new Yi(n.serializer.decoder);throw new Error("Invalid room or decoder")},getLegacy(n){if(n instanceof St)return Ki(n);if("decoder"in n.serializer)return Ki(n.serializer.decoder);throw new Error("Invalid room or decoder")},getRawChanges(n,e){return Ry(n,e)}};nn("map",{constructor:_n});nn("array",{constructor:wn});nn("set",{constructor:ms});nn("collection",{constructor:ps})});function $e(){return typeof performance<"u"?performance.now():Date.now()}var Rs=Oe(()=>{"use strict"});function ao(n,e){let t=globalThis,r=t.__colyseusDebug;if(!r){let s=[];r=t.__colyseusDebug={__buffer:s,publish(i,o){s.push([i,xy(o)]),s.length>Sy&&s.shift()}}}r.publish(n,e)}function co(){if(typeof globalThis>"u")return!1;let n=globalThis.__colyseusDebug;return n!=null&&n.__buffer===void 0}var xy,Sy,xs=Oe(()=>{"use strict";xy=typeof WeakRef<"u"?n=>new WeakRef(n):n=>({deref:()=>n}),Sy=64});function Ke(n){return n[$]}function Lt(n){return n.constructor[Ty]}function Ss(n,e){let t=Lt(n)?.[e];return typeof t=="number"?t:-1}function af(n){let e=Lt(n);if(!e)return[];let t=[];for(let r=0;;r++){let s=e[r];if(!s||typeof s.name!="string")break;typeof s.type=="string"&&t.push(s.name)}return t}function Ts(n){let e=Lt(n),t=[],r=[];if(e)for(let s=0;;s++){let i=e[s];if(!i||typeof i.name!="string")break;typeof i.type=="string"&&(t.push(i.name),ky[i.type]===void 0&&r.push(i.name))}return{fields:t,numeric:r}}function Ay(n){if(Number.isNaN(n))return 0;if(!Number.isFinite(n))return n>0?Number.MAX_SAFE_INTEGER:-Number.MAX_SAFE_INTEGER;if(n!==(n|0)&&Math.abs(n)<=34028235e31){let e=Math.fround(n);if(Math.abs(Math.abs(e)-Math.abs(n))<1e-4)return e}return n}function cf(n,e){let t=Lt(n),r=t?.[e];switch((typeof r=="number"?t[r]:void 0)?.type){case"float32":return Math.fround;case"number":return Ay;default:return vy}}function lf(n){if(n.length>Cy){let k=n;return I=>{let L={};for(let N=0;N<k.length;N++)L[k[N]]=I[k[N]];return L}}let e=n[0],t=n[1],r=n[2],s=n[3],i=n[4],o=n[5],a=n[6],c=n[7],u=n[8],d=n[9],h=n[10],m=n[11],g=n[12],p=n[13],y=n[14],x=n[15];return k=>{let I={};return e!==void 0&&(I[e]=k[e]),t!==void 0&&(I[t]=k[t]),r!==void 0&&(I[r]=k[r]),s!==void 0&&(I[s]=k[s]),i!==void 0&&(I[i]=k[i]),o!==void 0&&(I[o]=k[o]),a!==void 0&&(I[a]=k[a]),c!==void 0&&(I[c]=k[c]),u!==void 0&&(I[u]=k[u]),d!==void 0&&(I[d]=k[d]),h!==void 0&&(I[h]=k[h]),m!==void 0&&(I[m]=k[m]),g!==void 0&&(I[g]=k[g]),p!==void 0&&(I[p]=k[p]),y!==void 0&&(I[y]=k[y]),x!==void 0&&(I[x]=k[x]),I}}var Ty,lo,ky,vy,Cy,ks=Oe(()=>{"use strict";He();Ty=Symbol.metadata??Symbol.for("Symbol.metadata"),lo=Ue;ky={string:!0,boolean:!0,bigint64:!0,biguint64:!0};vy=n=>n;Cy=16});var _c,Iy,Py,Ye,Er,Ec=Oe(()=>{"use strict";He();Yt();Rs();xs();ks();_c=9,Iy=_c,Py=(n,e)=>(e?2:1)*(_c+4+_c*n),Ye=class Ye{constructor(e,t,r,s){l(this,"data");l(this,"_host");l(this,"_encoder");l(this,"_scratch",new Uint8Array(2048));l(this,"_framed",null);l(this,"_sentCount",0);l(this,"_lastProcessed",0);l(this,"_epoch",0);l(this,"_sendTimes");l(this,"_inputBufferSize");l(this,"_inputBuffer",null);l(this,"_reckonTimes",null);l(this,"_pendingReckon",0);l(this,"_lastStamp",0);l(this,"_stampRing",null);l(this,"_renderDeltaRing",null);l(this,"_ringSlots",0);l(this,"_warnedUnknownKeys",null);l(this,"_stampRender",!1);l(this,"_stampReckon",!1);l(this,"_allowRewind");l(this,"_sendListeners",null);l(this,"_renderDelay",0);l(this,"_renderDelayExplicit",!1);l(this,"_renderDelayProvider");l(this,"_tickRate");l(this,"_patchRate");l(this,"_subSteps",1);this._host=e,this.data=t,this._encoder=r,this._stampRender=s?.stampRender??!1,this._stampReckon=s?.stampReckon??!1,this._allowRewind=s?.allowRewind,this._allowRewind!==void 0&&r.mode==="unreliable"&&!Ye._warnedAllowRewindIgnored&&(Ye._warnedAllowRewindIgnored=!0,console.warn('@colyseus/sdk: `allowRewind` is ignored on `mode:"unreliable"` \u2014 a packet stamps its whole redundancy ring or none of it, so excluding one input would cost bandwidth rather than save it. Use `mode:"reliable"` to gate the lag-comp stamp per input.')),this._renderDelay=s?.renderDelay??0,this._renderDelayExplicit=s?.renderDelay!==void 0,this._tickRate=s?.tickRate,this._patchRate=s?.patchRate,this._subSteps=s?.subSteps??1;let i=this._tickRate?1e3/this._tickRate:1e3/60,o=Ye.BUFFER_RTT_BUDGET_MS+(this._patchRate??0);this._inputBufferSize=Math.max(Ye.BUFFER_FLOOR,Math.ceil(o/i*Ye.BUFFER_HEADROOM)),this._sendTimes=new Float64Array(this._inputBufferSize)}get mode(){return this._encoder.mode}get tickRate(){return this._tickRate}get stepSeconds(){return this._tickRate?1/this._tickRate:void 0}get stepMs(){return this._tickRate?1e3/this._tickRate:void 0}get patchRate(){return this._patchRate}get subSteps(){return this._subSteps}get subStepSeconds(){return this._tickRate?1/this._tickRate/this._subSteps:void 0}get subStepMs(){return this._tickRate?1e3/this._tickRate/this._subSteps:void 0}get lastProcessed(){return this._lastProcessed}get sentCount(){return this._sentCount}get pendingCount(){return this._sentCount-this._lastProcessed}get replayBufferSize(){return this._inputBufferSize}get epoch(){return this._epoch}at(e){if(this._inputBuffer!==null&&!(e<=this._lastProcessed||e>this._sentCount)){if(this._sentCount-e>=this._inputBufferSize){Ye._warnedBufferOverflow||(Ye._warnedBufferOverflow=!0,console.warn(`@colyseus/sdk: input replay buffer (${this._inputBufferSize}) overflowed \u2014 RTT exceeds its budget at this input rate; reconciliation may drift.`));return}return this._inputBuffer[e%this._inputBufferSize]}}reckonTimeAt(e){return this._reckonTimes===null||e<=this._lastProcessed||e>this._sentCount||this._sentCount-e>=this._inputBufferSize?0:this._reckonTimes[e%this._inputBufferSize]}reset(){this._encoder.reset(),this._sentCount=this._lastProcessed=this._encoder.seq,this._framed=null,this._lastStamp=0,this._ringSlots=0,this._sendTimes.fill(0),this._epoch++}bindRenderDelay(e){this._renderDelayExplicit||(this._renderDelayProvider=e)}_resolveRenderDelay(){return this._renderDelayProvider?this._renderDelayProvider():this._renderDelay}_warnUnknownFields(){let e=Lt(this.data);if(e)for(let t of Object.keys(this.data))e[t]!==void 0||this._warnedUnknownKeys?.has(t)||((this._warnedUnknownKeys??(this._warnedUnknownKeys=new Set)).add(t),console.warn(`@colyseus/sdk input: "${t}" is not a declared field on ${this.data.constructor.name} \u2014 the write is never encoded or sent. Declare it with @type(...) on the input schema, or remove the write.`))}send(){let e=this._host.connection;if(!e?.isOpen)return 0;co()&&this._warnUnknownFields();let t=this._encoder.encode(),r=this._encoder.mode==="reliable",s=this._stampReckon||this._stampRender,i=s&&r&&(this._allowRewind===void 0||this._allowRewind(this.data)),o=s&&!r,a=this._stampReckon&&this._stampRender,u=1+(i?Iy+(a?2:0):o?Py(this._encoder.historySize,a):0)+t.length;u>this._scratch.byteLength&&(this._scratch=new Uint8Array(Math.max(u,this._scratch.byteLength*2)),this._framed=null),this._scratch[0]=(r?_e.ROOM_INPUT_RELIABLE:_e.ROOM_INPUT_UNRELIABLE)|(i||o?pr.TIMED:0);let d={offset:1};if(o)this._writeRingStamps(d);else if(i){let{stamp:p,renderDelta:y}=this._sampleStamp();Q.number(this._scratch,p-this._lastStamp,d),this._lastStamp=p,a&&Q.uint16(this._scratch,y,d)}else this._pendingReckon=0;this._scratch.set(t,d.offset);let h=d.offset+t.length;(this._framed===null||this._framed.byteLength!==h)&&(this._framed=this._scratch.subarray(0,h));let m=this._framed,g;return r?(e.send(m),g=++this._sentCount):(e.sendUnreliable(m),g=this._sentCount=this._encoder.seq),this._recordSent(g),g}_writeRingStamps(e){let{stamp:t,renderDelta:r}=this._sampleStamp(),s=this._encoder.historySize,i=this._encoder.seq,o=this._ringSlots=Math.min(this._ringSlots+1,s),a=this._stampRing??(this._stampRing=new Float64Array(s));if(a[i%s]=t,Q.number(this._scratch,o,e),Q.uint32(this._scratch,t,e),this._writeSeriesDeltas(a,i,o,e),this._stampReckon&&this._stampRender){let c=this._renderDeltaRing??(this._renderDeltaRing=new Uint16Array(s));c[i%s]=r,Q.uint16(this._scratch,r,e),this._writeSeriesDeltas(c,i,o,e)}}_writeSeriesDeltas(e,t,r,s){let i=e.length;for(let o=1;o<r;o++)Q.number(this._scratch,e[(t-o+1)%i]-e[(t-o)%i],s)}_sampleStamp(){let e=this._host.clock,t=(e?.lastServerTime?.()??0)>0,r=t?Math.max(0,Math.round(e.serverNow()))>>>0:0,s=t?Math.min(65535,Math.max(0,Math.round(this._resolveRenderDelay()+(e.smoothedRtt?.()??0)/2))):0;return this._pendingReckon=r,{stamp:this._stampReckon?r:r>s?r-s:0,renderDelta:s}}_recordSent(e){if(this._inputBuffer===null){let r=this.data.constructor;this._inputBuffer=Array.from({length:this._inputBufferSize},()=>new r)}this._encoder.copyInto(this._inputBuffer[e%this._inputBufferSize]),this._sendTimes[e%this._inputBufferSize]=$e(),this._stampReckon&&((this._reckonTimes??(this._reckonTimes=new Float64Array(this._inputBufferSize)))[e%this._inputBufferSize]=this._pendingReckon);let t=this._sendListeners;if(t!==null)for(let r=0;r<t.length;r++)t[r](e)}onSend(e){let t=this._sendListeners;return this._sendListeners=t!==null?[...t,e]:[e],()=>{let r=this._sendListeners;if(r===null)return;let s=r.indexOf(e);if(s<0)return;let i=r.slice();i.splice(s,1),this._sendListeners=i.length>0?i:null}}ackInput(e){if(e<=this._lastProcessed)return-1;let t=this._sentCount-e>=this._inputBufferSize;if(this._lastProcessed=e,t)return-1;let r=this._sendTimes[e%this._inputBufferSize];return r>0?$e()-r:-1}};l(Ye,"BUFFER_FLOOR",64),l(Ye,"BUFFER_RTT_BUDGET_MS",1e3),l(Ye,"BUFFER_HEADROOM",1.5),l(Ye,"_warnedBufferOverflow",!1),l(Ye,"_warnedAllowRewindIgnored",!1);Er=Ye});var Rr,Ie,uo,fo=Oe(()=>{"use strict";Rs();Rr=Object.freeze({now:()=>$e(),serverNow:()=>$e(),renderNow:()=>$e(),rtt:()=>0,smoothedRtt:()=>0,jitter:()=>0,lastServerTime:()=>0,patchInterval:()=>0,setPatchInterval:n=>{},sample:(n,e)=>{}}),Ie=class Ie{constructor(){l(this,"_clockOffset",0);l(this,"_clockHasSample",!1);l(this,"_offsetCount",0);l(this,"_rttFloorT",[]);l(this,"_rttFloorV",[]);l(this,"_rtt",0);l(this,"_smoothedRtt",0);l(this,"_rttHasSample",!1);l(this,"_jitter",0);l(this,"_lastRecvTime",-1);l(this,"_lastServerTime",0);l(this,"_patchInterval",0);l(this,"_renderTau",Ie.RENDER_TAU);l(this,"_renderSn",0);l(this,"_renderSnAt",0)}serverNow(){return $e()+this._clockOffset}renderNow(){let e=this.serverNow();if(this._renderTau<=0)return e;let t=$e();if(this._renderSn===0)return this._renderSn=e,this._renderSnAt=t,this._renderSn;let r=Math.min(t-this._renderSnAt,100);return r<.5?this._renderSn:(this._renderSnAt=t,this._renderSn+=r,Math.abs(e-this._renderSn)>Ie.RENDER_SNAP?(this._renderSn=e,this._renderSn):(this._renderSn+=(e-this._renderSn)*(1-Math.exp(-r/this._renderTau)),this._renderSn))}setRenderTau(e){this._renderTau=e>0?e:0}now(){return $e()}rtt(){return this._rtt}smoothedRtt(){return this._smoothedRtt}jitter(){return this._jitter}lastServerTime(){return this._lastServerTime}patchInterval(){return this._patchInterval}setPatchInterval(e){this._patchInterval=e>0?e:0}sample(e,t){let r=$e(),s=Ie.EMA_ALPHA,i=this._patchInterval;if(this._lastRecvTime>=0&&i>0){let a=r-this._lastRecvTime,c=Math.round(a/i);c>=1&&c<=Ie.JITTER_STALL_X&&(this._jitter+=(Math.abs(a-c*i)-this._jitter)*Ie.JITTER_GAIN)}this._lastRecvTime=r,this._lastServerTime=e,(t<0||this._smoothedRtt>0&&t>this._smoothedRtt*Ie.RTT_OUTLIER_X)&&(t=-1);let o=t>=0?e+t/2-r:e-r;if(!this._clockHasSample)this._clockOffset=o,this._clockHasSample=!0,t>=0&&(this.pushRttFloor(t,r),this._offsetCount=1);else if(t>=0){let a=this.pushRttFloor(t,r),c=this._offsetCount<Ie.RTT_GATE_WARMUP;this._offsetCount++,(c||t<=a*Ie.RTT_GATE_FACTOR)&&(this._clockOffset=this._clockOffset*(1-s)+o*s)}t>=0&&(this._rtt=t,this._rttHasSample?this._smoothedRtt=this._smoothedRtt*(1-s)+t*s:(this._smoothedRtt=t,this._rttHasSample=!0))}pushRttFloor(e,t){let r=this._rttFloorT,s=this._rttFloorV;for(;s.length>0&&s[s.length-1]>=e;)s.pop(),r.pop();s.push(e),r.push(t);let i=t-Ie.RTT_GATE_WINDOW;for(;r.length>0&&r[0]<i;)r.shift(),s.shift();return s[0]}reset(){this._clockOffset=0,this._clockHasSample=!1,this._offsetCount=0,this._rtt=0,this._smoothedRtt=0,this._rttHasSample=!1,this._jitter=0,this._lastRecvTime=-1,this._lastServerTime=0,this._rttFloorT.length=0,this._rttFloorV.length=0,this._renderSn=0,this._renderSnAt=0}};l(Ie,"EMA_ALPHA",.1),l(Ie,"RENDER_TAU",250),l(Ie,"RENDER_SNAP",250),l(Ie,"RTT_OUTLIER_X",4),l(Ie,"JITTER_GAIN",1/16),l(Ie,"JITTER_STALL_X",4),l(Ie,"RTT_GATE_FACTOR",1.2),l(Ie,"RTT_GATE_WINDOW",1e4),l(Ie,"RTT_GATE_WARMUP",30);uo=Ie});var Nf=mp((JE,Df)=>{"use strict";Df.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});function n0(n,e){return{now:()=>n?.serverNow()??performance.now(),ttlMs:typeof e=="function"?()=>e(n?.smoothedRtt()??0):e}}var Hs,Po,Gc=Oe(()=>{"use strict";Hs=n=>Math.max(n*2,600),Po=class n{constructor(){l(this,"entries",new Map);l(this,"accepted",new Set);l(this,"cfg",{});l(this,"dead",!1)}static get(e,t={}){let r=new n;return r.configure(n0(e.clock??null,t.ttlMs??Hs)),t.onReject&&r.configure({onReject:t.onReject}),r}configure(e){this.cfg={...this.cfg,...e}}predict(e,t){return this.entries.set(e,t??this.cfg.now?.()??performance.now()),{key:e,cancel:()=>{this.entries.delete(e),this.accepted.delete(e)},accept:()=>{this.entries.has(e)&&this.accepted.add(e)}}}has(e){return this.entries.has(e)}confirm(e){this.entries.delete(e),this.accepted.delete(e)}reject(e){this.entries.delete(e)&&(this.accepted.delete(e),this.cfg.onReject?.(e))}prune(e,t){let r=e??this.cfg.now?.()??performance.now(),s=this.cfg.ttlMs,i=t??(typeof s=="function"?s():s)??1/0;for(let[o,a]of this.entries)this.accepted.has(o)||r-a>i&&(this.entries.delete(o),this.cfg.onReject?.(o))}clear(){this.entries.clear(),this.accepted.clear()}get size(){return this.entries.size}dispose(){this.dead=!0,this.entries.clear(),this.accepted.clear()}}});function Zf(){return{ema:0,peak:0}}function Hc(n,e){n.ema+=(e-n.ema)*.1,n.peak=Math.max(e,n.peak*.9)}function eh(n){n.ema=0,n.peak=0}function Nr(n,e){let t=e!==void 0&&e>Qf?e:Qf;return n.ema>=t?"diverging":n.peak>=t?"jitter":"matched"}var Qf,Oo=Oe(()=>{"use strict";Qf=.001});function zs(){return co()}function nh(){console.warn("@colyseus/sdk predict: a predicted value was read BEFORE this frame's input.send() calls. Reads between predict.tick() and the frame's sends are one fixed step stale and stutter on late frames. Send the frame's due inputs right after predict.tick(now) \u2014 tick and pump in your earliest per-frame callback, before anything reads value()/pose(). For game logic (zone checks, hit-reg) read .state/.world instead. See PREDICTION.md \xA74 (frame order).")}function rh(n,e){console.warn(e===""?`@colyseus/sdk predict: two key-less ctx.memo calls ran in one step (input seq ${n}) \u2014 the key-less form is ONE shared slot per step, so replay returns one frozen value for both (silent re-simulation corruption). Pass distinct keys: ctx.memo("a", \u2026) / ctx.memo("b", \u2026).`:`@colyseus/sdk predict: ctx.memo("${e}") ran twice in one step (input seq ${n}) \u2014 both calls share one slot on replay. Give each call site its own key (include the loop index for a per-iteration memo).`)}function sh(n,e,t,r){let s=$e();if(s-th<r0)return;th=s;let i="",o=-1;for(let c in e){let u=e[c],d=u<0?-u:u;d>o&&(o=d,i=c)}let a=i?e[i]:t;console.warn(`@colyseus/sdk predict: prediction is diverging at input seq ${n} \u2014 rolling drift ${t.toFixed(3)} \u2265 tolerance ${r}; "${i}" currently off by ${a.toFixed(3)}. Most likely the client and server simulations disagree: a different fixed dt, mismatched constants, a step function that isn't shared, or an input the server skipped. See PREDICTION.md \xA75 (Determinism).`)}var th,r0,zc=Oe(()=>{"use strict";Rs();xs();th=-1/0,r0=1e3});function ih(){return Jc>0}var Wc,Jc,Br,Mo=Oe(()=>{"use strict";Oo();zc();Wc=class{constructor(){l(this,"byTick",new Map);l(this,"diagTick",-1);l(this,"diagKeys",new Set);l(this,"warnedKeys",new Set)}run(e,t,r,s){if(t)return this.byTick.get(e)?.get(r);zs()&&(e!==this.diagTick?(this.diagTick=e,this.diagKeys.clear()):this.diagKeys.has(r)&&!this.warnedKeys.has(r)&&(this.warnedKeys.add(r),rh(e,r)),this.diagKeys.add(r));let i=s();if(i!==void 0){let o=this.byTick.get(e);o===void 0&&(o=new Map,this.byTick.set(e,o)),o.set(r,i)}return i}prune(e){for(let t of this.byTick.keys())t<=e&&this.byTick.delete(t)}clear(){this.byTick.clear(),this.diagTick=-1,this.diagKeys.clear()}},Jc=0;Br=class{constructor(e){l(this,"lastCorrection",{});l(this,"lastCorrectionMag",0);l(this,"reconcileSeq",0);l(this,"drift",Zf());l(this,"error",{});l(this,"prev",{});l(this,"renderedBefore",{});l(this,"lastTick",-1);l(this,"lastAcked",0);l(this,"lastEpoch");l(this,"replayFrom",0);l(this,"predictedSeq",0);l(this,"catching",!1);l(this,"unsubscribeSend",()=>{});l(this,"renderAcc",0);l(this,"tickSeq",0);l(this,"clampedReadTick",-1);l(this,"warnedStaleRead",!1);l(this,"stepCtx");l(this,"ackWatermark",()=>this.input_.lastProcessed);l(this,"memos",new Wc);l(this,"smoothMs");l(this,"snapThreshold");l(this,"stepMs");l(this,"input_");l(this,"onReconcile");l(this,"warnTolerance");l(this,"clock");l(this,"dead",!1);l(this,"disposedHooks",[]);this.input_=e.input,this.clock=e.clock,this.smoothMs=e.smoothMs??(this.input_.patchRate?this.input_.patchRate:50),this.snapThreshold=e.snap??0;let t=e.stepMs??this.input_.stepMs??(e.stepSeconds!==void 0?e.stepSeconds*1e3:void 0);if(t===void 0)throw new Error("@colyseus/sdk reconciler: fixed simulation step is unknown. The server room must call setFixedTimestep() (or setTimestep()) so the input handle advertises a tick rate, or pass stepMs/stepSeconds explicitly \u2014 a wrong dt silently diverges rollback-replay.");this.stepMs=t;let r=e.stepSeconds??this.input_.stepSeconds??t/1e3,s=e.subSteps??this.input_.subSteps??1;this.stepCtx={dt:r,dtMs:t,tick:0,isReplay:!1,reckonTime:0,lagCompActive:!1,subSteps:s,subDt:r/s,subDtMs:t/s,memo:(i,o)=>typeof i=="string"?this.memos.run(this.stepCtx.tick,this.stepCtx.isReplay,i,o):this.memos.run(this.stepCtx.tick,this.stepCtx.isReplay,"",i),predict:(i,o)=>{this.stepCtx.isReplay||i._predictFromSim(this.stepCtx.tick,o,this.ackWatermark)}},this.onReconcile=e.onReconcile,this.warnTolerance=e.warnOnDivergence,this.lastAcked=this.input_.lastProcessed,this.lastEpoch=this.input_.epoch,this.predictedSeq=this.input_.sentCount,this.unsubscribeSend=this.input_.onSend(()=>this.catchUp())}tick(e){this.tickSeq++;let t=this.lastTick<0?0:e-this.lastTick;this.lastTick=e,t>0&&this.stepMs>0&&(this.renderAcc+=t);let r=this.input_.epoch;r!==this.lastEpoch&&(this.lastEpoch=r,this.reset());let s=this.input_.lastProcessed;if(s>this.lastAcked&&(this.lastAcked=s,this.reconcile(s)),this.markDirty(),t<=0)return;let i=this.smoothMs<=0?1:1-Math.exp(-t/this.smoothMs);for(let o of this.smoothedFields())this.error[o]-=this.error[o]*i}renderAlpha(){if(this.stepMs<=0)return 1;let e=this.renderAcc/this.stepMs;return e<0?0:e>1?1:e}noteRenderRead(){this.catching||this.stepMs<=0||this.renderAcc<this.stepMs||(this.clampedReadTick=this.tickSeq)}catchUp(){let e=this.input_.sentCount;if(!(this.predictedSeq>=e||this.catching)){this.clampedReadTick===this.tickSeq&&!this.warnedStaleRead&&(this.warnedStaleRead=!0,nh()),this.catching=!0,this.stepCtx.isReplay=!1;for(let t=this.predictedSeq+1;t<=e;t++){let r=this.input_.at(t);r!==void 0&&(this.snapshotPrev(),this.runStep(t,r),this.refreshRender(),this.renderAcc-=this.stepMs,this.renderAcc<0?this.renderAcc=0:this.renderAcc>=this.stepMs&&(this.renderAcc%=this.stepMs)),this.predictedSeq=t}this.catching=!1}}runStep(e,t){this.stepCtx.tick=e;let r=this.input_.reckonTimeAt(e);this.stepCtx.lagCompActive=r>0,this.stepCtx.reckonTime=r>0?r:this.clock!==void 0?this.clock.serverNow():0,this.applyStep(t)}reconcile(e){let t=this.warnTolerance!==void 0||zs();if(this.truthMatchesAt(e)){if(t){for(let u of this.smoothedFields())this.lastCorrection[u]=0;this.lastCorrectionMag=0,Hc(this.drift,0)}this.reconcileSeq++,this.memos.prune(e),this.onReconcile?.(e);return}let r=this.renderedBefore;for(let u of this.smoothedFields())r[u]=this.readCurrent(u)+this.error[u];this.adoptTruth();let s=Math.max(e,this.replayFrom);this.stepCtx.isReplay=!0,this.catching=!0,Jc++;try{for(let u=s+1;u<=this.input_.sentCount;u++){let d=this.input_.at(u);d!==void 0&&this.runStep(u,d)}}finally{Jc--}this.catching=!1,this.refreshRender(),this.predictedSeq=this.input_.sentCount;let i=this.smoothMs<=0,o=t||this.snapThreshold>0,a=0;for(let u of this.smoothedFields()){let d=r[u]-this.readCurrent(u);if(this.error[u]=i?0:d,o){let h=d<0?-d:d;h>a&&(a=h)}t&&(this.lastCorrection[u]=d)}let c=this.snapThreshold>0&&a>this.snapThreshold;if(c)for(let u of this.smoothedFields())this.error[u]=0,this.prev[u]=this.readCurrent(u);this.reconcileSeq++,t&&(this.lastCorrectionMag=a,c||(Hc(this.drift,a),this.warnTolerance!==void 0&&Nr(this.drift,this.warnTolerance)==="diverging"&&sh(e,this.lastCorrection,this.drift.ema,this.warnTolerance))),this.memos.prune(e),this.onReconcile?.(e)}get pendingCount(){return this.input_.pendingCount}reset(){this.reseedState(),eh(this.drift),this.replayFrom=this.input_.sentCount,this.predictedSeq=this.input_.sentCount,this.lastAcked=this.input_.lastProcessed,this.renderAcc=0,this.memos.clear(),this.markDirty()}onDisposed(e){this.disposedHooks.push(e)}dispose(){this.dead=!0,this.unsubscribeSend();for(let e of this.disposedHooks.splice(0))e()}truthMatchesAt(e){return!1}refreshRender(){}markDirty(){}}});var s0,Kc,Lr,Yc=Oe(()=>{"use strict";Gc();Mo();s0=0,Kc=10,Lr=class{constructor(e,t){l(this,"opts");l(this,"store");l(this,"entries",new Map);l(this,"now");l(this,"cooldownUntil",-1/0);l(this,"warnedReplayPredict",!1);l(this,"dead",!1);l(this,"teardowns",[]);this.opts=e,this.now=()=>t?.serverNow()??performance.now(),this.store=Po.get({clock:t},{ttlMs:e.ttlMs??Hs,onReject:r=>{let s=this.entries.get(r);this.entries.delete(r),s&&this.opts.onReject?.(s.payload)}})}_predictFromSim(e,t,r){this.add(e,t,r)}predict(e){if(ih()){this.warnedReplayPredict||(this.warnedReplayPredict=!0,console.warn(`@colyseus/sdk: PredictedEventChannel${this.opts.label?` "${this.opts.label}"`:""}.predict() was called during a rollback replay and ignored. Inside a reconciler step, use ctx.predict(channel, payload).`));return}this.add(-1,e)}add(e,t,r){let s=this.opts.uniqueBy!==void 0?this.opts.uniqueBy(t):typeof t=="string"||typeof t=="number"?t:s0;if(this.entries.has(s))return;let i=this.now();if(this.opts.cooldownMs!==void 0){if(i<this.cooldownUntil)return;this.cooldownUntil=i+this.opts.cooldownMs}let o=this.store.predict(s,i);r!==void 0&&o.accept(),this.entries.set(s,{payload:t,seq:e,acked:r}),this.opts.onPredict?.(t)}has(e){return e===void 0?this.entries.size>0:this.entries.has(e)}get pendingCount(){return this.entries.size}confirm(e){let t=0;for(let r of this.settleKeys(e)){let s=this.entries.get(r);s!==void 0&&(this.entries.delete(r),this.store.confirm(r),this.opts.onConfirm?.(s.payload),t++)}return t===0&&this.opts.onUnpredicted?.(e),t}reject(e){let t=0;for(let r of this.settleKeys(e))this.entries.has(r)&&(this.store.reject(r),t++);return t}settleKeys(e){return e!==void 0?[e]:[...this.entries.keys()]}clear(){this.entries.clear(),this.store.clear()}prune(){if(this.entries.size>0){let e=this.opts.graceTicks??Kc;for(let[t,r]of[...this.entries])r.acked!==void 0&&r.acked()>=r.seq+e&&this.store.reject(t)}this.store.prune()}_addTeardown(e){this.teardowns.push(e)}dispose(){for(let e of this.teardowns.splice(0))e();this.dead=!0,this.clear(),this.store.dispose()}}});var Kn,Do=Oe(()=>{"use strict";Gc();Kn=class{constructor(e={},t=null){l(this,"opts");l(this,"clock");l(this,"correlate");l(this,"ttl");l(this,"byId",new Map);l(this,"byServer",new Map);l(this,"nextId",1);l(this,"lastTickAt");l(this,"detach");l(this,"dead",!1);l(this,"handleAdd",(e,t)=>{if(this.byServer.has(e))return;let r=this.isOwned(e)?this.takeMatch(e):void 0;if(r)this.confirmEntry(r,e);else{let s={id:this.nextId++,server:e,local:void 0,state:"confirmed",at:void 0,leadMs:0,accepted:!1,data:this.makeData()};this.byId.set(s.id,s),this.byServer.set(e,s)}});l(this,"handleRemove",(e,t)=>{let r=this.byServer.get(e);r&&(this.byServer.delete(e),this.byId.delete(r.id))});l(this,"readServer",(e,t)=>e[t]);this.opts=e,this.clock=t,this.correlate=e.correlate??"fifo",this.ttl=e.ttl??Hs}attach(e){this.detach?.(),this.detach=e(this.handleAdd,this.handleRemove)}spawn(e){let t=this.nextId++,r=this.makeData(),s={id:t,server:void 0,local:e,state:"pending",at:this.now(),leadMs:0,accepted:!1,data:r};return this.byId.set(t,s),{id:t,local:e,data:r,cancel:()=>{let i=this.byId.get(t);i&&i.state==="pending"&&this.byId.delete(t)},accept:()=>{let i=this.byId.get(t);i&&(i.accepted=!0)}}}confirmEntry(e,t){e.server=t,e.state="confirmed";let r=this.opts.spawnTime;r!==void 0&&e.at!==void 0&&(e.leadMs=r(t)-e.at),this.byServer.set(t,e)}takeMatch(e){let t=this.correlate;if(typeof t!="function"){for(let r of this.byId.values())if(r.state==="pending")return r;return}for(let r of this.byId.values())if(r.state==="pending"&&t(r.local,e))return r}isOwned(e){return this.opts.owned?this.opts.owned(e):!0}makeData(){return this.opts.data?this.opts.data():void 0}tick(e=performance.now()){let t=this.opts.step,r=this.clock!==null?this.clock.serverNow():e;if(t!==void 0&&this.lastTickAt!==void 0){let s=Math.max(0,(r-this.lastTickAt)/1e3);if(s>0)for(let i of this.byId.values())i.state==="pending"&&t(i.local,s)}this.lastTickAt=r}prune(){if(this.byId.size===0)return;let e=this.now(),t=this.ttl(this.clock?.smoothedRtt()??0);for(let r of this.byId.values())r.state==="pending"&&!r.accepted&&r.at!==void 0&&e-r.at>t&&(this.byId.delete(r.id),this.opts.onReject?.(r.local,r.id))}entries(){return this.byId.values()}entryFor(e){return this.byServer.get(e)}value(e,t){return e.server!==void 0?this.readServer(e.server,t):e.local[t]}bindReader(e){this.readServer=e}alive(e){return this.byId.has(e)}get size(){return this.byId.size}clear(){this.byId.clear(),this.byServer.clear()}dispose(){this.dead=!0,this.detach?.(),this.detach=void 0,this.clear()}now(){return this.clock?.serverNow()??performance.now()}}});var oh,Yn,No=Oe(()=>{"use strict";Mo();ks();zc();oh=n=>typeof n=="number"?n:typeof n=="boolean"?n?1:0:NaN,Yn=class extends Br{constructor(t,r){super(r);l(this,"local",{});l(this,"fields");l(this,"numericFields",[]);l(this,"step");l(this,"instance");l(this,"wireRound",[]);l(this,"history");l(this,"historySeq");l(this,"historySize");l(this,"historyOn");l(this,"undeclared",null);l(this,"devView",null);this.instance=t;let s=r.fields,i=s??Ts(t).fields;if(s===void 0&&i.length===0)throw new Error("predict.reconciler(): no `fields` given and none derivable \u2014 the instance has no schema metadata (a plain object, or a schema with no scalar fields). Pass the decoded instance from room.state, or list `fields` explicitly.");this.fields=i,this.step=r.step;let o=this.fields.length>0;for(let a of this.fields){let c=t[a];this.local[a]=c,typeof c=="number"?(this.numericFields.push(a),this.prev[a]=c,this.error[a]=0):typeof c!="boolean"&&(o=!1),this.wireRound.push(cf(t,a))}if(this.historyOn=o,this.historySize=this.input_.replayBufferSize??64,this.history=new Float64Array(this.historyOn?this.historySize*this.fields.length:0),this.historySeq=new Float64Array(this.historyOn?this.historySize:0).fill(-1),s!==void 0){let a=new Set(this.fields),c=Ts(t).fields.filter(u=>!a.has(u));c.length>0&&(this.undeclared=new Set(c))}}get state(){return this.local}get boundRegistrations(){return[{source:this.instance,fields:this.numericFields,poseKeys:this.numericFields}]}value(t){this.noteRenderRead();let r=this.local[t];if(typeof r!="number")return r;let s=r+(this.error[t]??0),i=this.prev[t]??s;return i+(s-i)*this.renderAlpha()}smoothedFields(){return this.numericFields}readCurrent(t){return this.local[t]}applyStep(t){let r=this.undeclared!==null&&zs()?this.stepView():this.local;if(this.step(this.stepCtx,r,t),this.historyOn){let s=this.stepCtx.tick,i=s%this.historySize,o=i*this.fields.length;for(let a=0;a<this.fields.length;a++)this.history[o+a]=oh(this.local[this.fields[a]]);this.historySeq[i]=s}}stepView(){if(this.devView!==null)return this.devView;let t=this.undeclared,r=new Set,s=(i,o)=>{typeof o!="string"||!t.has(o)||r.has(o)||(r.add(o),console.warn(`@colyseus/sdk predict: step ${i} "${o}" \u2014 a schema field NOT in this reconciler's \`fields\` list, so it is never mirrored or replayed: prediction integrates on top of a stale value and rubber-bands under latency. Add "${o}" to \`fields\`, or omit \`fields\` to mirror every scalar field. Read adopt-only fields off the raw instance instead of the predicted state.`))};return this.devView=new Proxy(this.local,{get(i,o,a){return s("read",o),Reflect.get(i,o,a)},set(i,o,a,c){return s("wrote",o),Reflect.set(i,o,a,c)}}),this.devView}truthMatchesAt(t){if(!this.historyOn)return!1;let r=t%this.historySize;if(this.historySeq[r]!==t)return!1;let s=r*this.fields.length,i=this.instance;for(let o=0;o<this.fields.length;o++)if(this.wireRound[o](this.history[s+o])!==oh(i[this.fields[o]]))return!1;return!0}snapshotPrev(){for(let t of this.numericFields)this.prev[t]=this.local[t]+this.error[t]}adoptTruth(){let t=this.instance;for(let r of this.fields)this.local[r]=t[r]}reseedState(){let t=this.instance;for(let r of this.fields)this.local[r]=t[r];for(let r of this.numericFields)this.prev[r]=this.local[r],this.error[r]=0;this.historySeq.fill(-1)}}});var Xn,Bo=Oe(()=>{"use strict";Mo();ks();Xn=class extends Br{constructor(t){super(t);l(this,"worldHandle");l(this,"bindings",[]);l(this,"curPose",{});l(this,"poseFields",[]);l(this,"customFields",[]);l(this,"fieldsReady",!1);l(this,"poseA",{});l(this,"poseB",{});l(this,"renderPose",{});l(this,"poseDirty",!0);l(this,"step");l(this,"adopt");l(this,"readPose");l(this,"interpolate");let r=t.world;for(let s of Object.keys(r)){let i=r[s];if(i===null||typeof i!="object")continue;if(Ke(i)===void 0){if(Lt(i)!==void 0)throw new Error(`predict.sim(): world.${s} is a schema instance that hasn't been decoded (no refId). Pass the decoded instance from room.state (e.g. inside onAdd), or a plain object for opaque scratch.`);continue}let{fields:o,numeric:a}=Ts(i);if(o.length===0)throw new Error(`predict.sim(): world.${s} is a decoded ref with no scalar fields to bind. Binding a whole COLLECTION isn't supported (yet) \u2014 spread its children into world parts (one entry per entity, fixed at construction). Nest a scalar-less instance below a plain wrapper if you meant it as an opaque handle.`);let c={};for(let d of o)c[d]=i[d];r[s]=c;let u=a.map(d=>`${s}.${d}`);this.bindings.push({source:i,mirror:c,fields:o,numeric:a,poseKeys:u})}if(this.bindings.length===0&&t.adopt===void 0)throw new Error("predict.sim(): no restore point \u2014 world has no schema-bound entries and no adopt() was provided. Put decoded schema instances in world (auto-bound), or provide adopt().");this.worldHandle=t.world,this.step=t.step,this.adopt=t.adopt,this.readPose=t.pose,this.interpolate=t.interpolate,this.refreshPose();for(let s of this.poseFields)this.prev[s]=this.curPose[s],this.error[s]=0}refreshPose(){let t=this.curPose;for(let r of this.bindings){let{mirror:s,numeric:i,poseKeys:o}=r;for(let a=0;a<i.length;a++)t[o[a]]=s[i[a]]}if(this.readPose!==void 0){let r=this.readPose(this.worldHandle);this.fieldsReady||(this.customFields=Object.keys(r));for(let s of this.customFields)t[s]=r[s]}if(!this.fieldsReady){let r=[];for(let s of this.bindings)for(let i of s.poseKeys)r.push(i);for(let s of this.customFields)r.includes(s)||r.push(s);this.poseFields=r,this.fieldsReady=!0}this.poseDirty=!0}get world(){return this.worldHandle}get boundRegistrations(){return this.bindings.map(t=>({source:t.source,fields:t.numeric,poseKeys:t.poseKeys}))}value(t){if(this.noteRenderRead(),this.interpolate)return this.pose()[t];let r=this.curPose[t]+(this.error[t]??0),s=this.prev[t]??r;return s+(r-s)*this.renderAlpha()}pose(){if(this.noteRenderRead(),!this.poseDirty)return this.renderPose;let t=this.renderAlpha(),r=this.poseA,s=this.poseB;for(let i of this.poseFields)r[i]=this.prev[i]??this.curPose[i],s[i]=this.curPose[i]+(this.error[i]??0);if(this.interpolate){let i=this.interpolate(r,s,t);for(let o of this.poseFields)this.renderPose[o]=i[o]}else for(let i of this.poseFields)this.renderPose[i]=r[i]+(s[i]-r[i])*t;return this.poseDirty=!1,this.renderPose}smoothedFields(){return this.poseFields}readCurrent(t){return this.curPose[t]}applyStep(t){this.step(this.stepCtx,this.worldHandle,t)}adoptTruth(){for(let t of this.bindings){let{source:r,mirror:s,fields:i}=t;for(let o=0;o<i.length;o++)s[i[o]]=r[i[o]]}this.adopt?.(this.worldHandle)}refreshRender(){this.refreshPose()}markDirty(){this.poseDirty=!0}snapshotPrev(){for(let t of this.poseFields)this.prev[t]=this.curPose[t]+this.error[t]}reseedState(){this.adoptTruth(),this.refreshPose();for(let t of this.poseFields)this.prev[t]=this.curPose[t],this.error[t]=0}}});function ah(n,e,t,r){let s=[];if(t.field!==void 0){let i=new Map;s.push(n.onAdd(t.collection,(o,a)=>{i.has(o)||i.set(o,n.listen(o,t.field,c=>{c===t.equals&&e.confirm(a)},!1))})),s.push(n.onRemove(t.collection,o=>{i.get(o)?.(),i.delete(o)})),s.push(()=>{for(let o of i.values())o();i.clear()})}else t.event==="remove"?s.push(n.onRemove(t.collection,(i,o)=>{e.confirm(o)})):s.push(n.onAdd(t.collection,i=>{t.mine!==void 0&&i[t.mine]!==r?.()||e.confirm()},!1));return()=>{for(let i of s.splice(0))i?.()}}var ch=Oe(()=>{"use strict"});function uh(n){return n===null||typeof n!="object"?!1:Array.isArray(n.fields)}function l0(){dh||(dh=!0,console.warn("@colyseus/sdk Predict: room.clock isn't server-synced because the server room didn't call defineInput(). Server-time interpolation and lag compensation fall back to local time. Add defineInput() on the server room to enable them \u2014 or ignore this if you only need local smoothing."))}var Me,ct,ht,on,vt,Ws,Js,Fr,Ur,$r,Ks,je,i0,o0,lh,Qe,Vr,Qn,Zn,jr,qr,Gr,Hr,jt,Ys,Uo,$o,Vo,a0,Lo,Xc,kn,Fo,c0,dh,zr,Xs,Qc=Oe(()=>{"use strict";He();Yc();Do();No();Bo();Ec();Oo();fo();xs();ks();ch();Me=16,ct=0,ht=1,on=2,vt=3,Ws=4,Js=5,Fr=6,Ur=7,$r=8,Ks=9,je=Ks+Me*2,i0=3,o0=1.5,lh=250,Qe=7,Vr=0,Qn=1,Zn=2,jr=3,qr=4,Gr=5,Hr=6,jt=0,Ys=0,Uo=1,$o=2,Vo=3,a0=4,Lo=5,Xc={lerp:Ys,extrapolate:Uo,damped:$o,reckon:Vo,raw:a0},kn={mode:"lerp",delay:100,smoothMs:50,maxExtrapolate:200,tickInterval:0,snap:0,angle:!1},Fo={step:void 0,smoothMs:50,substep:16,snap:0};c0=0,dh=!1;zr=class zr{constructor(e,t){l(this,"callbacks");l(this,"sessionSource");l(this,"slotBuf",new Float64Array(64*je));l(this,"slotCount",0);l(this,"slotDetach",[]);l(this,"slotAngle",[]);l(this,"freeSlots",[]);l(this,"slotByRef",new Map);l(this,"simByRef",new Map);l(this,"boundBySlot",new Map);l(this,"boundProfileIdx",-1);l(this,"renderTime",0);l(this,"defaultMode");l(this,"reckonDefaults");l(this,"clock");l(this,"useRenderClock",!1);l(this,"fixedStepMs");l(this,"stepAcc",0);l(this,"lastFrameNow",-1);l(this,"profileBuf",new Float64Array(8*Qe));l(this,"profileCount",0);l(this,"profileKeys",new Map);l(this,"profileLabels",[]);l(this,"profileComputers",[]);l(this,"trackListeners",[]);l(this,"name");l(this,"disposeListeners",[]);l(this,"driven",[]);l(this,"computeDamped",e=>{let t=this.slotBuf,r=e*je,s=this.profileBuf,i=(t[r+vt]|0)*Qe,o=this.renderTime,a=t[r+ct],c=t[r+on],u=o-c;t[r+on]=o;let d=t[r+ht];if(u>0){let h=s[i+Zn],m=h>0?1-Math.exp(-u/h):1;d+=(a-d)*m,t[r+ht]=d}return d});l(this,"computeLerp",e=>{let t=this.computeLerpRaw(e),r=this.slotBuf,s=e*je,i=this.profileBuf[(r[s+vt]|0)*Qe+Hr],o=this.renderTime;if(i<=0)return r[s+ht]=t,r[s+$r]=t,r[s+on]=o,t;let a=r[s+on],c=o-a;if(c<=0)return r[s+ht];let u=r[s+$r],d=r[s+ht],h=c/i,m=(t-u)/h,g=t-m+(d-u+m)*Math.exp(-h);return r[s+ht]=g,r[s+$r]=t,r[s+on]=o,g});l(this,"computeExtrapolate",e=>{let t=this.slotBuf,r=e*je,s=this.profileBuf,i=(t[r+vt]|0)*Qe,o=this.renderTime,a=t[r+Ur]|0;if(a===0)return t[r+ct];let c=t[r+Fr]|0,u=r+Ks,d=(c-a+Me)%Me,h=(d+a-1)%Me,m=u+h*2,g=t[m],p=t[m+1],y;if(a===1)y=p;else{let N=a>=3?2:1,C=(d+a-1-N+Me)%Me,O=u+C*2,A=t[O],P=t[O+1],V=g-A;if(V<=0)y=p;else{let Z=(p-P)/V,ee=s[i+jr],ve=o-g;ve<0?ve=0:ve>ee&&(ve=ee),y=p+Z*ve}}let x=t[r+on];t[r+on]=o;let k=s[i+Zn];if(k<=0)return t[r+ht]=y,y;let I=o-x,L=t[r+ht];if(I>0){let N=1-Math.exp(-I/k);L+=(y-L)*N,t[r+ht]=L}return L});l(this,"computeReckon",e=>{let t=this.slotBuf,r=e*je,s=t[r+Ws],i=t[r+Js]|0,o=this.simByRef.get(s);if(o!==void 0){let a=i<o.posOf.length?o.posOf[i]:-1;if(a>=0)return this.applySimulation(o,a)}return t[r+ct]});l(this,"computeRaw",e=>this.slotBuf[e*je+ct]);l(this,"computeBound",e=>{let t=this.boundBySlot.get(e);return t!==void 0?t.ctrl.value(t.key):this.slotBuf[e*je+ct]});this.callbacks=bc.get(e),this.sessionSource=e;let{clock:r,...s}=t;this.defaultMode=s.mode??"lerp";let i=this.defaultMode!=="reckon"&&this.defaultMode!=="raw",o=i?(()=>{let u=s;return{mode:u.mode??kn.mode,delay:u.delay??kn.delay,smoothMs:u.smoothMs??kn.smoothMs,maxExtrapolate:u.maxExtrapolate??kn.maxExtrapolate,tickInterval:u.tickInterval??kn.tickInterval,snap:u.snap??kn.snap,angle:u.angle??kn.angle}})():{...kn},a=i?s.smoothMs??0:0;if(this.allocProfile(this.defaultMode,o.delay,o.smoothMs,a,o.maxExtrapolate,o.tickInterval,o.snap,!1)!==jt)throw new Error("Predict: defaults profile must be at index 0");if(this.defaultMode==="reckon"){let u=s;this.reckonDefaults={step:u.step,smoothMs:u.smoothMs??Fo.smoothMs,substep:u.substep??Fo.substep,snap:u.snap??Fo.snap}}else this.reckonDefaults={...Fo};this.clock=r??e.clock??void 0,this.useRenderClock=s.renderPresent!==!1,this.clock===Rr&&l0(),this.name=s.name??`predict#${++c0}`,ao("predict",this.makeCoreHandle())}static get(e,t={}){return new zr(e,t)}get mode(){return this.defaultMode}presentFn(){let e=this.clock;if(e)return this.useRenderClock&&e.renderNow?e.renderNow.bind(e):e.serverNow.bind(e)}makeCoreHandle(){return{name:this.name,mode:()=>this.defaultMode,smoothingDefaults:()=>this.readSmoothingDefaults(),reckonDefaults:()=>({...this.reckonDefaults}),reconcilers:()=>this.snapshotReconcilers(),attachedCount:()=>this.slotByRef.size,setDefaults:e=>this.setDefaults(e),profiles:()=>this.snapshotProfiles(),setProfile:(e,t)=>this.setProfile(e,t),onTrack:e=>(this.trackListeners.push(e),()=>{let t=this.trackListeners.indexOf(e);t>=0&&this.trackListeners.splice(t,1)}),onDispose:e=>(this.disposeListeners.push(e),()=>{let t=this.disposeListeners.indexOf(e);t>=0&&this.disposeListeners.splice(t,1)})}}snapshotReconcilers(){let e=[],t=0;for(let r of this.driven){let s=r;if(!s.drift)continue;let i=s.warnTolerance;e.push({label:`reconciler #${t++}`,status:Nr(s.drift,i),severity:i!==void 0&&i>0?s.drift.ema/i:void 0,ema:s.drift.ema,peak:s.drift.peak,lastCorrectionMag:s.lastCorrectionMag??0,reconcileSeq:s.reconcileSeq??0})}return e}readSmoothingDefaults(){let e=this.profileBuf,t=jt*Qe,r=e[t+Vr]|0;return{mode:r===Ys?"lerp":r===Uo?"extrapolate":r===$o?"damped":r===Vo?"reckon":"raw",delay:e[t+Qn],smoothMs:e[t+Zn],lerpSmoothMs:e[t+Hr],maxExtrapolate:e[t+jr],tickInterval:e[t+qr],snap:e[t+Gr]}}allocProfile(e,t,r,s,i,o,a,c,u){let d=typeof e=="number"?e:Xc[e],h="";if(c){h=`${u??""}|${d}|${t}|${r}|${s}|${i}|${o}|${a}`;let y=this.profileKeys.get(h);if(y!==void 0)return y}let m=this.profileCount++;if((m+1)*Qe>this.profileBuf.length){let y=new Float64Array(this.profileBuf.length*2);y.set(this.profileBuf),this.profileBuf=y}let p=m*Qe;return this.profileBuf[p+Vr]=d,this.profileBuf[p+Qn]=t,this.profileBuf[p+Zn]=r,this.profileBuf[p+Hr]=s,this.profileBuf[p+jr]=i,this.profileBuf[p+qr]=o,this.profileBuf[p+Gr]=a,this.profileLabels[m]=u,this.profileComputers[m]=this.computerForMode(d),c&&this.profileKeys.set(h,m),m}computerForMode(e){return e===Ys?this.computeLerp:e===Uo?this.computeExtrapolate:e===$o?this.computeDamped:e===Vo?this.computeReckon:e===Lo?this.computeBound:this.computeRaw}profileFromOpts(e){if(e.mode===void 0&&e.delay===void 0&&e.smoothMs===void 0&&e.maxExtrapolate===void 0&&e.tickInterval===void 0&&e.snap===void 0)return jt;let t=this.readSmoothingDefaults(),r=e.mode??t.mode,s=e.delay??t.delay,i=e.smoothMs??t.smoothMs,o=e.smoothMs??t.lerpSmoothMs,a=e.maxExtrapolate??t.maxExtrapolate,c=e.tickInterval??t.tickInterval,u=e.snap??t.snap;return r===t.mode&&s===t.delay&&i===t.smoothMs&&o===t.lerpSmoothMs&&a===t.maxExtrapolate&&c===t.tickInterval&&u===t.snap?jt:this.allocProfile(r,s,i,o,a,c,u,!0)}groupProfile(e,t){let r=this.readSmoothingDefaults(),s=e.mode??this.defaultMode;return this.allocProfile(s,e.delay??r.delay,e.smoothMs??r.smoothMs,e.smoothMs??r.lerpSmoothMs,e.maxExtrapolate??r.maxExtrapolate,e.tickInterval??r.tickInterval,e.snap??r.snap,!0,t)}setDefaults(e){let t=e.mode;if(t!==void 0){this.defaultMode=t;let a=jt*Qe,c=Xc[t];this.profileBuf[a+Vr]=c,this.profileComputers[jt]=this.computerForMode(c)}let r=e,s=jt*Qe,i=this.profileBuf;r.delay!==void 0&&(i[s+Qn]=r.delay),r.smoothMs!==void 0&&(i[s+Zn]=r.smoothMs,i[s+Hr]=r.smoothMs),r.maxExtrapolate!==void 0&&(i[s+jr]=r.maxExtrapolate),r.tickInterval!==void 0&&(i[s+qr]=r.tickInterval),r.snap!==void 0&&(i[s+Gr]=r.snap,this.reckonDefaults.snap=r.snap);let o=e;o.step!==void 0&&(this.reckonDefaults.step=o.step),o.smoothMs!==void 0&&(this.reckonDefaults.smoothMs=o.smoothMs),o.substep!==void 0&&(this.reckonDefaults.substep=o.substep)}snapshotProfiles(){let e=[];for(let t=0;t<this.profileCount;t++){let r=t*Qe,s=this.profileBuf[r+Vr]|0;if(s===Lo)continue;let i=s===Ys?"lerp":s===Uo?"extrapolate":s===$o?"damped":s===Vo?"reckon":"raw";e.push({id:t,isDefault:t===jt,label:this.profileLabels[t],mode:i,delay:this.profileBuf[r+Qn],smoothMs:this.profileBuf[r+(s===Ys?Hr:Zn)],maxExtrapolate:this.profileBuf[r+jr],tickInterval:this.profileBuf[r+qr],snap:this.profileBuf[r+Gr]})}return e}setProfile(e,t){if(e<0||e>=this.profileCount)return;let r=e*Qe,s=this.profileBuf;if((s[r+Vr]|0)!==Lo){if(t.mode!==void 0){let i=Xc[t.mode];s[r+Vr]=i,this.profileComputers[e]=this.computerForMode(i),e===jt&&(this.defaultMode=t.mode)}t.delay!==void 0&&(s[r+Qn]=t.delay),t.smoothMs!==void 0&&(s[r+Zn]=t.smoothMs,s[r+Hr]=t.smoothMs),t.maxExtrapolate!==void 0&&(s[r+jr]=t.maxExtrapolate),t.tickInterval!==void 0&&(s[r+qr]=t.tickInterval),t.snap!==void 0&&(s[r+Gr]=t.snap)}}dispose(){for(let e of new Set([...this.slotByRef.keys(),...this.simByRef.keys()]))this.detachByRef(e);this.trackListeners.length=0;for(let e of this.driven.splice(0))e.dispose?.();for(let e of this.disposeListeners.splice(0))e()}track(e,t,r={}){return this.trackWithProfile(e,t,this.profileFromOpts(r),r.angle??!1)}trackWithProfile(e,t,r,s=!1){let i=Ke(e);if(i===void 0)throw new Error("Predict.track(): instance has no refId \u2014 track/attach must run AFTER the decoder delivers the instance (e.g. inside onAdd).");let o=Ss(e,t),a=e[t]??0,c,u=this.slotByRef.get(i)?.get(t);u!==void 0&&(c=this.boundBySlot.get(u),c!==void 0?this.freeStash(c):this.untrackSlot(i,t));let d=this.allocSlot(),h=this.slotBuf,m=d*je;if(h[m+ct]=a,h[m+ht]=a,h[m+on]=performance.now(),h[m+$r]=a,h[m+vt]=r,h[m+Ws]=i,h[m+Js]=o,h[m+Fr]=0,h[m+Ur]=0,this.slotAngle[d]=s,c!==void 0)c.stash=d;else{let p=this.slotByRef.get(i);p===void 0&&(p=new Map,this.slotByRef.set(i,p)),p.set(t,d)}for(let p=0;p<this.trackListeners.length;p++)this.trackListeners[p](r,t);let g=this.callbacks.listen(e,t,p=>{let y=this.clock&&this.clock.lastServerTime()>0?this.clock.lastServerTime():performance.now(),x=this.slotBuf,k=d*je;if(s){let ee=x[k+ct];p=ee+Math.atan2(Math.sin(p-ee),Math.cos(p-ee))}let I=(x[k+vt]|0)*Qe,L=this.profileBuf[I+qr],N=x[k+Fr]|0,C=x[k+Ur]|0,O=this.profileBuf[I+Gr];O>0&&C>0&&Math.abs(p-x[k+ct])>O&&(N=0,C=0,x[k+ht]=p,x[k+$r]=p);let A=C===0?Number.NEGATIVE_INFINITY:x[k+Ks+(N===0?Me-1:N-1)*2],P=y;if(L>0&&isFinite(A)){let ee=y-A,ve=ee>0?Math.max(1,Math.round(ee/L)):1;P=A+ve*L;let Pe=y+L;P>Pe&&(P=Pe)}x[k+ct]=p;let V=k+Ks;if(C>=2&&isFinite(A)){let ee=N===0?Me-1:N-1,ve=ee===0?Me-1:ee-1,Pe=A-x[V+ve*2],S=this.clock?.patchInterval?this.clock.patchInterval():0,F=S>0?S:Pe,B=S>0?o0*S:i0*Pe;if(F>0&&P-A>B){let D=F<lh?F:lh,M=V+N*2;x[M]=P-D,x[M+1]=x[V+ee*2+1],N=N+1>=Me?0:N+1,C<Me&&C++}}let Z=V+N*2;x[Z]=P,x[Z+1]=p,x[k+Fr]=N+1>=Me?0:N+1,C<Me&&(x[k+Ur]=C+1)},!0);return this.slotDetach[d]=g,()=>this.untrackSlot(i,t)}untrack(e,t){let r=Ke(e);r!==void 0&&this.untrackSlot(r,t)}untrackSlot(e,t){let r=this.slotByRef.get(e),s=r?.get(t);if(s===void 0)return;let i=this.boundBySlot.get(s);if(i!==void 0){this.freeStash(i);return}this.slotDetach[s]?.(),this.slotDetach[s]=void 0,this.freeSlots.push(s),r.delete(t),r.size===0&&this.slotByRef.delete(e)}freeStash(e){e.stash<0||(this.slotDetach[e.stash]?.(),this.slotDetach[e.stash]=void 0,this.freeSlots.push(e.stash),e.stash=-1)}allocSlot(){if(this.freeSlots.length>0)return this.freeSlots.pop();let e=this.slotCount++;if((e+1)*je>this.slotBuf.length){let r=new Float64Array(this.slotBuf.length*2);r.set(this.slotBuf),this.slotBuf=r}return e}registerBound(e,t,r,s,i){let o=Ke(t),a=this.slotByRef.get(o);a===void 0&&(a=new Map,this.slotByRef.set(o,a));let c=[];for(let u=0;u<r.length;u++){let d=r[u],h=a.get(d),m=-1;if(h!==void 0){let k=this.boundBySlot.get(h);k!==void 0?(console.warn(`@colyseus/sdk Predict: "${d}" (refId ${o}) is already bound to a controller \u2014 the newer registration wins.`),m=k.stash,this.boundBySlot.delete(h),this.freeSlots.push(h)):m=h}let g=this.allocSlot(),p=this.slotBuf,y=g*je,x=t[d]??0;p[y+ct]=x,p[y+ht]=x,p[y+on]=0,p[y+$r]=x,p[y+vt]=i,p[y+Ws]=o,p[y+Js]=Ss(t,d),p[y+Fr]=0,p[y+Ur]=0,this.slotAngle[g]=!1,this.boundBySlot.set(g,{ctrl:e,key:s[u],stash:m}),a.set(d,g),c.push(g);for(let k=0;k<this.trackListeners.length;k++)this.trackListeners[k](i,d)}return()=>{for(let u=0;u<c.length;u++){let d=c[u],h=this.boundBySlot.get(d);if(h===void 0||h.ctrl!==e)continue;this.boundBySlot.delete(d),this.freeSlots.push(d);let m=this.slotByRef.get(o);m?.get(r[u])===d&&(h.stash>=0?m.set(r[u],h.stash):(m.delete(r[u]),m.size===0&&this.slotByRef.delete(o)))}}}installBoundOverlay(e){let t=[];for(let r of e.boundRegistrations)r.fields.length===0||Ke(r.source)===void 0||(this.boundProfileIdx<0&&(this.boundProfileIdx=this.allocProfile(Lo,0,0,0,0,0,0,!1,"bound")),t.push(this.registerBound(e,r.source,r.fields,r.poseKeys,this.boundProfileIdx)));t.length>0&&e.onDisposed(()=>{for(let r of t)r()})}trackStepped(e,t){let r=t.substep??16,s=t.fields,i=s.map(p=>Ss(e,p)),o=t.step,a=this.clock,c=this.presentFn(),u=t.forwardMs??(c?()=>{let p=a.lastServerTime();return p>0?Math.max(0,c()-p):0}:()=>0),d=t.elapsedMs??c??(()=>performance.now()),h=e[lo],m=t.snapshot===void 0&&Array.isArray(h)&&i.every(p=>p>=0&&p<h.length),g;if(m){let p=new e.constructor,y=p[lo];g=(x,k,I,L)=>{let N=x[lo];for(let A=0;A<N.length;A++)y[A]=N[A];let C=k,O=L-k;for(;C>0;){let A=C<r?C:r;O+=A,o(p,A/1e3,O),C-=A}for(let A=0;A<i.length;A++)I[A]=y[i[A]]}}else{let p=af(e),y=t.snapshot??(p.length>0?lf(p):k=>({...k})),x=[...s];g=(k,I,L,N)=>{let C=y(k),O=I,A=N-I;for(;O>0;){let P=O<r?O:r;A+=P,o(C,P/1e3,A),O-=P}for(let P=0;P<x.length;P++)L[P]=C[x[P]]}}return this.trackSimulated(e,{fields:s,forwardMs:u,elapsedMs:d,smoothMs:t.smoothMs,snap:t.snap,advance:g})}trackSimulated(e,t){let r=Ke(e);if(r===void 0)throw new Error("Predict.trackStepped(): instance has no refId \u2014 must run AFTER the decoder delivers the instance (e.g. inside onAdd).");let s=t.fields,i=s.length,o=s.map(g=>Ss(e,g)),a=0;for(let g of o)g>a&&(a=g);let c=new Int8Array(a+1).fill(-1);for(let g=0;g<i;g++)o[g]>=0&&(c[o[g]]=g);let u=new Float64Array(i);for(let g=0;g<i;g++)u[g]=e[s[g]]??0;let d=this.presentFn(),h=t.elapsedMs??d??(()=>performance.now()),m={instance:e,fieldIds:o,posOf:c,forwardMs:t.forwardMs,elapsedMs:h,advance:t.advance,smoothMs:t.smoothMs??50,snap:t.snap??0,smoothed:u,out:new Float64Array(i),valueOut:new Float64Array(i),offset:new Float64Array(i),outPrev:new Float64Array(i),frameVel:new Float64Array(i),lastBaseT:NaN,lastApplyTime:-1/0};return this.simByRef.set(r,m),()=>this.untrackSimulated(r)}untrackSimulated(e){this.simByRef.delete(e)}attach(e,t){let r=this.makeGroup("(attach)",t);return this.attachWithPlan(e,this.planFor(r,e))}makeGroup(e,t){return{label:e,config:t,basePlan:this.buildGroupPlan(t,e),planByCtor:new Map}}planFor(e,t){let r=t.constructor,s=e.planByCtor.get(r);return s===void 0&&(s=this.resolveCtorPlan(e,t),e.planByCtor.set(r,s)),s}resolveCtorPlan(e,t){let r=Lt(t),s=t.constructor?.name||"?",i=e.config;if(!uh(i)){if(r===void 0)return e.basePlan;let c=Object.keys(i).filter(d=>i[d]!==void 0);if(c.every(d=>typeof r[d]=="number"))return e.basePlan;let u={};for(let d of c)typeof r[d]=="number"&&(u[d]=i[d]);return this.buildGroupPlan(u,`${e.label}:${s}`)}let o=i,a=o.fields;if(r!==void 0){let c=a.filter(u=>typeof r[u]=="number");c.length!==a.length&&(a=c)}return a===o.fields?e.basePlan:this.buildGroupPlan({...o,fields:a},`${e.label}:${s}`)}buildGroupPlan(e,t){let r=[];if(uh(e)){let i=e;if(!Array.isArray(i.fields))throw new Error("Predict.attach(): `fields` must be a numeric-key array.");let o=i.mode??this.defaultMode,a=i.step??this.reckonDefaults.step,c=o==="reckon";if(c&&typeof a!="function")throw new Error("Predict.attach(): reckon mode requires a 'step' function. Either pass `step` in the attach config OR construct the Predict with `Predict.get(room, { mode: 'reckon', step: yourStepFn })` so it can be inherited.");let u=this.groupProfile({mode:o,snap:i.snap,smoothMs:i.smoothMs},t);for(let d of i.fields)r.push({field:d,profileIdx:u,angle:i.angle});return{label:t,isReckon:c,reckonFields:c?i.fields:void 0,reckonStep:c?a:void 0,reckonSmoothMs:i.smoothMs??this.reckonDefaults.smoothMs,reckonSubstep:i.substep??this.reckonDefaults.substep,reckonSnap:i.snap??this.reckonDefaults.snap,reckonSnapshot:i.snapshot,fieldProfiles:r}}let s=e;for(let i of Object.keys(s)){let o=s[i];if(o===void 0)continue;let a=typeof o=="string"?{mode:o}:o;r.push({field:i,profileIdx:this.groupProfile(a,t),angle:a.angle})}return{label:t,isReckon:!1,fieldProfiles:r}}attachToGroup(e,t,r){let s=[];t.isReckon&&s.push(this.trackStepped(e,{fields:t.reckonFields,step:t.reckonStep,smoothMs:t.reckonSmoothMs,substep:t.reckonSubstep,snap:t.reckonSnap,snapshot:t.reckonSnapshot,forwardMs:r}));for(let{field:i,profileIdx:o,angle:a}of t.fieldProfiles)s.push(this.trackWithProfile(e,i,o,!!a));return()=>{for(let i of s)i()}}attachWithPlan(e,t){let r=Ke(e);if(r===void 0)throw new Error("Predict.attach(): instance has no refId \u2014 attach must run AFTER the decoder delivers the instance (e.g. inside onAdd).");return this.attachToGroup(e,t),()=>this.detachByRef(r)}detach(e){let t=Ke(e);t!==void 0&&this.detachByRef(t)}detachByRef(e){let t=this.slotByRef.get(e);if(t){for(let r of[...t.keys()]){let s=t.get(r);if(s===void 0)continue;let i=this.boundBySlot.get(s);i!==void 0?(this.freeStash(i),this.boundBySlot.delete(s),this.freeSlots.push(s),t.delete(r)):this.untrackSlot(e,r)}t.size===0&&this.slotByRef.delete(e)}this.simByRef.delete(e)}attachAll(...e){let t=typeof e[0]=="string",r=t?void 0:e[0],s=t?e[0]:e[1],i=t?e[1]:e[2],o=this.makeGroup(s,i),a=new Set,c=m=>{this.attachWithPlan(m,this.planFor(o,m)),a.add(m)},u=m=>{a.delete(m),this.detach(m)},d=t?this.callbacks.onAdd(s,c):this.callbacks.onAdd(r,s,c),h=t?this.callbacks.onRemove(s,u):this.callbacks.onRemove(r,s,u);return()=>{d?.(),h?.();for(let m of a)this.detach(m);a.clear()}}tick(e=performance.now()){this.renderTime=e;let t=0,r=this.fixedStepMs;if(r!==void 0&&r>0){let o=this.lastFrameNow<0?0:e-this.lastFrameNow;this.stepAcc+=o,t=Math.floor(this.stepAcc/r),t>zr.MAX_STEPS_PER_FRAME?(this.stepAcc=0,t=zr.MAX_STEPS_PER_FRAME):this.stepAcc-=t*r}this.lastFrameNow=e;let s=this.driven,i=0;for(let o=0;o<s.length;o++){let a=s[o];a.dead||(a.tick?.(e),a.prune?.(),i!==o&&(s[i]=a),i++)}return i!==s.length&&(s.length=i),t}defineEvent(e){let{confirmOn:t,...r}=e,s=new Lr(r,this.clock??null);if(t!==void 0){if(t.mine!==void 0&&typeof this.sessionSource.sessionId!="string")throw new Error(`Predict.defineEvent: confirmOn.mine ("${t.mine}") requires a Predict built from a Room (it compares against room.sessionId); confirm manually instead.`);s._addTeardown(ah(this.callbacks,s,t,()=>this.sessionSource.sessionId))}return this.driven.push(s),s}spawns(e,t={}){let r=new Kn(t,this.clock??null),s=t.fields,i=t.step,o=s!==void 0&&i!==void 0?this.makeGroup(String(e),{mode:"reckon",fields:s,step:i,smoothMs:t.smoothMs??0,substep:t.substep}):void 0,a=o!==void 0?new Map:void 0,c=this.clock;return r.attach((u,d)=>{let h=this.callbacks.onAdd(e,(g,p)=>{if(u(g,p),o===void 0||a.has(g))return;let y=r.entryFor(g)?.leadMs??0,x=c?()=>{let k=c.lastServerTime(),I=k>0?Math.max(0,c.serverNow()-k):0;return Math.max(0,I+y)}:()=>Math.max(0,y);a.set(g,this.attachToGroup(g,this.planFor(o,g),x))}),m=this.callbacks.onRemove(e,(g,p)=>{a?.get(g)?.(),a?.delete(g),d(g,p)});return()=>{if(h?.(),m?.(),a!==void 0){for(let g of a.values())g();a.clear()}}}),o!==void 0&&r.bindReader((u,d)=>this.value(u,d)),this.driven.push(r),r}canonicalDelay(){return this.profileBuf[jt*Qe+Qn]}bindInputRenderDelay(e){e instanceof Er&&e.bindRenderDelay(()=>this.canonicalDelay())}reconciler(e,t){let r=new Yn(e,{...t,clock:t.clock??this.clock});return this.adoptFixedStep(r.stepMs),this.bindInputRenderDelay(t.input),this.installBoundOverlay(r),this.driven.push(r),r}sim(e){let t=new Xn({...e,clock:e.clock??this.clock});return this.adoptFixedStep(t.stepMs),this.bindInputRenderDelay(e.input),this.installBoundOverlay(t),this.driven.push(t),t}adoptFixedStep(e){if(this.fixedStepMs===void 0){this.fixedStepMs=e,this.stepAcc=0,this.lastFrameNow=-1;return}Math.abs(this.fixedStepMs-e)>1e-6&&console.warn(`@colyseus/sdk Predict: a reconciler's fixed step (${e}ms) differs from this Predict's (${this.fixedStepMs}ms). tick() paces one rate for the whole room; use a separate Predict per rate.`)}value(e,t){let r=Ke(e),s=r===void 0?void 0:this.slotByRef.get(r)?.get(t);if(s===void 0)return e[t];let i=this.slotBuf[s*je+vt]|0;return this.profileComputers[i](s)}valueAt(e,t,r){let s=Ke(e),i=s===void 0?void 0:this.slotByRef.get(s)?.get(t);if(i===void 0)return e[t];let o=i*je,a=this.slotBuf[o+vt]|0;if(this.profileComputers[a]!==this.computeReckon)return this.profileComputers[a](i);let c=this.simByRef.get(this.slotBuf[o+Ws]);if(c!==void 0){let u=this.slotBuf[o+Js]|0,d=u<c.posOf.length?c.posOf[u]:-1;if(d>=0){let h=this.clock?.lastServerTime?.()??NaN,m=Number.isNaN(h)?0:Math.max(0,r-h);return c.advance(c.instance,m,c.valueOut,r),c.valueOut[d]}}return this.slotBuf[o+ct]}read(e,t,r){let s=r??{},i=Ke(e),o=i===void 0?void 0:this.slotByRef.get(i);for(let a=0;a<t.length;a++){let c=t[a],u=o?.get(c);s[c]=u===void 0?e[c]:this.profileComputers[this.slotBuf[u*je+vt]|0](u)}return s}readAt(e,t,r,s){let i=s??{},o=Ke(e),a=o===void 0?void 0:this.slotByRef.get(o),c,u=!1;for(let d=0;d<t.length;d++){let h=t[d],m=a?.get(h);if(m===void 0){i[h]=e[h];continue}let g=m*je,p=this.slotBuf[g+vt]|0;if(this.profileComputers[p]!==this.computeReckon){i[h]=this.profileComputers[p](m);continue}if(!u&&(u=!0,c=this.simByRef.get(this.slotBuf[g+Ws]),c!==void 0)){let y=this.clock?.lastServerTime?.()??NaN,x=Number.isNaN(y)?0:Math.max(0,r-y);c.advance(c.instance,x,c.valueOut,r)}if(c!==void 0){let y=this.slotBuf[g+Js]|0,x=y<c.posOf.length?c.posOf[y]:-1;if(x>=0){i[h]=c.valueOut[x];continue}}i[h]=this.slotBuf[g+ct]}return i}computeLerpRaw(e){let t=this.slotBuf,r=e*je,s=this.profileBuf,i=(t[r+vt]|0)*Qe,o=this.renderTime,a=t[r+Ur]|0;if(a===0)return t[r+ct];let c=t[r+Fr]|0,u=r+Ks,d=(c-a+Me)%Me,h=(d+a-1)%Me,m=u+h*2;if(a===1)return t[m+1];let g=s[i+Qn],p=this.clock&&this.clock.lastServerTime()>0?this.clock.serverNow()-g-this.clock.smoothedRtt()/2:o-g,y=u+d*2;if(p<=t[y])return t[y+1];if(p>=t[m])return t[m+1];let x=a-2,k=(d+x)%Me;for(;x>0&&!(t[u+k*2]<=p);)x--,k=k===0?Me-1:k-1;let I=u+k*2,L=k+1>=Me?0:k+1,N=u+L*2,C=t[I],A=t[N]-C;if(A<=0)return t[N+1];let P=(p-C)/A,V=t[I+1],Z=t[N+1];return V+(Z-V)*P}applySimulation(e,t){let r=this.renderTime;if(e.lastApplyTime!==r){let s=e.out,i=e.smoothed,o=e.offset,a=i.length,c=this.clock?.lastServerTime?.()??NaN;if(e.advance(e.instance,e.forwardMs(),s,e.elapsedMs()),e.lastApplyTime===-1/0||e.smoothMs<=0)for(let h=0;h<a;h++)o[h]=0,i[h]=s[h];else if(Number.isNaN(c)){let h=Math.max(0,Math.min(r-e.lastApplyTime,100)),m=1-Math.exp(-h/e.smoothMs);for(let g=0;g<a;g++)i[g]+=(s[g]-i[g])*m}else{let h=Math.max(0,Math.min(r-e.lastApplyTime,100));if(c!==e.lastBaseT&&!Number.isNaN(e.lastBaseT)){let g=e.snap,p=e.frameVel;for(let y=0;y<a;y++){let x=i[y]+p[y]*h-s[y];o[y]=g>0&&Math.abs(x)>g?0:x}}else if(h>0){let g=e.outPrev,p=e.frameVel;for(let y=0;y<a;y++)p[y]=(s[y]-g[y])/h}let m=Math.exp(-h/e.smoothMs);for(let g=0;g<a;g++)o[g]*=m,i[g]=s[g]+o[g]}let d=e.outPrev;for(let h=0;h<a;h++)d[h]=s[h];e.lastBaseT=c,e.lastApplyTime=r}return e.smoothed[t]}};l(zr,"MAX_STEPS_PER_FRAME",5);Xs=zr});var Mh={};Dl(Mh,{DEFAULT_GRACE_TICKS:()=>Kc,Predict:()=>Xs,PredictedEventChannel:()=>Lr,PredictedSpawns:()=>Kn,Reconciler:()=>Yn,SimReconciler:()=>Xn,classifyDrift:()=>Nr});var Dh=Oe(()=>{"use strict";Qc();No();Oo();Bo();Yc();Do()});var es="genex-native";var hi="genex_native";var pi="genex_protocol",mi="genex_attempt",gi="genex_nonce",pa="genex_caps";var sr="genex_";var ma="genex_r";var ga="entryRef",ya="genex_hash",ba="genex_referrer",wa="genex_ref";var yi="__genexNative";var bp=/^[0-9a-f]{32}$/,wp=/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;function Jt(n){return typeof n=="string"&&bp.test(n)}function _a(n){return typeof n=="string"&&wp.test(n)}var ir="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",_p=(()=>{let n=new Array(128).fill(-1);for(let e=0;e<ir.length;e++)n[ir.charCodeAt(e)]=e;return n})();function Nl(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);if(r>=55296&&r<=56319){let s=t+1<n.length?n.charCodeAt(t+1):0;s>=56320&&s<=57343?(r=65536+(r-55296<<10)+(s-56320),t++):r=65533}else r>=56320&&r<=57343&&(r=65533);r<128?e.push(r):r<2048?e.push(192|r>>6,128|r&63):r<65536?e.push(224|r>>12,128|r>>6&63,128|r&63):e.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return e}function Ep(n){let e="";for(let t=0;t<n.length;){let r=n[t],s,i;if(r<128)s=r,i=1;else if((r&224)===192)s=r&31,i=2;else if((r&240)===224)s=r&15,i=3;else if((r&248)===240)s=r&7,i=4;else return null;if(t+i>n.length)return null;for(let o=1;o<i;o++){let a=n[t+o];if((a&192)!==128)return null;s=s<<6|a&63}if(i===2&&s<128||i===3&&(s<2048||s>=55296&&s<=57343)||i===4&&(s<65536||s>1114111))return null;if(s>65535){let o=s-65536;e+=String.fromCharCode(55296+(o>>10),56320+(o&1023))}else e+=String.fromCharCode(s);t+=i}return e}function Ea(n){return Nl(n).length}function Ra(n){let e=Nl(JSON.stringify(n)),t="";for(let r=0;r<e.length;r+=3){let s=e[r],i=e[r+1],o=e[r+2];if(t+=ir[s>>2],t+=ir[(s&3)<<4|(i??0)>>4],i===void 0||(t+=ir[(i&15)<<2|(o??0)>>6],o===void 0))break;t+=ir[o&63]}return t}function xa(n){if(n.length%4===1)return;let e=[],t=0,r=0;for(let i=0;i<n.length;i++){let o=n.charCodeAt(i),a=o<128?_p[o]:-1;if(a<0)return;t=t<<6|a,r+=6,r>=8&&(r-=8,e.push(t>>r&255))}if(r>0&&(t&(1<<r)-1)!==0)return;let s=Ep(e);if(s!==null)try{return JSON.parse(s)}catch{return}}var Bl=2048,Ll=32;var xp=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;function Sp(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function bi(n,e){if(Object.keys(n).length!==e.length)return!1;for(let r of e)if(!Object.prototype.hasOwnProperty.call(n,r))return!1;return!0}var wi=["channel","v","type","slug","attemptId","nonce"];function Tp(n){return n.channel===es&&n.v===1&&_a(n.slug)&&Jt(n.attemptId)&&Jt(n.nonce)}function Sa(n){if(!(!Sp(n)||!Tp(n)))switch(n.type){case"ticket":return!bi(n,[...wi,"ticket","expiresAt"])||typeof n.ticket!="string"||n.ticket.length===0||n.ticket.length>Bl||typeof n.expiresAt!="string"||n.expiresAt.length>Ll||!xp.test(n.expiresAt)?void 0:n;case"guest":case"cancel":return bi(n,wi)?n:void 0;case"foreground":return!bi(n,[...wi,"active"])||typeof n.active!="boolean"?void 0:n;case"network":return!bi(n,[...wi,"online"])||typeof n.online!="boolean"?void 0:n;default:return}}function vp(n,e){if(typeof n!="string"||n.length===0)return{ok:!1,reason:"undecodable"};if(Ea(n)>4096)return{ok:!1,reason:"too-large"};let t=xa(n);if(t===void 0)return{ok:!1,reason:"undecodable"};let r=e(t);return r===void 0?{ok:!1,reason:"invalid"}:{ok:!0,message:r}}function ka(n){return vp(n,Sa)}function va(n){let e=Ra(n);if(!(e.length>4096))return e}function _i(n,e){let t=n.charAt(0)==="?"?n.slice(1):n;if(t.length===0)return null;for(let r of t.split("&")){let s=r.indexOf("=");if(s!==-1&&r.slice(0,s)===e)return r.slice(s+1)}return null}function Ei(n){return _i(n,hi)==="1"}function Ca(n){if(!Ei(n))return null;let e=_i(n,mi),t=_i(n,gi),r=Number(_i(n,pi));return!Jt(e)||!Jt(t)||r!==1?null:{attemptId:e,nonce:t,protocol:r}}function jl(n){return n.indexOf("%")===-1?n:n.replace(/%([0-9A-Fa-f]{2})/g,(e,t)=>{let r=parseInt(t,16);return r<128?String.fromCharCode(r):e})}function ql(n){let e=n.indexOf("="),t=e===-1?n:n.slice(0,e);return jl(t.indexOf("+")===-1?t:t.split("+").join(" "))}function Ri(n){return Gl(n,[ma])}var Cp=[hi,pi,mi,gi,pa];function Ia(n){return Gl(n,Cp)}function Gl(n,e){let t=n.charAt(0)==="?"?n.slice(1):n;if(t.length===0)return"";let r=t.split("&"),s=r.filter(o=>!e.includes(ql(o)));if(s.length===r.length)return`?${t}`;let i=s.join("&");return i.length===0?"":`?${i}`}var Ip=/^[!$-&(-;=?-~]+$/;function xi(n,e){if(typeof n!="string")return"";let t=n.charAt(0)==="?"?n.slice(1):n,r=t.indexOf("#");if(r!==-1&&(t=t.slice(0,r)),t.length===0||!Ip.test(t))return"";let i=t.split("&").filter(o=>{if(o.length===0)return!1;let a=ql(o);return!a.startsWith(sr)&&!e.includes(a)}).join("&");return i.length>1024?"":i}var Pp=/^#[!#-;=?-_a-~]+$/;function Si(n){return typeof n!="string"||n.length<2||n.length>4096||!Pp.test(n)||jl(n).includes(sr)?"":n}var Op=/^[a-z0-9._-]+$/,Mp=/^\[[0-9a-f:.]+\]$/;function Dp(n){return Op.test(n)&&/[a-z0-9]/.test(n)||Mp.test(n)}function Aa(n){let e=n.slice(0,8).toLowerCase(),t=e==="https://"?"https":e.slice(0,7)==="http://"?"http":null;if(t===null)return null;let r=t.length+3,s=n.length;for(let u=r;u<n.length;u++){let d=n.charAt(u);if(d==="/"||d==="?"||d==="#"||d==="\\"){s=u;break}}if(s-r>255)return null;let i=n.slice(r,s).toLowerCase();if(i.length===0||i.indexOf("@")!==-1)return null;let o=i,a="",c=i.lastIndexOf(":");if(c!==-1&&i.charAt(i.length-1)!=="]"&&(o=i.slice(0,c),a=i.slice(c+1)),!Dp(o))return null;if(a.length>0){if(!/^[0-9]{1,5}$/.test(a))return null;let u=Number(a);if(u>65535)return null;a=u===(t==="https"?443:80)?"":`:${u}`}return`${t}://${o}${a}`}function ar(n,e){if(typeof n!="string"||n.length===0)return null;let t=Aa(n);return t===null||t.length>255||typeof e=="string"&&Aa(e)===t?null:t}var Hl=["open","save","fullscreen"];var zl=50*1024*1024,Np=16;function Wl(n){return typeof n=="string"&&Hl.includes(n)}function Pa(n){if(!Array.isArray(n))return[];let e=[],t=Math.min(n.length,Np);for(let r=0;r<t;r++){let s=n[r];Wl(s)&&!e.includes(s)&&e.push(s)}return e}var Wp=null;function Kl(n){Wp=n}var Kp=null;function Yl(n){Kp=n}var Yp=null;function Xl(n){Yp=n}var ss=1,Ba="genex:embed:retry",du="genex:guest:popover-dismissed",fu="genex:embed:local-auth",hu="genex:embed:entry-referrer",Xp="none",Ql="genex:player",Qp="0.33.0",ue=null,fe="pending",rt=null,hn=!1,dn=null,cr=!1,fn,lr,pu=0,ze,La,pn=null,mu=[],dr=!1,Dn=!1,ns=!1,nt=0,fr=1e4,Zp=2e3,em=10*6e4,tm=6e4,Zl=500,nm=3e4,rm=3e4,we,gt,ur,eu=!1,tu,Ti=null,nu=new Set;var ru=!1,sm=new Map,gu=[],is=[],rs=null,ki=null,Mn,Oa,Ma=!1,vi=new Map;function Se(){return globalThis.window}function Fa(){return globalThis.document}function os(n,e,t){let r;if(t!==void 0)try{let s=globalThis.AbortSignal;s&&typeof s.timeout=="function"&&(r=s.timeout(t))}catch{}return globalThis.fetch(n,r?{...e,signal:r}:e)}function im(){try{return Se()?.sessionStorage?.getItem(Ba)==="1"}catch{return!1}}function om(){try{Se()?.sessionStorage?.setItem(Ba,"1")}catch{}}function Ua(){try{Se()?.sessionStorage?.removeItem(Ba)}catch{}}function am(){try{return Se()?.sessionStorage?.getItem(fu)==="1"}catch{return!1}}function cm(){try{Se()?.sessionStorage?.setItem(fu,"1")}catch{}}function lm(){try{let n=Se()?.sessionStorage?.getItem(hu);return n==null?void 0:ar(n)}catch{return}}function um(n){try{Se()?.sessionStorage?.setItem(hu,n??Xp)}catch{}}function dm(){try{return Se()?.sessionStorage?.getItem(du)==="1"}catch{return!1}}function fm(){try{Se()?.sessionStorage?.setItem(du,"1")}catch{}}function hm(){try{let n=Se()?.localStorage;if(!n)return"no-storage";let e=n.getItem(Ql);return e||(e=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,n.setItem(Ql,e)),e}catch{return"no-storage"}}function Ci(n){let e=Se();if(!e||dr)return;if(dr=!0,ur!==void 0&&(clearTimeout(ur),ur=void 0),ue={slug:n.slug,apiUrl:n.apiUrl.replace(/\/$/,""),dashboardOrigins:[...n.dashboardOrigins]},fe="pending",Ru(e),Yl({apiUrl:ue.apiUrl,dashboardOrigins:ue.dashboardOrigins,getToken:()=>ze,getParentOrigin:()=>pn,isEmbedded:We,isNative:ut,isLocalTest:()=>hn}),Xl({apiUrl:ue.apiUrl,dashboardOrigins:ue.dashboardOrigins,getToken:()=>ze,getParentOrigin:()=>pn,isEmbedded:We,isNative:ut,isLocalTest:()=>hn}),Ha(e)){Bm(e);return}Pi("connecting");let t=xu(e);if(t){Am(e,t);return}We()?km(e):Pm(e)}function We(){let n=Se();if(!n)return!1;try{return n.self!==n.top}catch{return!0}}function pm(){let n=Se();return n?We()?"page":ut()||Va(n)?"app":dr?hn?"local":"standalone":Ha(n,!1)?"local":"standalone":"standalone"}function yu(){return ze?{embedToken:ze}:void 0}function bu(){return La??[]}function $a(){return(fe==="authenticated"||fe==="guest")&&rt?Promise.resolve({user:rt,guest:fe==="guest"}):fe==="blocked"?Promise.reject(new Error("genex embed auth: blocked")):(mm("waitForPlayer"),new Promise((n,e)=>{is.push({resolve:n,reject:e})}))}function mm(n){if(!dr){if(!eu){eu=!0;try{console.error(`[genex] ${n}() called before initEmbed() \u2014 identity can never resolve and the game will sit black. Call initEmbed({ slug, apiUrl, dashboardOrigins }) first (genex-threejs-embed-auth), and draw a frame before you await identity.`)}catch{}}ur===void 0&&(ur=setTimeout(()=>{ur=void 0,dr||Kt("no-identity")},fr))}}var gm=32*1024;async function wu(){if(!ue)throw new Error("genex embed: call initEmbed() first");if(fe==="pending"&&await $a(),fe==="blocked")throw new Error("genex embed auth: blocked")}function _u(n,e={}){let t={Authorization:`Bearer ${ze}`};return e.body!==void 0&&(t["Content-Type"]="application/json"),e.ifVersion!==void 0&&(t["If-Match"]=String(e.ifVersion)),os(`${ue.apiUrl}/api/projects/${encodeURIComponent(ue.slug)}${n}`,{method:e.method??"GET",headers:t,body:e.body,keepalive:e.body!==void 0&&e.body.length<=gm?!0:void 0})}async function ym(n){return n.status!==403?!1:(await n.json().catch(()=>null))?.error==="staging_no_save"}async function bm(n){return n.status===409?{saved:!1,conflict:!0,version:(await n.json().catch(()=>({}))).version}:n.ok?{saved:!0,version:(await n.json()).version}:await ym(n)?{saved:!1,staging:!0}:(st("error",{error:new Error(`genex state save failed (${n.status})`)}),{saved:!1})}async function wm(n,e){return await wu(),fe==="guest"?(Oa=n,Ma=!0,{saved:!1,guest:!0,queued:!0}):bm(await _u("/state/me",{method:"PUT",body:JSON.stringify(n),ifVersion:e?.ifVersion}))}async function _m(n,e){let t=e?.board??"main",r=e?.mode??"max";if(await wu(),fe==="guest"){let o=vi.get(t);return(!o||(r==="min"?n<o.score:n>o.score))&&vi.set(t,{score:n,mode:r}),{submitted:!1,guest:!0,queued:!0}}let s=await _u("/scores",{method:"POST",body:JSON.stringify({score:n,board:t,mode:r})});if(!s.ok)return st("error",{error:new Error(`genex score submit failed (${s.status})`)}),{submitted:!1};let i=await s.json();return{submitted:!0,best:i.best,improved:i.improved}}async function Em(){try{if(Ma){let e=Oa;Oa=void 0,Ma=!1,await wm(e)}let n=[...vi.entries()];vi.clear();for(let[e,{score:t,mode:r}]of n)await _m(t,{board:e,mode:r})}catch(n){st("error",{error:n})}}function st(n,e){let t=sm.get(n);if(t)for(let r of[...t])try{r(e)}catch{}}var Rm=["embed"];function Eu(n,e){let t={ticket:null,guest:!1,entryHash:"",entryReferrer:null};if(!n||n.length<2)return t;try{let r=new URLSearchParams(n.slice(1));return{ticket:r.get("genex_ticket"),guest:r.get("genex_guest")==="1",entryHash:Si(r.get(ya)),entryReferrer:ar(r.get(ba),e)}}catch{return t}}function xm(n,e){try{return new URLSearchParams(n).get(e)}catch{return null}}function Ru(n){if(Ti)return Ti;let e="",t="",r=null;try{e=n.location.search??"",t=Ai??n.location.hash??"",r=n.location.origin??null}catch{}let s=We(),i=Eu(t,r),o=!s&&(!!i.ticket||i.guest),a=xi(e,Rm);return Ti={search:a?`?${a}`:"",hash:o?i.entryHash:t.includes(sr)?"":t,referrer:Sm(e,s,o,i.entryReferrer,r)},Ti}function Sm(n,e,t,r,s){let i=lm();if(i!==void 0)return i;let o;return e?o=ar(xm(n,wa),s):t?o=r:o=ar(Fa()?.referrer,s),um(o),o}function Tm(){if(!(ru||nu.size===0)){ru=!0;for(let n of[...nu])try{n()}catch{}}}function km(n){tu=e=>{vm(e)},n.addEventListener("message",tu),n.parent.postMessage({type:"genex:embed:ready",v:ss},"*"),we=setTimeout(()=>{hr()},fr)}function su(){return(fe==="pending"||fe==="guest")&&!Dn}async function vm(n){if(!ue)return;let e=n.data;if(!e||e.v!==ss)return;let t=e.type==="genex:embed:ticket",r=e.type==="genex:embed:guest";if(!(!t&&!r)&&!(t&&(!su()||typeof e.ticket!="string"||!e.ticket))&&!(r&&(fe!=="pending"||Dn||ns))){if(!ue.dashboardOrigins.includes(n.origin)){let s=await Da();if(t&&!su()||r&&(fe!=="pending"||Dn||ns)||!s.includes(n.origin))return}if(we!==void 0&&clearTimeout(we),pn=n.origin,mu=Pa(e.caps),r){await hr();return}await Ga(e.ticket)}}function Va(n){let e=n.ReactNativeWebView;return!e||typeof e!="object"?null:typeof e.postMessage=="function"?e:null}function xu(n){if(We())return null;let e;try{e=n.location.search??""}catch{return null}return!Ei(e)||!Va(n)?null:Ca(e)}function ut(){return dn!==null}function Nn(n){let e=Se();if(!e||!ue||!dn)return;let t=Va(e);if(!t)return;let r=va({channel:es,v:1,slug:ue.slug,attemptId:dn.attemptId,nonce:dn.nonce,...n});if(r)try{t.postMessage(r)}catch{}}function Su(n){ut()&&Nn({type:"error",code:n})}function Am(n,e){dn=e,pu=Date.now(),n[yi]=r=>{Cm(r)},Nn({type:"ready",sdkVersion:Qp,capabilities:["native-ticket","native-guest","heartbeat"]}),we=setTimeout(()=>{hr()},fr)}async function Cm(n){if(!ue||!dn)return;let e=ka(n);if(!e.ok)return;let t=e.message;if(!(t.slug!==ue.slug||t.attemptId!==dn.attemptId||t.nonce!==dn.nonce))switch(t.type){case"ticket":we!==void 0&&clearTimeout(we),await Ga(t.ticket);return;case"guest":we!==void 0&&clearTimeout(we),await hr();return;case"cancel":Tu(),Tm();return;case"foreground":case"network":return}}function Tu(){we!==void 0&&clearTimeout(we),we=void 0,gt!==void 0&&clearTimeout(gt),gt=void 0,fn!==void 0&&clearTimeout(fn),fn=void 0,lr!==void 0&&clearInterval(lr),lr=void 0}function ku(){!ut()||lr!==void 0||(lr=setInterval(()=>{Nn({type:"heartbeat",uptimeMs:Math.max(0,Date.now()-pu)})},rm),lr.unref?.())}function Im(){!ut()||cr||(cr=!0,Nn({type:"reauth-required"}),fn=setTimeout(()=>{fn=void 0,cr&&(cr=!1,st("error",{error:new Error("embed session expired")}),Kt("session-expired"))},nm))}function ja(){cr=!1,fn!==void 0&&clearTimeout(fn),fn=void 0}function qa(n,e){let t=Se();if(!(!t||!We()))try{t.parent.postMessage(n,e)}catch{}}async function Pm(n){let e=vu(n);if(e.ticket){iu(),await Ga(e.ticket);return}if(e.guest){iu(),await hr();return}Pi("redirecting"),await Ii(n,{guestOk:!0})}function iu(){we!==void 0&&clearTimeout(we),we=setTimeout(()=>{we=void 0,fe==="pending"&&Kt("no-identity")},fr+Zp)}var Ai=null;function Om(n){return n.location.pathname+Ri(n.location.search)}function vu(n){let e=Ai??n.location.hash;Ai=null;let{ticket:t,guest:r,entryHash:s}=Eu(e);if(t||r)try{n.history.replaceState(n.history.state??null,"",Om(n)+s)}catch{}return{ticket:t,guest:r}}async function Ii(n,e){if(!ue||hn||ut())return;let t=e?.guestOk?ue.dashboardOrigins[0]??(await Da())[0]:(await Da())[0]??ue.dashboardOrigins[0];if(!t){Kt();return}let r=n.location.origin+n.location.pathname,s=Ia(Ri(n.location.search));s.length-1<=1024&&r.length+s.length<=2048&&s.indexOf("#")===-1&&(r+=s);let i=e?.guestOk?"&guest=ok":"",o=`${t}/play/authorize?returnTo=${encodeURIComponent(r)}&slug=${encodeURIComponent(ue.slug)}${i}`,a=Ru(n).referrer;a&&(o+=`&${ga}=${encodeURIComponent(a)}`),o+=Si(n.location.hash),n.location.replace(o)}async function Da(){if(!ue)return[];try{let n=await os(`${ue.apiUrl}/api/embed/dashboard-origins`);if(!n.ok)return ue.dashboardOrigins;let e=await n.json();if(Array.isArray(e.origins)&&e.origins.every(t=>typeof t=="string"))return e.origins}catch{}return ue.dashboardOrigins}async function Ga(n){if(!ue||hn||Dn||fe!=="pending"&&fe!=="guest"&&!(cr&&fe==="authenticated"))return;let t=fe==="guest",r=++nt;Dn=!0;try{let s=await os(`${ue.apiUrl}/api/embed/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ticket:n})},fr);if(r!==nt)return;if(!s.ok){st("error",{error:new Error(`ticket redemption failed (${s.status})`)}),t||await ou();return}let i=await s.json();if(r!==nt)return;ze=i.embedToken,rt=i.user,La=i.colyseus?.urls,fe="authenticated",we!==void 0&&clearTimeout(we),we=void 0,Ua(),Oi(),Wa(),za(),We()&&pn&&qa({type:"genex:embed:authenticated",v:ss},pn),ut()&&(ja(),Nn({type:"authenticated",guest:!1}),ku()),t&&await Em();let o={user:rt};for(let a of gu.splice(0))a.resolve(o);for(let a of is.splice(0))a.resolve({user:rt,guest:!1});st("authenticated",o)}catch(s){if(r!==nt)return;st("error",{error:s}),t||await ou()}finally{Dn=!1}}async function hr(){if(!ue||hn||ns||Dn||fe!=="pending"&&fe!=="guest")return;let n=++nt;ns=!0;try{let e=await os(`${ue.apiUrl}/api/embed/guest-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:ue.slug,playerId:hm()})},fr);if(n!==nt)return;if(!e.ok){st("error",{error:new Error(`guest session failed (${e.status})`)}),Su("guest-failed"),Kt(e.status===404?"not-available":"no-identity");return}let t=await e.json();if(n!==nt)return;ze=t.embedToken,rt=t.user,La=t.colyseus?.urls,Mm()}catch(e){if(n!==nt)return;st("error",{error:e}),Kt()}finally{ns=!1}}function Mm(){let n=fe!=="guest";if(fe="guest",we!==void 0&&clearTimeout(we),Oi(),za(),We()?qa({type:"genex:embed:authenticated",v:ss,guest:!0},pn??"*"):ut()?(Nn({type:"authenticated",guest:!0}),ku()):n&&!dm()&&jm(),rt){let e={user:rt};for(let t of is.splice(0))t.resolve({user:rt,guest:!0});st("guest",e)}}function Dm(n){try{let e=new URL(n.location.origin);return e.protocol==="http:"&&(e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]")}catch{return!1}}function Ha(n,e=!0){if(We()||xu(n)||!Dm(n))return!1;let t=null;try{t=new URLSearchParams(n.location.search)}catch{}return t?.get("genex_local_test")==="1"?!0:t?.get("genex_auth")==="1"?(e&&cm(),!1):am()?!1:!Nm(n)}function Nm(n){let e=Ai??n.location.hash;return!!e&&e.includes("genex_")}function Bm(n){hn=!0,vu(n);let e={id:"local:test",name:"Local Tester"};rt=e,fe="guest",Oi();try{console.info("[genex] local test mode \u2014 local visuals and controls only. Auth, saves, leaderboards, and multiplayer are NOT validated here; no Genex credential exists.")}catch{}for(let t of is.splice(0))t.resolve({user:e,guest:!0});st("guest",{user:e})}async function ou(){let n=Se();if(we!==void 0&&clearTimeout(we),we=void 0,ut()){ja(),Su("ticket-rejected"),Kt();return}if(n&&!We()&&!im()){om(),Pi("redirecting"),await Ii(n,{guestOk:!0});return}Kt()}function za(){gt!==void 0&&clearTimeout(gt),gt=setTimeout(()=>{Au()},em)}async function Au(){if(!ue||fe!=="authenticated"&&fe!=="guest"||!ze)return;let n=nt,e=ze,t;try{let r=await os(`${ue.apiUrl}/api/embed/session/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`},keepalive:!0});if(t=r.status,n!==nt||ze!==e)return;if(r.ok){let s=await r.json();if(n!==nt||ze!==e)return;ze=s.embedToken,za();return}}catch{t=void 0}if(!(n!==nt||ze!==e)){if(t===401){if(fe==="guest"){hr();return}if(ut()){Im();return}st("error",{error:new Error("embed session expired")}),Kt("session-expired");return}gt!==void 0&&clearTimeout(gt),gt=setTimeout(()=>{Au()},tm)}}function Kt(n="no-identity"){if(fe==="blocked")return;nt++,fe="blocked",rt=null,ze=void 0,we!==void 0&&clearTimeout(we),gt!==void 0&&clearTimeout(gt),Wa(),ut()?(Tu(),ja(),Oi(),Nn({type:"blocked",reason:n})):Pi(We()?"blocked-embedded":"blocked-standalone"),We()&&qa({type:"genex:embed:blocked",v:ss},pn??"*");let e=new Error("genex embed auth: blocked");for(let t of gu.splice(0))t.reject(e);for(let t of is.splice(0))t.reject(e);st("blocked")}var Lm={connecting:{title:"GENEX",wordmark:!0},redirecting:{title:"GENEX",wordmark:!0},"blocked-standalone":{title:"Sign in to play",button:"Sign in",instant:!0},"blocked-embedded":{title:"Sign in on the Genex dashboard to continue",instant:!0}},Fm="https://cdn.genex.technology/fonts/GeistMono-variable.woff2",Cu="'Geist Mono',ui-monospace,SFMono-Regular,Menlo,monospace",au=!1,cu="!<>-_/[]{}=+*^?#$%&@",Iu=50,lu=10,uu=[{name:"churn",ticks:5},{name:"settle",ticks:10},{name:"hold",ticks:12},{name:"dissolve",ticks:8}];function Na(n){let e="";for(let t=0;t<n;t++)e+=cu[Math.floor(Math.random()*cu.length)];return e}function Pu(){try{let n=Se();return!n||typeof n.matchMedia!="function"?!0:n.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!0}}function Um(n,e){if(Pu())return n.textContent=e,()=>{};let t=0;n.textContent=Na(e.length);let r=setInterval(()=>{if(t++,t>=lu){n.textContent=e,clearInterval(r);return}let s=Math.floor(t/lu*e.length);n.textContent=e.slice(0,s)+Na(e.length-s)},Iu);return()=>clearInterval(r)}function $m(n,e){if(Pu())return n.textContent=e,()=>{};let t=0,r=0,s=()=>{let o=uu[t],a;o.name==="churn"?a=0:o.name==="settle"?a=Math.floor(r/o.ticks*e.length):o.name==="hold"?a=e.length:a=e.length-Math.floor(r/o.ticks*e.length),n.textContent=e.slice(0,a)+Na(e.length-a),r++,r>=o.ticks&&(r=0,t=(t+1)%uu.length)};s();let i=setInterval(s,Iu);return()=>clearInterval(i)}function Ou(n){if(!au){au=!0;try{let e=Se()?.FontFace,t=n.fonts;if(!e||!t?.add)return;new e("Geist Mono",`url(${Fm}) format('woff2')`,{weight:"100 900",display:"swap"}).load().then(s=>t.add(s)).catch(()=>{})}catch{}}}function Pi(n){let e=Fa();if(e?.createElement)try{rs||(rs=Vm(e)),rs.setContent(n)}catch{}}function Oi(n=!1){try{let e=rs;if(rs=null,!e)return;e.stopText();let t=e.root;if(n||!t.style){t.remove?.();return}t.style.pointerEvents="none",t.style.transition="opacity 180ms ease",t.style.opacity="0",setTimeout(()=>{try{t.remove?.()}catch{}},220)}catch{}}function Vm(n){Ou(n);let e=n.createElement("div");e.setAttribute("data-genex-embed-overlay",""),e.style.cssText=`position:fixed;inset:0;z-index:2147483647;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:14px;background:#000;color:#fff;font-family:${Cu};text-align:center;pointer-events:auto;user-select:none`;let t=n.createElement("div");t.style.cssText="font-size:13px;font-weight:400;line-height:1.3;padding:0 24px;opacity:0;min-height:1.3em;font-variant-ligatures:none",e.appendChild(t);let r=n.createElement("button");r.style.cssText="font-family:inherit;font-size:13px;font-weight:500;line-height:1.3;padding:8px 22px;border-radius:9px;border:none;cursor:pointer;background:#4b60bf;color:#fff;display:none",r.addEventListener("mouseenter",()=>{r.style.background="#3f51a8"}),r.addEventListener("mouseleave",()=>{r.style.background="#4b60bf"}),r.addEventListener("click",()=>{let c=Se();c&&(r.disabled=!0,Ua(),Ii(c))}),e.appendChild(r);let s=()=>{n.body&&!e.isConnected&&n.body.appendChild(e)};n.body?s():n.addEventListener?.("DOMContentLoaded",s);let i,o,a=()=>{i!==void 0&&(clearTimeout(i),i=void 0),o&&(o(),o=void 0)};return{root:e,stopText:a,setContent(c){let u=Lm[c];a(),t.textContent=u.title,t.style.letterSpacing=u.wordmark?"0.22em":"",t.style.marginRight=u.wordmark?"-0.22em":"";let d=()=>{t.style.opacity="1",o=u.wordmark?$m(t,u.title):Um(t,u.title)};u.instant||Zl<=0?d():(t.style.opacity="0",i=setTimeout(()=>{i=void 0,d()},Zl)),r.style.display=u.button?"inline-block":"none",u.button&&(r.textContent=u.button),s()}}}function jm(){let n=Fa();if(!(!n?.createElement||ki))try{ki=qm(n)}catch{}}function Wa(){Mn!==void 0&&(clearTimeout(Mn),Mn=void 0);try{ki?.root?.remove?.()}catch{}ki=null}function qm(n){Ou(n);let e=!1;try{let c=Se(),u=c?.navigator;if(c&&u){let d=c.matchMedia?.("(pointer: coarse)").matches??!1,h=(u.maxTouchPoints??0)>1,m=u.userAgentData?u.userAgentData.mobile:/Mobi|Android/i.test(u.userAgent??"");e=h&&d||m}}catch{}let t=n.createElement("div");t.setAttribute("data-genex-guest-popover",""),t.style.cssText="position:fixed;top:calc(12px + env(safe-area-inset-top));right:calc(12px + env(safe-area-inset-right));z-index:2147483646;display:flex;justify-content:flex-end;pointer-events:none";let r=n.createElement("div");r.style.cssText=`display:flex;align-items:center;border-radius:12px;background:rgba(0,0,0,0.85);color:#fff;font-family:${Cu};box-shadow:0 4px 24px rgba(0,0,0,0.4);pointer-events:auto;user-select:none;`+(e?"gap:8px;padding:8px 8px 8px 12px;font-size:12px;max-width:calc(100vw - 88px)":"gap:12px;padding:10px 12px 10px 16px;font-size:13px"),t.appendChild(r);let s=n.createElement("span");s.textContent=!e&&rt?.name?`Playing as ${rt.name} \u2014 sign in to save progress`:"Sign in to save progress",e&&(s.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap"),r.appendChild(s);let i=n.createElement("button");i.textContent="Sign in",i.style.cssText="font-family:inherit;font-weight:500;border-radius:9px;border:none;cursor:pointer;background:#4b60bf;color:#fff;"+(e?"font-size:12px;padding:5px 12px":"font-size:13px;padding:6px 16px"),i.addEventListener("mouseenter",()=>{i.style.background="#3f51a8"}),i.addEventListener("mouseleave",()=>{i.style.background="#4b60bf"}),i.addEventListener("click",()=>{let c=Se();c&&(i.disabled=!0,Ua(),Ii(c))}),r.appendChild(i);let o=n.createElement("button");if(o.textContent="\xD7",o.setAttribute("aria-label","Dismiss"),o.style.cssText="font-size:16px;line-height:1;padding:6px 8px;border:none;cursor:pointer;background:transparent;color:rgba(255,255,255,0.6)",o.addEventListener("click",()=>{fm(),Wa()}),r.appendChild(o),e){let c=n.createElement("button");c.setAttribute("aria-label","Sign in to save progress"),c.style.cssText="display:none;width:44px;height:44px;border-radius:50%;border:none;cursor:pointer;background:rgba(0,0,0,0.55);color:#fff;align-items:center;justify-content:center;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);pointer-events:auto",c.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" y1="12" x2="3" y2="12"/></svg>',t.appendChild(c);let u=d=>{r.style.display=d?"none":"flex",c.style.display=d?"flex":"none"};Mn=setTimeout(()=>u(!0),5e3),r.addEventListener("pointerdown",()=>{Mn!==void 0&&clearTimeout(Mn),Mn=void 0}),c.addEventListener("click",()=>u(!1))}let a=()=>{n.body&&!t.isConnected&&n.body.appendChild(t)};return n.body?a():n.addEventListener?.("DOMContentLoaded",a),{root:t}}Kl({getShell:pm,isLocalTest:()=>{let n=Se();return!n||We()?!1:dr?hn:Ha(n,!1)},getConfig:()=>ue,getParentOrigin:()=>pn,getShellCaps:()=>mu});var dl={};Dl(dl,{chatSend:()=>yb,claim:()=>bb,claimAsHost:()=>wb,connect:()=>ob,destroy:()=>Eb,dispose:()=>ab,drainEventsJson:()=>Pb,leave:()=>ep,listen:()=>pb,objectsJson:()=>Cb,open:()=>ib,playersJson:()=>Ab,release:()=>_b,reportEliminated:()=>Rb,reportFinish:()=>Sb,reportScore:()=>xb,send:()=>hb,sendInput:()=>mb,serverNow:()=>Tb,sessionJson:()=>vb,setIdentity:()=>eb,setMe:()=>cb,setObject:()=>db,setRoomOpen:()=>gb,setShared:()=>ub,sharedJson:()=>Ib,snapMe:()=>lb,snapObject:()=>fb,timeUntil:()=>kb,version:()=>Z0});ArrayBuffer.isView||(ArrayBuffer.isView=n=>n!==null&&typeof n=="object"&&n.buffer instanceof ArrayBuffer);typeof globalThis>"u"&&typeof window<"u"&&(window.globalThis=window);typeof FormData>"u"&&(globalThis.FormData=class{});Yt();var It=class extends Error{constructor(t,r,s){super(r);l(this,"code");l(this,"headers");l(this,"status");l(this,"response");l(this,"data");this.name="ServerError",this.code=t,s&&(this.headers=s.headers,this.status=s.status,this.response=s.response,this.data=s.data)}};var as=class n extends Error{constructor(t,r){super(t);l(this,"code");this.code=r,this.name="MatchMakeError",Object.setPrototypeOf(this,n.prototype)}};Yt();He();He();He();He();He();He();He();He();var of=256,wc=5,Gn=class Gn{constructor(e,t={}){l(this,"instance");l(this,"mode");l(this,"historySize");l(this,"_desc");l(this,"_numFields");l(this,"_slots");l(this,"_slotLens");l(this,"_slotHead",0);l(this,"_slotCount",0);l(this,"_outBuffer");l(this,"_seq",0);l(this,"_encoder");this.instance=e,this.mode=t.mode??"reliable",this.historySize=this.mode==="unreliable"?Math.max(1,t.historySize??3):1,this._desc=dc(e);let r=this._desc.metadata?.[Fe];if(r===void 0)throw new Error(`InputEncoder: '${e.constructor.name}' has no fields`);this._numFields=r;for(let s=0;s<=r;s++)if(this._desc.names[s]!==void 0&&this._desc.encoders[s]===void 0)throw new Error(`InputEncoder: non-primitive field '${this._desc.names[s]}' on '${e.constructor.name}' is not supported. Use Encoder for state containing refs/collections.`);if(this.mode==="unreliable"){this._slots=new Array(this.historySize),this._slotLens=new Array(this.historySize).fill(0);for(let s=0;s<this.historySize;s++)this._slots[s]=new Uint8Array(of);this._outBuffer=new Uint8Array((of+wc)*this.historySize)}this._encoder=new gs(e)}get seq(){return this._seq}encode(){let e=this._produceDelta();return this.mode==="reliable"?e:this._pushAndEmitRing(e)}reset(){this._slotHead=0,this._slotCount=0,this._encoder.discardChanges();let e=this.instance[_],t=this.instance[Ue];for(let r=0;r<=this._numFields;r++)t[r]===void 0||t[r]===null||e.markDirty(r)}copyInto(e){let t=this.instance[Ue],r=e[Ue];for(let s=0;s<=this._numFields;s++)r[s]=t[s]}_produceDelta(){let e=this._encoder.encode();return this._encoder.discardChanges(),e}_pushAndEmitRing(e){this._seq++;let t=this._slots[this._slotHead];return e.length>t.byteLength&&(t=this._slots[this._slotHead]=Gn._grow(t,e.length,"unreliable ring slot")),t.set(e),this._slotLens[this._slotHead]=e.length,this._slotHead=(this._slotHead+1)%this.historySize,this._slotCount<this.historySize&&this._slotCount++,this._emitRing()}_emitRing(){let e=this._seq-this._slotCount+1,t=wc;for(let o=0;o<this._slotCount;o++)t+=this._slotLens[o]+wc;let r=this._outBuffer;t>r.byteLength&&(r=this._outBuffer=Gn._grow(r,t,"unreliable output packet"));let s={offset:0};Q.number(r,e,s);let i=(this._slotHead-this._slotCount+this.historySize)%this.historySize;for(let o=0;o<this._slotCount;o++){let a=(i+o)%this.historySize,c=this._slotLens[a];Q.number(r,c,s),r.set(this._slots[a].subarray(0,c),s.offset),s.offset+=c}return r.subarray(0,s.offset)}static _grow(e,t,r){let s=Math.max(t,e.byteLength*2);return Gn._warned||(Gn._warned=!0,console.warn(`@colyseus/schema/input: InputEncoder buffer overflow in ${r}. Growing to ${s} bytes.`)),new Uint8Array(s)}};l(Gn,"_warned",!1);var oo=Gn;Yt();Ec();fo();var Hn,kt,xr,vs,As,Cs,Is,Ps,Os,Sr,Ms,ho,uf,Tr=class{constructor(e){he(this,ho);he(this,Hn);he(this,kt);he(this,xr);he(this,vs);he(this,As,!1);he(this,Cs);he(this,Is,!1);he(this,Ps,!1);he(this,Os);he(this,Sr);he(this,Ms);pe(this,Hn,e)}get patchRate(){return H(this,Sr)}applyReflection(e,t,r){let s=Tt.decode(e.subarray(0,r),t);Tt.makeEncodable(s.state.constructor),pe(this,Cs,s.state.constructor),H(this,Hn).clock===Rr&&(H(this,Hn).clock=new uo)}applyOptions(e,t){let r=e[t.offset++];pe(this,Is,(r&Bn.RENDER_TIME)!==0),pe(this,Ps,(r&Bn.RECKON_TIME)!==0),r&Bn.FIXED_TIMESTEP&&pe(this,Os,te.number(e,t)),r&Bn.PATCH_RATE&&pe(this,Sr,te.number(e,t)),r&Bn.SUB_STEPS&&pe(this,Ms,te.number(e,t))}ackInput(e){return H(this,kt)?H(this,kt).ackInput(e):-1}reset(){H(this,kt)?.reset()}handle(e){if(H(this,kt))return e!==void 0&&On(this,ho,uf).call(this,e),H(this,kt);let t=e?.type??H(this,Cs);if(!t)throw new Error("room.input(): no input schema available. The server room must call `defineInput(YourInput)`, or you can pass `{ type: YourInput }` explicitly.");let r=new t,s=new oo(r,e);return pe(this,kt,new Er(H(this,Hn),r,s,{stampRender:H(this,Is),stampReckon:H(this,Ps),renderDelay:e?.renderDelay,allowRewind:e?.allowRewind,tickRate:H(this,Os),patchRate:H(this,Sr),subSteps:H(this,Ms)})),pe(this,xr,e),pe(this,vs,s),H(this,kt)}};Hn=new WeakMap,kt=new WeakMap,xr=new WeakMap,vs=new WeakMap,As=new WeakMap,Cs=new WeakMap,Is=new WeakMap,Ps=new WeakMap,Os=new WeakMap,Sr=new WeakMap,Ms=new WeakMap,ho=new WeakSet,uf=function(e){if(H(this,As))return;let t=H(this,kt),r=[];e.type!==void 0&&e.type!==t.data?.constructor&&r.push("type"),e.mode!==void 0&&e.mode!==t.mode&&r.push("mode"),e.historySize!==void 0&&t.mode==="unreliable"&&e.historySize!==H(this,vs).historySize&&r.push("historySize"),e.renderDelay!==void 0&&e.renderDelay!==H(this,xr)?.renderDelay&&r.push("renderDelay"),e.allowRewind!==void 0!=(H(this,xr)?.allowRewind!==void 0)&&r.push("allowRewind"),r.length!==0&&(pe(this,As,!0),console.warn(`@colyseus/sdk: room.input() options ignored \u2014 the input handle was already created by an earlier call (first call wins). Differing: ${r.join(", ")}.`))};var xc;try{xc=new TextDecoder}catch{}var U,ft,w=0;var Ef=[],Sc=Ef,Tc=0,de={},se,Rn,dt=0,Ft=0,Le,rn,Xe=[],re,df={useRecords:!1,mapsAsObjects:!0},Ds=class{},vc=new Ds;vc.name="MessagePack 0xC1";var xn=!1,ff=2;var Sn=class n{constructor(e){e&&(e.useRecords===!1&&e.mapsAsObjects===void 0&&(e.mapsAsObjects=!0),e.sequential&&e.trusted!==!1&&(e.trusted=!0,!e.structures&&e.useRecords!=!1&&(e.structures=[],e.maxSharedStructures||(e.maxSharedStructures=0))),e.structures?e.structures.sharedLength=e.structures.length:e.getStructures&&((e.structures=[]).uninitialized=!0,e.structures.sharedLength=0),e.int64AsNumber&&(e.int64AsType="number")),Object.assign(this,e)}unpack(e,t){if(U)return kf(()=>(mo(),this?this.unpack(e,t):n.prototype.unpack.call(df,e,t)));!e.buffer&&e.constructor===ArrayBuffer&&(e=typeof Buffer<"u"?Buffer.from(e):new Uint8Array(e)),typeof t=="object"?(ft=t.end||e.length,w=t.start||0):(w=0,ft=t>-1?t:e.length),Tc=0,Ft=0,Rn=null,Sc=Ef,Le=null,U=e;try{re=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(r){throw U=null,e instanceof Uint8Array?r:new Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof n){if(de=this,this.structures)return se=this.structures,po(t);(!se||se.length>0)&&(se=[])}else de=df,(!se||se.length>0)&&(se=[]);return po(t)}unpackMultiple(e,t){let r,s=0;try{xn=!0;let i=e.length,o=this?this.unpack(e,i):yo.unpack(e,i);if(t){if(t(o,s,w)===!1)return;for(;w<i;)if(s=w,t(po(),s,w)===!1)return}else{for(r=[o];w<i;)s=w,r.push(po());return r}}catch(i){throw i.lastPosition=s,i.values=r,i}finally{xn=!1,mo()}}_mergeStructures(e,t){this._onLoadedStructures&&(e=this._onLoadedStructures(e)),e=e||[],Object.isFrozen(e)&&(e=e.map(r=>r.slice(0)));for(let r=0,s=e.length;r<s;r++){let i=e[r];i&&(i.isShared=!0,r>=32&&(i.highByte=r-32>>5))}e.sharedLength=e.length;for(let r in t||[])if(r>=0){let s=e[r],i=t[r];i&&(s&&((e.restoreStructures||(e.restoreStructures=[]))[r]=s),e[r]=i)}return this.structures=e}decode(e,t){return this.unpack(e,t)}};function po(n){try{if(!de.trusted&&!xn){let t=se.sharedLength||0;t<se.length&&(se.length=t)}let e;if(de._readStruct&&U[w]<64&&U[w]>=32?(e=de._readStruct(U,w,ft),U=null,!(n&&n.lazy)&&e&&(e=e.toJSON()),w=ft):e=ke(),Le&&(w=Le.postBundlePosition,Le=null),xn&&(se.restoreStructures=null),w==ft)se&&se.restoreStructures&&hf(),se=null,U=null,rn&&(rn=null);else{if(w>ft)throw new Error("Unexpected end of MessagePack data");if(!xn){let t;try{t=JSON.stringify(e,(r,s)=>typeof s=="bigint"?`${s}n`:s).slice(0,100)}catch(r){t="(JSON view not available "+r+")"}throw new Error("Data read, but end of buffer not reached "+t)}}return e}catch(e){throw se&&se.restoreStructures&&hf(),mo(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")||w>ft)&&(e.incomplete=!0),e}}function hf(){for(let n in se.restoreStructures)se[n]=se.restoreStructures[n];se.restoreStructures=null}function ke(){let n=U[w++];if(n<160)if(n<128){if(n<64)return n;{let e=se[n&63]||de.getStructures&&Rf()[n&63];return e?(e.read||(e.read=Ac(e,n&63)),e.read()):n}}else if(n<144)if(n-=128,de.mapsAsObjects){let e={};for(let t=0;t<n;t++){let r=Sf();r==="__proto__"&&(r="__proto_"),e[r]=ke()}return e}else{let e=new Map;for(let t=0;t<n;t++)e.set(ke(),ke());return e}else{n-=144;let e=new Array(n);for(let t=0;t<n;t++)e[t]=ke();return de.freezeData?Object.freeze(e):e}else if(n<192){let e=n-160;if(Ft>=w)return Rn.slice(w-dt,(w+=e)-dt);if(Ft==0&&ft<140){let t=e<16?Cc(e):xf(e);if(t!=null)return t}return kc(e)}else{let e;switch(n){case 192:return null;case 193:return Le?(e=ke(),e>0?Le[1].slice(Le.position1,Le.position1+=e):Le[0].slice(Le.position0,Le.position0-=e)):vc;case 194:return!1;case 195:return!0;case 196:if(e=U[w++],e===void 0)throw new Error("Unexpected end of buffer");return Rc(e);case 197:return e=re.getUint16(w),w+=2,Rc(e);case 198:return e=re.getUint32(w),w+=4,Rc(e);case 199:return zn(U[w++]);case 200:return e=re.getUint16(w),w+=2,zn(e);case 201:return e=re.getUint32(w),w+=4,zn(e);case 202:if(e=re.getFloat32(w),de.useFloat32>2){let t=go[(U[w]&127)<<1|U[w+1]>>7];return w+=4,(t*e+(e>0?.5:-.5)>>0)/t}return w+=4,e;case 203:return e=re.getFloat64(w),w+=8,e;case 204:return U[w++];case 205:return e=re.getUint16(w),w+=2,e;case 206:return e=re.getUint32(w),w+=4,e;case 207:return de.int64AsType==="number"?(e=re.getUint32(w)*4294967296,e+=re.getUint32(w+4)):de.int64AsType==="string"?e=re.getBigUint64(w).toString():de.int64AsType==="auto"?(e=re.getBigUint64(w),e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=re.getBigUint64(w),w+=8,e;case 208:return re.getInt8(w++);case 209:return e=re.getInt16(w),w+=2,e;case 210:return e=re.getInt32(w),w+=4,e;case 211:return de.int64AsType==="number"?(e=re.getInt32(w)*4294967296,e+=re.getUint32(w+4)):de.int64AsType==="string"?e=re.getBigInt64(w).toString():de.int64AsType==="auto"?(e=re.getBigInt64(w),e>=BigInt(-2)<<BigInt(52)&&e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=re.getBigInt64(w),w+=8,e;case 212:if(e=U[w++],e==114)return wf(U[w++]&63);{let t=Xe[e];if(t)return t.read?(w++,t.read(ke())):t.noBuffer?(w++,t()):t(U.subarray(w,++w));throw new Error("Unknown extension "+e)}case 213:return e=U[w],e==114?(w++,wf(U[w++]&63,U[w++])):zn(2);case 214:return zn(4);case 215:return zn(8);case 216:return zn(16);case 217:return e=U[w++],Ft>=w?Rn.slice(w-dt,(w+=e)-dt):My(e);case 218:return e=re.getUint16(w),w+=2,Ft>=w?Rn.slice(w-dt,(w+=e)-dt):Dy(e);case 219:return e=re.getUint32(w),w+=4,Ft>=w?Rn.slice(w-dt,(w+=e)-dt):Ny(e);case 220:return e=re.getUint16(w),w+=2,mf(e);case 221:return e=re.getUint32(w),w+=4,mf(e);case 222:return e=re.getUint16(w),w+=2,gf(e);case 223:return e=re.getUint32(w),w+=4,gf(e);default:if(n>=224)return n-256;if(n===void 0){let t=new Error("Unexpected end of MessagePack data");throw t.incomplete=!0,t}throw new Error("Unknown MessagePack token "+n)}}}var Oy=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function Ac(n,e){function t(){if(t.count++>ff){let s;try{s=n.read=new Function("r","return function(){return "+(de.freezeData?"Object.freeze":"")+"({"+n.map(i=>i==="__proto__"?"__proto_:r()":Oy.test(i)?i+":r()":"["+JSON.stringify(i)+"]:r()").join(",")+"})}")(ke)}catch{return ff=1/0,t()}return n.read0=s,n.highByte===0&&(n.read=pf(e,n.read)),s()}let r={};for(let s=0,i=n.length;s<i;s++){let o=n[s];o==="__proto__"&&(o="__proto_"),r[o]=ke()}return de.freezeData?Object.freeze(r):r}return t.count=0,n.read0=t,n.highByte===0?pf(e,t):t}var pf=(n,e)=>function(){let t=U[w++];if(t===0)return e();let r=n<32?-(n+(t<<5)):n+(t<<5),s=se[r]||Rf()[r];if(!s)throw new Error("Record id is not defined for "+r);return s.read||(s.read=Ac(s,n)),s.read()};function Rf(){let n=kf(()=>(U=null,de.getStructures()));return se=de._mergeStructures(n,se)}var kc=Ns,My=Ns,Dy=Ns,Ny=Ns;function Ns(n){let e;if(n<16&&(e=Cc(n)))return e;if(n>64&&xc)return xc.decode(U.subarray(w,w+=n));let t=w+n,r=[];for(e="";w<t;){let s=U[w++];if((s&128)===0)r.push(s);else if((s&224)===192){let i=U[w++]&63,o=(s&31)<<6|i;o<128?r.push(65533):r.push(o)}else if((s&240)===224){let i=U[w++]&63,o=U[w++]&63,a=(s&31)<<12|i<<6|o;a<2048||a>=55296&&a<=57343?r.push(65533):r.push(a)}else if((s&248)===240){let i=U[w++]&63,o=U[w++]&63,a=U[w++]&63,c=(s&7)<<18|i<<12|o<<6|a;c<65536||c>1114111?r.push(65533):(c>65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|c&1023),r.push(c))}else r.push(65533);r.length>=4096&&(e+=Be.apply(String,r),r.length=0)}return r.length>0&&(e+=Be.apply(String,r)),e}function mf(n){let e=new Array(n);for(let t=0;t<n;t++)e[t]=ke();return de.freezeData?Object.freeze(e):e}function gf(n){if(de.mapsAsObjects){let e={};for(let t=0;t<n;t++){let r=Sf();r==="__proto__"&&(r="__proto_"),e[r]=ke()}return e}else{let e=new Map;for(let t=0;t<n;t++)e.set(ke(),ke());return e}}var Be=String.fromCharCode;function xf(n){let e=w,t=new Array(n);for(let r=0;r<n;r++){let s=U[w++];if((s&128)>0){w=e;return}t[r]=s}return Be.apply(String,t)}function Cc(n){if(n<4)if(n<2){if(n===0)return"";{let e=U[w++];if((e&128)>1){w-=1;return}return Be(e)}}else{let e=U[w++],t=U[w++];if((e&128)>0||(t&128)>0){w-=2;return}if(n<3)return Be(e,t);let r=U[w++];if((r&128)>0){w-=3;return}return Be(e,t,r)}else{let e=U[w++],t=U[w++],r=U[w++],s=U[w++];if((e&128)>0||(t&128)>0||(r&128)>0||(s&128)>0){w-=4;return}if(n<6){if(n===4)return Be(e,t,r,s);{let i=U[w++];if((i&128)>0){w-=5;return}return Be(e,t,r,s,i)}}else if(n<8){let i=U[w++],o=U[w++];if((i&128)>0||(o&128)>0){w-=6;return}if(n<7)return Be(e,t,r,s,i,o);let a=U[w++];if((a&128)>0){w-=7;return}return Be(e,t,r,s,i,o,a)}else{let i=U[w++],o=U[w++],a=U[w++],c=U[w++];if((i&128)>0||(o&128)>0||(a&128)>0||(c&128)>0){w-=8;return}if(n<10){if(n===8)return Be(e,t,r,s,i,o,a,c);{let u=U[w++];if((u&128)>0){w-=9;return}return Be(e,t,r,s,i,o,a,c,u)}}else if(n<12){let u=U[w++],d=U[w++];if((u&128)>0||(d&128)>0){w-=10;return}if(n<11)return Be(e,t,r,s,i,o,a,c,u,d);let h=U[w++];if((h&128)>0){w-=11;return}return Be(e,t,r,s,i,o,a,c,u,d,h)}else{let u=U[w++],d=U[w++],h=U[w++],m=U[w++];if((u&128)>0||(d&128)>0||(h&128)>0||(m&128)>0){w-=12;return}if(n<14){if(n===12)return Be(e,t,r,s,i,o,a,c,u,d,h,m);{let g=U[w++];if((g&128)>0){w-=13;return}return Be(e,t,r,s,i,o,a,c,u,d,h,m,g)}}else{let g=U[w++],p=U[w++];if((g&128)>0||(p&128)>0){w-=14;return}if(n<15)return Be(e,t,r,s,i,o,a,c,u,d,h,m,g,p);let y=U[w++];if((y&128)>0){w-=15;return}return Be(e,t,r,s,i,o,a,c,u,d,h,m,g,p,y)}}}}}function yf(){let n=U[w++],e;if(n<192)e=n-160;else switch(n){case 217:e=U[w++];break;case 218:e=re.getUint16(w),w+=2;break;case 219:e=re.getUint32(w),w+=4;break;default:throw new Error("Expected string")}return Ns(e)}function Rc(n){return de.copyBuffers?Uint8Array.prototype.slice.call(U,w,w+=n):U.subarray(w,w+=n)}function zn(n){let e=U[w++];if(Xe[e]){let t;return Xe[e](U.subarray(w,t=w+=n),r=>{w=r;try{return ke()}finally{w=t}})}else throw new Error("Unknown extension type "+e)}var bf=new Array(4096);function Sf(){let n=U[w++];if(n>=160&&n<192){if(n=n-160,Ft>=w)return Rn.slice(w-dt,(w+=n)-dt);if(!(Ft==0&&ft<180))return kc(n)}else return w--,Tf(ke());let e=(n<<5^(n>1?re.getUint16(w):n>0?U[w]:0))&4095,t=bf[e],r=w,s=w+n-3,i,o=0;if(t&&t.bytes==n){for(;r<s;){if(i=re.getUint32(r),i!=t[o++]){r=1879048192;break}r+=4}for(s+=3;r<s;)if(i=U[r++],i!=t[o++]){r=1879048192;break}if(r===s)return w=r,t.string;s-=3,r=w}for(t=[],bf[e]=t,t.bytes=n;r<s;)i=re.getUint32(r),t.push(i),r+=4;for(s+=3;r<s;)i=U[r++],t.push(i);let a=n<16?Cc(n):xf(n);return a!=null?t.string=a:t.string=kc(n)}function Tf(n){if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean"||typeof n=="bigint")return n.toString();if(n==null)return n+"";if(de.allowArraysInMapKeys&&Array.isArray(n)&&n.flat().every(e=>["string","number","boolean","bigint"].includes(typeof e)))return n.flat().toString();throw new Error(`Invalid property type for record: ${typeof n}`)}var wf=(n,e)=>{let t=ke().map(Tf),r=n;e!==void 0&&(n=n<32?-((e<<5)+n):(e<<5)+n,t.highByte=e);let s=se[n];return s&&(s.isShared||xn)&&((se.restoreStructures||(se.restoreStructures=[]))[n]=s),se[n]=t,t.read=Ac(t,r),(t.read0||t.read)()};Xe[0]=()=>{};Xe[0].noBuffer=!0;Xe[66]=n=>{let e=n.byteLength%8||8,t=BigInt(n[0]&128?n[0]-256:n[0]);for(let r=1;r<e;r++)t<<=BigInt(8),t+=BigInt(n[r]);if(n.byteLength!==e){let r=new DataView(n.buffer,n.byteOffset,n.byteLength),s=(i,o)=>{let a=o-i;if(a<=40){let h=r.getBigUint64(i);for(let m=i+8;m<o;m+=8)h<<=BigInt(64),h|=r.getBigUint64(m);return h}let c=i+(a>>4<<3),u=s(i,c),d=s(c,o);return u<<BigInt((o-c)*8)|d};t=t<<BigInt((r.byteLength-e)*8)|s(e,r.byteLength)}return t};var _f={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError=="function"?AggregateError:null};Xe[101]=()=>{let n=ke();if(!_f[n[0]]){let e=Error(n[1],{cause:n[2]});return e.name=n[0],e}return _f[n[0]](n[1],{cause:n[2]})};Xe[105]=n=>{if(de.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=re.getUint32(w-4);rn||(rn=new Map);let t=U[w],r;t>=144&&t<160||t==220||t==221?r=[]:t>=128&&t<144||t==222||t==223?r=new Map:(t>=199&&t<=201||t>=212&&t<=216)&&U[w+1]===115?r=new Set:r={};let s={target:r};rn.set(e,s);let i=ke();if(s.used)Object.assign(r,i);else return s.target=i;if(r instanceof Map)for(let[o,a]of i.entries())r.set(o,a);if(r instanceof Set)for(let o of Array.from(i))r.add(o);return r};Xe[112]=n=>{if(de.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=re.getUint32(w-4),t=rn.get(e);return t.used=!0,t.target};Xe[115]=()=>new Set(ke());var Ic=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(n=>n+"Array"),By=typeof globalThis=="object"?globalThis:window;Xe[116]=n=>{let e=n[0],t=Uint8Array.prototype.slice.call(n,1).buffer,r=Ic[e];if(!r){if(e===16)return t;if(e===17)return new DataView(t);throw new Error("Could not find typed array for code "+e)}return new By[r](t)};Xe[120]=()=>{let n=ke();return new RegExp(n[0],n[1])};var Ly=[];Xe[98]=n=>{let e=(n[0]<<24)+(n[1]<<16)+(n[2]<<8)+n[3],t=w;return w+=e-n.length,Le=Ly,Le=[yf(),yf()],Le.position0=0,Le.position1=0,Le.postBundlePosition=w,w=t,ke()};Xe[255]=n=>n.length==4?new Date((n[0]*16777216+(n[1]<<16)+(n[2]<<8)+n[3])*1e3):n.length==8?new Date(((n[0]<<22)+(n[1]<<14)+(n[2]<<6)+(n[3]>>2))/1e6+((n[3]&3)*4294967296+n[4]*16777216+(n[5]<<16)+(n[6]<<8)+n[7])*1e3):n.length==12?new Date(((n[0]<<24)+(n[1]<<16)+(n[2]<<8)+n[3])/1e6+((n[4]&128?-281474976710656:0)+n[6]*1099511627776+n[7]*4294967296+n[8]*16777216+(n[9]<<16)+(n[10]<<8)+n[11])*1e3):new Date("invalid");function kf(n){de&&de._onSaveState&&de._onSaveState();let e=ft,t=w,r=Tc,s=dt,i=Ft,o=Rn,a=Sc,c=rn,u=Le,d=new Uint8Array(U.slice(0,ft)),h=se,m=se.slice(0,se.length),g=de,p=xn,y=n();return ft=e,w=t,Tc=r,dt=s,Ft=i,Rn=o,Sc=a,rn=c,Le=u,U=d,xn=p,se=h,se.splice(0,se.length,...m),de=g,re=new DataView(U.buffer,U.byteOffset,U.byteLength),y}function mo(){U=null,rn=null,se=null}var go=new Array(147);for(let n=0;n<256;n++)go[n]=+("1e"+Math.floor(45.15-n*.30103));var yo=new Sn({useRecords:!1}),bo=yo.unpack,Fy=yo.unpackMultiple,Uy=yo.unpack,wo={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},$y=new Float32Array(1),xE=new Uint8Array($y.buffer,0,4);Sn.SUPPORTS_STRUCT_HOOKS=!0;var Eo;try{Eo=new TextEncoder}catch{}var Mc,Dc,vr=typeof Buffer<"u",_o=vr?function(n){return Buffer.allocUnsafeSlow(n)}:Uint8Array,If=vr?Buffer:Uint8Array,vf=vr?4294967296:2144337920,T,Bs,me,E=0,Ve,xe=null,Vy=21760,jy=/[\u0080-\uFFFF]/,kr=Symbol("record-id"),Tn=class extends Sn{constructor(e){super(e),this.offset=0;let t,r,s,i,o,a=If.prototype.utf8Write?function(S,F){return T.utf8Write(S,F,T.byteLength-F)}:Eo&&Eo.encodeInto?function(S,F){return Eo.encodeInto(S,T.subarray(F)).written}:!1,c=this;e||(e={});let u=e&&e.sequential,d=e.structures||e.saveStructures,h=e.maxSharedStructures;if(h==null&&(h=d?32:0),h>8160)throw new Error("Maximum maxSharedStructure is 8160");e.structuredClone&&e.moreTypes==null&&(this.moreTypes=!0);let m=e.maxOwnStructures;m==null&&(m=d?32:64),!this.structures&&e.useRecords!=!1&&(this.structures=[]);let g=h>32||m+h>64,p=h+64,y=h+m+64;if(y>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let x=[],k=0,I=0;this.pack=this.encode=function(S,F){if(T||(T=new _o(8192),me=T.dataView||(T.dataView=new DataView(T.buffer,0,8192)),E=0),Ve=T.length-10,Ve-E<2048?(T=new _o(T.length),me=T.dataView||(T.dataView=new DataView(T.buffer,0,T.length)),Ve=T.length-10,E=0):E=E+7&2147483640,r=E,F&Ar&&(E+=F&255),o=c.structuredClone?new Map:null,c.bundleStrings&&typeof S!="string"?(xe=[],xe.size=1/0):xe=null,i=c.structures,i){i.uninitialized&&(i=c._mergeStructures(c.getStructures()));let D=i.sharedLength||0;if(D>h)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+i.sharedLength);if(!i.transitions){i.transitions=Object.create(null);for(let M=0;M<D;M++){let z=i[M];if(!z)continue;let W,q=i.transitions;for(let ae=0,Y=z.length;ae<Y;ae++){let Ze=z[ae];W=q[Ze],W||(W=q[Ze]=Object.create(null)),q=W}q[kr]=M+64}this.lastNamedStructuresLength=D}u||(i.nextId=D+64)}s&&(s=!1);let B;try{c._writeStruct&&S&&typeof S=="object"?S.constructor===Object?Z(S):S.constructor!==Map&&!Array.isArray(S)&&!Dc.some(M=>S instanceof M)?Z(S.toJSON?S.toJSON():S):C(S):C(S);let D=xe;if(xe&&Cf(r,C,0),o&&o.idsToInsert){let M=o.idsToInsert.sort((ae,Y)=>ae.offset>Y.offset?1:-1),z=M.length,W=-1;for(;D&&z>0;){let ae=M[--z].offset+r;ae<D.stringsPosition+r&&W===-1&&(W=0),ae>D.position+r?W>=0&&(W+=6):(W>=0&&(me.setUint32(D.position+r,me.getUint32(D.position+r)+W),W=-1),D=D.previous,z++)}W>=0&&D&&me.setUint32(D.position+r,me.getUint32(D.position+r)+W),E+=M.length*6,E>Ve&&ee(E),c.offset=E;let q=qy(T.subarray(r,E),M);return o=null,q}return c.offset=E,F&Of?(T.start=r,T.end=E,T):T.subarray(r,E)}catch(D){throw B=D,D}finally{if(i&&(L(),s&&c.saveStructures)){let D=i.sharedLength||0,M=T.subarray(r,E),z=(c._prepareStructures||Gy)(i,c);if(!B)return c.saveStructures(z,z.isCompatible)===!1?(i.uninitialized=!0,c.pack(S,F)):(c.lastNamedStructuresLength=D,T.length>1073741824&&(T=null),M)}T.length>1073741824&&(T=null),F&Mf&&(E=r)}};let L=()=>{I<10&&I++;let S=i.sharedLength||0;if(i.length>S&&!u&&(i.length=S),k>1e4)i.transitions=null,I=0,k=0,x.length>0&&(x=[]);else if(x.length>0&&!u){for(let F=0,B=x.length;F<B;F++)x[F][kr]=0;x=[]}},N=S=>{var F=S.length;F<16?T[E++]=144|F:F<65536?(T[E++]=220,T[E++]=F>>8,T[E++]=F&255):(T[E++]=221,me.setUint32(E,F),E+=4);for(let B=0;B<F;B++)C(S[B])},C=S=>{E>Ve&&(T=ee(E));var F=typeof S,B;if(F==="string"){let D=S.length;if(xe&&D>=4&&D<4096){if((xe.size+=D)>Vy){let q,ae=(xe[0]?xe[0].length*3+xe[1].length:0)+10;E+ae>Ve&&(T=ee(E+ae));let Y;xe.position?(Y=xe,T[E]=200,E+=3,T[E++]=98,q=E-r,E+=4,Cf(r,C,0),me.setUint16(q+r-3,E-r-q)):(T[E++]=214,T[E++]=98,q=E-r,E+=4),xe=["",""],xe.previous=Y,xe.size=0,xe.position=q}let W=jy.test(S);xe[W?0:1]+=S,T[E++]=193,C(W?-D:D);return}let M;D<32?M=1:D<256?M=2:D<65536?M=3:M=5;let z=D*3;if(E+z>Ve&&(T=ee(E+z)),D<64||!a){let W,q,ae,Y=E+M;for(W=0;W<D;W++)q=S.charCodeAt(W),q<128?T[Y++]=q:q<2048?(T[Y++]=q>>6|192,T[Y++]=q&63|128):(q&64512)===55296&&((ae=S.charCodeAt(W+1))&64512)===56320?(q=65536+((q&1023)<<10)+(ae&1023),W++,T[Y++]=q>>18|240,T[Y++]=q>>12&63|128,T[Y++]=q>>6&63|128,T[Y++]=q&63|128):(T[Y++]=q>>12|224,T[Y++]=q>>6&63|128,T[Y++]=q&63|128);B=Y-E-M}else B=a(S,E+M);B<32?T[E++]=160|B:B<256?(M<2&&T.copyWithin(E+2,E+1,E+1+B),T[E++]=217,T[E++]=B):B<65536?(M<3&&T.copyWithin(E+3,E+2,E+2+B),T[E++]=218,T[E++]=B>>8,T[E++]=B&255):(M<5&&T.copyWithin(E+5,E+3,E+3+B),T[E++]=219,me.setUint32(E,B),E+=4),E+=B}else if(F==="number")if(S>>>0===S)S<32||S<128&&this.useRecords===!1||S<64&&!this._writeStruct?T[E++]=S:S<256?(T[E++]=204,T[E++]=S):S<65536?(T[E++]=205,T[E++]=S>>8,T[E++]=S&255):(T[E++]=206,me.setUint32(E,S),E+=4);else if(S>>0===S)S>=-32?T[E++]=256+S:S>=-128?(T[E++]=208,T[E++]=S+256):S>=-32768?(T[E++]=209,me.setInt16(E,S),E+=2):(T[E++]=210,me.setInt32(E,S),E+=4);else{let D;if((D=this.useFloat32)>0&&S<4294967296&&S>=-2147483648){T[E++]=202,me.setFloat32(E,S);let M;if(D<4||(M=S*go[(T[E]&127)<<1|T[E+1]>>7])>>0===M){E+=4;return}else E--}T[E++]=203,me.setFloat64(E,S),E+=8}else if(F==="object"||F==="function")if(!S)T[E++]=192;else{if(o){let M=o.get(S);if(M){if(!M.id){let z=o.idsToInsert||(o.idsToInsert=[]);M.id=z.push(M)}T[E++]=214,T[E++]=112,me.setUint32(E,M.id),E+=4;return}else o.set(S,{offset:E-r})}let D=S.constructor;if(D===Object)V(S);else if(D===Array)N(S);else if(D===Map)if(this.mapAsEmptyObject)T[E++]=128;else{B=S.size,B<16?T[E++]=128|B:B<65536?(T[E++]=222,T[E++]=B>>8,T[E++]=B&255):(T[E++]=223,me.setUint32(E,B),E+=4);for(let[M,z]of S)C(M),C(z)}else{for(let M=0,z=Mc.length;M<z;M++){let W=Dc[M];if(S instanceof W){let q=Mc[M];if(q.write){q.type&&(T[E++]=212,T[E++]=q.type,T[E++]=0);let ln=q.write.call(this,S);ln===S?Array.isArray(S)?N(S):V(S):C(ln);return}let ae=T,Y=me,Ze=E;T=null;let pt;try{pt=q.pack.call(this,S,ln=>(T=ae,ae=null,E+=ln,E>Ve&&ee(E),{target:T,targetView:me,position:E-ln}),C)}finally{ae&&(T=ae,me=Y,E=Ze,Ve=T.length-10)}pt&&(pt.length+E>Ve&&ee(pt.length+E),E=Af(pt,T,E,q.type));return}}if(Array.isArray(S))N(S);else{if(S.toJSON){let M=S.toJSON();if(M!==S)return C(M)}if(F==="function")return C(this.writeFunction&&this.writeFunction(S));V(S)}}}else if(F==="boolean")T[E++]=S?195:194;else if(F==="bigint"){if(S<9223372036854776e3&&S>=-9223372036854776e3)T[E++]=211,me.setBigInt64(E,S);else if(S<18446744073709552e3&&S>0)T[E++]=207,me.setBigUint64(E,S);else if(this.largeBigIntToFloat)T[E++]=203,me.setFloat64(E,Number(S));else{if(this.largeBigIntToString)return C(S.toString());if(this.useBigIntExtension||this.moreTypes){let D=S<0?BigInt(-1):BigInt(0),M;if(S>>BigInt(65536)===D){let z=BigInt(18446744073709552e3)-BigInt(1),W=[];for(;W.push(S&z),S>>BigInt(63)!==D;)S>>=BigInt(64);M=new Uint8Array(new BigUint64Array(W).buffer),M.reverse()}else{let z=S<0,W=(z?~S:S).toString(16);if(W.length%2?W="0"+W:parseInt(W.charAt(0),16)>=8&&(W="00"+W),vr)M=Buffer.from(W,"hex");else{M=new Uint8Array(W.length/2);for(let q=0;q<M.length;q++)M[q]=parseInt(W.slice(q*2,q*2+2),16)}if(z)for(let q=0;q<M.length;q++)M[q]=~M[q]}M.length+E>Ve&&ee(M.length+E),E=Af(M,T,E,66);return}else throw new RangeError(S+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string")}E+=8}else if(F==="undefined")this.encodeUndefinedAsNil?T[E++]=192:(T[E++]=212,T[E++]=0,T[E++]=0);else throw new Error("Unknown type: "+F)},O=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?S=>{let F;if(this.skipValues){F=[];for(let M in S)(typeof S.hasOwnProperty!="function"||S.hasOwnProperty(M))&&!this.skipValues.includes(S[M])&&F.push(M)}else F=Object.keys(S);let B=F.length;B<16?T[E++]=128|B:B<65536?(T[E++]=222,T[E++]=B>>8,T[E++]=B&255):(T[E++]=223,me.setUint32(E,B),E+=4);let D;if(this.coercibleKeyAsNumber)for(let M=0;M<B;M++){D=F[M];let z=Number(D);C(isNaN(z)?D:z),C(S[D])}else for(let M=0;M<B;M++)C(D=F[M]),C(S[D])}:S=>{T[E++]=222;let F=E-r;E+=2;let B=0;for(let D in S)(typeof S.hasOwnProperty!="function"||S.hasOwnProperty(D))&&(C(D),C(S[D]),B++);if(B>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');T[F+++r]=B>>8,T[F+r]=B&255},A=this.useRecords===!1?O:e.progressiveRecords&&!g?S=>{let F,B=i.transitions||(i.transitions=Object.create(null)),D=E++-r,M;for(let z in S)if(typeof S.hasOwnProperty!="function"||S.hasOwnProperty(z)){if(F=B[z],F)B=F;else{let W=Object.keys(S),q=B;B=i.transitions;let ae=0;for(let Y=0,Ze=W.length;Y<Ze;Y++){let pt=W[Y];F=B[pt],F||(F=B[pt]=Object.create(null),ae++),B=F}D+r+1==E?(E--,ve(B,W,ae)):Pe(B,W,D,ae),M=!0,B=q[z]}C(S[z])}if(!M){let z=B[kr];z?T[D+r]=z:Pe(B,Object.keys(S),D,0)}}:S=>{let F,B=i.transitions||(i.transitions=Object.create(null)),D=0;for(let z in S)(typeof S.hasOwnProperty!="function"||S.hasOwnProperty(z))&&(F=B[z],F||(F=B[z]=Object.create(null),D++),B=F);let M=B[kr];M?M>=96&&g?(T[E++]=((M-=96)&31)+96,T[E++]=M>>5):T[E++]=M:ve(B,B.__keys__||Object.keys(S),D);for(let z in S)(typeof S.hasOwnProperty!="function"||S.hasOwnProperty(z))&&C(S[z])},P=typeof this.useRecords=="function"&&this.useRecords,V=P?S=>{P(S)?A(S):O(S)}:A,Z=S=>{let F=c._writeStruct(S,T,r,E,i,ee,(B,D,M)=>{if(M)return s=!0;E=D;let z=T;return C(B),L(),z!==T?{position:E,targetView:me,target:T}:E});if(F===0)return V(S);E=F},ee=S=>{let F;if(S>16777216){if(S-r>vf)throw new Error("Packed buffer would be larger than maximum buffer size");F=Math.min(vf,Math.round(Math.max((S-r)*(S>67108864?1.25:2),4194304)/4096)*4096)}else F=(Math.max(S-r<<2,T.length-1)>>12)+1<<12;let B=new _o(F);return me=B.dataView||(B.dataView=new DataView(B.buffer,0,F)),S=Math.min(S,T.length),T.copy?T.copy(B,0,r,S):B.set(T.slice(r,S)),E-=r,r=0,Ve=B.length-10,T=B},ve=(S,F,B)=>{let D=i.nextId;D||(D=64),D<p&&this.shouldShareStructure&&!this.shouldShareStructure(F)?(D=i.nextOwnId,D<y||(D=p),i.nextOwnId=D+1):(D>=y&&(D=p),i.nextId=D+1);let M=F.highByte=D>=96&&g?D-96>>5:-1;S[kr]=D,S.__keys__=F,i[D-64]=F,D<p?(F.isShared=!0,i.sharedLength=D-63,s=!0,M>=0?(T[E++]=(D&31)+96,T[E++]=M):T[E++]=D):(M>=0?(T[E++]=213,T[E++]=114,T[E++]=(D&31)+96,T[E++]=M):(T[E++]=212,T[E++]=114,T[E++]=D),B&&(k+=I*B),x.length>=m&&(x.shift()[kr]=0),x.push(S),C(F))},Pe=(S,F,B,D)=>{let M=T,z=E,W=Ve,q=r;T=Bs,E=0,r=0,T||(Bs=T=new _o(8192)),Ve=T.length-10,ve(S,F,D),Bs=T;let ae=E;if(T=M,E=z,Ve=W,r=q,ae>1){let Y=E+ae-1;Y>Ve&&ee(Y);let Ze=B+r;T.copyWithin(Ze+ae,Ze+1,E),T.set(Bs.slice(0,ae),Ze),E=Y}else T[B+r]=Bs[0]}}useBuffer(e){T=e,T.dataView||(T.dataView=new DataView(T.buffer,T.byteOffset,T.byteLength)),me=T.dataView,E=0}set position(e){E=e}get position(){return E}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}};Dc=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,Ds];Mc=[{pack(n,e,t){let r=n.getTime()/1e3;if((this.useTimestamp32||n.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:s,targetView:i,position:o}=e(6);s[o++]=214,s[o++]=255,i.setUint32(o,r)}else if(r>0&&r<4294967296){let{target:s,targetView:i,position:o}=e(10);s[o++]=215,s[o++]=255,i.setUint32(o,n.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),i.setUint32(o+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return e(0),t(this.onInvalidDate());let{target:s,targetView:i,position:o}=e(3);s[o++]=212,s[o++]=255,s[o++]=255}else{let{target:s,targetView:i,position:o}=e(15);s[o++]=199,s[o++]=12,s[o++]=255,i.setUint32(o,n.getMilliseconds()*1e6),i.setBigInt64(o+4,BigInt(Math.floor(r)))}}},{pack(n,e,t){if(this.setAsEmptyObject)return e(0),t({});let r=Array.from(n),{target:s,position:i}=e(this.moreTypes?3:0);this.moreTypes&&(s[i++]=212,s[i++]=115,s[i++]=0),t(r)}},{pack(n,e,t){let{target:r,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(r[s++]=212,r[s++]=101,r[s++]=0),t([n.name,n.message,n.cause])}},{pack(n,e,t){let{target:r,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(r[s++]=212,r[s++]=120,r[s++]=0),t([n.source,n.flags])}},{pack(n,e){this.moreTypes?Pc(n,16,e):Oc(vr?Buffer.from(n):new Uint8Array(n),e)}},{pack(n,e){let t=n.constructor;t!==If&&this.moreTypes?Pc(n,Ic.indexOf(t.name),e):Oc(n,e)}},{pack(n,e){this.moreTypes?Pc(n,17,e):Oc(vr?Buffer.from(n):new Uint8Array(n),e)}},{pack(n,e){let{target:t,position:r}=e(1);t[r]=193}}];function Pc(n,e,t,r){let s=n.byteLength;if(s+1<256){var{target:i,position:o}=t(4+s);i[o++]=199,i[o++]=s+1}else if(s+1<65536){var{target:i,position:o}=t(5+s);i[o++]=200,i[o++]=s+1>>8,i[o++]=s+1&255}else{var{target:i,position:o,targetView:a}=t(7+s);i[o++]=201,a.setUint32(o,s+1),o+=4}i[o++]=116,i[o++]=e,n.buffer||(n=new Uint8Array(n)),i.set(new Uint8Array(n.buffer,n.byteOffset,n.byteLength),o)}function Oc(n,e){let t=n.byteLength;var r,s;if(t<256){var{target:r,position:s}=e(t+2);r[s++]=196,r[s++]=t}else if(t<65536){var{target:r,position:s}=e(t+3);r[s++]=197,r[s++]=t>>8,r[s++]=t&255}else{var{target:r,position:s,targetView:i}=e(t+5);r[s++]=198,i.setUint32(s,t),s+=4}r.set(n,s)}function Af(n,e,t,r){let s=n.length;switch(s){case 1:e[t++]=212;break;case 2:e[t++]=213;break;case 4:e[t++]=214;break;case 8:e[t++]=215;break;case 16:e[t++]=216;break;default:s<256?(e[t++]=199,e[t++]=s):s<65536?(e[t++]=200,e[t++]=s>>8,e[t++]=s&255):(e[t++]=201,e[t++]=s>>24,e[t++]=s>>16&255,e[t++]=s>>8&255,e[t++]=s&255)}return e[t++]=r,e.set(n,t),t+=s,t}function qy(n,e){let t,r=e.length*6,s=n.length-r;for(;t=e.pop();){let i=t.offset,o=t.id;n.copyWithin(i+r,i,s),r-=6;let a=i+r;n[a++]=214,n[a++]=105,n[a++]=o>>24,n[a++]=o>>16&255,n[a++]=o>>8&255,n[a++]=o&255,s=i}return n}function Cf(n,e,t){if(xe.length>0){me.setUint32(xe.position+n,E+t-xe.position-n),xe.stringsPosition=E-n;let r=xe;xe=null,e(r[0]),e(r[1])}}function Gy(n,e){return n.isCompatible=t=>{let r=!t||(e.lastNamedStructuresLength||0)===t.length;return r||e._mergeStructures(t),r},n}Tn.SUPPORTS_STRUCT_HOOKS=!0;var Pf=new Tn({useRecords:!1}),Hy=Pf.pack,zy=Pf.pack;var{NEVER:Wy,ALWAYS:Jy,DECIMAL_ROUND:Ky,DECIMAL_FIT:Yy}=wo,Of=512,Mf=1024,Ar=2048;He();Yt();var Xy=9,Ro=class{constructor(){l(this,"pending",new Uint8Array(0))}push(e){if(!e||e.byteLength===0)return[];let t=this.pending.byteLength===0?e:Qy(this.pending,e),r=[],s=0;for(;s<t.byteLength;){let i={offset:s},o;try{o=te.number(t,i)}catch(c){if(t.byteLength-s<=Xy)break;throw c}let a=i.offset+o;if(a>t.byteLength)break;r.push(t.subarray(i.offset,a)),s=a}return this.pending=s<t.byteLength?t.slice(s):new Uint8Array(0),r}};function Qy(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}var Ls=class{constructor(e){l(this,"wt");l(this,"url");l(this,"isOpen",!1);l(this,"events");l(this,"reader");l(this,"writer");l(this,"unreliableReader");l(this,"unreliableWriter");l(this,"lengthPrefixBuffer",new Uint8Array(9));l(this,"reliableReassembler",new Ro);l(this,"unreliableReassembler",new Ro);this.events=e}connect(e,t={}){this.url=e;let r=t.fingerprint&&{serverCertificateHashes:[{algorithm:"sha-256",value:new Uint8Array(t.fingerprint)}]}||void 0;this.wt=new WebTransport(e,r),this.wt.ready.then(s=>{console.log("WebTransport ready!",s),this.isOpen=!0,this.unreliableReader=this.wt.datagrams.readable.getReader();let i=this.wt.datagrams;this.unreliableWriter=(i.createWritable?i.createWritable():i.writable).getWriter(),this.wt.incomingBidirectionalStreams.getReader().read().then(a=>{this.reader=a.value.readable.getReader(),this.writer=a.value.writable.getWriter(),this.sendSeatReservation(t.roomId,t.sessionId,t.reconnectionToken,t.skipHandshake),this.readIncomingData(),this.readIncomingUnreliableData()}).catch(a=>{console.error("failed to read incoming stream",a),console.error("TODO: close the connection")})}).catch(s=>{console.log("WebTransport not ready!",s),this._close()}),this.wt.closed.then(s=>{console.log("WebTransport closed w/ success",s),this.events.onclose({code:s.closeCode,reason:s.reason})}).catch(s=>{console.log("WebTransport closed w/ error",s),this.events.onerror(s),this.events.onclose({code:s.closeCode,reason:s.reason})}).finally(()=>{this._close()})}send(e){this.writer.write(this.frame(e))}sendUnreliable(e){this.unreliableWriter.write(this.frame(e))}frame(e){let t=e instanceof Uint8Array?e:new Uint8Array(e),r=Q.number(this.lengthPrefixBuffer,t.length,{offset:0}),s=new Uint8Array(r+t.length);return s.set(this.lengthPrefixBuffer.subarray(0,r),0),s.set(t,r),s}close(e,t){this.isOpen=!1;try{let r=this.wt?.close({closeCode:e,reason:t});r&&typeof r.catch=="function"&&r.catch(()=>{})}catch{}}readIncomingData(){return this.readLoop(this.reader,this.reliableReassembler,"reliable")}readIncomingUnreliableData(){return this.readLoop(this.unreliableReader,this.unreliableReassembler,"unreliable")}async readLoop(e,t,r){for(;this.isOpen;){let s;try{s=await e.read()}catch(i){await this.onChannelFailure(r,i);return}if(s.done||!s.value)return;for(let i of t.push(s.value))this.events.onmessage({data:i})}}async onChannelFailure(e,t){await new Promise(r=>setTimeout(r,0)),this.isOpen&&(console.error(`H3Transport: stopped reading the ${e} channel while the session was open`,t),this.close(Ne.ABNORMAL_CLOSURE,`h3 ${e} channel failed`))}sendSeatReservation(e,t,r,s){let i={offset:0},o=[];Q.string(o,e,i),Q.string(o,t,i),r&&Q.string(o,r,i),s&&Q.boolean(o,1,i),this.writer.write(new Uint8Array(o).buffer)}_close(){this.isOpen=!1}};var Lf=yp(Nf(),1);Yt();var Nc=globalThis.WebSocket||Lf.default,Bf=!1,xo=class{constructor(e){l(this,"ws");l(this,"protocols");l(this,"events");this.events=e}send(e){this.ws.send(e)}sendUnreliable(e){Bf||(Bf=!0,console.warn('@colyseus/sdk: the WebSocket transport has no unreliable channel \u2014 sending `mode:"unreliable"` traffic reliably instead. Use @colyseus/h3-transport (WebTransport) for datagram delivery.')),this.send(e)}connect(e,t){try{this.ws=new Nc(e,{headers:t,protocols:this.protocols})}catch{this.ws=new Nc(e,this.protocols)}this.ws.binaryType="arraybuffer",this.ws.onopen=r=>this.events.onopen?.(r),this.ws.onmessage=r=>this.events.onmessage?.(r),this.ws.onclose=r=>this.events.onclose?.(r),this.ws.onerror=r=>this.events.onerror?.(r)}close(e,t){e===Ne.MAY_TRY_RECONNECT&&this.events.onclose&&(this.ws.onclose=null,this.events.onclose({code:e,reason:t})),this.ws.close(e,t)}get isOpen(){return this.ws.readyState===Nc.OPEN}};Yt();var Fs=[],Bc=typeof addEventListener=="function"&&typeof removeEventListener=="function";Bc&&addEventListener("offline",()=>{console.warn(`@colyseus/sdk: \u{1F6D1} Network offline. Closing ${Fs.length} connection(s)`),Fs.forEach(n=>n())},!1);var Us,Cr=class{constructor(e){l(this,"transport");l(this,"events",{});l(this,"url");l(this,"options");he(this,Us,Bc?()=>this.close(Ne.MAY_TRY_RECONNECT):null);e==="h3"?this.transport=new Ls(this.events):this.transport=new xo(this.events)}connect(e,t){if(Bc){let r=this.events.onopen;this.events.onopen=i=>{Fs.push(H(this,Us)),r?.(i)};let s=this.events.onclose;this.events.onclose=i=>{Fs.splice(Fs.indexOf(H(this,Us)),1),s?.(i)}}this.url=e,this.options=t,this.transport.connect(e,t)}send(e){this.transport.send(e)}sendUnreliable(e){this.transport.sendUnreliable(e)}reconnect(e){if(this.transport instanceof Ls){this.transport.connect(this.url,{...this.options,...e});return}let t=new URL(this.url);for(let r in e)t.searchParams.set(r,e[r]);this.transport.connect(t.toString(),this.options)}close(e,t){this.transport.close(e,t)}get isOpen(){return this.transport.isOpen}};Us=new WeakMap;var Ff={};function Lc(n,e){Ff[n]=e}function Fc(n){let e=Ff[n];if(!e)throw new Error("missing serializer: "+n);return e}var So=()=>({emit(n,...e){let t=this.events[n]||[];for(let r=0,s=t.length;r<s;r++)t[r](...e)},events:{},on(n,e){return this.events[n]?.push(e)||(this.events[n]=[e]),()=>{this.events[n]=this.events[n]?.filter(t=>e!==t)}}});var Uf=new WeakMap,Uc=class{constructor(){l(this,"handlers",[])}register(e,t=!1){return this.handlers.push(e),this}invoke(...e){let t=this.handlers;for(let r=0,s=t.length;r<s;r++)t[r].apply(this,e)}invokeAsync(...e){return Promise.all(this.handlers.map(t=>t.apply(this,e)))}remove(e){let t=this.handlers.indexOf(e);t===-1&&(t=this.handlers.findIndex(r=>Uf.get(r)===e)),t!==-1&&(this.handlers=this.handlers.filter((r,s)=>s!==t))}clear(){this.handlers=[]}};function Wn(){let n=new Uc;function e(t){return n.register(t,this===null)}return e.once=t=>{let r=function(...s){n.remove(r),t.apply(this,s)};Uf.set(r,t),n.register(r)},e.remove=t=>n.remove(t),e.invoke=(...t)=>n.invoke(...t),e.invokeAsync=(...t)=>n.invokeAsync(...t),e.clear=()=>n.clear(),e}He();function $c(n){try{return Ki(n.serializer.decoder)}catch{return}}var Ir=class{constructor(){l(this,"state");l(this,"decoder")}setState(e,t){this.decoder.root.refs.size>1&&typeof this.decoder.decodeResync=="function"?this.decoder.decodeResync(e,t):this.decoder.decode(e,t)}getState(){return this.state}patch(e,t){return this.decoder.decode(e,t)}teardown(){this.decoder.root.clearRefs()}handshake(e,t){this.state?(Tt.decode(e,t),this.decoder=new St(this.state)):(this.decoder=Tt.decode(e,t),this.state=this.decoder.state)}};fo();function $f(){return{enabled:!0,retryCount:0,maxRetries:15,delay:100,minDelay:100,maxDelay:5e3,minUptime:5e3,backoff:Zy,maxEnqueuedMessages:10,enqueuedMessages:[],isReconnecting:!1}}var Zy=(n,e)=>Math.floor(Math.pow(2,n)*e);function To(n,e){n.reconnection.enqueuedMessages.push({data:e}),n.reconnection.enqueuedMessages.length>n.reconnection.maxEnqueuedMessages&&n.reconnection.enqueuedMessages.shift()}function Vf(n,e){if(!e){let r=new Error("request rejected");return r.name="rejected",r.reason=n,r}let t=new Error(n?.message??"request failed");return n?.name&&(t.name=n.name),n?.code!==void 0&&(t.code=n.code),t}Rs();var Vs,Pr,Or,Ut,$t,Mr,Vt,jf,qf,Gf,Hf,ko=class ko{constructor(e,t){he(this,Vt);l(this,"roomId");l(this,"sessionId");l(this,"reconnectionToken");l(this,"name");l(this,"connection");l(this,"onStateChange",Wn());l(this,"onError",Wn());l(this,"onLeave",Wn());l(this,"onReconnect",Wn());l(this,"onDrop",Wn());l(this,"onJoin",Wn());l(this,"serializerId");l(this,"serializer");l(this,"reconnection",$f());l(this,"joinedAtTime",0);l(this,"clock",Rr);l(this,"onMessageHandlers",So());l(this,"packr");l(this,"sharedBuffer");he(this,Vs,0);he(this,Pr);he(this,Or,0);he(this,Ut,new Map);he(this,$t);he(this,Mr,0);if(this.name=e,this.packr=new Tn,this.sharedBuffer=new Uint8Array(8192),t){let r=new(Fc("schema"));this.serializer=r;let s=new t;r.state=s,r.decoder=new St(s)}this.onLeave(()=>{this.removeAllListeners(),this.destroy()})}connect(e,t,r){this.connection=new Cr(t.protocol),this.connection.events.onmessage=this.onMessageCallback.bind(this),this.connection.events.onclose=i=>{if(On(this,Vt,Gf).call(this,"connection closed before a response was received."),this.joinedAtTime===0){console.warn?.(`Room connection was closed unexpectedly (${i.code}): ${i.reason}`),this.onError.invoke(i.code,i.reason);return}i.code===Ne.NO_STATUS_RECEIVED||i.code===Ne.ABNORMAL_CLOSURE||i.code===Ne.GOING_AWAY||i.code===Ne.MAY_TRY_RECONNECT?(this.onDrop.invoke(i.code,i.reason),this.handleReconnection(i.code,i.reason)):this.onLeave.invoke(i.code,i.reason)},this.connection.events.onerror=i=>{this.onError.invoke(i.code,i.reason)};let s=this.serializer?.getState()!==void 0;if(t.protocol==="h3"){let i=new URL(e);this.connection.connect(i.origin,{...t,skipHandshake:s})}else this.connection.connect(`${e}${s?"&skipHandshake=1":""}`,r)}leave(e=!0){return new Promise(t=>{this.onLeave(r=>t(r)),this.connection?e?(this.sharedBuffer[0]=_e.LEAVE_ROOM,this.connection.send(this.sharedBuffer.subarray(0,1))):this.connection.close():this.onLeave.invoke(Ne.CONSENTED)})}onMessage(e,t){return this.onMessageHandlers.on(this.getMessageHandlerKey(e),t)}ping(e){this.connection?.isOpen&&(pe(this,Vs,$e()),pe(this,Pr,e),this.sharedBuffer[0]=_e.PING,this.connection.send(this.sharedBuffer.subarray(0,1)))}send(e,t,r){if(r!==void 0){this.request(e,t).then(a=>r(a,void 0),a=>r(void 0,a));return}let s={offset:1};this.sharedBuffer[0]=_e.ROOM_DATA,typeof e=="string"?Q.string(this.sharedBuffer,e,s):Q.number(this.sharedBuffer,e,s);let i=s.offset,o;t!==void 0?(o=this.packr.pack(t,Ar|i),o.set(this.sharedBuffer.subarray(0,i),0)):o=this.sharedBuffer.subarray(0,i),this.connection.isOpen?this.connection.send(o):To(this,new Uint8Array(o))}request(e,t,r){if(!this.connection.isOpen)return Promise.reject(new Error(`cannot send request "${e}": connection is not open.`));let s=r?.timeout??ko.defaultRequestTimeout;return new Promise((i,o)=>{let a,c=this.sendRequest(e,t,{mode:r?.mode},(u,d,h)=>{clearTimeout(a),u?i(d):o(Vf(d,h))},u=>{clearTimeout(a),o(new Error(u))});a=setTimeout(()=>{this.cancelRequest(c),o(new Error(`request "${e}" timed out after ${s}ms.`))},s)})}sendRequest(e,t,r,s,i){let o=On(this,Vt,jf).call(this),a=On(this,Vt,qf).call(this,o,e,t);if(r.mode==="unreliable"){if(!this.connection.isOpen)return-1;this.connection.sendUnreliable(a)}else this.connection.isOpen?this.connection.send(a):To(this,new Uint8Array(a));return H(this,Ut).set(o,{onReply:s,onClose:i}),o}cancelRequest(e){H(this,Ut).delete(e)}sendUnreliable(e,t){if(!this.connection.isOpen)return;let r={offset:1};this.sharedBuffer[0]=_e.ROOM_DATA,typeof e=="string"?Q.string(this.sharedBuffer,e,r):Q.number(this.sharedBuffer,e,r);let s=r.offset,i;t!==void 0?(i=this.packr.pack(t,Ar|s),i.set(this.sharedBuffer.subarray(0,s),0)):i=this.sharedBuffer.subarray(0,s),this.connection.sendUnreliable(i)}sendBytes(e,t){let r={offset:1};this.sharedBuffer[0]=_e.ROOM_DATA_BYTES,typeof e=="string"?Q.string(this.sharedBuffer,e,r):Q.number(this.sharedBuffer,e,r);let s=r.offset;if(s+t.byteLength>this.sharedBuffer.byteLength){let i=new Uint8Array(s+t.byteLength);i.set(this.sharedBuffer.subarray(0,s)),this.sharedBuffer=i}this.sharedBuffer.set(t,s),this.connection.isOpen?this.connection.send(this.sharedBuffer.subarray(0,s+t.byteLength)):To(this,this.sharedBuffer.subarray(0,s+t.byteLength))}input(e){return(H(this,$t)??pe(this,$t,new Tr(this))).handle(e)}get state(){return this.serializer.getState()}removeAllListeners(){this.onJoin.clear(),this.onStateChange.clear(),this.onError.clear(),this.onLeave.clear(),this.onReconnect.clear(),this.onDrop.clear(),this.onMessageHandlers.events={},this.serializer instanceof Ir&&(this.serializer.decoder.root.callbacks={})}onMessageCallback(e){On(this,Vt,Hf).call(this,new Uint8Array(e.data))}dispatchMessage(e,t){let r=this.getMessageHandlerKey(e);this.onMessageHandlers.events[r]?this.onMessageHandlers.emit(r,t):this.onMessageHandlers.events["*"]?this.onMessageHandlers.emit("*",e,t):r.startsWith("__")||console.warn?.(`@colyseus/sdk: onMessage() not registered for type '${e}'.`)}destroy(){this.serializer&&this.serializer.teardown()}getMessageHandlerKey(e){switch(typeof e){case"string":return e;case"number":return`i${e}`;default:throw new Error("invalid message type.")}}handleReconnection(e,t){if(!this.reconnection.enabled){this.onLeave.invoke(e,t);return}if(Date.now()-this.joinedAtTime<this.reconnection.minUptime){console.info(`[Colyseus reconnection]: ${String.fromCodePoint(10060)} Room has not been up for long enough for automatic reconnection. (min uptime: ${this.reconnection.minUptime}ms)`),this.onLeave.invoke(Ne.ABNORMAL_CLOSURE,"Room uptime too short for reconnection.");return}this.reconnection.isReconnecting||(this.reconnection.retryCount=0,this.reconnection.isReconnecting=!0,H(this,$t)?.reset()),this.retryReconnection()}retryReconnection(){if(this.reconnection.retryCount>=this.reconnection.maxRetries){console.info(`[Colyseus reconnection]: ${String.fromCodePoint(10060)} \u274C Reconnection failed after ${this.reconnection.maxRetries} attempts.`),this.reconnection.isReconnecting=!1,this.onLeave.invoke(Ne.FAILED_TO_RECONNECT,"No more retries. Reconnection failed.");return}this.reconnection.retryCount++;let e=Math.min(this.reconnection.maxDelay,Math.max(this.reconnection.minDelay,this.reconnection.backoff(this.reconnection.retryCount,this.reconnection.delay)));console.info(`[Colyseus reconnection]: ${String.fromCodePoint(9203)} will retry in ${(e/1e3).toFixed(1)} seconds...`),setTimeout(()=>{try{console.info(`[Colyseus reconnection]: ${String.fromCodePoint(128260)} Re-establishing sessionId '${this.sessionId}' with roomId '${this.roomId}'... (attempt ${this.reconnection.retryCount} of ${this.reconnection.maxRetries})`),this.connection.reconnect({reconnectionToken:this.reconnectionToken.split(":")[1],skipHandshake:!0})}catch{this.retryReconnection()}},e)}};Vs=new WeakMap,Pr=new WeakMap,Or=new WeakMap,Ut=new WeakMap,$t=new WeakMap,Mr=new WeakMap,Vt=new WeakSet,jf=function(){let e=H(this,Or);return pe(this,Or,H(this,Or)+1>>>0),e},qf=function(e,t,r){let s={offset:1};this.sharedBuffer[0]=_e.ROOM_REQUEST,Q.number(this.sharedBuffer,e,s),typeof t=="string"?Q.string(this.sharedBuffer,t,s):Q.number(this.sharedBuffer,t,s);let i=s.offset;if(r!==void 0){let o=this.packr.pack(r,Ar|i);return o.set(this.sharedBuffer.subarray(0,i),0),o}return this.sharedBuffer.subarray(0,i)},Gf=function(e){if(H(this,Ut).size!==0){for(let t of H(this,Ut).values())t.onClose?.(e);H(this,Ut).clear()}},Hf=function(e){var i;let t={offset:1},r=e[0],s=r&Ja;if(r&pr.TIMED){let o=te.uint32(e,t),a=te.uint32(e,t),c=H(this,$t)?H(this,$t).ackInput(a):-1;this.clock.sample(o,c)}if(s===_e.JOIN_ROOM){let o=te.utf8Read(e,t,e[t.offset++]);if(this.serializerId=te.utf8Read(e,t,e[t.offset++]),!this.serializer){let u=Fc(this.serializerId);this.serializer=new u}let a=te.number(e,t);if(a>0&&this.serializer.handshake){let u=t.offset+a;this.serializer.handshake(e.subarray(0,u),t),t.offset=u}for(;t.offset<e.byteLength;){let u=e[t.offset++],d=te.number(e,t),h=t.offset+d;u===Di.INPUT_REFLECTION?(H(this,$t)??pe(this,$t,new Tr(this))).applyReflection(e,t,h):u===Di.INPUT_OPTIONS&&(H(this,$t)??pe(this,$t,new Tr(this))).applyOptions(e,t),t.offset=h}let c=H(this,$t)?.patchRate;if(c!==void 0&&this.clock.setPatchInterval?.(c),this.joinedAtTime===0?(this.joinedAtTime=Date.now(),this.onJoin.invoke()):(console.info(`[Colyseus reconnection]: ${String.fromCodePoint(9989)} reconnection successful!`),this.reconnection.isReconnecting=!1,this.onReconnect.invoke()),this.reconnectionToken=`${this.roomId}:${o}`,this.sharedBuffer[0]=_e.JOIN_ROOM,this.connection.send(this.sharedBuffer.subarray(0,1)),this.reconnection.enqueuedMessages.length>0){for(let u of this.reconnection.enqueuedMessages)this.connection.send(u.data);this.reconnection.enqueuedMessages=[]}}else if(s===_e.ERROR){let o=te.number(e,t),a=te.string(e,t);this.onError.invoke(o,a)}else if(s===_e.LEAVE_ROOM)this.leave();else if(s===_e.ROOM_STATE)pe(this,Mr,0),this.serializer.setState(e,t),this.onStateChange.invoke(this.serializer.getState());else if(s===_e.ROOM_STATE_PATCH){if(r&pr.UNRELIABLE){let o=te.uint16(e,t);if(o-H(this,Mr)<<16>>16<=0)return;pe(this,Mr,o)}this.serializer.patch(e,t),this.onStateChange.invoke(this.serializer.getState())}else if(s===_e.ROOM_DATA){let o=te.stringCheck(e,t)?te.string(e,t):te.number(e,t),a=e.byteLength>t.offset?bo(e,{start:t.offset}):void 0;this.dispatchMessage(o,a)}else if(s===_e.ROOM_DATA_BYTES){let o=te.stringCheck(e,t)?te.string(e,t):te.number(e,t);this.dispatchMessage(o,e.subarray(t.offset))}else if(s===_e.ROOM_RESPONSE){let o=te.number(e,t),a=e[t.offset++],c=e.byteLength>t.offset?bo(e,{start:t.offset}):void 0,u=H(this,Ut).get(o);u!==void 0&&(H(this,Ut).delete(o),u.onReply(a===Mi.OK,c,a===Mi.ERROR))}else s===_e.PING&&((i=H(this,Pr))==null||i.call(this,Math.round($e()-H(this,Vs))),pe(this,Pr,void 0))},l(ko,"defaultRequestTimeout",1e4);var $s=ko;function zf(n,e){return new Promise((t,r)=>{let s=new XMLHttpRequest,i=e?.method||"GET";s.open(i,n.toString()),s.withCredentials=e?.credentials==="include",e?.headers&&(e.headers instanceof Headers?e.headers:new Headers(e.headers)).forEach((a,c)=>{s.setRequestHeader(c,a)}),s.onload=()=>{let o=new Headers,a=s.getAllResponseHeaders().trim();if(a)for(let u of a.split(/[\r\n]+/)){let d=u.indexOf(": ");d>0&&o.append(u.substring(0,d),u.substring(d+2))}let c=s.response??s.responseText;t(new Vc(c,{status:s.status,statusText:s.statusText,headers:o}))},s.onerror=()=>r(new TypeError("Network request failed")),s.ontimeout=()=>r(new TypeError("Network request timed out")),s.send(e?.body??null)})}var Vc=class{constructor(e,t){l(this,"status");l(this,"statusText");l(this,"headers");l(this,"ok");l(this,"body");this.body=e,this.status=t.status,this.statusText=t.statusText,this.headers=t.headers,this.ok=t.status>=200&&t.status<300}async json(){return typeof this.body=="string"?JSON.parse(this.body):this.body}async text(){return typeof this.body=="string"?this.body:JSON.stringify(this.body)}async blob(){return new Blob([this.body])}};function e0(n){if(n===void 0)return!1;let e=typeof n;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(n)?!0:n.buffer?!1:n.constructor&&n.constructor.name==="Object"||typeof n.toJSON=="function"}function t0(n,e){let{params:t,query:r}=e||{},[s,i]=n.split("?"),o=s;if(t)if(Array.isArray(t)){let u=o.split("/").filter(d=>d.startsWith(":"));for(let[d,h]of u.entries()){let m=t[d];o=o.replace(h,m)}}else for(let[u,d]of Object.entries(t))o=o.replace(`:${u}`,String(d));let a=new URLSearchParams(i);if(r)for(let[u,d]of Object.entries(r))d!=null&&a.set(u,String(d));let c=a.toString();return c=c.length>0?`?${c}`.replace(/\+/g,"%20"):"",`${o}${c}`}var vo=class{constructor(e,t,r){l(this,"authToken");l(this,"options");l(this,"sdk");l(this,"_fetchFn");l(this,"del",this.delete);this.sdk=e,this.options=t,this._fetchFn=r}get fetchFn(){return this._fetchFn||(this._fetchFn=typeof globalThis.fetch<"u"?globalThis.fetch.bind(globalThis):zf),this._fetchFn}async request(e,t,r){return this.executeRequest(e,t,r)}get(e,t){return this.request("GET",e,t)}post(e,t){return this.request("POST",e,t)}delete(e,t){return this.request("DELETE",e,t)}patch(e,t){return this.request("PATCH",e,t)}put(e,t){return this.request("PUT",e,t)}async executeRequest(e,t,r){let s=this.options.body?{...this.options.body,...r?.body||{}}:r?.body,i=this.options.query?{...this.options.query,...r?.query||{}}:r?.query,o=this.options.params?{...this.options.params,...r?.params||{}}:r?.params,a=new Headers(this.options.headers?{...this.options.headers,...r?.headers||{}}:r?.headers);if(this.authToken&&!a.has("authorization")&&a.set("authorization",`Bearer ${this.authToken}`),e0(s)&&typeof s=="object"&&s!==null){a.has("content-type")||a.set("content-type","application/json");for(let[g,p]of Object.entries(s))p instanceof Date&&(s[g]=p.toISOString());s=JSON.stringify(s)}let c={credentials:r?.credentials||"include",...this.options,...r,query:i,params:o,headers:a,body:s,method:e},u=t0(this.sdk.getHttpEndpoint(t.toString()),c),d;try{d=await this.fetchFn(u,c)}catch(g){if(g.name==="AbortError")throw g;let p=new It(g.cause?.code||g.code,g.message);throw p.response=d,p.cause=g.cause,p}let h=d.headers.get("content-type"),m;if(h?.includes("json")?m=await d.json():h?.includes("text")?m=await d.text():m=await d.blob(),!d.ok)throw new It(d.status,m.message??m.error??d.statusText,{headers:d.headers,status:d.status,response:d,data:m});return{raw:d,data:m,headers:d.headers,status:d.status,statusText:d.statusText}}};var Jn;function qc(){if(!Jn)try{Jn=typeof cc<"u"&&cc.sys&&cc.sys.localStorage?cc.sys.localStorage:window.localStorage}catch{}return!Jn&&typeof globalThis.indexedDB<"u"&&(Jn=new jc),Jn||(Jn={cache:{},setItem:function(n,e){this.cache[n]=e},getItem:function(n){return this.cache[n]},removeItem:function(n){delete this.cache[n]}}),Jn}function Wf(n,e){qc().setItem(n,e)}function Jf(n){qc().removeItem(n)}function Kf(n,e){let t=qc().getItem(n);typeof Promise>"u"||!(t instanceof Promise)?e(t):t.then(r=>e(r))}var jc=class{constructor(){l(this,"dbPromise",new Promise(e=>{let t=indexedDB.open("_colyseus_storage",1);t.onupgradeneeded=()=>t.result.createObjectStore("store"),t.onsuccess=()=>e(t.result)}))}async tx(e,t){let s=(await this.dbPromise).transaction("store",e).objectStore("store");return t(s)}setItem(e,t){return this.tx("readwrite",r=>r.put(t,e)).then()}async getItem(e){let t=await this.tx("readonly",r=>r.get(e));return new Promise(r=>{t.onsuccess=()=>r(t.result)})}removeItem(e){return this.tx("readwrite",t=>t.delete(e)).then()}};var qs,sn,Gs,js=class{constructor(e){l(this,"settings",{path:"/auth",key:"colyseus-auth-token"});he(this,qs,!1);he(this,sn,null);he(this,Gs,So());l(this,"http");this.http=e,Kf(this.settings.key,t=>this.token=t)}set token(e){this.http.authToken=e}get token(){return this.http.authToken}onChange(e){let t=H(this,Gs).on("change",e);return H(this,qs)||this.getUserData().then(r=>{this.emitChange({...r,token:this.token})}).catch(r=>{this.emitChange({user:null,token:void 0})}),pe(this,qs,!0),t}async getUserData(){if(this.token)return(await this.http.get(`${this.settings.path}/userdata`)).data;throw new Error("missing auth.token")}async registerWithEmailAndPassword(e,t,r){let s=(await this.http.post(`${this.settings.path}/register`,{body:{email:e,password:t,options:r}})).data;return this.emitChange(s),s}async signInWithEmailAndPassword(e,t){let r=(await this.http.post(`${this.settings.path}/login`,{body:{email:e,password:t}})).data;return this.emitChange(r),r}async signInAnonymously(e){let t=(await this.http.post(`${this.settings.path}/anonymous`,{body:{options:e}})).data;return this.emitChange(t),t}async sendPasswordResetEmail(e){return(await this.http.post(`${this.settings.path}/forgot-password`,{body:{email:e}})).data}async signInWithProvider(e,t={}){return new Promise((r,s)=>{let i=t.width||480,o=t.height||768,a=this.token?`?token=${this.token}`:"",c=`Login with ${e[0].toUpperCase()+e.substring(1)}`,u=this.http.sdk.getHttpEndpoint(`${t.prefix||`${this.settings.path}/provider`}/${e}${a}`),d=screen.width/2-i/2,h=screen.height/2-o/2;pe(this,sn,window.open(u,c,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width="+i+", height="+o+", top="+h+", left="+d));let m=p=>{if(!(p.data.user===void 0&&p.data.token===void 0))if(clearInterval(g),H(this,sn)?.close(),pe(this,sn,null),window.removeEventListener("message",m),p.data.error!==void 0){let y=new Error(String(p.data.error));y.code=p.data.error,p.data.reason!==void 0&&(y.reason=p.data.reason),p.data.until!==void 0&&(y.until=p.data.until),s(y)}else r(p.data),this.emitChange(p.data)},g=setInterval(()=>{(!H(this,sn)||H(this,sn).closed)&&(pe(this,sn,null),s("cancelled"),window.removeEventListener("message",m))},200);window.addEventListener("message",m)})}async signOut(){this.emitChange({user:null,token:null})}emitChange(e){e.token!==void 0&&(this.token=e.token,e.token===null?Jf(this.settings.key):Wf(this.settings.key,e.token)),H(this,Gs).emit("change",e)}};qs=new WeakMap,sn=new WeakMap,Gs=new WeakMap;function Yf(n){let e=window?.location?.hostname||"localhost",t=n.hostname.split("."),r=!n.hostname.includes("trycloudflare.com")&&!n.hostname.includes("discordsays.com")&&t.length>2?`/${t[0]}`:"";return n.pathname.startsWith("/.proxy")?`${n.protocol}//${e}${r}${n.pathname}${n.search}`:`${n.protocol}//${e}/.proxy/colyseus${r}${n.pathname}${n.search}`}xs();var Xf=typeof window<"u"&&typeof window?.location?.hostname<"u"?`${window.location.protocol.replace("http","ws")}//${window.location.hostname}${window.location.port&&`:${window.location.port}`}`:"ws://127.0.0.1:2567",Co=class Co{constructor(e=Xf,t){l(this,"http");l(this,"auth");l(this,"settings");l(this,"urlBuilder");if(typeof e=="string"){let r=e.startsWith("/")?new URL(e,Xf):new URL(e),s=r.protocol==="https:"||r.protocol==="wss:",i=Number(r.port||(s?443:80));this.settings={hostname:r.hostname,pathname:r.pathname,port:i,secure:s,searchParams:r.searchParams.toString()||void 0}}else e.port===void 0&&(e.port=e.secure?443:80),e.pathname===void 0&&(e.pathname=""),this.settings=e;this.settings.pathname.endsWith("/")&&(this.settings.pathname=this.settings.pathname.slice(0,-1)),t?.protocol&&(this.settings.protocol=t.protocol),this.http=new vo(this,{headers:t?.headers||{}},t?.fetchFn),this.auth=new js(this.http),this.urlBuilder=t?.urlBuilder,!this.urlBuilder&&typeof window<"u"&&window?.location?.hostname?.includes("discordsays.com")&&(this.urlBuilder=Yf,console.log("Colyseus SDK: Discord Embedded SDK detected. Using custom URL builder."))}static async selectByLatency(e,t,r={}){let s=e.map(o=>new Co(o,t)),i=(await Promise.allSettled(s.map((o,a)=>o.getLatency(r).then(c=>{let u=s[a].settings;return console.log(`\u{1F6DC} Endpoint Latency: ${c}ms - ${u.hostname}:${u.port}${u.pathname}`),[a,c]})))).filter(o=>o.status==="fulfilled").map(o=>o.value);if(i.length===0)throw new Error("All endpoints failed to respond");return s[i.sort((o,a)=>o[1]-a[1])[0][0]]}async joinOrCreate(e,t={},r){return await this.createMatchMakeRequest("joinOrCreate",e,t,r)}async create(e,t={},r){return await this.createMatchMakeRequest("create",e,t,r)}async join(e,t={},r){return await this.createMatchMakeRequest("join",e,t,r)}async joinById(e,t={},r){return await this.createMatchMakeRequest("joinById",e,t,r)}async reconnect(e,t){if(typeof e=="string"&&typeof t=="string")throw new Error("DEPRECATED: .reconnect() now only accepts 'reconnectionToken' as argument.\nYou can get this token from previously connected `room.reconnectionToken`");let[r,s]=e.split(":");if(!r||!s)throw new Error(`Invalid reconnection token format.
|
|
13
|
-
The format should be roomId:reconnectionToken`);return await this.createMatchMakeRequest("reconnect",r,{reconnectionToken:s},t)}async consumeSeatReservation(e,t){let r=this.createRoom(e.name,t);r.roomId=e.roomId,r.sessionId=e.sessionId;let s={sessionId:r.sessionId};return e.reconnectionToken&&(s.reconnectionToken=e.reconnectionToken),r.connect(this.buildEndpoint(e,s),{...e,protocol:this.settings.protocol},this.http.options.headers),new Promise((i,o)=>{let a=(c,u)=>o(new It(c,u));r.onError.once(a),r.onJoin.once(()=>{r.onError.remove(a),ao("room",r),i(r)})})}getLatency(e={}){let t=e.protocol??"ws",r=e.pingCount??1,s=e.timeout??1500;return new Promise((i,o)=>{let a=new Cr(t),c=[],u=0,d=!1,h,m=p=>{if(!d){d=!0,clearTimeout(h);try{a.close()}catch{}p()}},g=p=>m(()=>o(new It(Ne.ABNORMAL_CLOSURE,`Failed to get latency: ${p}`)));h=setTimeout(()=>g(`timed out after ${s}ms`),s),a.events.onopen=()=>{u=Date.now(),a.send(new Uint8Array([_e.PING]))},a.events.onmessage=p=>{if(c.push(Date.now()-u),c.length<r)u=Date.now(),a.send(new Uint8Array([_e.PING]));else{let y=c.reduce((x,k)=>x+k,0)/c.length;m(()=>i(y))}},a.events.onclose=p=>g(`connection closed${p?.code?` (${p.code})`:""}${p?.reason?`: ${p.reason}`:""}`),a.events.onerror=p=>g(p.message);try{a.connect(this.getHttpEndpoint())}catch(p){g(p?.message??"failed to connect")}})}async createMatchMakeRequest(e,t,r={},s){try{if(!t)throw new Error("Must provide a room name");let o=(await this.http.post(`/matchmake/${e}/${t}`,{headers:{Accept:"application/json","Content-Type":"application/json"},body:r})).data;return e==="reconnect"&&(o.reconnectionToken=r.reconnectionToken),await this.consumeSeatReservation(o,s)}catch(i){throw i instanceof It?new as(i.message,i.code):i}}createRoom(e,t){return new $s(e,t)}buildEndpoint(e,t={}){let r=this.settings.protocol||"ws",s=this.settings.searchParams||"";this.http.authToken&&(t._authToken=this.http.authToken);for(let a in t)t.hasOwnProperty(a)&&(s+=(s?"&":"")+`${a}=${t[a]}`);r==="h3"&&(r="http");let i=this.settings.secure?`${r}s://`:`${r}://`;e.publicAddress?i+=`${e.publicAddress}`:i+=`${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}`;let o=`${i}/${e.processId}/${e.roomId}?${s}`;return this.urlBuilder?this.urlBuilder(new URL(o)):o}getHttpEndpoint(e=""){let t=e.startsWith("/")?e:`/${e}`,r=`${this.settings.secure?"https":"http"}://${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}${t}`;return this.settings.searchParams&&(r+=`?${this.settings.searchParams}`),this.urlBuilder?this.urlBuilder(new URL(r)):r}getEndpointPort(){return this.settings.port!==80&&this.settings.port!==443?`:${this.settings.port}`:""}};l(Co,"VERSION","0.18");var Ao=Co,Dr=Ao;Yt();var Io=class{setState(e){}getState(){return null}patch(e){}teardown(){}handshake(e){}};He();Qc();No();Bo();Do();Lc("schema",Ir);Lc("none",Io);var jo={PLAY:"play",QUEUE:"queue",MATCH:"match"};var fh={BAD_OPTION:400,AUTH_REQUIRED:401,FORBIDDEN:403,PROTOCOL_UNSUPPORTED:426};var J={STATE:"state",STATE_SNAP:"__state:snap",SHARED:"shared",CLAIM:"claim",RELEASE:"release",DESTROY:"destroy",OBJECT:"obj",OBJECT_SNAP:"__object:snap",INPUT:"__input",ROOM_OPEN:"__room:open",CHAT:"__chat",CHAT_HISTORY_REQUEST:"__chat:history:request",VOICE_ICE_REQUEST:"__voice:ice:request",VOICE_JOIN:"__voice:join",VOICE_LEAVE:"__voice:leave",VOICE_SIGNAL:"__voice:signal",MATCH_ELIMINATED:"match:eliminated",MATCH_SCORE:"match:score",MATCH_FINISH:"match:finish",POSE:"__pose",POSE_SNAP:"__pose:snap"},ne={OBJECT_RESULT:"__object:result",INPUT:"__input",ROOM_OPEN:"__room:open",CHAT:"__chat",CHAT_HISTORY:"__chat:history",VOICE_ICE:"__voice:ice",VOICE_SIGNAL:"__voice:signal",VOICE_REJECTED:"__voice:rejected",RATE_DROP:"rate:drop",SERVER_RESTART:"server:restart",MATCH_START:"match:start",MATCH_ENDED:"match:ended",MATCH_REQUEUE:"match:requeue",QUEUE:"queue",SEAT:"seat"},u0=["__","match:","server:","rate:"],d0=["state","shared","claim","release","destroy","obj","queue","seat"];function Qs(n){return d0.includes(n)||u0.some(e=>n.startsWith(e))}var qo="__",qt="__t";var eS={[J.STATE]:"state",[J.STATE_SNAP]:"state",[J.SHARED]:"bulk",[J.CLAIM]:"control",[J.RELEASE]:"control",[J.DESTROY]:"control",[J.OBJECT]:"bulk",[J.OBJECT_SNAP]:"bulk",[J.INPUT]:"input",[J.ROOM_OPEN]:"control",[J.CHAT]:"chat",[J.CHAT_HISTORY_REQUEST]:"control",[J.VOICE_ICE_REQUEST]:"voice",[J.VOICE_JOIN]:"voice",[J.VOICE_LEAVE]:"voice",[J.VOICE_SIGNAL]:"voice",[J.MATCH_ELIMINATED]:"bulk",[J.MATCH_SCORE]:"bulk",[J.MATCH_FINISH]:"bulk",[J.POSE]:"pose",[J.POSE_SNAP]:"pose"},Zc={GOING_AWAY:1001,NO_STATUS:1005,ABNORMAL:1006,MAY_TRY_RECONNECT:4010,NORMAL:1e3,CONSENTED:4e3,MATCH_BOOT:4e3,SERVER_SHUTDOWN:4001,WITH_ERROR:4002,FAILED_TO_RECONNECT:4003,REVOKED:4401,SUPERSEDED:4409},vn={ROOM_MAX_CLIENTS:64,MAX_NAME_CHARS:64,MAX_AVATAR_URL_CHARS:512,MAX_UID_CHARS:64,MAX_STATE_BYTES:16*1024,MAX_SHARED_KEY_CHARS:256,MAX_SHARED_VALUE_BYTES:64*1024,MAX_SHARED_KEYS:256,MAX_OBJECT_ID_CHARS:128,MAX_OBJECT_STATE_BYTES:64*1024,MAX_OBJECTS:128,MAX_REQUEST_ID_CHARS:96,MAX_EVENT_BYTES:16*1024,MAX_EVENT_TYPE_CHARS:128,MAX_JSON_DEPTH:32,MAX_JSON_NODES:4096,MAX_CHAT_CHARS:500,CHAT_HISTORY_MAX:50,CHAT_HISTORY_MAX_BYTES:8*1024,MAX_VOICE_PARTICIPANTS:6,MAX_VOICE_SIGNAL_BYTES:8*1024,MAX_SCORE_DELTA:1e3,CONTROL_RESULTS_PER_SESSION:128,CONTROL_RESULT_TTL_MS:6e4,MAX_TEAMS:8,MAX_ANIM_CHARS:64,MAX_POSE_ABS:1e9},tS={PATCH_INTERVAL_MS:1e3/30,RECONNECT_GRACE_S:30,GOING_AWAY_GRACE_S:5,HOST_FAILOVER_GRACE_MS:1500,MIN_OWNERSHIP_HOLD_MS:300,SHUTDOWN_DRAIN_MS:3e3,REQUEUE_GRACE_MS:5e3,SEAT_RESERVATION_S:15,QUEUE_TICK_MS:1e3,REVOCATION_SWEEP_MS:3e4},Gt={enabled:!0,minUptime:0,delay:125,minDelay:100,maxDelay:4e3,maxRetries:9,maxEnqueuedMessages:0,firstStateTimeoutMs:2e3},hh=["x","y","z","yaw","vx","vy","vz","anim"],ye={RATIO:1.5,JITTER_SAFETY:1.25,MIN_MS:90,MAX_MS:300,DEFAULT_MS:100,EASE:.1,CLOCK_WINDOW:80,CLOCK_WINDOW_MS:5e3,CLOCK_WINDOW_MAX:4096,INTERVAL_WINDOW:30,MIN_GAP_MS:5,MAX_GAP_MS:2e3,HISTORY_MS:1500,MAX_EXTRAP_MS:250,ROT_EXTRAP_MS:150,SMOOTH_TAU_POS_MS:30,SMOOTH_TAU_ROT_MS:70,POISON_GUARD_MS:2e3,REBASE_AFTER_GAP_MS:1e3,MAX_HOST_TICK_DT_MS:250},an={HEARTBEAT_HZ:10,MIN_HEARTBEAT_HZ:5,MAX_HEARTBEAT_HZ:20,HEARTBEAT_DITHER:.15,RELAY_BUFFER:4,WARMUP_ACKS:30};var el={SAMPLES:3,TIMEOUT_MS:4e3,GRACE_MS:1e3};async function ph(n,e={}){let t=n[0];if(t===void 0)throw new Error("genex multiplayer: `urls` must contain at least one relay URL");if(n.length===1)return t;let r=e.probe??f0,s=Math.max(1,e.samples??el.SAMPLES),i=e.timeoutMs??el.TIMEOUT_MS,o=e.graceMs??el.GRACE_MS,a=n.map(()=>{});await new Promise(u=>{let d=n.length*s,h,m=setTimeout(g,i);function g(){clearTimeout(m),clearTimeout(h),u()}let p=()=>{--d===0&&g()};n.forEach((y,x)=>{for(let k=0;k<s;k++){let I;try{I=r(y,i)}catch(L){I=Promise.reject(L)}I.then(L=>{Number.isFinite(L)&&L>=0&&(a[x]=Math.min(a[x]??1/0,L),h??(h=setTimeout(g,o))),p()},p)}})});let c=-1;return a.forEach((u,d)=>{u!==void 0&&(c<0||u<a[c])&&(c=d)}),c<0?(console.warn(`genex multiplayer: no relay answered the latency probe \u2014 connecting to ${t}`),t):n[c]}var f0=(n,e)=>new Dr(n).getLatency({pingCount:1,timeout:e});function mh(n,e){let t=null,r=null;return{request(){return t||(t=new Promise(s=>{let i,o=a=>{r&&(r=null,t=null,i&&clearTimeout(i),s(a))};r=o,i=setTimeout(()=>o(null),e),n()}),t)},deliver(s){r?.(s)},get pending(){return t!==null}}}var gh=["x","y","z","yaw","vx","vy","vz"],yh=[["x","vx"],["y","vy"],["z","vz"]],tl=Math.PI*2,h0=n=>hh.includes(n);function nl(n){if(!Number.isFinite(n))return 0;let e=n%tl;return e<=-Math.PI?e+=tl:e>Math.PI&&(e-=tl),e}var bh=n=>typeof n=="number"&&Number.isFinite(n)&&Math.abs(n)<=vn.MAX_POSE_ABS;function wh(n){let e={},t={},r=[];for(let s of Object.keys(n)){let i=n[s];if(!h0(s)){t[s]=i;continue}i!==void 0&&(s==="anim"?typeof i=="string"&&i.length<=vn.MAX_ANIM_CHARS?e.anim=i:r.push(s):bh(i)?e[s]=i:r.push(s))}return{pose:e,data:t,invalid:r}}function _h(n){for(let e in n)if(n[e]!==void 0)return!0;return!1}function Eh(n,e,t){let r={...n},s={t:e},i=t?e-t.t:0,o=t!==void 0&&i>ye.MIN_GAP_MS&&i<ye.MAX_GAP_MS;for(let[a,c]of yh){let u=n[a];if(u===void 0||(s[a]=u,n[c]!==void 0))continue;let d=t?.[a],h=o&&d!==void 0?(u-d)/i*1e3:0;r[c]=bh(h)?h:0}return{pose:r,memory:s}}function zo(n){let e=t=>typeof t=="number"&&Number.isFinite(t)?t:0;return{x:e(n.x),y:e(n.y),z:e(n.z),yaw:e(n.yaw),vx:e(n.vx),vy:e(n.vy),vz:e(n.vz),anim:typeof n.anim=="string"?n.anim:""}}var Wr=(n,e)=>{let t=n[e];return typeof t=="number"&&Number.isFinite(t)?t:0};function Rh(n,e){let t=n.length;if(t===0)return;let r=0;for(;r<t&&n[r].t<=e;)r++;if(r===0)return n[0].state;if(r>=t){let u=n[t-1],d={...u.state},h=Math.min(Math.max(0,e-u.t),ye.MAX_EXTRAP_MS)/1e3;for(let[m,g]of yh)d[m]=Wr(u.state,m)+Wr(u.state,g)*h;if(t>=2){let m=n[t-2],g=u.t-m.t;if(g>0){let p=Math.min(Math.max(0,e-u.t),ye.ROT_EXTRAP_MS)/g,y=Wr(u.state,"yaw");d.yaw=y+nl(y-Wr(m.state,"yaw"))*p}}return d}let s=n[r-1],i=n[r],o=i.t-s.t,a=o>0?(e-s.t)/o:1,c={...s.state};for(let u of gh){let d=Wr(s.state,u),h=Wr(i.state,u);c[u]=u==="yaw"?d+nl(h-d)*a:d+(h-d)*a}return c}function xh(n,e,t,r){let s={...e};for(let i of gh){let o=n[i],a=e[i];typeof o!="number"||typeof a!="number"||!Number.isFinite(o)||!Number.isFinite(a)||(s[i]=i==="yaw"?o+nl(a-o)*r:o+(a-o)*t)}return s}var Ho=class Ho{constructor(){l(this,"pending",[]);l(this,"current")}push(e,t){for(this.pending.push({t:e,state:t});this.pending.length>Ho.MAX_PENDING;)this.current=this.pending.shift()?.state}at(e){for(;this.pending.length>0;){let t=this.pending[0];if(this.current!==void 0&&e!==void 0&&t.t!==void 0&&t.t>e)break;this.current=t.state,this.pending.shift()}return this.current}flush(){this.at(void 0)}};l(Ho,"MAX_PENDING",64);var Go=Ho;function Sh(n){try{let e=n.input();return e&&typeof e.send=="function"?e:null}catch{return null}}function Th(n,e,t=an.HEARTBEAT_HZ,r=Math.random){let i=1e3/Math.min(an.MAX_HEARTBEAT_HZ,Math.max(an.MIN_HEARTBEAT_HZ,t)),o=1e3/an.MAX_HEARTBEAT_HZ,a=1e3/an.MIN_HEARTBEAT_HZ,c=!1,u=!1,d,h=()=>{if(u)return;if(e()){try{n.send()}catch{}!c&&n.lastProcessed>=an.WARMUP_ACKS&&(c=!0)}let m=i*(1+(r()*2-1)*an.HEARTBEAT_DITHER);d=setTimeout(h,Math.min(a,Math.max(o,m)))};return h(),{get synced(){return!c&&n.lastProcessed>=an.WARMUP_ACKS&&(c=!0),c},stop(){u=!0,d&&clearTimeout(d)}}}function kh(n,e){return e.synced&&e.clockOrigin>0&&e.serverNow!==void 0&&Number.isFinite(e.serverNow)?n-e.clockOrigin-e.serverNow:n-e.wallNow}function Zs(n){let e=n.reconnection;return e.enabled=Gt.enabled,e.minUptime=Gt.minUptime,e.delay=Gt.delay,e.minDelay=Gt.minDelay,e.maxDelay=Gt.maxDelay,e.maxRetries=Gt.maxRetries,e.maxEnqueuedMessages=Gt.maxEnqueuedMessages,e.enqueuedMessages.length=0,n}function vh(n){return n.reconnection.enabled=!1,n}function Ah(n,e){return new Promise(t=>{let r=()=>{clearTimeout(s),t(!0)},s=setTimeout(()=>{n.onStateChange.remove(r),t(!1)},e);n.onStateChange.once(r)})}function Ch(n,e,t){return n!==e&&t!=null}var p0="The microphone was refused by the page that frames this game, not by the player: the frame was not given it, so the browser never asked. On its Genex page a build is given the microphone only when it declares it. An up-to-date genex CLI declares it at `genex preview` and `genex publish` when the game's own source calls voice.join(); to declare it by hand, add \"microphone\" to genex.capabilities in the game's package.json. Then preview or publish again.",rl=class extends Error{constructor(e){super(p0,{cause:e}),this.name="VoiceNotDelegatedError"}},Ih=[{urls:"stun:stun.l.google.com:19302"}],m0=120,Ph=.02,g0=.6,Wo=class{constructor(e){l(this,"transport");l(this,"peers",new Map);l(this,"listeners",new Set);l(this,"roster",[]);l(this,"local",null);l(this,"audio",null);l(this,"localAnalyser",null);l(this,"levelTimer",null);l(this,"iceServers",Ih);l(this,"spatial",!1);l(this,"threshold",Ph);l(this,"micOn",!0);l(this,"selfSpeaking",!1);l(this,"running",!1);l(this,"peeringHeld",!1);this.transport=e}get active(){return this.running}get micEnabled(){return this.micOn}get speaking(){return this.selfSpeaking}get participants(){return[...this.peers.values()].map(e=>({id:e.id,name:this.transport.nameOf(e.id),stream:e.stream,speaking:e.speaking,muted:e.muted,volume:e.volume,connection:e.connection}))}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async start(e={},t=!1){if(!this.running){this.peeringHeld=t,this.iceServers=e.iceServers?.length?e.iceServers:Ih,this.spatial=e.spatial===!0,this.threshold=e.speakingThreshold??Ph,this.micOn=e.startMuted!==!0;try{this.local=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1})}catch(r){throw b0(r)}for(let r of this.local.getAudioTracks())r.enabled=this.micOn;this.audio=new AudioContext,this.localAnalyser=this.makeAnalyser(this.local),this.running=!0,this.levelTimer=setInterval(()=>this.pollLevels(),m0)}}stop(){this.running=!1,this.peeringHeld=!1,this.levelTimer&&(clearInterval(this.levelTimer),this.levelTimer=null);for(let e of[...this.peers.keys()])this.destroyPeer(e);for(let e of this.local?.getTracks()??[])e.stop();this.local=null,this.localAnalyser=null,this.audio?.close().catch(()=>{}),this.audio=null,this.roster=[],this.selfSpeaking=!1,this.emit()}setIceServers(e){if(e.length){this.iceServers=e;for(let t of this.peers.values())try{t.pc.setConfiguration({iceServers:e})}catch{}}}releasePeering(){this.peeringHeld&&(this.peeringHeld=!1,this.setRoster(this.roster))}setRoster(e){if(this.roster=e,!this.running||this.peeringHeld)return;let t=this.transport.selfId(),r=new Set(e.filter(s=>s!==t));for(let s of r)this.peers.has(s)||this.createPeer(s);for(let s of[...this.peers.keys()])r.has(s)||this.destroyPeer(s);this.emit()}setMicEnabled(e){this.micOn=e;for(let t of this.local?.getAudioTracks()??[])t.enabled=e;!e&&this.selfSpeaking&&(this.selfSpeaking=!1,this.emit())}mute(e){this.setMuted(e,!0)}unmute(e){this.setMuted(e,!1)}setVolume(e,t){let r=this.peers.get(e);r&&(r.volume=Math.max(0,Math.min(1,t)),r.el&&(r.el.volume=r.volume),this.emit())}async handleSignal(e,t){if(!this.running)return;let r=t;if(!r||typeof r!="object"||typeof r.t!="string")return;let s=this.peers.get(e)??(this.roster.includes(e)?this.createPeer(e):void 0);if(s)try{if(r.t==="offer"){await s.pc.setRemoteDescription(r.sdp),await this.flushIce(s);let i=await s.pc.createAnswer();await s.pc.setLocalDescription(i),this.transport.sendSignal(e,{t:"answer",sdp:i})}else if(r.t==="answer"){if(s.pc.signalingState!=="have-local-offer")return;await s.pc.setRemoteDescription(r.sdp),await this.flushIce(s)}else r.t==="ice"&&(s.pc.remoteDescription?await s.pc.addIceCandidate(r.c):s.pendingIce.push(r.c))}catch(i){console.warn(`[multiplayer] voice signaling failed with ${e}`,i)}}setMuted(e,t){let r=this.peers.get(e);!r||r.muted===t||(r.muted=t,r.el&&(r.el.muted=t||this.spatial),t&&r.speaking&&(r.speaking=!1),this.emit())}createPeer(e){let t=new RTCPeerConnection({iceServers:this.iceServers}),r={id:e,pc:t,el:null,stream:null,analyser:null,pendingIce:[],speaking:!1,muted:!1,volume:1,connection:"connecting"};this.peers.set(e,r);for(let s of this.local?.getAudioTracks()??[])this.local&&t.addTrack(s,this.local);return t.onicecandidate=s=>{s.candidate&&this.transport.sendSignal(e,{t:"ice",c:s.candidate.toJSON()})},t.ontrack=s=>{let i=s.streams[0]??new MediaStream([s.track]);r.stream=i,r.el=this.attachSink(i,r),r.analyser=this.makeAnalyser(i),this.emit()},t.onconnectionstatechange=()=>{let s=t.connectionState,i=s==="connected"?"connected":s==="failed"||s==="closed"?"failed":"connecting";if(i!==r.connection){if(r.connection=i,i==="failed"){let o=this.iceServers.some(a=>w0(a));console.warn(`[multiplayer] voice connection to ${e} failed`+(o?"":" \u2014 no TURN in the ICE list (relay offered none?)"))}this.emit()}},this.transport.selfId()<e&&this.offer(r),r}async offer(e){try{let t=await e.pc.createOffer();await e.pc.setLocalDescription(t),this.transport.sendSignal(e.id,{t:"offer",sdp:t})}catch(t){console.warn(`[multiplayer] voice offer to ${e.id} failed`,t)}}async flushIce(e){let t=e.pendingIce.splice(0);for(let r of t)try{await e.pc.addIceCandidate(r)}catch{}}destroyPeer(e){let t=this.peers.get(e);if(t){this.peers.delete(e),t.pc.onicecandidate=null,t.pc.ontrack=null,t.pc.onconnectionstatechange=null;try{t.pc.close()}catch{}t.el&&(t.el.srcObject=null,t.el.remove())}}attachSink(e,t){let r=document.createElement("audio");return r.autoplay=!0,r.srcObject=e,r.muted=this.spatial||t.muted,r.volume=t.volume,r.style.display="none",document.body.appendChild(r),r.play().catch(s=>{console.warn("[multiplayer] voice playback was blocked \u2014 join voice from a click/tap",s)}),r}makeAnalyser(e){if(!this.audio)return null;try{let t=this.audio.createMediaStreamSource(e),r=this.audio.createAnalyser();return r.fftSize=512,t.connect(r),r}catch{return null}}pollLevels(){let e=!1,t=this.micOn?Oh(this.localAnalyser):0,r=this.crossed(t,this.selfSpeaking);r!==this.selfSpeaking&&(this.selfSpeaking=r,e=!0);for(let s of this.peers.values()){let i=s.muted?!1:this.crossed(Oh(s.analyser),s.speaking);i!==s.speaking&&(s.speaking=i,e=!0)}e&&this.emit()}crossed(e,t){return e>=(t?this.threshold*g0:this.threshold)}emit(){for(let e of[...this.listeners])try{e()}catch(t){console.error("[multiplayer] a voice listener threw",t)}}};function y0(){try{return window.self!==window.top}catch{return!0}}function b0(n){if(n?.name!=="NotAllowedError")return n;try{if(!y0()||document.featurePolicy?.allowsFeature?.("microphone")!==!1)return n}catch{return n}return new rl(n)}function w0(n){return(Array.isArray(n.urls)?n.urls:[n.urls]).some(t=>typeof t=="string"&&t.startsWith("turn"))}function Oh(n){if(!n)return 0;let e=new Uint8Array(n.fftSize);n.getByteTimeDomainData(e);let t=0;for(let r=0;r<e.length;r++){let s=((e[r]??128)-128)/128;t+=s*s}return Math.sqrt(t/e.length)}var sl=Symbol("genex.roomRef"),cn=n=>n[sl]();var _0=ye.RATIO,E0=ye.MIN_MS,R0=ye.MAX_MS,Jo=ye.DEFAULT_MS,x0=ye.JITTER_SAFETY,S0=ye.POISON_GUARD_MS,T0=ye.EASE,k0=ye.MAX_EXTRAP_MS,v0=ye.ROT_EXTRAP_MS,Nh=ye.CLOCK_WINDOW,A0=ye.CLOCK_WINDOW_MS,C0=ye.CLOCK_WINDOW_MAX,I0=ye.INTERVAL_WINDOW,P0=ye.MIN_GAP_MS,O0=ye.MAX_GAP_MS,M0=ye.HISTORY_MS,D0=ye.SMOOTH_TAU_POS_MS,N0=ye.SMOOTH_TAU_ROT_MS,Bh=ye.MAX_HOST_TICK_DT_MS,B0=ye.REBASE_AFTER_GAP_MS,Ht="obj:",L0=3e3,F0=5e3,U0=6e4,$0=2e3;async function Xo(n){return n.url?new Dr(n.url):new Dr(await ph(n.urls))}var V0=n=>typeof n=="function"?n():n;function Uh(n){if(n==="predict")return{mode:"lerp"};if(n&&typeof n=="object"&&n.engine==="predict")return{mode:n.mode==="damped"?"damped":"lerp",delay:n.delay,smoothMs:n.smoothMs}}var Qo=async n=>Uh(n)?Promise.resolve().then(()=>(Dh(),Mh)):void 0;function Lh(n){if(!n)return{state:{}};try{let e=JSON.parse(n);if(!e||typeof e!="object")return{state:{}};let t=e,r=t[qt];if(typeof r=="number"&&Number.isFinite(r)){let s={...t};return delete s[qt],{state:s,sendTime:r}}return{state:t}}catch{return{state:{}}}}function Ko(n){if(n!=null)try{return JSON.parse(n)}catch{return}}var j0=(n,e)=>typeof e=="number"?Number.isFinite(e)?e:0:typeof e=="bigint"?Number(e):e;function Jr(n){return JSON.parse(JSON.stringify(n,j0))}var er=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function $h(n,e,t){let[r,s,i,o]=e,[a,c,u,d]=n,h=a*r+c*s+u*i+d*o;if(h<0&&(r=-r,s=-s,i=-i,o=-o,h=-h),h>.9995){let x=a+(r-a)*t,k=c+(s-c)*t,I=u+(i-u)*t,L=d+(o-d)*t,N=Math.hypot(x,k,I,L)||1;return[x/N,k/N,I/N,L/N]}let m=Math.acos(h),g=Math.sin(m),p=Math.sin(m-m*t)/g,y=Math.sin(m*t)/g;return[a*p+r*y,c*p+s*y,u*p+i*y,d*p+o*y]}function Yo(n){return Array.isArray(n)&&n.length===4&&n.every(e=>typeof e=="number"&&Number.isFinite(e))}function Fh(n,e,t,r){let s={},i=t<1;for(let o in e){let a=n[o],c=e[o];typeof a=="number"&&typeof c=="number"&&Number.isFinite(a)&&Number.isFinite(c)?s[o]=a+(c-a)*t:Yo(a)&&Yo(c)?s[o]=$h(a,c,r):s[o]=i&&o in n?a:c}return s}function q0(n,e,t,r){let s={};for(let i in e){let o=e[i],a=n[i];typeof a=="number"&&typeof o=="number"&&Number.isFinite(a)&&Number.isFinite(o)?s[i]=a+(o-a)*t:Yo(a)&&Yo(o)?s[i]=$h(a,o,r):s[i]=o}return s}function G0(n,e){let t=n.length;if(t===0)return;if(t===1)return n[0].state;let r=0;for(;r<t&&n[r].t<=e;)r++;if(r===0)return n[0].state;if(r>=t){let c=n[t-2],u=n[t-1],d=u.t-c.t;if(d<=0)return u.state;let h=(Math.min(e,u.t+k0)-c.t)/d,m=(Math.min(e,u.t+v0)-c.t)/d;return Fh(c.state,u.state,h,m)}let s=n[r-1],i=n[r],o=i.t-s.t,a=o>0?(e-s.t)/o:1;return Fh(s.state,i.state,a,a)}function H0(n){if(n.length===0)return 66;let e=[...n].sort((t,r)=>t-r);return e[e.length>>1]}function z0(n,e){if(n.length===0)return 0;let t=[...n].sort((s,i)=>s-i),r=Math.min(t.length-1,Math.max(0,Math.round(e*(t.length-1))));return t[r]}async function Vh(n){let e=await Xo(n),t=await Qo(n.smoothing),r=Zs(await e.joinOrCreate(jo.PLAY,{...jh(n.room,n.name,n.auth),...n.options,protocol:3}).catch(W0));return ol(r,{pose:n.pose,smoothing:n.smoothing,predict:t})}function jh(n,e,t){return{gameId:n,name:e,embedToken:V0(t)?.embedToken,protocol:3}}var qh=n=>!!n&&typeof n=="object"&&n.code===fh.PROTOCOL_UNSUPPORTED,Gh=()=>console.error(`[multiplayer] the relay refused protocol ${3} (code 426) \u2014 this game was built with a @genex-ai/multiplayer that this relay no longer serves. Update the package and republish.`),W0=n=>{throw qh(n)&&Gh(),n},J0=n=>typeof n=="string"&&n.length>0&&n.length<=vn.MAX_EVENT_TYPE_CHARS&&!Qs(n),K0=new Set(["join","leave","change","shared","object","host","reconnecting","reconnected","disconnect","room:open","voice","voice:rejected"]),Y0=new Set([ne.OBJECT_RESULT,ne.INPUT,ne.ROOM_OPEN,ne.CHAT,ne.CHAT_HISTORY,ne.VOICE_ICE,ne.VOICE_SIGNAL,ne.VOICE_REJECTED,ne.RATE_DROP,...Object.values(J)]),X0=[500,1e3,2e3,4e3,8e3];function ol(n,e={}){let t=new Map,r=new Map,s=new Map,i=new Map,o=new Map,a=new Map,c=new Set,u=new Map,d=new Map,h=new Map,m=new Map,g,p=new Map,y=new Map,x=new Map,k=new Map,I=new Map,L=new Map,N=new Map,C=new Map,O=new Set,A=new Map,P,V=0,Z=new Map,ee=f=>{for(let b of Z.values())if(b.id===f)return!0;return!1},ve=typeof globalThis<"u"&&globalThis.__GENEX_MP_TEST_SKEW__||0,Pe=ve?()=>er()+ve:er,S=(f,b)=>{if(p.get(b)===n.sessionId)return!1;let v=`${f}:${b}`;return O.has(v)||(O.add(v),console.warn(`[multiplayer] objects.${f}('${b}') ignored because this session does not own the object \u2014 await objects.claimConfirmed('${b}') and check accepted before publishing`)),!0},F=(f,b,v,j)=>{let ie=Pe(),K=v,oe=ie-v,G=i.get(j);G||i.set(j,G={samples:[],mins:[],n:0});let ge=++G.n;for(G.samples.push({at:ie,n:ge});G.mins.length>0&&G.mins[G.mins.length-1].v>=oe;)G.mins.pop();for(G.mins.push({v:oe,n:ge});G.samples.length>C0||G.samples.length>Nh&&G.samples[0].at<ie-A0;)G.samples.shift();let Re=G.samples[0].n;for(;G.mins[0].n<Re;)G.mins.shift();s.set(j,G.mins[0].v);let et=o.get(f);et||o.set(f,et=[]),et.push(oe),et.length>Nh&&et.shift(),a.set(f,j);let mt=r.get(f);if(r.set(f,K),mt!=null){let tt=K-mt;if(tt>P0&&tt<O0){let rr=h.get(f);rr||h.set(f,rr=[]),rr.push(tt),rr.length>I0&&rr.shift();let ap=et.length>=8?Math.max(0,z0(et,.9)-G.mins[0].v):0,cp=Math.min(R0,Math.max(E0,_0*H0(rr),x0*ap)),Ol=m.get(f)??Jo;m.set(f,Ol+(cp-Ol)*T0)}}let Ae=t.get(f);Ae||t.set(f,Ae=[]);let di=A.get(f);if(di&&Ae.length===0){let tt=m.get(f)??Jo;Ae.push({t:K-Math.max(1,tt),state:di})}A.delete(f),Ae.push({t:K,state:b});let Pn=K-M0;for(;Ae.length>2&&Ae[0].t<Pn;)Ae.shift();for(;Ae.length>1&&Ae[0].t>Ae[Ae.length-1].t+S0;)Ae.shift()},B=(f,b)=>{let v=a.get(f),j=v===void 0?void 0:s.get(v);if(j!==void 0)return b-j-(m.get(f)??Jo)},D=(f,b)=>{let v=t.get(f),j=B(f,b)??b-Jo,ie=c.has(f),K=v&&(ie?Rh(v,j):G0(v,j));if(!K)return u.get(f);let oe=u.get(f),G;if(oe){let ge=Math.min(Bh,Math.max(0,b-(d.get(f)??b))),Re=1-Math.exp(-ge/D0),et=1-Math.exp(-ge/N0);G=ie?xh(oe,K,Re,et):q0(oe,K,Re,et)}else G=K;return u.set(f,G),d.set(f,b),G},M=f=>{t.delete(f),r.delete(f),a.delete(f),u.delete(f),d.delete(f),h.delete(f),m.delete(f),o.delete(f),A.delete(f)},z=f=>{t.delete(f),r.delete(f),a.delete(f),h.delete(f),m.delete(f),o.delete(f)},W=f=>{s.delete(f),i.delete(f)},q=new Map,ae=new Set,Y=(f,...b)=>q.get(f)?.forEach(v=>{try{v(...b)}catch(j){console.error(`[multiplayer] a '${f}' listener threw:`,j)}}),Ze=new Map,pt=(f,b)=>{Ze.get(b)!==f&&(Ze.set(b,f),Y("shared",b,Ko(f)))},ln=f=>{let b=f||void 0;b!==P&&(P=b,Y("host",P))},fl="",ia=()=>{let f=n.state?.voice?[...n.state.voice.keys()].sort():[],b=f.join(`
|
|
14
|
-
`);b!==fl&&(fl=b,be.setRoster(f),Y("voice",be.participants))},hl=(f,b)=>{let v=Ht+f,j=n.sessionId,ie=k.has(f),K=b.owner||void 0,oe=Number.isFinite(b.seq)?b.seq:0,G=Number.isFinite(b.epoch)?b.epoch:0,ge=Number.isFinite(b.t)?b.t:0,Re=typeof b.d=="string"?b.d:"",mt=K!==y.get(f)||ie&&oe!==k.get(f),Ae=x.has(f)&&G!==x.get(f),di=ge!==I.get(f);if(k.set(f,oe),x.set(f,G),I.set(f,ge),Re!==L.get(f)){L.set(f,Re);let tt=Re?Ko(Re):void 0;tt&&typeof tt=="object"&&!Array.isArray(tt)&&N.set(f,tt)}K?y.set(f,K):y.delete(f),(mt||p.get(f)!==K&&!ee(f))&&(K?p.set(f,K):p.delete(f)),Ae&&M(v),mt&&K!==j&&(C.delete(f),Ae||z(v));let Pn=N.get(f);if(Pn&&K!==j){let tt=ge!==0&&di&&K!==void 0;Ae?(u.set(v,Pn),d.set(v,Pe()),tt&&F(v,Pn,ge,K)):(mt&&A.set(v,u.get(v)??Pn),tt&&F(v,Pn,ge,K))}(!ie||mt)&&Y("object",f)},pl=f=>{let b=k.has(f)||p.has(f)||N.has(f)||C.has(f);M(Ht+f),N.delete(f),p.delete(f),y.delete(f),x.delete(f),k.delete(f),I.delete(f),L.delete(f),C.delete(f),b&&Y("object",f)},oa=new Map,Yr=new Map,aa=new Map,tp=(f,b)=>{if(!b)return{};let v=oa.get(f);if(v&&v.raw===b)return v.state;let{state:j}=Lh(b);return oa.set(f,{raw:b,state:j}),j},ti=new Map,ca=new Map,tr=e.predict?Uh(e.smoothing):void 0,At,un=new Map,np=(f,b)=>{if(!tr||!e.predict)return;At??(At=e.predict.Predict.get(n));let v={mode:tr.mode,delay:tr.delay,smoothMs:tr.smoothMs};At.attach(b,{x:v,y:v,z:v,vx:v,vy:v,vz:v}),At.attach(b,{yaw:{...v,angle:!0}}),un.set(f,b)},ml=f=>{let b=un.get(f);b&&At&&At.detach(b),un.delete(f)},rp=f=>{let b=At;return{x:b.value(f,"x"),y:b.value(f,"y"),z:b.value(f,"z"),yaw:b.value(f,"yaw"),vx:b.value(f,"vx"),vy:b.value(f,"vy"),vz:b.value(f,"vz"),anim:f.anim??""}},Ct=!1,Wt=!1,Cn=!0,ni=!1,gl=0,ri=0,la=0,ua=new Set,si=()=>ua.forEach(f=>f()),Xr=(f,b)=>{if(Z.delete(f.requestId),f.timeout&&clearTimeout(f.timeout),f.abort?.(),f.operation==="claim"&&f.optimistic&&!b.accepted){let v=b.owner??y.get(f.id);v?p.set(f.id,v):p.delete(f.id),v!==n.sessionId&&C.delete(f.id)}f.operation==="claim"&&b.accepted&&(p.set(f.id,n.sessionId),z(Ht+f.id)),f.operation==="release"&&b.accepted&&(C.delete(f.id),p.get(f.id)===n.sessionId&&p.delete(f.id),z(Ht+f.id)),f.operation==="remove"&&b.accepted&&(C.delete(f.id),N.delete(f.id),p.delete(f.id),M(Ht+f.id)),f.resolve(b)},Qr=(f,b)=>{let v=n.state?.objects?.get(f.id);return{requestId:f.requestId,operation:f.operation,id:f.id,accepted:!1,owner:v?.owner||void 0,sequence:v&&Number.isFinite(v.seq)?v.seq:0,reason:b}},yl=f=>{for(let b of[...Z.values()])Xr(b,Qr(b,f))},bl=(f,b=!1)=>{if(!b&&!Cn)return;let v=f.operation==="claim"?J.CLAIM:f.operation==="release"?J.RELEASE:J.DESTROY;De(v,f.payload)},nr=(f,b,v={})=>{let j=String(b),ie=`${n.sessionId.slice(0,12)}:${Date.now().toString(36)}:${(++V).toString(36)}`,K=Math.max(250,Math.min(v.timeoutMs??F0,U0));return new Promise(oe=>{let G={operation:f,id:j,requestId:ie,payload:{id:j,requestId:ie,...v.authority==="host"?{authority:"host"}:{}},optimistic:f==="claim"&&v.optimistic===!0,resolve:oe,timeout:null,abort:void 0};if(Ct||Wt){oe(Qr(G,Ct?"aborted":"disconnected"));return}if(G.optimistic&&p.set(j,n.sessionId),G.timeout=setTimeout(()=>Xr(G,Qr(G,"timeout")),K),v.signal){let ge=()=>Xr(G,Qr(G,"aborted"));v.signal.addEventListener("abort",ge,{once:!0}),G.abort=()=>v.signal?.removeEventListener("abort",ge)}if(Z.set(ie,G),v.signal?.aborted){Xr(G,Qr(G,"aborted"));return}bl(G)})},ii=0,De=(f,b,v=!1)=>{if(n.connection?.isOpen)try{return n.send(f,b),!0}catch{}return v&&ii++,!1},oi,wl=0,_l,El=new Set,Rl=(f,b)=>{let{pose:v,data:j,invalid:ie}=wh(f);for(let Re of ie)El.has(Re)||(El.add(Re),console.warn(`[multiplayer] me.set: '${Re}' is a typed pose key (pose: true) and its value is not a `+(Re==="anim"?`string of \u2264${vn.MAX_ANIM_CHARS} chars`:"finite number")+" \u2014 it is not sent."));if(!_h(v))return!1;let K=Pe(),oe=Eh(v,K,b?void 0:_l);_l=oe.memory;let G=JSON.stringify(j),ge=b||G!==oi||K-wl>=$0;return ge&&De(J.STATE,JSON.stringify({...j,[qt]:K}))?(oi=G,wl=K):ge&&(oi=void 0),De(b?J.POSE_SNAP:J.POSE,{...oe.pose,t:K})||(oi=void 0),!0},be=new Wo({selfId:()=>n.sessionId,nameOf:f=>n.state?.players?.get(f)?.name??"",sendSignal:(f,b)=>De(J.VOICE_SIGNAL,{to:f,data:b},!0)});be.onChange(()=>Y("voice",be.participants));let ai=null,da=mh(()=>De(J.VOICE_ICE_REQUEST,{},!0),L0),ci=()=>{ai&&clearTimeout(ai),ai=null},xl=f=>{ci(),!(typeof f!="number"||!Number.isFinite(f)||f<=0)&&(ai=setTimeout(()=>{be.active&&da.request().then(b=>{!be.active||!b?.iceServers?.length||(be.setIceServers(b.iceServers),xl(b.ttl))})},Math.max(6e4,Math.floor(f*800))))},In=[],Sl=new Set,fa=new Set,li=new Set,sp=f=>!!f&&typeof f=="object"&&typeof f.id=="number"&&typeof f.from=="string"&&typeof f.name=="string"&&typeof f.text=="string",Tl=f=>{if(!sp(f)||Sl.has(f.id)||li.has(f.from))return;Sl.add(f.id);let b=In[In.length-1];if(!b||f.id>b.id)In.push(f);else{let v=In.length;for(;v>0&&(In[v-1]?.id??0)>f.id;)v--;In.splice(v,0,f)}for(let v of[...fa])try{v(f)}catch(j){console.error("[multiplayer] a chat listener threw",j)}},lt=$c(n);if(!lt)throw new Error("genex multiplayer: the relay room has no schema state");let kl=(f,b,v)=>{let j=f===n.sessionId,{state:ie,sendTime:K}=Lh(b.data),oe=Number.isFinite(b.epoch)?b.epoch:0,G=Yr.has(f)&&oe!==Yr.get(f);Yr.set(f,oe);let ge=v||b.data!==aa.get(f);aa.set(f,b.data);let Re=Number.isFinite(b.poseT)?b.poseT:0,et=Re!==(ca.get(f)??0);ca.set(f,Re);let mt=b.posed===!0;if(!j&&mt&&!c.has(f)&&(M(f),c.add(f),ti.set(f,new Go)),!j&&G&&(M(f),un.has(f)&&ml(f)),Y(v?"join":"change",f,mt?{...ie,...zo(b)}:ie),!j){if(mt){let Ae=ti.get(f);(ge||G)&&(Ae.push(K,ie),(G||tr)&&Ae.flush()),tr?un.has(f)||np(f,b):Re!==0&&(et||G)&&F(f,zo(b),Re,f);return}(ge||G)&&Ch(f,n.sessionId,K)&&F(f,ie,K,f)}};lt(n.state).players.onAdd((f,b)=>{kl(b,f,!0),lt(f).onChange(()=>kl(b,f,!1))});let vl=f=>{Y("leave",f),M(f),W(f),ml(f),oa.delete(f),Yr.delete(f),aa.delete(f),ca.delete(f),c.delete(f),ti.delete(f)};lt(n.state).players.onRemove((f,b)=>vl(b)),lt(n.state).shared.onAdd(pt),lt(n.state).shared.onChange(pt),lt(n.state).objects.onAdd((f,b)=>{hl(b,f),lt(f).onChange(()=>hl(b,f))}),lt(n.state).objects.onRemove((f,b)=>pl(b)),lt(n.state).listen("host",f=>ln(f)),lt(n.state).voice.onAdd(ia),lt(n.state).voice.onRemove(ia);let ip=()=>{let f=n.state;if(f){for(let b of new Set([...p.keys(),...N.keys(),...k.keys()]))f.objects?.has(b)||pl(b);for(let b of[...Yr.keys()])f.players?.has(b)||vl(b);ln(f.host),ia()}};n.onMessage(ne.VOICE_SIGNAL,f=>{f&&typeof f.from=="string"&&be.handleSignal(f.from,f.data)}),n.onMessage(ne.VOICE_REJECTED,f=>{ci(),be.stop(),Y("voice:rejected",f??{reason:"full"})}),n.onMessage(ne.VOICE_ICE,f=>{da.deliver(f??null)}),n.onMessage(ne.CHAT,f=>Tl(f)),n.onMessage(ne.CHAT_HISTORY,f=>{if(Array.isArray(f?.messages))for(let b of f.messages)Tl(b)}),n.onMessage(ne.OBJECT_RESULT,f=>{if(!f||typeof f.requestId!="string")return;let b=Z.get(f.requestId);!b||f.operation!==b.operation||f.id!==b.id||Xr(b,f)}),n.onMessage(ne.INPUT,f=>{f&&typeof f.from=="string"&&Y(ne.INPUT,f.from,f.d)}),n.onMessage(ne.ROOM_OPEN,f=>{typeof f?.open=="boolean"&&Y("room:open",{open:f.open})}),n.onMessage(ne.RATE_DROP,f=>{console.warn(`[multiplayer] the relay dropped ${f?.dropped??"some"} of your messages in the last second \u2014 you are publishing over budget. Publish idle/unchanged objects at \u22642Hz keepalive, not every tick (see the multiplayer skill's "message budget" section).`)}),n.onMessage(ne.SERVER_RESTART,()=>{}),De(J.CHAT_HISTORY_REQUEST,{});let Al=Sh(n),Zr=Al?Th(Al,()=>!Wt&&!Ct):void 0,Cl=()=>Zr?n.clock.serverNow():void 0,op=f=>kh(f,{synced:Zr?.synced===!0,clockOrigin:Number.isFinite(n.state?.clockOrigin)?n.state?.clockOrigin:0,serverNow:Cl(),wallNow:Date.now()}),Il=()=>{Zr?.stop(),At?.dispose(),At=void 0,un.clear()};n.onDrop(f=>{if(Ct||Wt)return;la++,ni||(ni=!0,gl=0,ri=er()),Cn=!1,si();let{isReconnecting:b,retryCount:v,maxRetries:j}=n.reconnection;b&&v>=j||Y("reconnecting",{attempt:++gl,code:f})}),n.onReconnect(()=>{if(Wt)return;if(Ct){n.leave().catch(()=>{});return}let f=la;if((ri?er()-ri:0)>B0){for(let v of[...t.keys()])M(v);for(let v of[...i.keys()])W(v)}(async()=>{if(await Ah(n,Gt.firstStateTimeoutMs),!(f!==la||Wt||Ct)){ip();for(let v of[...Z.values()])bl(v,!0);De(J.CHAT_HISTORY_REQUEST,{}),ni=!1,ri=0,Cn=!0,si(),Y("reconnected"),ii>0&&(console.warn(`[multiplayer] ${ii} fire-and-forget event(s)/input(s) were dropped while reconnecting \u2014 they are not buffered; player/object state re-synced automatically.`),ii=0)}})()}),n.onLeave(f=>{Wt||(Wt=!0,Cn=!1,ni=!1,Il(),si(),!Ct&&(yl("disconnected"),Y("disconnect",f??1006)))}),n.onError(()=>{});let Pl=((f,b)=>{let v=q.get(f);return v||q.set(f,v=new Set),v.add(b),!K0.has(f)&&!Y0.has(f)&&!ae.has(f)&&(ae.add(f),n.onMessage(f,j=>Y(f,j))),()=>{v?.delete(b)}}),ui={id:n.sessionId,get players(){let f=new Map,b=Pe();return At&&un.size>0&&At.tick(er()),n.state?.players?.forEach((v,j)=>{let ie=tp(j,v.data),K=ie,oe=ie,G=ti.get(j);if(j!==n.sessionId&&G){let ge=zo(v);if(oe={...ie,...ge},un.has(j))K={...G.at(void 0)??ie,...rp(v)};else{let Re=D(j,b)??ge;K={...G.at(B(j,b))??ie,...Re}}}else j===n.sessionId?g&&(K=g,oe=g):K=D(j,b)??ie;f.set(j,{id:j,name:v.name??"",avatarUrl:v.avatarUrl??"",connected:v.connected!==!1,uid:v.uid??"",team:Number.isFinite(v.team)?v.team:-1,state:K,stateRaw:oe})}),f},get activePlayers(){return new Map([...ui.players].filter(([,f])=>f.connected))},me:{set(f){qt in f&&console.warn(`[multiplayer] '${qt}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let b=Jr(f);g=b,!(e.pose&&Rl(b,!1))&&De(J.STATE,JSON.stringify({...b,[qt]:Pe()}))},snap(f){qt in f&&console.warn(`[multiplayer] '${qt}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let b=Jr(f);g=b,!(e.pose&&Rl(b,!0))&&De(J.STATE_SNAP,JSON.stringify({...b,[qt]:Pe()}))}},shared:{get(f){return Ko(n.state?.shared?.get(f))},set(f,b){f.startsWith(qo)||De(J.SHARED,{key:f,value:JSON.stringify(Jr(b))})},keys(){return n.state?.shared?Array.from(n.state.shared.keys()):[]}},objects:{claim(f){nr("claim",f,{optimistic:!0})},claimConfirmed(f,b){return nr("claim",f,b)},release(f){let b=String(f);C.delete(b),p.get(b)===n.sessionId&&p.delete(b),z(Ht+b),nr("release",b)},releaseConfirmed(f,b){return nr("release",f,b)},remove(f){let b=String(f);p.get(b)===n.sessionId&&(C.delete(b),N.delete(b),p.delete(b),M(Ht+b)),nr("remove",b)},removeConfirmed(f,b){return nr("remove",f,b)},set(f,b){let v=String(f);if(S("set",v))return;let j=Jr(b);p.get(v)===n.sessionId&&C.set(v,j),De(J.OBJECT,{id:v,d:j,t:Pe()})},snap(f,b){let v=String(f);if(S("snap",v))return;let j=Jr(b);p.get(v)===n.sessionId&&C.set(v,j),De(J.OBJECT_SNAP,{id:v,d:j,t:Pe()})},get(f){let b=String(f),v=p.get(b),j=C.get(b);if(v===void 0&&!N.has(b)&&!j)return;let ie=v!==void 0&&v===n.sessionId,K,oe;return ie&&j?(K=j,oe=j,u.set(Ht+b,j),d.set(Ht+b,Pe())):(oe=N.get(b)??{},K=D(Ht+b,Pe())??oe),{id:b,epoch:x.get(b)??0,owner:v,isMine:ie,state:K,stateRaw:oe}},ids(){return[...new Set([...p.keys(),...N.keys(),...C.keys()])]}},get isHost(){return Cn&&!Ct&&!Wt&&P!==void 0&&P===n.sessionId},get host(){return P},inputs:{send(f){De(J.INPUT,Jr(f),!0)},on(f){let b=q.get(ne.INPUT);b||q.set(ne.INPUT,b=new Set);let v=(j,ie)=>f(j,ie);return b.add(v),()=>{b?.delete(v)}}},onHostTick(f,b){let v=null,j=0,ie=Number.isFinite(f)&&f>0?Math.min(f,100):20,K=Math.max(10,Math.round(1e3/ie)),oe=()=>{let ge=Cn&&!Ct&&!Wt&&P!==void 0&&P===n.sessionId;ge&&!v?(j=er(),v=setInterval(()=>{let Re=er();b(Math.min(Re-j,Bh)),j=Re},K)):!ge&&v&&(clearInterval(v),v=null)},G=Pl("host",oe);return ua.add(oe),oe(),()=>{G(),ua.delete(oe),v&&clearInterval(v),v=null}},on:Pl,send(f,b){if(!J0(f)){console.warn(`[multiplayer] send('${f}') collides with a relay-internal channel \u2014 use a different event name`);return}De(f,b,!0)},chat:{send(f){typeof f=="string"&&f.trim()&&De(J.CHAT,{text:f},!0)},on(f){return fa.add(f),()=>fa.delete(f)},get history(){return[...In]},mute(f){typeof f=="string"&&f&&li.add(f)},unmute(f){li.delete(f)},get muted(){return[...li]}},voice:{async join(f){if(await be.start(f,!0),!f?.iceServers?.length){let b=await da.request();be.active&&b?.iceServers?.length&&(be.setIceServers(b.iceServers),xl(b.ttl))}be.active&&(De(J.VOICE_JOIN,{},!0),be.releasePeering())},leave(){ci(),De(J.VOICE_LEAVE,{},!0),be.stop()},get active(){return be.active},get participants(){return be.participants},setMicEnabled(f){be.setMicEnabled(f===!0)},get micEnabled(){return be.micEnabled},get speaking(){return be.speaking},mute(f){be.mute(f)},unmute(f){be.unmute(f)},setVolume(f,b){be.setVolume(f,b)},get muted(){return be.participants.filter(f=>f.muted).map(f=>f.id)}},setRoomOpen(f){De(J.ROOM_OPEN,{open:f===!0})},leave(){Ct=!0,Il(),be.stop(),ci(),Cn=!1,si(),yl("aborted"),n.reconnection.enabled=!1,n.leave().catch(()=>{})},serverNow:Cl,get rtt(){if(!Zr)return;let f=n.clock.smoothedRtt();return f>0?f:void 0},get clockSynced(){return Zr?.synced===!0},timeUntil:op};return Object.defineProperty(ui,sl,{value:()=>n,enumerable:!1}),Object.defineProperty(ui,Symbol.for("genex.multiplayer.internals"),{enumerable:!1,value:{senderOf:f=>a.get(f),offsetOf:f=>{let b=a.get(f);return b===void 0?void 0:s.get(b)},offsetSamples:f=>i.get(f)?.samples.length??0,bufferLength:f=>t.get(f)?.length??0}}),ui}var Q0=[1e3,2e3,4e3],al=n=>jh(n.room,n.name,n.auth);function Hh(n,e,t=r=>r-Date.now()){let r=n?.state?.match,s=r?Ko(r):null,i=s&&typeof s=="object"?s:null;if(!i)return{status:n?"waiting":"searching",role:"player",queue:e,players:[],connectedPlayers:[],opponents:[],teams:{},myTeam:null,scores:{},config:{},winCondition:"lastStanding",championId:null,challengerId:null,roundId:0,winnerId:null,message:n?"Waiting for players\u2026":"Finding a match\u2026",startsAt:null,endsBy:null,startsInMs:null,endsInMs:null};let o=n?.sessionId,a=i.championId??null,c=i.challengerId??null,u=i.teams??{},d=Array.isArray(i.players)?i.players:[],h=i.connectedPlayers??d,m=o!=null&&d.includes(o),g=m?i.phase:"spectating",p=d.filter(O=>O!==o),y=o?Object.keys(u).find(O=>u[O]?.includes(o))??null:null,{winCondition:x,...k}=i.cfg??{},I=O=>typeof O=="number"&&Number.isFinite(O)&&O>0?O:null,L=I(i.startsAt),N=I(i.endsBy),C=O=>O===null?null:Math.max(0,t(O));return{status:g,role:m?"player":"spectator",queue:{position:0,size:0},players:d,connectedPlayers:h,opponents:p,teams:u,myTeam:y,scores:i.scores??{},config:k,winCondition:x?.type??"lastStanding",championId:a,challengerId:c,roundId:i.roundId??0,winnerId:i.winnerId??null,message:i.message??"",startsAt:L,endsBy:N,startsInMs:C(L),endsInMs:C(N)}}function Kr(n,e,t){if(n?.connection?.isOpen)try{n.send(e,t)}catch{}}async function zh(n){let e=await Xo(n),t=await Qo(n.smoothing),r=new Map,s=(O,...A)=>r.get(O)?.forEach(P=>P(...A)),i=((O,A)=>{let P=r.get(O);return P||r.set(O,P=new Set),P.add(A),()=>{P?.delete(A)}}),o=null,a=null,c=null,u={position:0,size:0},d=!1,h=!1,m=0,g=!1,p=!1,y=async()=>{if(d||h)return;h=!0;let O=++m;try{o=null,a=null;for(let A=0;;A++){c&&(c.leave(),c=null),u={position:0,size:0};let P;try{P=vh(await e.joinOrCreate(jo.QUEUE,al(n)))}catch(V){if(d)return;let Z=qh(V);Z&&Gh();let ee=Z?void 0:Q0[A];if(ee==null){if(A===0&&await new Promise(ve=>setTimeout(ve,0)),d)return;s("error",V);return}if(await new Promise(ve=>setTimeout(ve,ee)),d)return;continue}if(d||O!==m){P.leave();return}c=P,P.onMessage(ne.QUEUE,V=>{u={position:V.position,size:V.size},s("queue",V)}),P.onMessage(ne.SEAT,V=>{d||O!==m||c!==P||g||(g=!0,c=null,P.leave(),x(V.reservation,V.role,O))}),P.onLeave(()=>{d||c!==P||(c=null,(async()=>{for(let V of X0)if(await new Promise(Z=>setTimeout(Z,V)),d||c||o||(await y(),c||o))return})())}),s("searching");return}}finally{h=!1}},x=async(O,A,P)=>{try{let V=Zs(await e.consumeSeatReservation(O));if(d||P!==m){V.leave();return}a=V;let Z=ol(V,{pose:n.pose,smoothing:n.smoothing,predict:t});o=Z,Z.on(ne.MATCH_START,ee=>s("matchStart",ee)),Z.on(ne.MATCH_ENDED,ee=>s("matchEnded",ee)),Z.on(ne.MATCH_REQUEUE,()=>{o===Z&&k()}),Z.on("disconnect",ee=>{if(!(d||o!==Z)){if(ee===Zc.SUPERSEDED||ee===Zc.REVOKED){m++,g=!1,a=null,o=null,s("disconnect",ee);return}k()}}),c&&(c.leave(),c=null),s("matched"),A==="spectator"&&s("spectate")}catch{!d&&P===m&&(g=!1,y())}finally{P===m&&(g=!1)}},k=async()=>{if(!(d||p)){p=!0;try{m++,g=!1,o?.leave(),a=null,o=null,await y()}finally{p=!1}}};y();let I=()=>o?cn(o):null,L=null,N=null,C=()=>{o!==L&&(L=o,N=null);let O=I(),A=!!O?.state?.match;if(!A&&o&&N)return N;let P=Hh(O,u,o?o.timeUntil:void 0);return A&&(N=P),P};return{get session(){return o},get matchmaking(){return C()},on:i,eliminated(){Kr(I(),J.MATCH_ELIMINATED,{})},score(O=1){Kr(I(),J.MATCH_SCORE,{delta:O})},finish(){Kr(I(),J.MATCH_FINISH,{})},retry(){d||h||c||a||y()},cancel(){d=!0,m++,g=!1,o?.leave(),!o&&a&&a.leave(),c&&c.leave(),a=null,c=null,o=null}}}function Wh(n,e){let t=new Map,r=(c,...u)=>t.get(c)?.forEach(d=>d(...u)),s=((c,u)=>{let d=t.get(c);return d||t.set(c,d=new Set),d.add(u),()=>{d?.delete(u)}}),i=!0,o=ol(n,e);o.on(ne.MATCH_START,c=>r("matchStart",c)),o.on(ne.MATCH_ENDED,c=>r("matchEnded",c)),o.on(ne.MATCH_REQUEUE,()=>{i=!1}),o.on("disconnect",()=>{i=!1});let a=()=>i?cn(o):null;return{get session(){return i?o:null},get matchmaking(){return Hh(a(),{position:0,size:0},o.timeUntil)},on:s,eliminated(){Kr(a(),J.MATCH_ELIMINATED,{})},score(c=1){Kr(a(),J.MATCH_SCORE,{delta:c})},finish(){Kr(a(),J.MATCH_FINISH,{})},retry(){},cancel(){o.leave(),i=!1}}}async function Jh(n){let e=await Xo(n),t=await Qo(n.smoothing),r=Zs(await e.create(jo.MATCH,al(n))),s=Wh(r,{pose:n.pose,smoothing:n.smoothing,predict:t});return Object.defineProperty(s,"code",{value:r.roomId,enumerable:!0}),s}async function Kh(n,e){let t=await Xo(e),r=await Qo(e.smoothing),s=Zs(await t.joinById(n,al(e)));return Wh(s,{pose:e.pose,smoothing:e.smoothing,predict:r})}var Z0=1,Xh={ready(n){let e=globalThis.__GENEX__;return n&&e&&typeof e.apiUrl=="string"&&Array.isArray(e.dashboardOrigins)&&Ci({slug:n,apiUrl:e.apiUrl,dashboardOrigins:e.dashboardOrigins.filter(t=>typeof t=="string")}),$a()},auth:()=>yu(),urls:()=>bu()},Zo=Xh;function eb(n){Zo=n??Xh}var zt=n=>!!n&&typeof n=="object"&&!Array.isArray(n);function tb(n){let e=JSON.parse(n);if(!zt(e))throw new TypeError("genex bridge: options must be a JSON object");let t=typeof e.gameId=="string"?e.gameId:"";if(!t)throw new TypeError("genex bridge: `gameId` (the game slug) is required");let r=Array.isArray(e.urls)?e.urls.filter(a=>typeof a=="string"&&a!==""):[],s="play";if(e.room==="queue"||e.room==="private")s=e.room;else if(zt(e.room)&&typeof e.room.joinById=="string"&&e.room.joinById)s={joinById:e.room.joinById};else if(e.room!==void 0&&e.room!==null&&e.room!=="play")throw new TypeError('genex bridge: `room` must be "play", "queue", "private" or {"joinById": code}');let i=typeof e.controlTimeoutMs=="number"&&Number.isFinite(e.controlTimeoutMs)?e.controlTimeoutMs:void 0,o=e.smoothing==="genex"||e.smoothing==="predict"||zt(e.smoothing)?e.smoothing:void 0;return{gameId:t,name:typeof e.name=="string"&&e.name?e.name:void 0,urls:r,room:s,pose:e.pose===!0,smoothing:o,controlTimeoutMs:i,options:zt(e.options)?e.options:void 0}}var nb=4096,cl=new Map,rb=1;function le(n,e){n.q.length>=nb&&(n.overflowed?n.q.splice(1,1):(n.overflowed=!0,n.q.splice(0,2,{type:"warning",message:"genex bridge: event queue full; drain it every frame (oldest events dropped)"}))),n.q.push(e)}var ll=n=>n.closed?null:n.mm?n.mm.session:n.session,ul=n=>{let e=zt(n)||n instanceof Error?n.code:void 0;return typeof e=="number"&&Number.isFinite(e)?e:0},ta=n=>n instanceof Error?n.message:typeof n=="string"?n:"join failed";function ei(n){n.closed=!0,n.connected=!1;for(let e of n.unwire.splice(0))e();n.wired=null,n.session=null,n.mm=null}function Qh(n,e){if(n.wired===e)return;for(let o of n.unwire.splice(0))o();n.wired=e,n.connected=!0,n.lastConnected.clear(),n.lastMatch="";let t=cn(e);n.sessionId=e.id,n.roomId=t.roomId;let r=n.unwire,s=o=>t.state?.players?.get(o)?.connected!==!1,i=o=>{let a=s(o),c=n.lastConnected.get(o);n.lastConnected.set(o,a),c!==void 0&&c!==a&&le(n,{type:"playerConnection",id:o,connected:a})};le(n,{type:"joined",sessionId:e.id}),t.state?.players?.forEach((o,a)=>{n.lastConnected.set(a,s(a)),le(n,{type:"playerJoined",id:a})});for(let o of e.objects.ids())le(n,{type:"objectChanged",id:o,owner:e.objects.get(o)?.owner??null});e.host!==void 0&&le(n,{type:"hostChanged",host:e.host}),r.push(e.on("join",o=>{n.lastConnected.set(o,s(o)),le(n,{type:"playerJoined",id:o})}),e.on("change",o=>{i(o),n.changed.has(o)||(n.changed.add(o),le(n,{type:"playerChanged",id:o}))}),e.on("leave",o=>{n.lastConnected.delete(o),le(n,{type:"playerLeft",id:o})}),e.on("host",o=>le(n,{type:"hostChanged",host:o??null})),e.on("shared",(o,a)=>le(n,{type:"sharedChanged",key:o,value:a??null})),e.on("object",o=>{let a=e.objects.get(o);le(n,a?{type:"objectChanged",id:o,owner:a.owner??null}:{type:"objectRemoved",id:o})}),e.on("room:open",({open:o})=>le(n,{type:"roomOpen",open:o})),e.on("reconnecting",({attempt:o,code:a})=>{n.connected=!1,le(n,{type:"reconnecting",code:a,attempt:o})}),e.on("reconnected",()=>{n.connected=!0,le(n,{type:"reconnected"})}),e.on("disconnect",o=>{n.connected=!1,n.opts.room!=="queue"&&(ei(n),le(n,{type:"disconnected",code:o,reason:""}))}),e.on(ne.SERVER_RESTART,()=>le(n,{type:"serverRestart"})),e.on(ne.MATCH_START,o=>le(n,{type:"matchStart",roundId:zt(o)&&typeof o.roundId=="number"?o.roundId:0})),e.on(ne.MATCH_ENDED,o=>le(n,{type:"matchEnded",data:o??null})),e.on(ne.MATCH_REQUEUE,o=>le(n,{type:"matchRequeue",reason:zt(o)&&typeof o.reason=="string"?o.reason:null})),e.inputs.on((o,a)=>le(n,{type:"input",from:o,data:a??null})),e.chat.on(o=>le(n,{type:"chat",id:o.id,from:o.from,name:o.name,text:o.text,at:o.at})),t.onMessage(ne.RATE_DROP,o=>le(n,{type:"rateDrop",dropped:zt(o)&&typeof o.dropped=="number"?o.dropped:0})),t.onMessage("*",(o,a)=>{typeof o=="string"&&!Qs(o)&&le(n,{type:"message",kind:o,data:a??null})}))}function ea(n){let e=ll(n);e&&e!==n.wired&&Qh(n,e)}async function sb(n){let e=n.opts;if(await Zo.ready(e.gameId),n.closed)return;let t=e.urls.length?e.urls:Zo.urls();if(!t.length)throw Object.assign(new Error("genex bridge: no relay URL (pass urls, or run on a Genex page)"),{code:0});let r=()=>Zo.auth(),s={urls:t,room:e.gameId,name:e.name,auth:r,pose:e.pose,smoothing:e.smoothing};if(e.room==="play"){let a=await Vh({...s,options:e.options});if(n.closed)return void a.leave();n.session=a,Qh(n,a);return}let i=s,o=e.room==="queue"?await zh(i):e.room==="private"?await Jh(i):await Kh(e.room.joinById,i);if(n.closed)return void o.cancel();n.mm=o,o.on("queue",a=>{zt(a)&&le(n,{type:"queue",position:Number(a.position)||0,size:Number(a.size)||0})}),o.on("matched",()=>{le(n,{type:"seated"}),ea(n)}),o.on("searching",()=>{if(n.wired){for(let a of n.unwire.splice(0))a();n.wired=null,n.connected=!1}}),o.on("error",a=>{let c=n.mm;ei(n),c?.cancel(),le(n,{type:"joinFailed",code:ul(a),message:ta(a)})}),o.on("disconnect",a=>{ei(n),le(n,{type:"disconnected",code:typeof a=="number"?a:0,reason:""})}),ea(n)}function Zh(n){let e=tb(n),t=rb++,r={opts:e,q:[],overflowed:!1,session:null,mm:null,wired:null,unwire:[],changed:new Set,lastConnected:new Map,lastMatch:"",sessionId:"",roomId:"",connected:!1,closed:!1};cl.set(t,r);let s=sb(r).catch(i=>{throw ei(r),le(r,{type:"joinFailed",code:ul(i),message:ta(i)}),i});return{handle:t,done:s}}function ib(n){let{handle:e,done:t}=Zh(n);return t.catch(()=>{}),e}async function ob(n){let{handle:e,done:t}=Zh(n);try{await t}catch(r){let s=new Error(ta(r));throw s.code=ul(r),s}return e}var An=n=>cl.get(n),qe=n=>{let e=An(n);return e?(ea(e),ll(e)):null};function na(n,e){if(typeof n!="string")throw new TypeError(`genex bridge: ${e} must be a JSON string`);return JSON.parse(n)}function ra(n,e){let t=na(n,e);if(!zt(t))throw new TypeError(`genex bridge: ${e} must be a JSON object`);return t}function ep(n){let e=An(n);if(!e||e.closed)return;let{mm:t,session:r}=e;ei(e),t?t.cancel():r?.leave(),le(e,{type:"disconnected",code:4e3,reason:"left"})}function ab(n){ep(n),typeof n=="number"&&cl.delete(n)}function cb(n,e){let t=ra(e,"state"),r=qe(n);return r?(r.me.set(t),!0):!1}function lb(n,e){let t=ra(e,"state"),r=qe(n);return r?(r.me.snap(t),!0):!1}function ub(n,e,t){let r=na(t,"value");if(typeof e!="string"||!e||e.startsWith(qo))return!1;let s=qe(n);return s?(s.shared.set(e,r),!0):!1}function db(n,e,t){let r=ra(t,"object state"),s=qe(n);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.set(e,r),!0)}function fb(n,e,t){let r=ra(t,"object state"),s=qe(n);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.snap(e,r),!0)}function hb(n,e,t){let r=na(t,"event data");if(typeof e!="string"||!e||e.length>vn.MAX_EVENT_TYPE_CHARS||Qs(e))return!1;let s=qe(n);return s?(s.send(e,r),!0):!1}function pb(n,e){}function mb(n,e){let t=na(e,"input"),r=qe(n);return r?(r.inputs.send(t),!0):!1}function gb(n,e){let t=qe(n);return t?(t.setRoomOpen(e===!0),!0):!1}function yb(n,e){let t=qe(n);return!t||typeof e!="string"?!1:(t.chat.send(e),!0)}function sa(n,e,t,r,s=!1){if(typeof t!="string"||!t)throw new TypeError("genex bridge: object id must be a non-empty string");let i=An(n),o=qe(n),a=d=>{if(!i)return;let h={type:"controlResult",requestId:String(r),operation:e,id:t,accepted:d.accepted,owner:d.owner??null,sequence:d.sequence,reason:d.reason};typeof d.retryAfterMs=="number"&&(h.retryAfterMs=d.retryAfterMs),le(i,h)};if(!o){a({accepted:!1,sequence:0,reason:"disconnected"});return}let c={timeoutMs:i?.opts.controlTimeoutMs,...s?{authority:"host"}:{}};(e==="claim"?o.objects.claimConfirmed(t,c):e==="release"?o.objects.releaseConfirmed(t,c):o.objects.removeConfirmed(t,c)).then(a,()=>a({accepted:!1,sequence:0,reason:"disconnected"}))}function bb(n,e,t){sa(n,"claim",e,t)}function wb(n,e,t){sa(n,"claim",e,t,!0)}function _b(n,e,t){sa(n,"release",e,t)}function Eb(n,e,t){sa(n,"remove",e,t)}function Rb(n){let e=An(n);return!e?.mm||e.closed?!1:(e.mm.eliminated(),!0)}function xb(n,e=1){let t=An(n);return!t?.mm||t.closed||typeof e!="number"||!Number.isFinite(e)?!1:(t.mm.score(e),!0)}function Sb(n){let e=An(n);return!e?.mm||e.closed?!1:(e.mm.finish(),!0)}function Tb(n){return qe(n)?.serverNow()??null}function kb(n,e){let t=qe(n);return t?t.timeUntil(e):e-Date.now()}var Yh=n=>typeof n=="number"&&Number.isFinite(n)?n:null;function vb(n){let e=An(n),t=qe(n),r=t?cn(t):null,s=r?.state?.match,i=null;if(s)try{i=JSON.parse(s)}catch{i=null}return JSON.stringify({sessionId:t?.id??e?.sessionId??"",roomId:r?.roomId??e?.roomId??"",hostId:t?.host??null,isHost:t?.isHost??!1,connected:!!t&&!!e?.connected,closed:!e||e.closed,serverNow:Yh(t?.serverNow()),rtt:Yh(t?.rtt),clockSynced:t?.clockSynced??!1,clockOrigin:r?.state?.clockOrigin??0,matchState:i})}function Ab(n){let e=qe(n);if(!e)return"[]";let t=cn(e).state?.players,r=[];for(let[s,i]of e.players){let o=t?.get(s);r.push({id:s,name:i.name,uid:i.uid,team:i.team,connected:i.connected,avatarUrl:i.avatarUrl,state:i.state??{},stateRaw:i.stateRaw??{},epoch:o?.epoch??0,isMe:s===e.id,posed:o?.posed===!0})}return JSON.stringify(r)}function Cb(n){let e=qe(n);if(!e)return"[]";let t=cn(e).state?.objects,r=[];for(let s of e.objects.ids()){let i=e.objects.get(s);i&&r.push({id:s,owner:i.owner??null,isMine:i.isMine,seq:t?.get(s)?.seq??0,epoch:i.epoch,state:i.state??null,stateRaw:i.stateRaw??null})}return JSON.stringify(r)}function Ib(n){let e=qe(n),t={};if(e)for(let r of e.shared.keys())t[r]=e.shared.get(r)??null;return JSON.stringify(t)}function Pb(n){let e=An(n);if(!e)return"[]";try{ea(e);let t=ll(e);if(t){let r=cn(t).state?.match??"";if(r!==e.lastMatch){e.lastMatch=r;let s=null;try{s=r?JSON.parse(r):null}catch{s=null}le(e,{type:"matchState",state:s})}}return e.changed.clear(),e.overflowed=!1,JSON.stringify(e.q.splice(0))}catch(t){return JSON.stringify([{type:"warning",message:`genex bridge: ${ta(t)}`}])}}var Ob=Object.freeze({...dl,initEmbed:Ci});globalThis.GenexMultiplayerBridge=Ob;})();
|
|
12
|
+
`);let s=new Uint8Array(r);return s.set(e),e===this.sharedBuffer&&(this.sharedBuffer=s),s}encodeAll(e={offset:0},t=this.sharedBuffer){return this.encodeFullSync(e,t,!1)}encodeAllView(e,t,r,s=this.sharedBuffer){let i=r.offset;return s=this.encodeFullSync(r,s,!0,e,i),tc(s.subarray(0,t),s.subarray(i,r.offset))}ensureCapacity(e,t){if(t+Dt.BUFFER_SIZE<=e.byteLength)return e;let r=Math.ceil((t+Dt.BUFFER_SIZE)/Dt.BUFFER_SIZE)*Dt.BUFFER_SIZE,s=new Uint8Array(r);return s.set(e.subarray(0,t)),e===this.sharedBuffer&&(this.sharedBuffer=s),s}encodeView(e,t,r,s=this.sharedBuffer){let i=r.offset;this._emitStreamPriority(e);for(let o of e.changes.keys()){let a=e.changes.get(o),c=this.root.changeTrees[o];if(c===void 0){e.changes.delete(o);continue}if(a.size===0)continue;let u=c.encDescriptor,d=u.encoder,h=u.metadata,m=c.ref,g=c.refTarget;s=this.ensureCapacity(s,r.offset),s[r.offset++]=255,Q.number(s,m[$],r);for(let[p,y]of a){let x;if(p===Dy){let B=g.tmpItems,N=g.deletedIndexes;for(let C=0;C<B.length;C++)B[C]===void 0||N[C]===!0||d(this,s,c,C,R.ADD,r,!1,!0,h);continue}if(typeof p=="number")x=p;else{let B=p.indexInParent(m);if(B===void 0)continue;if(x=B,y===R.ADD&&c.getChange(x)===R.DELETE){e.changes.delete(p.ref[$]);continue}}let I=g[Te](x)!==void 0&&y||R.DELETE;d(this,s,c,x,I,r,!1,!0,h)}}return e.changes.clear(),s=this.encode(r,e,s),tc(s.subarray(0,t),s.subarray(i,r.offset))}encodeUnreliableView(e,t,r,s=this.sharedBuffer){let i=r.offset;return s=this.encodeUnreliable(r,e,s,i),tc(s.subarray(0,t),s.subarray(i,r.offset))}_emitStreamBroadcast(e,t){let r=this.root.streamTrees;for(let s of r){let i=s,o=i[_],a=i[$];if(a===void 0)continue;let c=i._stream,u=c.broadcastDeletes,d=c.broadcastPending,h=c.sentBroadcast,m=u.size>0,g=d.size>0,p=o.encDescriptor,y=p.encoder,x=p.metadata;if(m||g){if(e[t.offset++]=255,Q.number(e,a,t),m){for(let C of u)y(this,e,o,C,R.DELETE,t,!1,!1,x);u.clear()}let k=c.maxPerTick,I=[],B=0,N=[];for(let C of d){if(B>=k)break;let P=i[Te](C);if(P===void 0){N.push(C);continue}y(this,e,o,C,R.ADD,t,!1,!1,x),h.add(C),I.push(P),N.push(C),B++}for(let C of N)d.delete(C);for(let C of I){let P=C[_];if(P===void 0)continue;let v=C[$];if(v===void 0)continue;e[t.offset++]=255,Q.number(e,v,t);let O=P.encDescriptor,V=O.encoder,Z=O.metadata;P.forEachLive(ee=>{le.hasUnreliableAtIndex(Z,ee)||V(this,e,P,ee,R.ADD,t,!1,!1,Z)})}}for(let k of h){let I=i[Te](k);if(I===void 0)continue;let B=I[_];if(B===void 0||!B.has())continue;let N=I[$];if(N===void 0)continue;e[t.offset++]=255,Q.number(e,N,t);let C=B.encDescriptor,P=C.encoder,v=C.metadata;B.forEach((O,V)=>{O<0||le.hasUnreliableAtIndex(v,O)||P(this,e,B,O,V,t,!1,!1,v)})}}}_emitStreamPriority(e){let t=this.root.streamTrees;if(t.size===0)return;let r=e.id;for(let s of t){let i=s,o=i._stream,a=o.pendingByView.get(r);if(a===void 0||a.size===0)continue;let c=o.priorityByView?.get(r),u=c!==void 0,d=o.priority,h=o.maxPerTick,m=[],g=[];if(u||d!==void 0){let x=[],k=[],I=0;for(let B of a){let N=i[Te](B);if(N===void 0){g.push(B);continue}let C=u?c(N):d(e,N);if(I<h){let P=I++;for(;P>0&&k[P-1]<C;)k[P]=k[P-1],x[P]=x[P-1],P--;k[P]=C,x[P]=B}else if(C>k[h-1]){let P=h-1;for(;P>0&&k[P-1]<C;)k[P]=k[P-1],x[P]=x[P-1],P--;k[P]=C,x[P]=B}}for(let B=0;B<I;B++)m.push(x[B])}else for(let x of a){if(m.length>=h)break;m.push(x)}for(let x of g)a.delete(x);let p=m.length,y=o.sentByView.get(r);y===void 0&&(y=new Set,o.sentByView.set(r,y));for(let x=0;x<p;x++){let k=m[x],I=i[Te](k);if(I===void 0){a.delete(k);continue}e._addImmediate(I);let B=I[_];if(B!==void 0){let N=I[$],C=e.changes.get(N);C===void 0&&(C=new Map,e.changes.set(N,C));let P=B.metadata;B.forEachLive(v=>{le.hasUnreliableAtIndex(P,v)||C.set(v,R.ADD)})}a.delete(k),y.add(k)}}}discardChanges(){let e=this.root.changes,t=e.next,r=this.root;for(;t;){let s=t.next;t.changeTree.endEncode(),r.releaseNode(t),t=s}e.next=void 0,e.tail=void 0}discardUnreliableChanges(){let e=this.root.unreliableChanges,t=e.next,r=this.root;for(;t;){let s=t.next;t.changeTree.endEncodeUnreliable(),r.releaseNode(t),t=s}e.next=void 0,e.tail=void 0}tryEncodeTypeId(e,t,r,s){let i=this.context.getTypeId(t),o=this.context.getTypeId(r);if(o===void 0){console.warn(`@colyseus/schema WARNING: Class "${r.name}" is not registered on TypeRegistry - Please either tag the class with @entity or define a @type() field.`);return}i!==o&&(e[s.offset++]=213,Q.number(e,o,s))}get hasChanges(){return this.root.changes.next!==void 0||this._hasStreamBacklog()}get _isStreamBroadcastMode(){return this.root.activeViews.size===0&&this.root.streamTrees.size>0}_hasStreamBacklog(){let e=this.root;if(e.streamTrees.size===0)return!1;let t=e.activeViews.size===0;for(let r of e.streamTrees)if(t?Ag(r):kg(r,e))return!0;return!1}get hasUnreliableChanges(){return this.root.unreliableChanges.next!==void 0}};l(Dt,"BUFFER_SIZE",16*1024);ws=Dt,Zi=class extends Error{constructor(e){super(e),this.name="DecodingWarning"}},td={value:0,enumerable:!1,writable:!0},lc=class{constructor(){l(this,"refs",new Map);l(this,"refCount",{});l(this,"deletedRefs",new Set);l(this,"callbacks",{});l(this,"nextUniqueId",0)}getNextUniqueId(){return this.nextUniqueId++}addRef(e,t,r=!0){this.refs.set(e,t),t[$]===void 0?(td.value=e,Object.defineProperty(t,$,td)):t[$]!==e&&(t[$]=e),r&&(this.refCount[e]=(this.refCount[e]||0)+1),this.deletedRefs.has(e)&&this.deletedRefs.delete(e)}removeRef(e){let t=this.refCount[e];if(t===void 0){try{throw new Zi("trying to remove refId that doesn't exist: "+e)}catch(r){console.warn(r)}return}if(t===0){try{let r=this.refs.get(e);throw new Zi(`trying to remove refId '${e}' with 0 refCount (${r.constructor.name}: ${JSON.stringify(r)})`)}catch(r){console.warn(r)}return}(this.refCount[e]=t-1)<=0&&this.deletedRefs.add(e)}clearRefs(){this.refs.clear(),this.deletedRefs.clear(),this.callbacks={},this.refCount={}}garbageCollectDeletedRefs(){this.deletedRefs.forEach(e=>{if(this.refCount[e]>0)return;let t=this.refs.get(e),r=t.constructor[Symbol.metadata];if(r!=null)for(let s in r){let i=r[s].name,o=t[i];if(typeof o=="object"&&o){let a=o[$];a!==void 0&&!this.deletedRefs.has(a)&&this.removeRef(a)}}else typeof t[X]=="function"&&Array.from(t.values()).forEach(s=>{let i=s[$];i!==void 0&&!this.deletedRefs.has(i)&&this.removeRef(i)});this.refs.delete(e),delete this.refCount[e],delete this.callbacks[e]}),this.deletedRefs.clear()}addCallback(e,t,r){if(e===void 0){let s=typeof t=="number"?R[t]:t;throw new Error(`Can't addCallback on '${s}' (refId is undefined)`)}return this.callbacks[e]||(this.callbacks[e]={}),this.callbacks[e][t]||(this.callbacks[e][t]=[]),this.callbacks[e][t].push(r),()=>this.removeCallback(e,t,r)}removeCallback(e,t,r){let s=this.callbacks?.[e]?.[t]?.indexOf(r);s!==void 0&&s!==-1&&Py(this.callbacks[e][t],s)}},Tt=class{constructor(e,t){l(this,"context");l(this,"state");l(this,"root");l(this,"currentRefId",0);l(this,"triggerChanges");l(this,"resyncVisited",null);l(this,"resyncDamaged",!1);this.setState(e),this.context=t||new jn(e.constructor)}setState(e){this.state=e,this.root=new lc,this.root.addRef(0,e)}decode(e,t={offset:0},r=this.state){let s=this.triggerChanges!==void 0?[]:null,i=this.root,o=e.byteLength,a=r.constructor[Et];for(this.currentRefId=0;t.offset<o;){if(e[t.offset]==255){t.offset++,r[zi]?.();let u=te.number(e,t),d=i.refs.get(u);d?(r=d,a=r.constructor[Et],this.currentRefId=u):(console.error(`"refId" not found: ${u}`,{previousRef:r,previousRefId:this.currentRefId}),console.warn("Please report this issue to the developers."),this.skipCurrentStructure(e,t,o));continue}if(a(this,e,t,r,s)===uf){console.warn("@colyseus/schema: definition mismatch"),this.skipCurrentStructure(e,t,o);continue}}return r[zi]?.(),this.resyncVisited!==null&&ly(this,s),s!==null&&this.triggerChanges?.(s),i.garbageCollectDeletedRefs(),s}decodeResync(e,t={offset:0}){this.resyncVisited=new Map,this.resyncDamaged=!1;try{return this.decode(e,t)}finally{this.resyncVisited=null}}skipCurrentStructure(e,t,r){this.resyncVisited!==null&&(this.resyncDamaged=!0);let s={offset:t.offset};for(;t.offset<r&&!(e[t.offset]===255&&(s.offset=t.offset+1,this.root.refs.has(te.number(e,s))));)t.offset++}getInstanceType(e,t,r){let s;if(e[t.offset]===213){t.offset++;let i=te.number(e,t);s=this.context.get(i)}return s||r}createInstanceOfType(e){return e.initializeForDecoder()}removeChildRefs(e,t){let r=typeof e[X]!="string",s=e[$];e.forEach((i,o)=>{t?.push({ref:e,refId:s,op:R.DELETE,field:o,value:void 0,previousValue:i}),r&&this.root.removeRef(i[$])})}},pf=Ss({min:Ye.float64(),max:Ye.float64(),bits:Ye.uint8(),mode:Ye.uint8()},"QuantizedDescriptor"),mf=Ss({name:Ye.string(),type:Ye.string(),referencedType:Ye.number(),childPrimitive:Ye.string(),quantized:Ye.ref(pf).optional()},"ReflectionField"),gf=Ss({id:Ye.number(),extendsId:Ye.number(),fields:Ye.array(mf)},"ReflectionType"),kt=Ss({types:Ye.array(gf),rootType:Ye.number()},"Reflection");kt.encode=function(n,e={offset:0}){let t=n.context,r=new kt,s=new ws(r),i=t.schemas.get(n.state.constructor);i>0&&(r.rootType=i);let o=new Set,a={},c=d=>{if(d.extendsId===void 0||o.has(d.extendsId)){o.add(d.id),r.types.push(d);let h=a[d.id];h!==void 0&&(delete a[d.id],h.forEach(m=>c(m)))}else a[d.extendsId]===void 0&&(a[d.extendsId]=[]),a[d.extendsId].push(d)};t.schemas.forEach((d,h)=>{let m=new gf;m.id=Number(d);let g=Object.getPrototypeOf(h);g!==Ee&&(m.extendsId=t.schemas.get(g));let p=h[Symbol.metadata];if(p!==g[Symbol.metadata]){let y=p[Ue]??-1;for(let x=0;x<=y;x++){let k=p[x];if(k===void 0)continue;let I=k.name;if(!Object.prototype.hasOwnProperty.call(p,I))continue;let B=new mf;B.name=I;let N;if(typeof k.type=="string")N=k.type;else if(Vn(k.type)){let C=k.type.quantized;N="quantized";let P=new pf;P.min=C.min,P.max=C.max,P.bits=C.bits,P.mode=C.wrap?1:0,B.quantized=P}else{let C;Ee.is(k.type)?(N="ref",C=k.type):(N=Object.keys(k.type)[0],typeof k.type[N]=="string"?B.childPrimitive=k.type[N]:C=k.type[N]),B.referencedType=C?t.getTypeId(C):-1}B.type=N,m.fields.push(B)}}c(m)});for(let d in a)a[d].forEach(h=>r.types.push(h));return s.encodeAll(e).slice(0,e.offset)};kt.decode=function(n,e){let t=new kt;new Tt(t).decode(n,e);let s=new jn;t.types.forEach(a=>{let c=s.get(a.extendsId)??Ee,u=class extends c{};jn.register(u),s.add(u,a.id)},{});let i=(a,c,u)=>{c.fields.forEach((d,h)=>{let m=u+h;if(d.quantized!==void 0){let g=d.quantized;le.addField(a,m,d.name,{quantized:hc({min:g.min,max:g.max,bits:g.bits,mode:g.mode===1?"wrap":"clamp"})})}else if(d.referencedType!==void 0){let g=d.type,p=s.get(d.referencedType)??d.childPrimitive;g==="ref"?le.addField(a,m,d.name,p):le.addField(a,m,d.name,{[g]:p})}else le.addField(a,m,d.name,d.type)})};t.types.forEach(a=>{let c=s.get(a.id),u=le.initialize(c),d=[],h=a;do d.push(h),h=t.types.find(g=>g.id===h.extendsId);while(h);let m=0;d.reverse().forEach(g=>{i(u,g,m),m+=g.fields.length})});let o=new(s.get(t.rootType||0));return new Tt(o,s)};kt.makeEncodable=function(n){let e=n[Symbol.metadata];if(!e)return n;let t=e[Ue];if(t===void 0)return n;for(let r=0;r<=t;r++){let s=e[r];s&&le.defineField(n,e,r,s.name,s.type)}return Object.prototype.hasOwnProperty.call(n,fs)&&delete n[fs],n};to=class{constructor(e){l(this,"decoder");l(this,"uniqueRefIds",new Set);l(this,"isTriggering",!1);this.decoder=e,this.decoder.triggerChanges=this.triggerChanges.bind(this)}get callbacks(){return this.decoder.root.callbacks}get state(){return this.decoder.state}addCallback(e,t,r){return this.decoder.root.addCallback(e,t,r)}addCallbackOrWaitCollectionAvailable(e,t,r,s,i=!0){let o=()=>{},a=()=>o(),c=e[t];if(!c||c[$]===void 0){let u;return u=this.addCallback(e[$],t,(d,h)=>{d!=null&&(u(),o=this.addCallback(d[$],r,s))}),o=u,a}else return i=i&&this.isTriggering===!1,r===R.ADD&&i&&c.forEach((u,d)=>{s(u,d)}),this.addCallback(c[$],r,s)}listen(...e){return typeof e[0]=="string"?this.listenInstance(this.state,e[0],e[1],e[2]):this.listenInstance(e[0],e[1],e[2],e[3])}listenInstance(e,t,r,s=!0){s=s&&this.isTriggering===!1;let i=e[t];return s&&i!==null&&i!==void 0&&r(i,void 0),this.addCallback(e[$],t,r)}onChange(...e){if(e.length===2&&typeof e[0]!="string"){let t=e[0],r=e[1];return this.addCallback(t[$],R.REPLACE,r)}return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],R.REPLACE,e[1]):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],R.REPLACE,e[2])}onAdd(...e){return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],R.ADD,e[1],e[2]!==!1):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],R.ADD,e[2],e[3]!==!1)}onRemove(...e){return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],R.DELETE,e[1]):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],R.DELETE,e[2])}bindTo(e,t,r,s=!0){let i=e.constructor[Symbol.metadata];r||(r=Object.keys(i).filter(a=>!isNaN(Number(a))).map(a=>i[a].name));let o=()=>{for(let a of r){let c=e[a];c!==void 0&&(t[a]=c)}};return s&&o(),this.addCallback(e[$],R.REPLACE,o)}triggerChanges(e){this.uniqueRefIds.clear(),this.isTriggering=!0;for(let t=0,r=e.length;t<r;t++){let s=e[t],i=s.refId,o=s.ref,a=this.callbacks[i];if(a){if((s.op&R.DELETE)===R.DELETE&&Ee.isSchema(s.previousValue)){let c=s.previousValue[$],u=this.callbacks[c]?.[R.DELETE];if(u)for(let d=u.length-1;d>=0;d--)try{u[d]()}catch(h){console.error(h)}}if(Ee.isSchema(o)){if(!this.uniqueRefIds.has(i)){let u=a[R.REPLACE];if(u)for(let d=u.length-1;d>=0;d--)try{u[d]()}catch(h){console.error(h)}}let c=a[s.field];if(c)for(let u=c.length-1;u>=0;u--)try{c[u](s.value,s.previousValue)}catch(d){console.error(d)}}else{let c=s.dynamicIndex??s.field;if((s.op&R.DELETE)===R.DELETE){if(s.previousValue!==void 0){let u=a[R.DELETE];if(u)for(let d=u.length-1;d>=0;d--)try{u[d](s.previousValue,c)}catch(h){console.error(h)}}if((s.op&R.ADD)===R.ADD){let u=a[R.ADD];if(u)for(let d=u.length-1;d>=0;d--)try{u[d](s.value,c)}catch(h){console.error(h)}}}else if((s.op&R.ADD)===R.ADD&&s.previousValue!==s.value){let u=a[R.ADD];if(u)for(let d=u.length-1;d>=0;d--)try{u[d](s.value,c)}catch(h){console.error(h)}}if(s.value!==s.previousValue){let u=a[R.REPLACE];if(u)for(let d=u.length-1;d>=0;d--)try{u[d](c,s.value)}catch(h){console.error(h)}}}this.uniqueRefIds.add(i)}}this.isTriggering=!1}},Ec={get(n){if(n instanceof Tt)return new to(n);if("decoder"in n.serializer)return new to(n.serializer.decoder);throw new Error("Invalid room or decoder")},getLegacy(n){if(n instanceof Tt)return eo(n);if("decoder"in n.serializer)return eo(n.serializer.decoder);throw new Error("Invalid room or decoder")},getRawChanges(n,e){return By(n,e)}};nn("map",{constructor:_n});nn("array",{constructor:wn});nn("set",{constructor:bs});nn("collection",{constructor:ys})});function $e(){return typeof performance<"u"?performance.now():Date.now()}var Ts=Pe(()=>{"use strict"});function ho(n,e){let t=globalThis,r=t.__colyseusDebug;if(!r){let s=[];r=t.__colyseusDebug={__buffer:s,publish(i,o){s.push([i,Uy(o)]),s.length>Fy&&s.shift()}}}r.publish(n,e)}function po(){if(typeof globalThis>"u")return!1;let n=globalThis.__colyseusDebug;return n!=null&&n.__buffer===void 0}var Uy,Fy,ks=Pe(()=>{"use strict";Uy=typeof WeakRef<"u"?n=>new WeakRef(n):n=>({deref:()=>n}),Fy=64});function Je(n){return n[$]}function Ut(n){return n.constructor[$y]}function As(n,e){let t=Ut(n)?.[e];return typeof t=="number"?t:-1}function bf(n){let e=Ut(n);if(!e)return[];let t=[];for(let r=0;;r++){let s=e[r];if(!s||typeof s.name!="string")break;typeof s.type=="string"&&t.push(s.name)}return t}function vs(n){let e=Ut(n),t=[],r=[];if(e)for(let s=0;;s++){let i=e[s];if(!i||typeof i.name!="string")break;typeof i.type=="string"&&(t.push(i.name),Vy[i.type]===void 0&&r.push(i.name))}return{fields:t,numeric:r}}function Hy(n){if(Number.isNaN(n))return 0;if(!Number.isFinite(n))return n>0?Number.MAX_SAFE_INTEGER:-Number.MAX_SAFE_INTEGER;if(n!==(n|0)&&Math.abs(n)<=34028235e31){let e=Math.fround(n);if(Math.abs(Math.abs(e)-Math.abs(n))<1e-4)return e}return n}function wf(n,e){let t=Ut(n),r=t?.[e];switch((typeof r=="number"?t[r]:void 0)?.type){case"float32":return Math.fround;case"number":return Hy;default:return jy}}function _f(n){if(n.length>Gy){let k=n;return I=>{let B={};for(let N=0;N<k.length;N++)B[k[N]]=I[k[N]];return B}}let e=n[0],t=n[1],r=n[2],s=n[3],i=n[4],o=n[5],a=n[6],c=n[7],u=n[8],d=n[9],h=n[10],m=n[11],g=n[12],p=n[13],y=n[14],x=n[15];return k=>{let I={};return e!==void 0&&(I[e]=k[e]),t!==void 0&&(I[t]=k[t]),r!==void 0&&(I[r]=k[r]),s!==void 0&&(I[s]=k[s]),i!==void 0&&(I[i]=k[i]),o!==void 0&&(I[o]=k[o]),a!==void 0&&(I[a]=k[a]),c!==void 0&&(I[c]=k[c]),u!==void 0&&(I[u]=k[u]),d!==void 0&&(I[d]=k[d]),h!==void 0&&(I[h]=k[h]),m!==void 0&&(I[m]=k[m]),g!==void 0&&(I[g]=k[g]),p!==void 0&&(I[p]=k[p]),y!==void 0&&(I[y]=k[y]),x!==void 0&&(I[x]=k[x]),I}}var $y,mo,Vy,jy,Gy,Cs=Pe(()=>{"use strict";qe();$y=Symbol.metadata??Symbol.for("Symbol.metadata"),mo=Fe;Vy={string:!0,boolean:!0,bigint64:!0,biguint64:!0};jy=n=>n;Gy=16});var xc,qy,zy,Ke,Rr,Sc=Pe(()=>{"use strict";qe();Kt();Ts();ks();Cs();xc=9,qy=xc,zy=(n,e)=>(e?2:1)*(xc+4+xc*n),Ke=class Ke{constructor(e,t,r,s){l(this,"data");l(this,"_host");l(this,"_encoder");l(this,"_scratch",new Uint8Array(2048));l(this,"_framed",null);l(this,"_sentCount",0);l(this,"_lastProcessed",0);l(this,"_epoch",0);l(this,"_sendTimes");l(this,"_inputBufferSize");l(this,"_inputBuffer",null);l(this,"_reckonTimes",null);l(this,"_pendingReckon",0);l(this,"_lastStamp",0);l(this,"_stampRing",null);l(this,"_renderDeltaRing",null);l(this,"_ringSlots",0);l(this,"_warnedUnknownKeys",null);l(this,"_stampRender",!1);l(this,"_stampReckon",!1);l(this,"_allowRewind");l(this,"_sendListeners",null);l(this,"_renderDelay",0);l(this,"_renderDelayExplicit",!1);l(this,"_renderDelayProvider");l(this,"_tickRate");l(this,"_patchRate");l(this,"_subSteps",1);this._host=e,this.data=t,this._encoder=r,this._stampRender=s?.stampRender??!1,this._stampReckon=s?.stampReckon??!1,this._allowRewind=s?.allowRewind,this._allowRewind!==void 0&&r.mode==="unreliable"&&!Ke._warnedAllowRewindIgnored&&(Ke._warnedAllowRewindIgnored=!0,console.warn('@colyseus/sdk: `allowRewind` is ignored on `mode:"unreliable"` \u2014 a packet stamps its whole redundancy ring or none of it, so excluding one input would cost bandwidth rather than save it. Use `mode:"reliable"` to gate the lag-comp stamp per input.')),this._renderDelay=s?.renderDelay??0,this._renderDelayExplicit=s?.renderDelay!==void 0,this._tickRate=s?.tickRate,this._patchRate=s?.patchRate,this._subSteps=s?.subSteps??1;let i=this._tickRate?1e3/this._tickRate:1e3/60,o=Ke.BUFFER_RTT_BUDGET_MS+(this._patchRate??0);this._inputBufferSize=Math.max(Ke.BUFFER_FLOOR,Math.ceil(o/i*Ke.BUFFER_HEADROOM)),this._sendTimes=new Float64Array(this._inputBufferSize)}get mode(){return this._encoder.mode}get tickRate(){return this._tickRate}get stepSeconds(){return this._tickRate?1/this._tickRate:void 0}get stepMs(){return this._tickRate?1e3/this._tickRate:void 0}get patchRate(){return this._patchRate}get subSteps(){return this._subSteps}get subStepSeconds(){return this._tickRate?1/this._tickRate/this._subSteps:void 0}get subStepMs(){return this._tickRate?1e3/this._tickRate/this._subSteps:void 0}get lastProcessed(){return this._lastProcessed}get sentCount(){return this._sentCount}get pendingCount(){return this._sentCount-this._lastProcessed}get replayBufferSize(){return this._inputBufferSize}get epoch(){return this._epoch}at(e){if(this._inputBuffer!==null&&!(e<=this._lastProcessed||e>this._sentCount)){if(this._sentCount-e>=this._inputBufferSize){Ke._warnedBufferOverflow||(Ke._warnedBufferOverflow=!0,console.warn(`@colyseus/sdk: input replay buffer (${this._inputBufferSize}) overflowed \u2014 RTT exceeds its budget at this input rate; reconciliation may drift.`));return}return this._inputBuffer[e%this._inputBufferSize]}}reckonTimeAt(e){return this._reckonTimes===null||e<=this._lastProcessed||e>this._sentCount||this._sentCount-e>=this._inputBufferSize?0:this._reckonTimes[e%this._inputBufferSize]}reset(){this._encoder.reset(),this._sentCount=this._lastProcessed=this._encoder.seq,this._framed=null,this._lastStamp=0,this._ringSlots=0,this._sendTimes.fill(0),this._epoch++}bindRenderDelay(e){this._renderDelayExplicit||(this._renderDelayProvider=e)}_resolveRenderDelay(){return this._renderDelayProvider?this._renderDelayProvider():this._renderDelay}_warnUnknownFields(){let e=Ut(this.data);if(e)for(let t of Object.keys(this.data))e[t]!==void 0||this._warnedUnknownKeys?.has(t)||((this._warnedUnknownKeys??(this._warnedUnknownKeys=new Set)).add(t),console.warn(`@colyseus/sdk input: "${t}" is not a declared field on ${this.data.constructor.name} \u2014 the write is never encoded or sent. Declare it with @type(...) on the input schema, or remove the write.`))}send(){let e=this._host.connection;if(!e?.isOpen)return 0;po()&&this._warnUnknownFields();let t=this._encoder.encode(),r=this._encoder.mode==="reliable",s=this._stampReckon||this._stampRender,i=s&&r&&(this._allowRewind===void 0||this._allowRewind(this.data)),o=s&&!r,a=this._stampReckon&&this._stampRender,u=1+(i?qy+(a?2:0):o?zy(this._encoder.historySize,a):0)+t.length;u>this._scratch.byteLength&&(this._scratch=new Uint8Array(Math.max(u,this._scratch.byteLength*2)),this._framed=null),this._scratch[0]=(r?_e.ROOM_INPUT_RELIABLE:_e.ROOM_INPUT_UNRELIABLE)|(i||o?mr.TIMED:0);let d={offset:1};if(o)this._writeRingStamps(d);else if(i){let{stamp:p,renderDelta:y}=this._sampleStamp();Q.number(this._scratch,p-this._lastStamp,d),this._lastStamp=p,a&&Q.uint16(this._scratch,y,d)}else this._pendingReckon=0;this._scratch.set(t,d.offset);let h=d.offset+t.length;(this._framed===null||this._framed.byteLength!==h)&&(this._framed=this._scratch.subarray(0,h));let m=this._framed,g;return r?(e.send(m),g=++this._sentCount):(e.sendUnreliable(m),g=this._sentCount=this._encoder.seq),this._recordSent(g),g}_writeRingStamps(e){let{stamp:t,renderDelta:r}=this._sampleStamp(),s=this._encoder.historySize,i=this._encoder.seq,o=this._ringSlots=Math.min(this._ringSlots+1,s),a=this._stampRing??(this._stampRing=new Float64Array(s));if(a[i%s]=t,Q.number(this._scratch,o,e),Q.uint32(this._scratch,t,e),this._writeSeriesDeltas(a,i,o,e),this._stampReckon&&this._stampRender){let c=this._renderDeltaRing??(this._renderDeltaRing=new Uint16Array(s));c[i%s]=r,Q.uint16(this._scratch,r,e),this._writeSeriesDeltas(c,i,o,e)}}_writeSeriesDeltas(e,t,r,s){let i=e.length;for(let o=1;o<r;o++)Q.number(this._scratch,e[(t-o+1)%i]-e[(t-o)%i],s)}_sampleStamp(){let e=this._host.clock,t=(e?.lastServerTime?.()??0)>0,r=t?Math.max(0,Math.round(e.serverNow()))>>>0:0,s=t?Math.min(65535,Math.max(0,Math.round(this._resolveRenderDelay()+(e.smoothedRtt?.()??0)/2))):0;return this._pendingReckon=r,{stamp:this._stampReckon?r:r>s?r-s:0,renderDelta:s}}_recordSent(e){if(this._inputBuffer===null){let r=this.data.constructor;this._inputBuffer=Array.from({length:this._inputBufferSize},()=>new r)}this._encoder.copyInto(this._inputBuffer[e%this._inputBufferSize]),this._sendTimes[e%this._inputBufferSize]=$e(),this._stampReckon&&((this._reckonTimes??(this._reckonTimes=new Float64Array(this._inputBufferSize)))[e%this._inputBufferSize]=this._pendingReckon);let t=this._sendListeners;if(t!==null)for(let r=0;r<t.length;r++)t[r](e)}onSend(e){let t=this._sendListeners;return this._sendListeners=t!==null?[...t,e]:[e],()=>{let r=this._sendListeners;if(r===null)return;let s=r.indexOf(e);if(s<0)return;let i=r.slice();i.splice(s,1),this._sendListeners=i.length>0?i:null}}ackInput(e){if(e<=this._lastProcessed)return-1;let t=this._sentCount-e>=this._inputBufferSize;if(this._lastProcessed=e,t)return-1;let r=this._sendTimes[e%this._inputBufferSize];return r>0?$e()-r:-1}};l(Ke,"BUFFER_FLOOR",64),l(Ke,"BUFFER_RTT_BUDGET_MS",1e3),l(Ke,"BUFFER_HEADROOM",1.5),l(Ke,"_warnedBufferOverflow",!1),l(Ke,"_warnedAllowRewindIgnored",!1);Rr=Ke});var xr,Ie,go,yo=Pe(()=>{"use strict";Ts();xr=Object.freeze({now:()=>$e(),serverNow:()=>$e(),renderNow:()=>$e(),rtt:()=>0,smoothedRtt:()=>0,jitter:()=>0,lastServerTime:()=>0,patchInterval:()=>0,setPatchInterval:n=>{},sample:(n,e)=>{}}),Ie=class Ie{constructor(){l(this,"_clockOffset",0);l(this,"_clockHasSample",!1);l(this,"_offsetCount",0);l(this,"_rttFloorT",[]);l(this,"_rttFloorV",[]);l(this,"_rtt",0);l(this,"_smoothedRtt",0);l(this,"_rttHasSample",!1);l(this,"_jitter",0);l(this,"_lastRecvTime",-1);l(this,"_lastServerTime",0);l(this,"_patchInterval",0);l(this,"_renderTau",Ie.RENDER_TAU);l(this,"_renderSn",0);l(this,"_renderSnAt",0)}serverNow(){return $e()+this._clockOffset}renderNow(){let e=this.serverNow();if(this._renderTau<=0)return e;let t=$e();if(this._renderSn===0)return this._renderSn=e,this._renderSnAt=t,this._renderSn;let r=Math.min(t-this._renderSnAt,100);return r<.5?this._renderSn:(this._renderSnAt=t,this._renderSn+=r,Math.abs(e-this._renderSn)>Ie.RENDER_SNAP?(this._renderSn=e,this._renderSn):(this._renderSn+=(e-this._renderSn)*(1-Math.exp(-r/this._renderTau)),this._renderSn))}setRenderTau(e){this._renderTau=e>0?e:0}now(){return $e()}rtt(){return this._rtt}smoothedRtt(){return this._smoothedRtt}jitter(){return this._jitter}lastServerTime(){return this._lastServerTime}patchInterval(){return this._patchInterval}setPatchInterval(e){this._patchInterval=e>0?e:0}sample(e,t){let r=$e(),s=Ie.EMA_ALPHA,i=this._patchInterval;if(this._lastRecvTime>=0&&i>0){let a=r-this._lastRecvTime,c=Math.round(a/i);c>=1&&c<=Ie.JITTER_STALL_X&&(this._jitter+=(Math.abs(a-c*i)-this._jitter)*Ie.JITTER_GAIN)}this._lastRecvTime=r,this._lastServerTime=e,(t<0||this._smoothedRtt>0&&t>this._smoothedRtt*Ie.RTT_OUTLIER_X)&&(t=-1);let o=t>=0?e+t/2-r:e-r;if(!this._clockHasSample)this._clockOffset=o,this._clockHasSample=!0,t>=0&&(this.pushRttFloor(t,r),this._offsetCount=1);else if(t>=0){let a=this.pushRttFloor(t,r),c=this._offsetCount<Ie.RTT_GATE_WARMUP;this._offsetCount++,(c||t<=a*Ie.RTT_GATE_FACTOR)&&(this._clockOffset=this._clockOffset*(1-s)+o*s)}t>=0&&(this._rtt=t,this._rttHasSample?this._smoothedRtt=this._smoothedRtt*(1-s)+t*s:(this._smoothedRtt=t,this._rttHasSample=!0))}pushRttFloor(e,t){let r=this._rttFloorT,s=this._rttFloorV;for(;s.length>0&&s[s.length-1]>=e;)s.pop(),r.pop();s.push(e),r.push(t);let i=t-Ie.RTT_GATE_WINDOW;for(;r.length>0&&r[0]<i;)r.shift(),s.shift();return s[0]}reset(){this._clockOffset=0,this._clockHasSample=!1,this._offsetCount=0,this._rtt=0,this._smoothedRtt=0,this._rttHasSample=!1,this._jitter=0,this._lastRecvTime=-1,this._lastServerTime=0,this._rttFloorT.length=0,this._rttFloorV.length=0,this._renderSn=0,this._renderSnAt=0}};l(Ie,"EMA_ALPHA",.1),l(Ie,"RENDER_TAU",250),l(Ie,"RENDER_SNAP",250),l(Ie,"RTT_OUTLIER_X",4),l(Ie,"JITTER_GAIN",1/16),l(Ie,"JITTER_STALL_X",4),l(Ie,"RTT_GATE_FACTOR",1.2),l(Ie,"RTT_GATE_WINDOW",1e4),l(Ie,"RTT_GATE_WARMUP",30);go=Ie});var zf=xp((dR,qf)=>{"use strict";qf.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});function y0(n,e){return{now:()=>n?.serverNow()??performance.now(),ttlMs:typeof e=="function"?()=>e(n?.smoothedRtt()??0):e}}var Ys,Lo,Wc=Pe(()=>{"use strict";Ys=n=>Math.max(n*2,600),Lo=class n{constructor(){l(this,"entries",new Map);l(this,"accepted",new Set);l(this,"cfg",{});l(this,"dead",!1)}static get(e,t={}){let r=new n;return r.configure(y0(e.clock??null,t.ttlMs??Ys)),t.onReject&&r.configure({onReject:t.onReject}),r}configure(e){this.cfg={...this.cfg,...e}}predict(e,t){return this.entries.set(e,t??this.cfg.now?.()??performance.now()),{key:e,cancel:()=>{this.entries.delete(e),this.accepted.delete(e)},accept:()=>{this.entries.has(e)&&this.accepted.add(e)}}}has(e){return this.entries.has(e)}confirm(e){this.entries.delete(e),this.accepted.delete(e)}reject(e){this.entries.delete(e)&&(this.accepted.delete(e),this.cfg.onReject?.(e))}prune(e,t){let r=e??this.cfg.now?.()??performance.now(),s=this.cfg.ttlMs,i=t??(typeof s=="function"?s():s)??1/0;for(let[o,a]of this.entries)this.accepted.has(o)||r-a>i&&(this.entries.delete(o),this.cfg.onReject?.(o))}clear(){this.entries.clear(),this.accepted.clear()}get size(){return this.entries.size}dispose(){this.dead=!0,this.entries.clear(),this.accepted.clear()}}});function uh(){return{ema:0,peak:0}}function Yc(n,e){n.ema+=(e-n.ema)*.1,n.peak=Math.max(e,n.peak*.9)}function dh(n){n.ema=0,n.peak=0}function Lr(n,e){let t=e!==void 0&&e>lh?e:lh;return n.ema>=t?"diverging":n.peak>=t?"jitter":"matched"}var lh,Bo=Pe(()=>{"use strict";lh=.001});function Js(){return po()}function hh(){console.warn("@colyseus/sdk predict: a predicted value was read BEFORE this frame's input.send() calls. Reads between predict.tick() and the frame's sends are one fixed step stale and stutter on late frames. Send the frame's due inputs right after predict.tick(now) \u2014 tick and pump in your earliest per-frame callback, before anything reads value()/pose(). For game logic (zone checks, hit-reg) read .state/.world instead. See PREDICTION.md \xA74 (frame order).")}function ph(n,e){console.warn(e===""?`@colyseus/sdk predict: two key-less ctx.memo calls ran in one step (input seq ${n}) \u2014 the key-less form is ONE shared slot per step, so replay returns one frozen value for both (silent re-simulation corruption). Pass distinct keys: ctx.memo("a", \u2026) / ctx.memo("b", \u2026).`:`@colyseus/sdk predict: ctx.memo("${e}") ran twice in one step (input seq ${n}) \u2014 both calls share one slot on replay. Give each call site its own key (include the loop index for a per-iteration memo).`)}function mh(n,e,t,r){let s=$e();if(s-fh<b0)return;fh=s;let i="",o=-1;for(let c in e){let u=e[c],d=u<0?-u:u;d>o&&(o=d,i=c)}let a=i?e[i]:t;console.warn(`@colyseus/sdk predict: prediction is diverging at input seq ${n} \u2014 rolling drift ${t.toFixed(3)} \u2265 tolerance ${r}; "${i}" currently off by ${a.toFixed(3)}. Most likely the client and server simulations disagree: a different fixed dt, mismatched constants, a step function that isn't shared, or an input the server skipped. See PREDICTION.md \xA75 (Determinism).`)}var fh,b0,Jc=Pe(()=>{"use strict";Ts();ks();fh=-1/0,b0=1e3});function gh(){return Xc>0}var Kc,Xc,Br,Uo=Pe(()=>{"use strict";Bo();Jc();Kc=class{constructor(){l(this,"byTick",new Map);l(this,"diagTick",-1);l(this,"diagKeys",new Set);l(this,"warnedKeys",new Set)}run(e,t,r,s){if(t)return this.byTick.get(e)?.get(r);Js()&&(e!==this.diagTick?(this.diagTick=e,this.diagKeys.clear()):this.diagKeys.has(r)&&!this.warnedKeys.has(r)&&(this.warnedKeys.add(r),ph(e,r)),this.diagKeys.add(r));let i=s();if(i!==void 0){let o=this.byTick.get(e);o===void 0&&(o=new Map,this.byTick.set(e,o)),o.set(r,i)}return i}prune(e){for(let t of this.byTick.keys())t<=e&&this.byTick.delete(t)}clear(){this.byTick.clear(),this.diagTick=-1,this.diagKeys.clear()}},Xc=0;Br=class{constructor(e){l(this,"lastCorrection",{});l(this,"lastCorrectionMag",0);l(this,"reconcileSeq",0);l(this,"drift",uh());l(this,"error",{});l(this,"prev",{});l(this,"renderedBefore",{});l(this,"lastTick",-1);l(this,"lastAcked",0);l(this,"lastEpoch");l(this,"replayFrom",0);l(this,"predictedSeq",0);l(this,"catching",!1);l(this,"unsubscribeSend",()=>{});l(this,"renderAcc",0);l(this,"tickSeq",0);l(this,"clampedReadTick",-1);l(this,"warnedStaleRead",!1);l(this,"stepCtx");l(this,"ackWatermark",()=>this.input_.lastProcessed);l(this,"memos",new Kc);l(this,"smoothMs");l(this,"snapThreshold");l(this,"stepMs");l(this,"input_");l(this,"onReconcile");l(this,"warnTolerance");l(this,"clock");l(this,"dead",!1);l(this,"disposedHooks",[]);this.input_=e.input,this.clock=e.clock,this.smoothMs=e.smoothMs??(this.input_.patchRate?this.input_.patchRate:50),this.snapThreshold=e.snap??0;let t=e.stepMs??this.input_.stepMs??(e.stepSeconds!==void 0?e.stepSeconds*1e3:void 0);if(t===void 0)throw new Error("@colyseus/sdk reconciler: fixed simulation step is unknown. The server room must call setFixedTimestep() (or setTimestep()) so the input handle advertises a tick rate, or pass stepMs/stepSeconds explicitly \u2014 a wrong dt silently diverges rollback-replay.");this.stepMs=t;let r=e.stepSeconds??this.input_.stepSeconds??t/1e3,s=e.subSteps??this.input_.subSteps??1;this.stepCtx={dt:r,dtMs:t,tick:0,isReplay:!1,reckonTime:0,lagCompActive:!1,subSteps:s,subDt:r/s,subDtMs:t/s,memo:(i,o)=>typeof i=="string"?this.memos.run(this.stepCtx.tick,this.stepCtx.isReplay,i,o):this.memos.run(this.stepCtx.tick,this.stepCtx.isReplay,"",i),predict:(i,o)=>{this.stepCtx.isReplay||i._predictFromSim(this.stepCtx.tick,o,this.ackWatermark)}},this.onReconcile=e.onReconcile,this.warnTolerance=e.warnOnDivergence,this.lastAcked=this.input_.lastProcessed,this.lastEpoch=this.input_.epoch,this.predictedSeq=this.input_.sentCount,this.unsubscribeSend=this.input_.onSend(()=>this.catchUp())}tick(e){this.tickSeq++;let t=this.lastTick<0?0:e-this.lastTick;this.lastTick=e,t>0&&this.stepMs>0&&(this.renderAcc+=t);let r=this.input_.epoch;r!==this.lastEpoch&&(this.lastEpoch=r,this.reset());let s=this.input_.lastProcessed;if(s>this.lastAcked&&(this.lastAcked=s,this.reconcile(s)),this.markDirty(),t<=0)return;let i=this.smoothMs<=0?1:1-Math.exp(-t/this.smoothMs);for(let o of this.smoothedFields())this.error[o]-=this.error[o]*i}renderAlpha(){if(this.stepMs<=0)return 1;let e=this.renderAcc/this.stepMs;return e<0?0:e>1?1:e}noteRenderRead(){this.catching||this.stepMs<=0||this.renderAcc<this.stepMs||(this.clampedReadTick=this.tickSeq)}catchUp(){let e=this.input_.sentCount;if(!(this.predictedSeq>=e||this.catching)){this.clampedReadTick===this.tickSeq&&!this.warnedStaleRead&&(this.warnedStaleRead=!0,hh()),this.catching=!0,this.stepCtx.isReplay=!1;for(let t=this.predictedSeq+1;t<=e;t++){let r=this.input_.at(t);r!==void 0&&(this.snapshotPrev(),this.runStep(t,r),this.refreshRender(),this.renderAcc-=this.stepMs,this.renderAcc<0?this.renderAcc=0:this.renderAcc>=this.stepMs&&(this.renderAcc%=this.stepMs)),this.predictedSeq=t}this.catching=!1}}runStep(e,t){this.stepCtx.tick=e;let r=this.input_.reckonTimeAt(e);this.stepCtx.lagCompActive=r>0,this.stepCtx.reckonTime=r>0?r:this.clock!==void 0?this.clock.serverNow():0,this.applyStep(t)}reconcile(e){let t=this.warnTolerance!==void 0||Js();if(this.truthMatchesAt(e)){if(t){for(let u of this.smoothedFields())this.lastCorrection[u]=0;this.lastCorrectionMag=0,Yc(this.drift,0)}this.reconcileSeq++,this.memos.prune(e),this.onReconcile?.(e);return}let r=this.renderedBefore;for(let u of this.smoothedFields())r[u]=this.readCurrent(u)+this.error[u];this.adoptTruth();let s=Math.max(e,this.replayFrom);this.stepCtx.isReplay=!0,this.catching=!0,Xc++;try{for(let u=s+1;u<=this.input_.sentCount;u++){let d=this.input_.at(u);d!==void 0&&this.runStep(u,d)}}finally{Xc--}this.catching=!1,this.refreshRender(),this.predictedSeq=this.input_.sentCount;let i=this.smoothMs<=0,o=t||this.snapThreshold>0,a=0;for(let u of this.smoothedFields()){let d=r[u]-this.readCurrent(u);if(this.error[u]=i?0:d,o){let h=d<0?-d:d;h>a&&(a=h)}t&&(this.lastCorrection[u]=d)}let c=this.snapThreshold>0&&a>this.snapThreshold;if(c)for(let u of this.smoothedFields())this.error[u]=0,this.prev[u]=this.readCurrent(u);this.reconcileSeq++,t&&(this.lastCorrectionMag=a,c||(Yc(this.drift,a),this.warnTolerance!==void 0&&Lr(this.drift,this.warnTolerance)==="diverging"&&mh(e,this.lastCorrection,this.drift.ema,this.warnTolerance))),this.memos.prune(e),this.onReconcile?.(e)}get pendingCount(){return this.input_.pendingCount}reset(){this.reseedState(),dh(this.drift),this.replayFrom=this.input_.sentCount,this.predictedSeq=this.input_.sentCount,this.lastAcked=this.input_.lastProcessed,this.renderAcc=0,this.memos.clear(),this.markDirty()}onDisposed(e){this.disposedHooks.push(e)}dispose(){this.dead=!0,this.unsubscribeSend();for(let e of this.disposedHooks.splice(0))e()}truthMatchesAt(e){return!1}refreshRender(){}markDirty(){}}});var w0,Qc,Ur,Zc=Pe(()=>{"use strict";Wc();Uo();w0=0,Qc=10,Ur=class{constructor(e,t){l(this,"opts");l(this,"store");l(this,"entries",new Map);l(this,"now");l(this,"cooldownUntil",-1/0);l(this,"warnedReplayPredict",!1);l(this,"dead",!1);l(this,"teardowns",[]);this.opts=e,this.now=()=>t?.serverNow()??performance.now(),this.store=Lo.get({clock:t},{ttlMs:e.ttlMs??Ys,onReject:r=>{let s=this.entries.get(r);this.entries.delete(r),s&&this.opts.onReject?.(s.payload)}})}_predictFromSim(e,t,r){this.add(e,t,r)}predict(e){if(gh()){this.warnedReplayPredict||(this.warnedReplayPredict=!0,console.warn(`@colyseus/sdk: PredictedEventChannel${this.opts.label?` "${this.opts.label}"`:""}.predict() was called during a rollback replay and ignored. Inside a reconciler step, use ctx.predict(channel, payload).`));return}this.add(-1,e)}add(e,t,r){let s=this.opts.uniqueBy!==void 0?this.opts.uniqueBy(t):typeof t=="string"||typeof t=="number"?t:w0;if(this.entries.has(s))return;let i=this.now();if(this.opts.cooldownMs!==void 0){if(i<this.cooldownUntil)return;this.cooldownUntil=i+this.opts.cooldownMs}let o=this.store.predict(s,i);r!==void 0&&o.accept(),this.entries.set(s,{payload:t,seq:e,acked:r}),this.opts.onPredict?.(t)}has(e){return e===void 0?this.entries.size>0:this.entries.has(e)}get pendingCount(){return this.entries.size}confirm(e){let t=0;for(let r of this.settleKeys(e)){let s=this.entries.get(r);s!==void 0&&(this.entries.delete(r),this.store.confirm(r),this.opts.onConfirm?.(s.payload),t++)}return t===0&&this.opts.onUnpredicted?.(e),t}reject(e){let t=0;for(let r of this.settleKeys(e))this.entries.has(r)&&(this.store.reject(r),t++);return t}settleKeys(e){return e!==void 0?[e]:[...this.entries.keys()]}clear(){this.entries.clear(),this.store.clear()}prune(){if(this.entries.size>0){let e=this.opts.graceTicks??Qc;for(let[t,r]of[...this.entries])r.acked!==void 0&&r.acked()>=r.seq+e&&this.store.reject(t)}this.store.prune()}_addTeardown(e){this.teardowns.push(e)}dispose(){for(let e of this.teardowns.splice(0))e();this.dead=!0,this.clear(),this.store.dispose()}}});var Jn,Fo=Pe(()=>{"use strict";Wc();Jn=class{constructor(e={},t=null){l(this,"opts");l(this,"clock");l(this,"correlate");l(this,"ttl");l(this,"byId",new Map);l(this,"byServer",new Map);l(this,"nextId",1);l(this,"lastTickAt");l(this,"detach");l(this,"dead",!1);l(this,"handleAdd",(e,t)=>{if(this.byServer.has(e))return;let r=this.isOwned(e)?this.takeMatch(e):void 0;if(r)this.confirmEntry(r,e);else{let s={id:this.nextId++,server:e,local:void 0,state:"confirmed",at:void 0,leadMs:0,accepted:!1,data:this.makeData()};this.byId.set(s.id,s),this.byServer.set(e,s)}});l(this,"handleRemove",(e,t)=>{let r=this.byServer.get(e);r&&(this.byServer.delete(e),this.byId.delete(r.id))});l(this,"readServer",(e,t)=>e[t]);this.opts=e,this.clock=t,this.correlate=e.correlate??"fifo",this.ttl=e.ttl??Ys}attach(e){this.detach?.(),this.detach=e(this.handleAdd,this.handleRemove)}spawn(e){let t=this.nextId++,r=this.makeData(),s={id:t,server:void 0,local:e,state:"pending",at:this.now(),leadMs:0,accepted:!1,data:r};return this.byId.set(t,s),{id:t,local:e,data:r,cancel:()=>{let i=this.byId.get(t);i&&i.state==="pending"&&this.byId.delete(t)},accept:()=>{let i=this.byId.get(t);i&&(i.accepted=!0)}}}confirmEntry(e,t){e.server=t,e.state="confirmed";let r=this.opts.spawnTime;r!==void 0&&e.at!==void 0&&(e.leadMs=r(t)-e.at),this.byServer.set(t,e)}takeMatch(e){let t=this.correlate;if(typeof t!="function"){for(let r of this.byId.values())if(r.state==="pending")return r;return}for(let r of this.byId.values())if(r.state==="pending"&&t(r.local,e))return r}isOwned(e){return this.opts.owned?this.opts.owned(e):!0}makeData(){return this.opts.data?this.opts.data():void 0}tick(e=performance.now()){let t=this.opts.step,r=this.clock!==null?this.clock.serverNow():e;if(t!==void 0&&this.lastTickAt!==void 0){let s=Math.max(0,(r-this.lastTickAt)/1e3);if(s>0)for(let i of this.byId.values())i.state==="pending"&&t(i.local,s)}this.lastTickAt=r}prune(){if(this.byId.size===0)return;let e=this.now(),t=this.ttl(this.clock?.smoothedRtt()??0);for(let r of this.byId.values())r.state==="pending"&&!r.accepted&&r.at!==void 0&&e-r.at>t&&(this.byId.delete(r.id),this.opts.onReject?.(r.local,r.id))}entries(){return this.byId.values()}entryFor(e){return this.byServer.get(e)}value(e,t){return e.server!==void 0?this.readServer(e.server,t):e.local[t]}bindReader(e){this.readServer=e}alive(e){return this.byId.has(e)}get size(){return this.byId.size}clear(){this.byId.clear(),this.byServer.clear()}dispose(){this.dead=!0,this.detach?.(),this.detach=void 0,this.clear()}now(){return this.clock?.serverNow()??performance.now()}}});var yh,Kn,$o=Pe(()=>{"use strict";Uo();Cs();Jc();yh=n=>typeof n=="number"?n:typeof n=="boolean"?n?1:0:NaN,Kn=class extends Br{constructor(t,r){super(r);l(this,"local",{});l(this,"fields");l(this,"numericFields",[]);l(this,"step");l(this,"instance");l(this,"wireRound",[]);l(this,"history");l(this,"historySeq");l(this,"historySize");l(this,"historyOn");l(this,"undeclared",null);l(this,"devView",null);this.instance=t;let s=r.fields,i=s??vs(t).fields;if(s===void 0&&i.length===0)throw new Error("predict.reconciler(): no `fields` given and none derivable \u2014 the instance has no schema metadata (a plain object, or a schema with no scalar fields). Pass the decoded instance from room.state, or list `fields` explicitly.");this.fields=i,this.step=r.step;let o=this.fields.length>0;for(let a of this.fields){let c=t[a];this.local[a]=c,typeof c=="number"?(this.numericFields.push(a),this.prev[a]=c,this.error[a]=0):typeof c!="boolean"&&(o=!1),this.wireRound.push(wf(t,a))}if(this.historyOn=o,this.historySize=this.input_.replayBufferSize??64,this.history=new Float64Array(this.historyOn?this.historySize*this.fields.length:0),this.historySeq=new Float64Array(this.historyOn?this.historySize:0).fill(-1),s!==void 0){let a=new Set(this.fields),c=vs(t).fields.filter(u=>!a.has(u));c.length>0&&(this.undeclared=new Set(c))}}get state(){return this.local}get boundRegistrations(){return[{source:this.instance,fields:this.numericFields,poseKeys:this.numericFields}]}value(t){this.noteRenderRead();let r=this.local[t];if(typeof r!="number")return r;let s=r+(this.error[t]??0),i=this.prev[t]??s;return i+(s-i)*this.renderAlpha()}smoothedFields(){return this.numericFields}readCurrent(t){return this.local[t]}applyStep(t){let r=this.undeclared!==null&&Js()?this.stepView():this.local;if(this.step(this.stepCtx,r,t),this.historyOn){let s=this.stepCtx.tick,i=s%this.historySize,o=i*this.fields.length;for(let a=0;a<this.fields.length;a++)this.history[o+a]=yh(this.local[this.fields[a]]);this.historySeq[i]=s}}stepView(){if(this.devView!==null)return this.devView;let t=this.undeclared,r=new Set,s=(i,o)=>{typeof o!="string"||!t.has(o)||r.has(o)||(r.add(o),console.warn(`@colyseus/sdk predict: step ${i} "${o}" \u2014 a schema field NOT in this reconciler's \`fields\` list, so it is never mirrored or replayed: prediction integrates on top of a stale value and rubber-bands under latency. Add "${o}" to \`fields\`, or omit \`fields\` to mirror every scalar field. Read adopt-only fields off the raw instance instead of the predicted state.`))};return this.devView=new Proxy(this.local,{get(i,o,a){return s("read",o),Reflect.get(i,o,a)},set(i,o,a,c){return s("wrote",o),Reflect.set(i,o,a,c)}}),this.devView}truthMatchesAt(t){if(!this.historyOn)return!1;let r=t%this.historySize;if(this.historySeq[r]!==t)return!1;let s=r*this.fields.length,i=this.instance;for(let o=0;o<this.fields.length;o++)if(this.wireRound[o](this.history[s+o])!==yh(i[this.fields[o]]))return!1;return!0}snapshotPrev(){for(let t of this.numericFields)this.prev[t]=this.local[t]+this.error[t]}adoptTruth(){let t=this.instance;for(let r of this.fields)this.local[r]=t[r]}reseedState(){let t=this.instance;for(let r of this.fields)this.local[r]=t[r];for(let r of this.numericFields)this.prev[r]=this.local[r],this.error[r]=0;this.historySeq.fill(-1)}}});var Xn,Vo=Pe(()=>{"use strict";Uo();Cs();Xn=class extends Br{constructor(t){super(t);l(this,"worldHandle");l(this,"bindings",[]);l(this,"curPose",{});l(this,"poseFields",[]);l(this,"customFields",[]);l(this,"fieldsReady",!1);l(this,"poseA",{});l(this,"poseB",{});l(this,"renderPose",{});l(this,"poseDirty",!0);l(this,"step");l(this,"adopt");l(this,"readPose");l(this,"interpolate");let r=t.world;for(let s of Object.keys(r)){let i=r[s];if(i===null||typeof i!="object")continue;if(Je(i)===void 0){if(Ut(i)!==void 0)throw new Error(`predict.sim(): world.${s} is a schema instance that hasn't been decoded (no refId). Pass the decoded instance from room.state (e.g. inside onAdd), or a plain object for opaque scratch.`);continue}let{fields:o,numeric:a}=vs(i);if(o.length===0)throw new Error(`predict.sim(): world.${s} is a decoded ref with no scalar fields to bind. Binding a whole COLLECTION isn't supported (yet) \u2014 spread its children into world parts (one entry per entity, fixed at construction). Nest a scalar-less instance below a plain wrapper if you meant it as an opaque handle.`);let c={};for(let d of o)c[d]=i[d];r[s]=c;let u=a.map(d=>`${s}.${d}`);this.bindings.push({source:i,mirror:c,fields:o,numeric:a,poseKeys:u})}if(this.bindings.length===0&&t.adopt===void 0)throw new Error("predict.sim(): no restore point \u2014 world has no schema-bound entries and no adopt() was provided. Put decoded schema instances in world (auto-bound), or provide adopt().");this.worldHandle=t.world,this.step=t.step,this.adopt=t.adopt,this.readPose=t.pose,this.interpolate=t.interpolate,this.refreshPose();for(let s of this.poseFields)this.prev[s]=this.curPose[s],this.error[s]=0}refreshPose(){let t=this.curPose;for(let r of this.bindings){let{mirror:s,numeric:i,poseKeys:o}=r;for(let a=0;a<i.length;a++)t[o[a]]=s[i[a]]}if(this.readPose!==void 0){let r=this.readPose(this.worldHandle);this.fieldsReady||(this.customFields=Object.keys(r));for(let s of this.customFields)t[s]=r[s]}if(!this.fieldsReady){let r=[];for(let s of this.bindings)for(let i of s.poseKeys)r.push(i);for(let s of this.customFields)r.includes(s)||r.push(s);this.poseFields=r,this.fieldsReady=!0}this.poseDirty=!0}get world(){return this.worldHandle}get boundRegistrations(){return this.bindings.map(t=>({source:t.source,fields:t.numeric,poseKeys:t.poseKeys}))}value(t){if(this.noteRenderRead(),this.interpolate)return this.pose()[t];let r=this.curPose[t]+(this.error[t]??0),s=this.prev[t]??r;return s+(r-s)*this.renderAlpha()}pose(){if(this.noteRenderRead(),!this.poseDirty)return this.renderPose;let t=this.renderAlpha(),r=this.poseA,s=this.poseB;for(let i of this.poseFields)r[i]=this.prev[i]??this.curPose[i],s[i]=this.curPose[i]+(this.error[i]??0);if(this.interpolate){let i=this.interpolate(r,s,t);for(let o of this.poseFields)this.renderPose[o]=i[o]}else for(let i of this.poseFields)this.renderPose[i]=r[i]+(s[i]-r[i])*t;return this.poseDirty=!1,this.renderPose}smoothedFields(){return this.poseFields}readCurrent(t){return this.curPose[t]}applyStep(t){this.step(this.stepCtx,this.worldHandle,t)}adoptTruth(){for(let t of this.bindings){let{source:r,mirror:s,fields:i}=t;for(let o=0;o<i.length;o++)s[i[o]]=r[i[o]]}this.adopt?.(this.worldHandle)}refreshRender(){this.refreshPose()}markDirty(){this.poseDirty=!0}snapshotPrev(){for(let t of this.poseFields)this.prev[t]=this.curPose[t]+this.error[t]}reseedState(){this.adoptTruth(),this.refreshPose();for(let t of this.poseFields)this.prev[t]=this.curPose[t],this.error[t]=0}}});function bh(n,e,t,r){let s=[];if(t.field!==void 0){let i=new Map;s.push(n.onAdd(t.collection,(o,a)=>{i.has(o)||i.set(o,n.listen(o,t.field,c=>{c===t.equals&&e.confirm(a)},!1))})),s.push(n.onRemove(t.collection,o=>{i.get(o)?.(),i.delete(o)})),s.push(()=>{for(let o of i.values())o();i.clear()})}else t.event==="remove"?s.push(n.onRemove(t.collection,(i,o)=>{e.confirm(o)})):s.push(n.onAdd(t.collection,i=>{t.mine!==void 0&&i[t.mine]!==r?.()||e.confirm()},!1));return()=>{for(let i of s.splice(0))i?.()}}var wh=Pe(()=>{"use strict"});function Eh(n){return n===null||typeof n!="object"?!1:Array.isArray(n.fields)}function S0(){Rh||(Rh=!0,console.warn("@colyseus/sdk Predict: room.clock isn't server-synced because the server room didn't call defineInput(). Server-time interpolation and lag compensation fall back to local time. Add defineInput() on the server room to enable them \u2014 or ignore this if you only need local smoothing."))}var Me,ct,ht,on,vt,Ks,Xs,Fr,$r,Vr,Qs,je,_0,E0,_h,Qe,jr,Qn,Zn,Hr,Gr,qr,zr,Ht,Zs,Go,qo,zo,R0,jo,el,kn,Ho,x0,Rh,Wr,ei,tl=Pe(()=>{"use strict";qe();Zc();Fo();$o();Vo();Sc();Bo();yo();ks();Cs();wh();Me=16,ct=0,ht=1,on=2,vt=3,Ks=4,Xs=5,Fr=6,$r=7,Vr=8,Qs=9,je=Qs+Me*2,_0=3,E0=1.5,_h=250,Qe=7,jr=0,Qn=1,Zn=2,Hr=3,Gr=4,qr=5,zr=6,Ht=0,Zs=0,Go=1,qo=2,zo=3,R0=4,jo=5,el={lerp:Zs,extrapolate:Go,damped:qo,reckon:zo,raw:R0},kn={mode:"lerp",delay:100,smoothMs:50,maxExtrapolate:200,tickInterval:0,snap:0,angle:!1},Ho={step:void 0,smoothMs:50,substep:16,snap:0};x0=0,Rh=!1;Wr=class Wr{constructor(e,t){l(this,"callbacks");l(this,"sessionSource");l(this,"slotBuf",new Float64Array(64*je));l(this,"slotCount",0);l(this,"slotDetach",[]);l(this,"slotAngle",[]);l(this,"freeSlots",[]);l(this,"slotByRef",new Map);l(this,"simByRef",new Map);l(this,"boundBySlot",new Map);l(this,"boundProfileIdx",-1);l(this,"renderTime",0);l(this,"defaultMode");l(this,"reckonDefaults");l(this,"clock");l(this,"useRenderClock",!1);l(this,"fixedStepMs");l(this,"stepAcc",0);l(this,"lastFrameNow",-1);l(this,"profileBuf",new Float64Array(8*Qe));l(this,"profileCount",0);l(this,"profileKeys",new Map);l(this,"profileLabels",[]);l(this,"profileComputers",[]);l(this,"trackListeners",[]);l(this,"name");l(this,"disposeListeners",[]);l(this,"driven",[]);l(this,"computeDamped",e=>{let t=this.slotBuf,r=e*je,s=this.profileBuf,i=(t[r+vt]|0)*Qe,o=this.renderTime,a=t[r+ct],c=t[r+on],u=o-c;t[r+on]=o;let d=t[r+ht];if(u>0){let h=s[i+Zn],m=h>0?1-Math.exp(-u/h):1;d+=(a-d)*m,t[r+ht]=d}return d});l(this,"computeLerp",e=>{let t=this.computeLerpRaw(e),r=this.slotBuf,s=e*je,i=this.profileBuf[(r[s+vt]|0)*Qe+zr],o=this.renderTime;if(i<=0)return r[s+ht]=t,r[s+Vr]=t,r[s+on]=o,t;let a=r[s+on],c=o-a;if(c<=0)return r[s+ht];let u=r[s+Vr],d=r[s+ht],h=c/i,m=(t-u)/h,g=t-m+(d-u+m)*Math.exp(-h);return r[s+ht]=g,r[s+Vr]=t,r[s+on]=o,g});l(this,"computeExtrapolate",e=>{let t=this.slotBuf,r=e*je,s=this.profileBuf,i=(t[r+vt]|0)*Qe,o=this.renderTime,a=t[r+$r]|0;if(a===0)return t[r+ct];let c=t[r+Fr]|0,u=r+Qs,d=(c-a+Me)%Me,h=(d+a-1)%Me,m=u+h*2,g=t[m],p=t[m+1],y;if(a===1)y=p;else{let N=a>=3?2:1,C=(d+a-1-N+Me)%Me,P=u+C*2,v=t[P],O=t[P+1],V=g-v;if(V<=0)y=p;else{let Z=(p-O)/V,ee=s[i+Hr],Ae=o-g;Ae<0?Ae=0:Ae>ee&&(Ae=ee),y=p+Z*Ae}}let x=t[r+on];t[r+on]=o;let k=s[i+Zn];if(k<=0)return t[r+ht]=y,y;let I=o-x,B=t[r+ht];if(I>0){let N=1-Math.exp(-I/k);B+=(y-B)*N,t[r+ht]=B}return B});l(this,"computeReckon",e=>{let t=this.slotBuf,r=e*je,s=t[r+Ks],i=t[r+Xs]|0,o=this.simByRef.get(s);if(o!==void 0){let a=i<o.posOf.length?o.posOf[i]:-1;if(a>=0)return this.applySimulation(o,a)}return t[r+ct]});l(this,"computeRaw",e=>this.slotBuf[e*je+ct]);l(this,"computeBound",e=>{let t=this.boundBySlot.get(e);return t!==void 0?t.ctrl.value(t.key):this.slotBuf[e*je+ct]});this.callbacks=Ec.get(e),this.sessionSource=e;let{clock:r,...s}=t;this.defaultMode=s.mode??"lerp";let i=this.defaultMode!=="reckon"&&this.defaultMode!=="raw",o=i?(()=>{let u=s;return{mode:u.mode??kn.mode,delay:u.delay??kn.delay,smoothMs:u.smoothMs??kn.smoothMs,maxExtrapolate:u.maxExtrapolate??kn.maxExtrapolate,tickInterval:u.tickInterval??kn.tickInterval,snap:u.snap??kn.snap,angle:u.angle??kn.angle}})():{...kn},a=i?s.smoothMs??0:0;if(this.allocProfile(this.defaultMode,o.delay,o.smoothMs,a,o.maxExtrapolate,o.tickInterval,o.snap,!1)!==Ht)throw new Error("Predict: defaults profile must be at index 0");if(this.defaultMode==="reckon"){let u=s;this.reckonDefaults={step:u.step,smoothMs:u.smoothMs??Ho.smoothMs,substep:u.substep??Ho.substep,snap:u.snap??Ho.snap}}else this.reckonDefaults={...Ho};this.clock=r??e.clock??void 0,this.useRenderClock=s.renderPresent!==!1,this.clock===xr&&S0(),this.name=s.name??`predict#${++x0}`,ho("predict",this.makeCoreHandle())}static get(e,t={}){return new Wr(e,t)}get mode(){return this.defaultMode}presentFn(){let e=this.clock;if(e)return this.useRenderClock&&e.renderNow?e.renderNow.bind(e):e.serverNow.bind(e)}makeCoreHandle(){return{name:this.name,mode:()=>this.defaultMode,smoothingDefaults:()=>this.readSmoothingDefaults(),reckonDefaults:()=>({...this.reckonDefaults}),reconcilers:()=>this.snapshotReconcilers(),attachedCount:()=>this.slotByRef.size,setDefaults:e=>this.setDefaults(e),profiles:()=>this.snapshotProfiles(),setProfile:(e,t)=>this.setProfile(e,t),onTrack:e=>(this.trackListeners.push(e),()=>{let t=this.trackListeners.indexOf(e);t>=0&&this.trackListeners.splice(t,1)}),onDispose:e=>(this.disposeListeners.push(e),()=>{let t=this.disposeListeners.indexOf(e);t>=0&&this.disposeListeners.splice(t,1)})}}snapshotReconcilers(){let e=[],t=0;for(let r of this.driven){let s=r;if(!s.drift)continue;let i=s.warnTolerance;e.push({label:`reconciler #${t++}`,status:Lr(s.drift,i),severity:i!==void 0&&i>0?s.drift.ema/i:void 0,ema:s.drift.ema,peak:s.drift.peak,lastCorrectionMag:s.lastCorrectionMag??0,reconcileSeq:s.reconcileSeq??0})}return e}readSmoothingDefaults(){let e=this.profileBuf,t=Ht*Qe,r=e[t+jr]|0;return{mode:r===Zs?"lerp":r===Go?"extrapolate":r===qo?"damped":r===zo?"reckon":"raw",delay:e[t+Qn],smoothMs:e[t+Zn],lerpSmoothMs:e[t+zr],maxExtrapolate:e[t+Hr],tickInterval:e[t+Gr],snap:e[t+qr]}}allocProfile(e,t,r,s,i,o,a,c,u){let d=typeof e=="number"?e:el[e],h="";if(c){h=`${u??""}|${d}|${t}|${r}|${s}|${i}|${o}|${a}`;let y=this.profileKeys.get(h);if(y!==void 0)return y}let m=this.profileCount++;if((m+1)*Qe>this.profileBuf.length){let y=new Float64Array(this.profileBuf.length*2);y.set(this.profileBuf),this.profileBuf=y}let p=m*Qe;return this.profileBuf[p+jr]=d,this.profileBuf[p+Qn]=t,this.profileBuf[p+Zn]=r,this.profileBuf[p+zr]=s,this.profileBuf[p+Hr]=i,this.profileBuf[p+Gr]=o,this.profileBuf[p+qr]=a,this.profileLabels[m]=u,this.profileComputers[m]=this.computerForMode(d),c&&this.profileKeys.set(h,m),m}computerForMode(e){return e===Zs?this.computeLerp:e===Go?this.computeExtrapolate:e===qo?this.computeDamped:e===zo?this.computeReckon:e===jo?this.computeBound:this.computeRaw}profileFromOpts(e){if(e.mode===void 0&&e.delay===void 0&&e.smoothMs===void 0&&e.maxExtrapolate===void 0&&e.tickInterval===void 0&&e.snap===void 0)return Ht;let t=this.readSmoothingDefaults(),r=e.mode??t.mode,s=e.delay??t.delay,i=e.smoothMs??t.smoothMs,o=e.smoothMs??t.lerpSmoothMs,a=e.maxExtrapolate??t.maxExtrapolate,c=e.tickInterval??t.tickInterval,u=e.snap??t.snap;return r===t.mode&&s===t.delay&&i===t.smoothMs&&o===t.lerpSmoothMs&&a===t.maxExtrapolate&&c===t.tickInterval&&u===t.snap?Ht:this.allocProfile(r,s,i,o,a,c,u,!0)}groupProfile(e,t){let r=this.readSmoothingDefaults(),s=e.mode??this.defaultMode;return this.allocProfile(s,e.delay??r.delay,e.smoothMs??r.smoothMs,e.smoothMs??r.lerpSmoothMs,e.maxExtrapolate??r.maxExtrapolate,e.tickInterval??r.tickInterval,e.snap??r.snap,!0,t)}setDefaults(e){let t=e.mode;if(t!==void 0){this.defaultMode=t;let a=Ht*Qe,c=el[t];this.profileBuf[a+jr]=c,this.profileComputers[Ht]=this.computerForMode(c)}let r=e,s=Ht*Qe,i=this.profileBuf;r.delay!==void 0&&(i[s+Qn]=r.delay),r.smoothMs!==void 0&&(i[s+Zn]=r.smoothMs,i[s+zr]=r.smoothMs),r.maxExtrapolate!==void 0&&(i[s+Hr]=r.maxExtrapolate),r.tickInterval!==void 0&&(i[s+Gr]=r.tickInterval),r.snap!==void 0&&(i[s+qr]=r.snap,this.reckonDefaults.snap=r.snap);let o=e;o.step!==void 0&&(this.reckonDefaults.step=o.step),o.smoothMs!==void 0&&(this.reckonDefaults.smoothMs=o.smoothMs),o.substep!==void 0&&(this.reckonDefaults.substep=o.substep)}snapshotProfiles(){let e=[];for(let t=0;t<this.profileCount;t++){let r=t*Qe,s=this.profileBuf[r+jr]|0;if(s===jo)continue;let i=s===Zs?"lerp":s===Go?"extrapolate":s===qo?"damped":s===zo?"reckon":"raw";e.push({id:t,isDefault:t===Ht,label:this.profileLabels[t],mode:i,delay:this.profileBuf[r+Qn],smoothMs:this.profileBuf[r+(s===Zs?zr:Zn)],maxExtrapolate:this.profileBuf[r+Hr],tickInterval:this.profileBuf[r+Gr],snap:this.profileBuf[r+qr]})}return e}setProfile(e,t){if(e<0||e>=this.profileCount)return;let r=e*Qe,s=this.profileBuf;if((s[r+jr]|0)!==jo){if(t.mode!==void 0){let i=el[t.mode];s[r+jr]=i,this.profileComputers[e]=this.computerForMode(i),e===Ht&&(this.defaultMode=t.mode)}t.delay!==void 0&&(s[r+Qn]=t.delay),t.smoothMs!==void 0&&(s[r+Zn]=t.smoothMs,s[r+zr]=t.smoothMs),t.maxExtrapolate!==void 0&&(s[r+Hr]=t.maxExtrapolate),t.tickInterval!==void 0&&(s[r+Gr]=t.tickInterval),t.snap!==void 0&&(s[r+qr]=t.snap)}}dispose(){for(let e of new Set([...this.slotByRef.keys(),...this.simByRef.keys()]))this.detachByRef(e);this.trackListeners.length=0;for(let e of this.driven.splice(0))e.dispose?.();for(let e of this.disposeListeners.splice(0))e()}track(e,t,r={}){return this.trackWithProfile(e,t,this.profileFromOpts(r),r.angle??!1)}trackWithProfile(e,t,r,s=!1){let i=Je(e);if(i===void 0)throw new Error("Predict.track(): instance has no refId \u2014 track/attach must run AFTER the decoder delivers the instance (e.g. inside onAdd).");let o=As(e,t),a=e[t]??0,c,u=this.slotByRef.get(i)?.get(t);u!==void 0&&(c=this.boundBySlot.get(u),c!==void 0?this.freeStash(c):this.untrackSlot(i,t));let d=this.allocSlot(),h=this.slotBuf,m=d*je;if(h[m+ct]=a,h[m+ht]=a,h[m+on]=performance.now(),h[m+Vr]=a,h[m+vt]=r,h[m+Ks]=i,h[m+Xs]=o,h[m+Fr]=0,h[m+$r]=0,this.slotAngle[d]=s,c!==void 0)c.stash=d;else{let p=this.slotByRef.get(i);p===void 0&&(p=new Map,this.slotByRef.set(i,p)),p.set(t,d)}for(let p=0;p<this.trackListeners.length;p++)this.trackListeners[p](r,t);let g=this.callbacks.listen(e,t,p=>{let y=this.clock&&this.clock.lastServerTime()>0?this.clock.lastServerTime():performance.now(),x=this.slotBuf,k=d*je;if(s){let ee=x[k+ct];p=ee+Math.atan2(Math.sin(p-ee),Math.cos(p-ee))}let I=(x[k+vt]|0)*Qe,B=this.profileBuf[I+Gr],N=x[k+Fr]|0,C=x[k+$r]|0,P=this.profileBuf[I+qr];P>0&&C>0&&Math.abs(p-x[k+ct])>P&&(N=0,C=0,x[k+ht]=p,x[k+Vr]=p);let v=C===0?Number.NEGATIVE_INFINITY:x[k+Qs+(N===0?Me-1:N-1)*2],O=y;if(B>0&&isFinite(v)){let ee=y-v,Ae=ee>0?Math.max(1,Math.round(ee/B)):1;O=v+Ae*B;let Oe=y+B;O>Oe&&(O=Oe)}x[k+ct]=p;let V=k+Qs;if(C>=2&&isFinite(v)){let ee=N===0?Me-1:N-1,Ae=ee===0?Me-1:ee-1,Oe=v-x[V+Ae*2],S=this.clock?.patchInterval?this.clock.patchInterval():0,U=S>0?S:Oe,L=S>0?E0*S:_0*Oe;if(U>0&&O-v>L){let D=U<_h?U:_h,M=V+N*2;x[M]=O-D,x[M+1]=x[V+ee*2+1],N=N+1>=Me?0:N+1,C<Me&&C++}}let Z=V+N*2;x[Z]=O,x[Z+1]=p,x[k+Fr]=N+1>=Me?0:N+1,C<Me&&(x[k+$r]=C+1)},!0);return this.slotDetach[d]=g,()=>this.untrackSlot(i,t)}untrack(e,t){let r=Je(e);r!==void 0&&this.untrackSlot(r,t)}untrackSlot(e,t){let r=this.slotByRef.get(e),s=r?.get(t);if(s===void 0)return;let i=this.boundBySlot.get(s);if(i!==void 0){this.freeStash(i);return}this.slotDetach[s]?.(),this.slotDetach[s]=void 0,this.freeSlots.push(s),r.delete(t),r.size===0&&this.slotByRef.delete(e)}freeStash(e){e.stash<0||(this.slotDetach[e.stash]?.(),this.slotDetach[e.stash]=void 0,this.freeSlots.push(e.stash),e.stash=-1)}allocSlot(){if(this.freeSlots.length>0)return this.freeSlots.pop();let e=this.slotCount++;if((e+1)*je>this.slotBuf.length){let r=new Float64Array(this.slotBuf.length*2);r.set(this.slotBuf),this.slotBuf=r}return e}registerBound(e,t,r,s,i){let o=Je(t),a=this.slotByRef.get(o);a===void 0&&(a=new Map,this.slotByRef.set(o,a));let c=[];for(let u=0;u<r.length;u++){let d=r[u],h=a.get(d),m=-1;if(h!==void 0){let k=this.boundBySlot.get(h);k!==void 0?(console.warn(`@colyseus/sdk Predict: "${d}" (refId ${o}) is already bound to a controller \u2014 the newer registration wins.`),m=k.stash,this.boundBySlot.delete(h),this.freeSlots.push(h)):m=h}let g=this.allocSlot(),p=this.slotBuf,y=g*je,x=t[d]??0;p[y+ct]=x,p[y+ht]=x,p[y+on]=0,p[y+Vr]=x,p[y+vt]=i,p[y+Ks]=o,p[y+Xs]=As(t,d),p[y+Fr]=0,p[y+$r]=0,this.slotAngle[g]=!1,this.boundBySlot.set(g,{ctrl:e,key:s[u],stash:m}),a.set(d,g),c.push(g);for(let k=0;k<this.trackListeners.length;k++)this.trackListeners[k](i,d)}return()=>{for(let u=0;u<c.length;u++){let d=c[u],h=this.boundBySlot.get(d);if(h===void 0||h.ctrl!==e)continue;this.boundBySlot.delete(d),this.freeSlots.push(d);let m=this.slotByRef.get(o);m?.get(r[u])===d&&(h.stash>=0?m.set(r[u],h.stash):(m.delete(r[u]),m.size===0&&this.slotByRef.delete(o)))}}}installBoundOverlay(e){let t=[];for(let r of e.boundRegistrations)r.fields.length===0||Je(r.source)===void 0||(this.boundProfileIdx<0&&(this.boundProfileIdx=this.allocProfile(jo,0,0,0,0,0,0,!1,"bound")),t.push(this.registerBound(e,r.source,r.fields,r.poseKeys,this.boundProfileIdx)));t.length>0&&e.onDisposed(()=>{for(let r of t)r()})}trackStepped(e,t){let r=t.substep??16,s=t.fields,i=s.map(p=>As(e,p)),o=t.step,a=this.clock,c=this.presentFn(),u=t.forwardMs??(c?()=>{let p=a.lastServerTime();return p>0?Math.max(0,c()-p):0}:()=>0),d=t.elapsedMs??c??(()=>performance.now()),h=e[mo],m=t.snapshot===void 0&&Array.isArray(h)&&i.every(p=>p>=0&&p<h.length),g;if(m){let p=new e.constructor,y=p[mo];g=(x,k,I,B)=>{let N=x[mo];for(let v=0;v<N.length;v++)y[v]=N[v];let C=k,P=B-k;for(;C>0;){let v=C<r?C:r;P+=v,o(p,v/1e3,P),C-=v}for(let v=0;v<i.length;v++)I[v]=y[i[v]]}}else{let p=bf(e),y=t.snapshot??(p.length>0?_f(p):k=>({...k})),x=[...s];g=(k,I,B,N)=>{let C=y(k),P=I,v=N-I;for(;P>0;){let O=P<r?P:r;v+=O,o(C,O/1e3,v),P-=O}for(let O=0;O<x.length;O++)B[O]=C[x[O]]}}return this.trackSimulated(e,{fields:s,forwardMs:u,elapsedMs:d,smoothMs:t.smoothMs,snap:t.snap,advance:g})}trackSimulated(e,t){let r=Je(e);if(r===void 0)throw new Error("Predict.trackStepped(): instance has no refId \u2014 must run AFTER the decoder delivers the instance (e.g. inside onAdd).");let s=t.fields,i=s.length,o=s.map(g=>As(e,g)),a=0;for(let g of o)g>a&&(a=g);let c=new Int8Array(a+1).fill(-1);for(let g=0;g<i;g++)o[g]>=0&&(c[o[g]]=g);let u=new Float64Array(i);for(let g=0;g<i;g++)u[g]=e[s[g]]??0;let d=this.presentFn(),h=t.elapsedMs??d??(()=>performance.now()),m={instance:e,fieldIds:o,posOf:c,forwardMs:t.forwardMs,elapsedMs:h,advance:t.advance,smoothMs:t.smoothMs??50,snap:t.snap??0,smoothed:u,out:new Float64Array(i),valueOut:new Float64Array(i),offset:new Float64Array(i),outPrev:new Float64Array(i),frameVel:new Float64Array(i),lastBaseT:NaN,lastApplyTime:-1/0};return this.simByRef.set(r,m),()=>this.untrackSimulated(r)}untrackSimulated(e){this.simByRef.delete(e)}attach(e,t){let r=this.makeGroup("(attach)",t);return this.attachWithPlan(e,this.planFor(r,e))}makeGroup(e,t){return{label:e,config:t,basePlan:this.buildGroupPlan(t,e),planByCtor:new Map}}planFor(e,t){let r=t.constructor,s=e.planByCtor.get(r);return s===void 0&&(s=this.resolveCtorPlan(e,t),e.planByCtor.set(r,s)),s}resolveCtorPlan(e,t){let r=Ut(t),s=t.constructor?.name||"?",i=e.config;if(!Eh(i)){if(r===void 0)return e.basePlan;let c=Object.keys(i).filter(d=>i[d]!==void 0);if(c.every(d=>typeof r[d]=="number"))return e.basePlan;let u={};for(let d of c)typeof r[d]=="number"&&(u[d]=i[d]);return this.buildGroupPlan(u,`${e.label}:${s}`)}let o=i,a=o.fields;if(r!==void 0){let c=a.filter(u=>typeof r[u]=="number");c.length!==a.length&&(a=c)}return a===o.fields?e.basePlan:this.buildGroupPlan({...o,fields:a},`${e.label}:${s}`)}buildGroupPlan(e,t){let r=[];if(Eh(e)){let i=e;if(!Array.isArray(i.fields))throw new Error("Predict.attach(): `fields` must be a numeric-key array.");let o=i.mode??this.defaultMode,a=i.step??this.reckonDefaults.step,c=o==="reckon";if(c&&typeof a!="function")throw new Error("Predict.attach(): reckon mode requires a 'step' function. Either pass `step` in the attach config OR construct the Predict with `Predict.get(room, { mode: 'reckon', step: yourStepFn })` so it can be inherited.");let u=this.groupProfile({mode:o,snap:i.snap,smoothMs:i.smoothMs},t);for(let d of i.fields)r.push({field:d,profileIdx:u,angle:i.angle});return{label:t,isReckon:c,reckonFields:c?i.fields:void 0,reckonStep:c?a:void 0,reckonSmoothMs:i.smoothMs??this.reckonDefaults.smoothMs,reckonSubstep:i.substep??this.reckonDefaults.substep,reckonSnap:i.snap??this.reckonDefaults.snap,reckonSnapshot:i.snapshot,fieldProfiles:r}}let s=e;for(let i of Object.keys(s)){let o=s[i];if(o===void 0)continue;let a=typeof o=="string"?{mode:o}:o;r.push({field:i,profileIdx:this.groupProfile(a,t),angle:a.angle})}return{label:t,isReckon:!1,fieldProfiles:r}}attachToGroup(e,t,r){let s=[];t.isReckon&&s.push(this.trackStepped(e,{fields:t.reckonFields,step:t.reckonStep,smoothMs:t.reckonSmoothMs,substep:t.reckonSubstep,snap:t.reckonSnap,snapshot:t.reckonSnapshot,forwardMs:r}));for(let{field:i,profileIdx:o,angle:a}of t.fieldProfiles)s.push(this.trackWithProfile(e,i,o,!!a));return()=>{for(let i of s)i()}}attachWithPlan(e,t){let r=Je(e);if(r===void 0)throw new Error("Predict.attach(): instance has no refId \u2014 attach must run AFTER the decoder delivers the instance (e.g. inside onAdd).");return this.attachToGroup(e,t),()=>this.detachByRef(r)}detach(e){let t=Je(e);t!==void 0&&this.detachByRef(t)}detachByRef(e){let t=this.slotByRef.get(e);if(t){for(let r of[...t.keys()]){let s=t.get(r);if(s===void 0)continue;let i=this.boundBySlot.get(s);i!==void 0?(this.freeStash(i),this.boundBySlot.delete(s),this.freeSlots.push(s),t.delete(r)):this.untrackSlot(e,r)}t.size===0&&this.slotByRef.delete(e)}this.simByRef.delete(e)}attachAll(...e){let t=typeof e[0]=="string",r=t?void 0:e[0],s=t?e[0]:e[1],i=t?e[1]:e[2],o=this.makeGroup(s,i),a=new Set,c=m=>{this.attachWithPlan(m,this.planFor(o,m)),a.add(m)},u=m=>{a.delete(m),this.detach(m)},d=t?this.callbacks.onAdd(s,c):this.callbacks.onAdd(r,s,c),h=t?this.callbacks.onRemove(s,u):this.callbacks.onRemove(r,s,u);return()=>{d?.(),h?.();for(let m of a)this.detach(m);a.clear()}}tick(e=performance.now()){this.renderTime=e;let t=0,r=this.fixedStepMs;if(r!==void 0&&r>0){let o=this.lastFrameNow<0?0:e-this.lastFrameNow;this.stepAcc+=o,t=Math.floor(this.stepAcc/r),t>Wr.MAX_STEPS_PER_FRAME?(this.stepAcc=0,t=Wr.MAX_STEPS_PER_FRAME):this.stepAcc-=t*r}this.lastFrameNow=e;let s=this.driven,i=0;for(let o=0;o<s.length;o++){let a=s[o];a.dead||(a.tick?.(e),a.prune?.(),i!==o&&(s[i]=a),i++)}return i!==s.length&&(s.length=i),t}defineEvent(e){let{confirmOn:t,...r}=e,s=new Ur(r,this.clock??null);if(t!==void 0){if(t.mine!==void 0&&typeof this.sessionSource.sessionId!="string")throw new Error(`Predict.defineEvent: confirmOn.mine ("${t.mine}") requires a Predict built from a Room (it compares against room.sessionId); confirm manually instead.`);s._addTeardown(bh(this.callbacks,s,t,()=>this.sessionSource.sessionId))}return this.driven.push(s),s}spawns(e,t={}){let r=new Jn(t,this.clock??null),s=t.fields,i=t.step,o=s!==void 0&&i!==void 0?this.makeGroup(String(e),{mode:"reckon",fields:s,step:i,smoothMs:t.smoothMs??0,substep:t.substep}):void 0,a=o!==void 0?new Map:void 0,c=this.clock;return r.attach((u,d)=>{let h=this.callbacks.onAdd(e,(g,p)=>{if(u(g,p),o===void 0||a.has(g))return;let y=r.entryFor(g)?.leadMs??0,x=c?()=>{let k=c.lastServerTime(),I=k>0?Math.max(0,c.serverNow()-k):0;return Math.max(0,I+y)}:()=>Math.max(0,y);a.set(g,this.attachToGroup(g,this.planFor(o,g),x))}),m=this.callbacks.onRemove(e,(g,p)=>{a?.get(g)?.(),a?.delete(g),d(g,p)});return()=>{if(h?.(),m?.(),a!==void 0){for(let g of a.values())g();a.clear()}}}),o!==void 0&&r.bindReader((u,d)=>this.value(u,d)),this.driven.push(r),r}canonicalDelay(){return this.profileBuf[Ht*Qe+Qn]}bindInputRenderDelay(e){e instanceof Rr&&e.bindRenderDelay(()=>this.canonicalDelay())}reconciler(e,t){let r=new Kn(e,{...t,clock:t.clock??this.clock});return this.adoptFixedStep(r.stepMs),this.bindInputRenderDelay(t.input),this.installBoundOverlay(r),this.driven.push(r),r}sim(e){let t=new Xn({...e,clock:e.clock??this.clock});return this.adoptFixedStep(t.stepMs),this.bindInputRenderDelay(e.input),this.installBoundOverlay(t),this.driven.push(t),t}adoptFixedStep(e){if(this.fixedStepMs===void 0){this.fixedStepMs=e,this.stepAcc=0,this.lastFrameNow=-1;return}Math.abs(this.fixedStepMs-e)>1e-6&&console.warn(`@colyseus/sdk Predict: a reconciler's fixed step (${e}ms) differs from this Predict's (${this.fixedStepMs}ms). tick() paces one rate for the whole room; use a separate Predict per rate.`)}value(e,t){let r=Je(e),s=r===void 0?void 0:this.slotByRef.get(r)?.get(t);if(s===void 0)return e[t];let i=this.slotBuf[s*je+vt]|0;return this.profileComputers[i](s)}valueAt(e,t,r){let s=Je(e),i=s===void 0?void 0:this.slotByRef.get(s)?.get(t);if(i===void 0)return e[t];let o=i*je,a=this.slotBuf[o+vt]|0;if(this.profileComputers[a]!==this.computeReckon)return this.profileComputers[a](i);let c=this.simByRef.get(this.slotBuf[o+Ks]);if(c!==void 0){let u=this.slotBuf[o+Xs]|0,d=u<c.posOf.length?c.posOf[u]:-1;if(d>=0){let h=this.clock?.lastServerTime?.()??NaN,m=Number.isNaN(h)?0:Math.max(0,r-h);return c.advance(c.instance,m,c.valueOut,r),c.valueOut[d]}}return this.slotBuf[o+ct]}read(e,t,r){let s=r??{},i=Je(e),o=i===void 0?void 0:this.slotByRef.get(i);for(let a=0;a<t.length;a++){let c=t[a],u=o?.get(c);s[c]=u===void 0?e[c]:this.profileComputers[this.slotBuf[u*je+vt]|0](u)}return s}readAt(e,t,r,s){let i=s??{},o=Je(e),a=o===void 0?void 0:this.slotByRef.get(o),c,u=!1;for(let d=0;d<t.length;d++){let h=t[d],m=a?.get(h);if(m===void 0){i[h]=e[h];continue}let g=m*je,p=this.slotBuf[g+vt]|0;if(this.profileComputers[p]!==this.computeReckon){i[h]=this.profileComputers[p](m);continue}if(!u&&(u=!0,c=this.simByRef.get(this.slotBuf[g+Ks]),c!==void 0)){let y=this.clock?.lastServerTime?.()??NaN,x=Number.isNaN(y)?0:Math.max(0,r-y);c.advance(c.instance,x,c.valueOut,r)}if(c!==void 0){let y=this.slotBuf[g+Xs]|0,x=y<c.posOf.length?c.posOf[y]:-1;if(x>=0){i[h]=c.valueOut[x];continue}}i[h]=this.slotBuf[g+ct]}return i}computeLerpRaw(e){let t=this.slotBuf,r=e*je,s=this.profileBuf,i=(t[r+vt]|0)*Qe,o=this.renderTime,a=t[r+$r]|0;if(a===0)return t[r+ct];let c=t[r+Fr]|0,u=r+Qs,d=(c-a+Me)%Me,h=(d+a-1)%Me,m=u+h*2;if(a===1)return t[m+1];let g=s[i+Qn],p=this.clock&&this.clock.lastServerTime()>0?this.clock.serverNow()-g-this.clock.smoothedRtt()/2:o-g,y=u+d*2;if(p<=t[y])return t[y+1];if(p>=t[m])return t[m+1];let x=a-2,k=(d+x)%Me;for(;x>0&&!(t[u+k*2]<=p);)x--,k=k===0?Me-1:k-1;let I=u+k*2,B=k+1>=Me?0:k+1,N=u+B*2,C=t[I],v=t[N]-C;if(v<=0)return t[N+1];let O=(p-C)/v,V=t[I+1],Z=t[N+1];return V+(Z-V)*O}applySimulation(e,t){let r=this.renderTime;if(e.lastApplyTime!==r){let s=e.out,i=e.smoothed,o=e.offset,a=i.length,c=this.clock?.lastServerTime?.()??NaN;if(e.advance(e.instance,e.forwardMs(),s,e.elapsedMs()),e.lastApplyTime===-1/0||e.smoothMs<=0)for(let h=0;h<a;h++)o[h]=0,i[h]=s[h];else if(Number.isNaN(c)){let h=Math.max(0,Math.min(r-e.lastApplyTime,100)),m=1-Math.exp(-h/e.smoothMs);for(let g=0;g<a;g++)i[g]+=(s[g]-i[g])*m}else{let h=Math.max(0,Math.min(r-e.lastApplyTime,100));if(c!==e.lastBaseT&&!Number.isNaN(e.lastBaseT)){let g=e.snap,p=e.frameVel;for(let y=0;y<a;y++){let x=i[y]+p[y]*h-s[y];o[y]=g>0&&Math.abs(x)>g?0:x}}else if(h>0){let g=e.outPrev,p=e.frameVel;for(let y=0;y<a;y++)p[y]=(s[y]-g[y])/h}let m=Math.exp(-h/e.smoothMs);for(let g=0;g<a;g++)o[g]*=m,i[g]=s[g]+o[g]}let d=e.outPrev;for(let h=0;h<a;h++)d[h]=s[h];e.lastBaseT=c,e.lastApplyTime=r}return e.smoothed[t]}};l(Wr,"MAX_STEPS_PER_FRAME",5);ei=Wr});var qh={};Ul(qh,{DEFAULT_GRACE_TICKS:()=>Qc,Predict:()=>ei,PredictedEventChannel:()=>Ur,PredictedSpawns:()=>Jn,Reconciler:()=>Kn,SimReconciler:()=>Xn,classifyDrift:()=>Lr});var zh=Pe(()=>{"use strict";tl();$o();Bo();Vo();Zc();Fo()});var ts="genex-native";var yi="genex_native";var bi="genex_protocol",wi="genex_attempt",_i="genex_nonce",ga="genex_caps";var sr="genex_";var ya="genex_r";var ba="entryRef",wa="genex_hash",_a="genex_referrer",Ea="genex_ref";var Ei="__genexNative";var kp=/^[0-9a-f]{32}$/,Ap=/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;function Yt(n){return typeof n=="string"&&kp.test(n)}function Ra(n){return typeof n=="string"&&Ap.test(n)}var ir="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",vp=(()=>{let n=new Array(128).fill(-1);for(let e=0;e<ir.length;e++)n[ir.charCodeAt(e)]=e;return n})();function Fl(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);if(r>=55296&&r<=56319){let s=t+1<n.length?n.charCodeAt(t+1):0;s>=56320&&s<=57343?(r=65536+(r-55296<<10)+(s-56320),t++):r=65533}else r>=56320&&r<=57343&&(r=65533);r<128?e.push(r):r<2048?e.push(192|r>>6,128|r&63):r<65536?e.push(224|r>>12,128|r>>6&63,128|r&63):e.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return e}function Cp(n){let e="";for(let t=0;t<n.length;){let r=n[t],s,i;if(r<128)s=r,i=1;else if((r&224)===192)s=r&31,i=2;else if((r&240)===224)s=r&15,i=3;else if((r&248)===240)s=r&7,i=4;else return null;if(t+i>n.length)return null;for(let o=1;o<i;o++){let a=n[t+o];if((a&192)!==128)return null;s=s<<6|a&63}if(i===2&&s<128||i===3&&(s<2048||s>=55296&&s<=57343)||i===4&&(s<65536||s>1114111))return null;if(s>65535){let o=s-65536;e+=String.fromCharCode(55296+(o>>10),56320+(o&1023))}else e+=String.fromCharCode(s);t+=i}return e}function xa(n){return Fl(n).length}function Sa(n){let e=Fl(JSON.stringify(n)),t="";for(let r=0;r<e.length;r+=3){let s=e[r],i=e[r+1],o=e[r+2];if(t+=ir[s>>2],t+=ir[(s&3)<<4|(i??0)>>4],i===void 0||(t+=ir[(i&15)<<2|(o??0)>>6],o===void 0))break;t+=ir[o&63]}return t}function Ta(n){if(n.length%4===1)return;let e=[],t=0,r=0;for(let i=0;i<n.length;i++){let o=n.charCodeAt(i),a=o<128?vp[o]:-1;if(a<0)return;t=t<<6|a,r+=6,r>=8&&(r-=8,e.push(t>>r&255))}if(r>0&&(t&(1<<r)-1)!==0)return;let s=Cp(e);if(s!==null)try{return JSON.parse(s)}catch{return}}var $l=2048,Vl=32;var Op=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;function Pp(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Ri(n,e){if(Object.keys(n).length!==e.length)return!1;for(let r of e)if(!Object.prototype.hasOwnProperty.call(n,r))return!1;return!0}var xi=["channel","v","type","slug","attemptId","nonce"];function Mp(n){return n.channel===ts&&n.v===1&&Ra(n.slug)&&Yt(n.attemptId)&&Yt(n.nonce)}function ka(n){if(!(!Pp(n)||!Mp(n)))switch(n.type){case"ticket":return!Ri(n,[...xi,"ticket","expiresAt"])||typeof n.ticket!="string"||n.ticket.length===0||n.ticket.length>$l||typeof n.expiresAt!="string"||n.expiresAt.length>Vl||!Op.test(n.expiresAt)?void 0:n;case"guest":case"cancel":return Ri(n,xi)?n:void 0;case"foreground":return!Ri(n,[...xi,"active"])||typeof n.active!="boolean"?void 0:n;case"network":return!Ri(n,[...xi,"online"])||typeof n.online!="boolean"?void 0:n;default:return}}function Np(n,e){if(typeof n!="string"||n.length===0)return{ok:!1,reason:"undecodable"};if(xa(n)>4096)return{ok:!1,reason:"too-large"};let t=Ta(n);if(t===void 0)return{ok:!1,reason:"undecodable"};let r=e(t);return r===void 0?{ok:!1,reason:"invalid"}:{ok:!0,message:r}}function va(n){return Np(n,ka)}function Ca(n){let e=Sa(n);if(!(e.length>4096))return e}function Si(n,e){let t=n.charAt(0)==="?"?n.slice(1):n;if(t.length===0)return null;for(let r of t.split("&")){let s=r.indexOf("=");if(s!==-1&&r.slice(0,s)===e)return r.slice(s+1)}return null}function Ti(n){return Si(n,yi)==="1"}function Oa(n){if(!Ti(n))return null;let e=Si(n,wi),t=Si(n,_i),r=Number(Si(n,bi));return!Yt(e)||!Yt(t)||r!==1?null:{attemptId:e,nonce:t,protocol:r}}function zl(n){return n.indexOf("%")===-1?n:n.replace(/%([0-9A-Fa-f]{2})/g,(e,t)=>{let r=parseInt(t,16);return r<128?String.fromCharCode(r):e})}function Wl(n){let e=n.indexOf("="),t=e===-1?n:n.slice(0,e);return zl(t.indexOf("+")===-1?t:t.split("+").join(" "))}function ki(n){return Yl(n,[ya])}var Bp=[yi,bi,wi,_i,ga];function Pa(n){return Yl(n,Bp)}function Yl(n,e){let t=n.charAt(0)==="?"?n.slice(1):n;if(t.length===0)return"";let r=t.split("&"),s=r.filter(o=>!e.includes(Wl(o)));if(s.length===r.length)return`?${t}`;let i=s.join("&");return i.length===0?"":`?${i}`}var Up=/^[!$-&(-;=?-~]+$/;function Ai(n,e){if(typeof n!="string")return"";let t=n.charAt(0)==="?"?n.slice(1):n,r=t.indexOf("#");if(r!==-1&&(t=t.slice(0,r)),t.length===0||!Up.test(t))return"";let i=t.split("&").filter(o=>{if(o.length===0)return!1;let a=Wl(o);return!a.startsWith(sr)&&!e.includes(a)}).join("&");return i.length>1024?"":i}var Fp=/^#[!#-;=?-_a-~]+$/;function vi(n){return typeof n!="string"||n.length<2||n.length>4096||!Fp.test(n)||zl(n).includes(sr)?"":n}var $p=/^[a-z0-9._-]+$/,Vp=/^\[[0-9a-f:.]+\]$/;function jp(n){return $p.test(n)&&/[a-z0-9]/.test(n)||Vp.test(n)}function Ia(n){let e=n.slice(0,8).toLowerCase(),t=e==="https://"?"https":e.slice(0,7)==="http://"?"http":null;if(t===null)return null;let r=t.length+3,s=n.length;for(let u=r;u<n.length;u++){let d=n.charAt(u);if(d==="/"||d==="?"||d==="#"||d==="\\"){s=u;break}}if(s-r>255)return null;let i=n.slice(r,s).toLowerCase();if(i.length===0||i.indexOf("@")!==-1)return null;let o=i,a="",c=i.lastIndexOf(":");if(c!==-1&&i.charAt(i.length-1)!=="]"&&(o=i.slice(0,c),a=i.slice(c+1)),!jp(o))return null;if(a.length>0){if(!/^[0-9]{1,5}$/.test(a))return null;let u=Number(a);if(u>65535)return null;a=u===(t==="https"?443:80)?"":`:${u}`}return`${t}://${o}${a}`}function ar(n,e){if(typeof n!="string"||n.length===0)return null;let t=Ia(n);return t===null||t.length>255||typeof e=="string"&&Ia(e)===t?null:t}var Jl=["open","save","fullscreen"];var Kl=50*1024*1024,Hp=16;function Xl(n){return typeof n=="string"&&Jl.includes(n)}function Ma(n){if(!Array.isArray(n))return[];let e=[],t=Math.min(n.length,Hp);for(let r=0;r<t;r++){let s=n[r];Xl(s)&&!e.includes(s)&&e.push(s)}return e}var tm=null;function Zl(n){tm=n}var rm=null;function eu(n){rm=n}var sm=null;function tu(n){sm=n}var is=1,Ua="genex:embed:retry",mu="genex:guest:popover-dismissed",gu="genex:embed:local-auth",yu="genex:embed:entry-referrer",im="none",nu="genex:player",om="0.35.0",ue=null,fe="pending",rt=null,hn=!1,dn=null,cr=!1,fn,lr,bu=0,ze,wu,_u,am,Eu=!1,pn=null,Ru=[],dr=!1,Dn=!1,rs=!1,nt=0,fr=1e4,cm=2e3,lm=10*6e4,um=6e4,ru=500,dm=3e4,fm=3e4,we,gt,ur,su=!1,iu,Ci=null,ou=new Set;var au=!1,hm=new Map,xu=[],os=[],ss=null,Ii=null,Mn,Da,Na=!1,Oi=new Map;function Se(){return globalThis.window}function Fa(){return globalThis.document}function as(n,e,t){let r;if(t!==void 0)try{let s=globalThis.AbortSignal;s&&typeof s.timeout=="function"&&(r=s.timeout(t))}catch{}return globalThis.fetch(n,r?{...e,signal:r}:e)}function pm(){try{return Se()?.sessionStorage?.getItem(Ua)==="1"}catch{return!1}}function mm(){try{Se()?.sessionStorage?.setItem(Ua,"1")}catch{}}function $a(){try{Se()?.sessionStorage?.removeItem(Ua)}catch{}}function gm(){try{return Se()?.sessionStorage?.getItem(gu)==="1"}catch{return!1}}function ym(){try{Se()?.sessionStorage?.setItem(gu,"1")}catch{}}function bm(){try{let n=Se()?.sessionStorage?.getItem(yu);return n==null?void 0:ar(n)}catch{return}}function wm(n){try{Se()?.sessionStorage?.setItem(yu,n??im)}catch{}}function _m(){try{return Se()?.sessionStorage?.getItem(mu)==="1"}catch{return!1}}function Em(){try{Se()?.sessionStorage?.setItem(mu,"1")}catch{}}function Rm(){try{let n=Se()?.localStorage;if(!n)return"no-storage";let e=n.getItem(nu);return e||(e=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,n.setItem(nu,e)),e}catch{return"no-storage"}}function Mi(n){let e=Se();if(!e||dr)return;if(dr=!0,ur!==void 0&&(clearTimeout(ur),ur=void 0),ue={slug:n.slug,apiUrl:n.apiUrl.replace(/\/$/,""),dashboardOrigins:[...n.dashboardOrigins]},fe="pending",Cu(e),eu({apiUrl:ue.apiUrl,dashboardOrigins:ue.dashboardOrigins,getToken:()=>ze,getParentOrigin:()=>pn,isEmbedded:We,isNative:ut,isLocalTest:()=>hn}),tu({apiUrl:ue.apiUrl,dashboardOrigins:ue.dashboardOrigins,getToken:()=>ze,getParentOrigin:()=>pn,isEmbedded:We,isNative:ut,isLocalTest:()=>hn}),za(e)){Ym(e);return}Ni("connecting");let t=Iu(e);if(t){Bm(e,t);return}We()?Nm(e):$m(e)}function We(){let n=Se();if(!n)return!1;try{return n.self!==n.top}catch{return!0}}function xm(){let n=Se();return n?We()?"page":ut()||ja(n)?"app":dr?hn?"local":"standalone":za(n,!1)?"local":"standalone":"standalone"}function Su(){return Eu?{embedToken:Gm}:ze?{embedToken:ze}:void 0}function Tu(){return wu??[]}function Va(){return(fe==="authenticated"||fe==="guest")&&rt?Promise.resolve({user:rt,guest:fe==="guest"}):fe==="blocked"?Promise.reject(new Error("genex embed auth: blocked")):(Sm("waitForPlayer"),new Promise((n,e)=>{os.push({resolve:n,reject:e})}))}function Sm(n){if(!dr){if(!su){su=!0;try{console.error(`[genex] ${n}() called before initEmbed() \u2014 identity can never resolve and the game will sit black. Call initEmbed({ slug, apiUrl, dashboardOrigins }) first (genex-threejs-embed-auth), and draw a frame before you await identity.`)}catch{}}ur===void 0&&(ur=setTimeout(()=>{ur=void 0,dr||Jt("no-identity")},fr))}}var Tm=32*1024;async function ku(){if(!ue)throw new Error("genex embed: call initEmbed() first");if(fe==="pending"&&await Va(),fe==="blocked")throw new Error("genex embed auth: blocked")}function Au(n,e={}){let t={Authorization:`Bearer ${ze}`};return e.body!==void 0&&(t["Content-Type"]="application/json"),e.ifVersion!==void 0&&(t["If-Match"]=String(e.ifVersion)),as(`${ue.apiUrl}/api/projects/${encodeURIComponent(ue.slug)}${n}`,{method:e.method??"GET",headers:t,body:e.body,keepalive:e.body!==void 0&&e.body.length<=Tm?!0:void 0})}async function km(n){return n.status!==403?!1:(await n.json().catch(()=>null))?.error==="staging_no_save"}async function Am(n){return n.status===409?{saved:!1,conflict:!0,version:(await n.json().catch(()=>({}))).version}:n.ok?{saved:!0,version:(await n.json()).version}:await km(n)?{saved:!1,staging:!0}:(st("error",{error:new Error(`genex state save failed (${n.status})`)}),{saved:!1})}async function vm(n,e){return await ku(),fe==="guest"?(Da=n,Na=!0,{saved:!1,guest:!0,queued:!0}):Am(await Au("/state/me",{method:"PUT",body:JSON.stringify(n),ifVersion:e?.ifVersion}))}async function Cm(n,e){let t=e?.board??"main",r=e?.mode??"max";if(await ku(),fe==="guest"){let o=Oi.get(t);return(!o||(r==="min"?n<o.score:n>o.score))&&Oi.set(t,{score:n,mode:r}),{submitted:!1,guest:!0,queued:!0}}let s=await Au("/scores",{method:"POST",body:JSON.stringify({score:n,board:t,mode:r})});if(!s.ok)return st("error",{error:new Error(`genex score submit failed (${s.status})`)}),{submitted:!1};let i=await s.json();return{submitted:!0,best:i.best,improved:i.improved}}async function Im(){try{if(Na){let e=Da;Da=void 0,Na=!1,await vm(e)}let n=[...Oi.entries()];Oi.clear();for(let[e,{score:t,mode:r}]of n)await Cm(t,{board:e,mode:r})}catch(n){st("error",{error:n})}}function st(n,e){let t=hm.get(n);if(t)for(let r of[...t])try{r(e)}catch{}}var Om=["embed"];function vu(n,e){let t={ticket:null,guest:!1,entryHash:"",entryReferrer:null};if(!n||n.length<2)return t;try{let r=new URLSearchParams(n.slice(1));return{ticket:r.get("genex_ticket"),guest:r.get("genex_guest")==="1",entryHash:vi(r.get(wa)),entryReferrer:ar(r.get(_a),e)}}catch{return t}}function Pm(n,e){try{return new URLSearchParams(n).get(e)}catch{return null}}function Cu(n){if(Ci)return Ci;let e="",t="",r=null;try{e=n.location.search??"",t=Pi??n.location.hash??"",r=n.location.origin??null}catch{}let s=We(),i=vu(t,r),o=!s&&(!!i.ticket||i.guest),a=Ai(e,Om);return Ci={search:a?`?${a}`:"",hash:o?i.entryHash:t.includes(sr)?"":t,referrer:Mm(e,s,o,i.entryReferrer,r)},Ci}function Mm(n,e,t,r,s){let i=bm();if(i!==void 0)return i;let o;return e?o=ar(Pm(n,Ea),s):t?o=r:o=ar(Fa()?.referrer,s),wm(o),o}function Dm(){if(!(au||ou.size===0)){au=!0;for(let n of[...ou])try{n()}catch{}}}function Nm(n){iu=e=>{Lm(e)},n.addEventListener("message",iu),n.parent.postMessage({type:"genex:embed:ready",v:is},"*"),we=setTimeout(()=>{hr()},fr)}function cu(){return(fe==="pending"||fe==="guest")&&!Dn}async function Lm(n){if(!ue)return;let e=n.data;if(!e||e.v!==is)return;let t=e.type==="genex:embed:ticket",r=e.type==="genex:embed:guest";if(!(!t&&!r)&&!(t&&(!cu()||typeof e.ticket!="string"||!e.ticket))&&!(r&&(fe!=="pending"||Dn||rs))){if(!ue.dashboardOrigins.includes(n.origin)){let s=await La();if(t&&!cu()||r&&(fe!=="pending"||Dn||rs)||!s.includes(n.origin))return}if(we!==void 0&&clearTimeout(we),pn=n.origin,Ru=Ma(e.caps),r){await hr();return}await qa(e.ticket)}}function ja(n){let e=n.ReactNativeWebView;return!e||typeof e!="object"?null:typeof e.postMessage=="function"?e:null}function Iu(n){if(We())return null;let e;try{e=n.location.search??""}catch{return null}return!Ti(e)||!ja(n)?null:Oa(e)}function ut(){return dn!==null}function Nn(n){let e=Se();if(!e||!ue||!dn)return;let t=ja(e);if(!t)return;let r=Ca({channel:ts,v:1,slug:ue.slug,attemptId:dn.attemptId,nonce:dn.nonce,...n});if(r)try{t.postMessage(r)}catch{}}function Ou(n){ut()&&Nn({type:"error",code:n})}function Bm(n,e){dn=e,bu=Date.now(),n[Ei]=r=>{Um(r)},Nn({type:"ready",sdkVersion:om,capabilities:["native-ticket","native-guest","heartbeat"]}),we=setTimeout(()=>{hr()},fr)}async function Um(n){if(!ue||!dn)return;let e=va(n);if(!e.ok)return;let t=e.message;if(!(t.slug!==ue.slug||t.attemptId!==dn.attemptId||t.nonce!==dn.nonce))switch(t.type){case"ticket":we!==void 0&&clearTimeout(we),await qa(t.ticket);return;case"guest":we!==void 0&&clearTimeout(we),await hr();return;case"cancel":Pu(),Dm();return;case"foreground":case"network":return}}function Pu(){we!==void 0&&clearTimeout(we),we=void 0,gt!==void 0&&clearTimeout(gt),gt=void 0,fn!==void 0&&clearTimeout(fn),fn=void 0,lr!==void 0&&clearInterval(lr),lr=void 0}function Mu(){!ut()||lr!==void 0||(lr=setInterval(()=>{Nn({type:"heartbeat",uptimeMs:Math.max(0,Date.now()-bu)})},fm),lr.unref?.())}function Fm(){!ut()||cr||(cr=!0,Nn({type:"reauth-required"}),fn=setTimeout(()=>{fn=void 0,cr&&(cr=!1,st("error",{error:new Error("embed session expired")}),Jt("session-expired"))},dm))}function Ha(){cr=!1,fn!==void 0&&clearTimeout(fn),fn=void 0}function Ga(n,e){let t=Se();if(!(!t||!We()))try{t.parent.postMessage(n,e)}catch{}}async function $m(n){let e=Du(n);if(e.ticket){lu(),await qa(e.ticket);return}if(e.guest){lu(),await hr();return}Ni("redirecting"),await Di(n,{guestOk:!0})}function lu(){we!==void 0&&clearTimeout(we),we=setTimeout(()=>{we=void 0,fe==="pending"&&Jt("no-identity")},fr+cm)}var Pi=null;function Vm(n){return n.location.pathname+ki(n.location.search)}function Du(n){let e=Pi??n.location.hash;Pi=null;let{ticket:t,guest:r,entryHash:s}=vu(e);if(t||r)try{n.history.replaceState(n.history.state??null,"",Vm(n)+s)}catch{}return{ticket:t,guest:r}}async function Di(n,e){if(!ue||hn||ut())return;let t=e?.guestOk?ue.dashboardOrigins[0]??(await La())[0]:(await La())[0]??ue.dashboardOrigins[0];if(!t){Jt();return}let r=n.location.origin+n.location.pathname,s=Pa(ki(n.location.search));s.length-1<=1024&&r.length+s.length<=2048&&s.indexOf("#")===-1&&(r+=s);let i=e?.guestOk?"&guest=ok":"",o=`${t}/play/authorize?returnTo=${encodeURIComponent(r)}&slug=${encodeURIComponent(ue.slug)}${i}`,a=Cu(n).referrer;a&&(o+=`&${ba}=${encodeURIComponent(a)}`),o+=vi(n.location.hash),n.location.replace(o)}async function La(){if(!ue)return[];try{let n=await as(`${ue.apiUrl}/api/embed/dashboard-origins`);if(!n.ok)return ue.dashboardOrigins;let e=await n.json();if(Array.isArray(e.origins)&&e.origins.every(t=>typeof t=="string"))return e.origins}catch{}return ue.dashboardOrigins}async function qa(n){if(!ue||hn||Dn||fe!=="pending"&&fe!=="guest"&&!(cr&&fe==="authenticated"))return;let t=fe==="guest",r=++nt;Dn=!0;try{let s=await as(`${ue.apiUrl}/api/embed/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ticket:n})},fr);if(r!==nt)return;if(!s.ok){st("error",{error:new Error(`ticket redemption failed (${s.status})`)}),t||await uu();return}let i=await s.json();if(r!==nt)return;ze=i.embedToken,rt=i.user,Bu(i.colyseus),fe="authenticated",we!==void 0&&clearTimeout(we),we=void 0,$a(),Li(),Ya(),Wa(),We()&&pn&&Ga({type:"genex:embed:authenticated",v:is},pn),ut()&&(Ha(),Nn({type:"authenticated",guest:!1}),Mu()),t&&await Im();let o={user:rt};for(let a of xu.splice(0))a.resolve(o);for(let a of os.splice(0))a.resolve({user:rt,guest:!1});st("authenticated",o)}catch(s){if(r!==nt)return;st("error",{error:s}),t||await uu()}finally{Dn=!1}}async function hr(){if(!ue||hn||rs||Dn||fe!=="pending"&&fe!=="guest")return;let n=++nt;rs=!0;try{let e=await as(`${ue.apiUrl}/api/embed/guest-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:ue.slug,playerId:Rm()})},fr);if(n!==nt)return;if(!e.ok){st("error",{error:new Error(`guest session failed (${e.status})`)}),Ou("guest-failed"),Jt(e.status===404?"not-available":"no-identity");return}let t=await e.json();if(n!==nt)return;ze=t.embedToken,rt=t.user,Bu(t.colyseus),jm()}catch(e){if(n!==nt)return;st("error",{error:e}),Jt()}finally{rs=!1}}function jm(){let n=fe!=="guest";if(fe="guest",we!==void 0&&clearTimeout(we),Li(),Wa(),We()?Ga({type:"genex:embed:authenticated",v:is,guest:!0},pn??"*"):ut()?(Nn({type:"authenticated",guest:!0}),Mu()):n&&!_m()&&tg(),rt){let e={user:rt};for(let t of os.splice(0))t.resolve({user:rt,guest:!0});st("guest",e)}}function Nu(n){try{let e=new URL(n.location.origin);return e.protocol==="http:"&&Lu.has(e.hostname)}catch{return!1}}var Lu=new Set(["localhost","127.0.0.1","[::1]"]),Hm="genex_authority_url",Gm="local:test",qm=64;function zm(n){if(!n||n.length>qm)return null;let e;try{e=new URL(n)}catch{return null}let t=!e.username&&!e.password&&e.pathname==="/"&&!e.search&&!e.hash;return e.protocol!=="ws:"||!Lu.has(e.hostname)||!t?null:`ws://${e.host}`}function Bu(n){wu=n?.urls,_u=n?.authorityUrls,am=n?.authorityRegions}function za(n,e=!0){if(We()||Iu(n)||!Nu(n))return!1;let t=null;try{t=new URLSearchParams(n.location.search)}catch{}return t?.get("genex_local_test")==="1"?!0:t?.get("genex_auth")==="1"?(e&&ym(),!1):gm()?!1:!Wm(n)}function Wm(n){let e=Pi??n.location.hash;return!!e&&e.includes("genex_")}function Ym(n){hn=!0,Du(n),Jm(n);let e={id:"local:test",name:"Local Tester"};rt=e,fe="guest",Li();try{console.info("[genex] local test mode \u2014 local visuals and controls only. Auth, saves, leaderboards, and multiplayer are NOT validated here; no Genex credential exists.")}catch{}for(let t of os.splice(0))t.resolve({user:e,guest:!0});st("guest",{user:e})}function Jm(n){if(!Nu(n))return;let e=null;try{e=new URLSearchParams(n.location.search).get(Hm)}catch{return}let t=zm(e);t&&(_u=[t],Eu=!0)}async function uu(){let n=Se();if(we!==void 0&&clearTimeout(we),we=void 0,ut()){Ha(),Ou("ticket-rejected"),Jt();return}if(n&&!We()&&!pm()){mm(),Ni("redirecting"),await Di(n,{guestOk:!0});return}Jt()}function Wa(){gt!==void 0&&clearTimeout(gt),gt=setTimeout(()=>{Uu()},lm)}async function Uu(){if(!ue||fe!=="authenticated"&&fe!=="guest"||!ze)return;let n=nt,e=ze,t;try{let r=await as(`${ue.apiUrl}/api/embed/session/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`},keepalive:!0});if(t=r.status,n!==nt||ze!==e)return;if(r.ok){let s=await r.json();if(n!==nt||ze!==e)return;ze=s.embedToken,Wa();return}}catch{t=void 0}if(!(n!==nt||ze!==e)){if(t===401){if(fe==="guest"){hr();return}if(ut()){Fm();return}st("error",{error:new Error("embed session expired")}),Jt("session-expired");return}gt!==void 0&&clearTimeout(gt),gt=setTimeout(()=>{Uu()},um)}}function Jt(n="no-identity"){if(fe==="blocked")return;nt++,fe="blocked",rt=null,ze=void 0,we!==void 0&&clearTimeout(we),gt!==void 0&&clearTimeout(gt),Ya(),ut()?(Pu(),Ha(),Li(),Nn({type:"blocked",reason:n})):Ni(We()?"blocked-embedded":"blocked-standalone"),We()&&Ga({type:"genex:embed:blocked",v:is},pn??"*");let e=new Error("genex embed auth: blocked");for(let t of xu.splice(0))t.reject(e);for(let t of os.splice(0))t.reject(e);st("blocked")}var Km={connecting:{title:"GENEX",wordmark:!0},redirecting:{title:"GENEX",wordmark:!0},"blocked-standalone":{title:"Sign in to play",button:"Sign in",instant:!0},"blocked-embedded":{title:"Sign in on the Genex dashboard to continue",instant:!0}},Xm="https://cdn.genex.technology/fonts/GeistMono-variable.woff2",Fu="'Geist Mono',ui-monospace,SFMono-Regular,Menlo,monospace",du=!1,fu="!<>-_/[]{}=+*^?#$%&@",$u=50,hu=10,pu=[{name:"churn",ticks:5},{name:"settle",ticks:10},{name:"hold",ticks:12},{name:"dissolve",ticks:8}];function Ba(n){let e="";for(let t=0;t<n;t++)e+=fu[Math.floor(Math.random()*fu.length)];return e}function Vu(){try{let n=Se();return!n||typeof n.matchMedia!="function"?!0:n.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!0}}function Qm(n,e){if(Vu())return n.textContent=e,()=>{};let t=0;n.textContent=Ba(e.length);let r=setInterval(()=>{if(t++,t>=hu){n.textContent=e,clearInterval(r);return}let s=Math.floor(t/hu*e.length);n.textContent=e.slice(0,s)+Ba(e.length-s)},$u);return()=>clearInterval(r)}function Zm(n,e){if(Vu())return n.textContent=e,()=>{};let t=0,r=0,s=()=>{let o=pu[t],a;o.name==="churn"?a=0:o.name==="settle"?a=Math.floor(r/o.ticks*e.length):o.name==="hold"?a=e.length:a=e.length-Math.floor(r/o.ticks*e.length),n.textContent=e.slice(0,a)+Ba(e.length-a),r++,r>=o.ticks&&(r=0,t=(t+1)%pu.length)};s();let i=setInterval(s,$u);return()=>clearInterval(i)}function ju(n){if(!du){du=!0;try{let e=Se()?.FontFace,t=n.fonts;if(!e||!t?.add)return;new e("Geist Mono",`url(${Xm}) format('woff2')`,{weight:"100 900",display:"swap"}).load().then(s=>t.add(s)).catch(()=>{})}catch{}}}function Ni(n){let e=Fa();if(e?.createElement)try{ss||(ss=eg(e)),ss.setContent(n)}catch{}}function Li(n=!1){try{let e=ss;if(ss=null,!e)return;e.stopText();let t=e.root;if(n||!t.style){t.remove?.();return}t.style.pointerEvents="none",t.style.transition="opacity 180ms ease",t.style.opacity="0",setTimeout(()=>{try{t.remove?.()}catch{}},220)}catch{}}function eg(n){ju(n);let e=n.createElement("div");e.setAttribute("data-genex-embed-overlay",""),e.style.cssText=`position:fixed;inset:0;z-index:2147483647;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:14px;background:#000;color:#fff;font-family:${Fu};text-align:center;pointer-events:auto;user-select:none`;let t=n.createElement("div");t.style.cssText="font-size:13px;font-weight:400;line-height:1.3;padding:0 24px;opacity:0;min-height:1.3em;font-variant-ligatures:none",e.appendChild(t);let r=n.createElement("button");r.style.cssText="font-family:inherit;font-size:13px;font-weight:500;line-height:1.3;padding:8px 22px;border-radius:9px;border:none;cursor:pointer;background:#4b60bf;color:#fff;display:none",r.addEventListener("mouseenter",()=>{r.style.background="#3f51a8"}),r.addEventListener("mouseleave",()=>{r.style.background="#4b60bf"}),r.addEventListener("click",()=>{let c=Se();c&&(r.disabled=!0,$a(),Di(c))}),e.appendChild(r);let s=()=>{n.body&&!e.isConnected&&n.body.appendChild(e)};n.body?s():n.addEventListener?.("DOMContentLoaded",s);let i,o,a=()=>{i!==void 0&&(clearTimeout(i),i=void 0),o&&(o(),o=void 0)};return{root:e,stopText:a,setContent(c){let u=Km[c];a(),t.textContent=u.title,t.style.letterSpacing=u.wordmark?"0.22em":"",t.style.marginRight=u.wordmark?"-0.22em":"";let d=()=>{t.style.opacity="1",o=u.wordmark?Zm(t,u.title):Qm(t,u.title)};u.instant||ru<=0?d():(t.style.opacity="0",i=setTimeout(()=>{i=void 0,d()},ru)),r.style.display=u.button?"inline-block":"none",u.button&&(r.textContent=u.button),s()}}}function tg(){let n=Fa();if(!(!n?.createElement||Ii))try{Ii=ng(n)}catch{}}function Ya(){Mn!==void 0&&(clearTimeout(Mn),Mn=void 0);try{Ii?.root?.remove?.()}catch{}Ii=null}function ng(n){ju(n);let e=!1;try{let c=Se(),u=c?.navigator;if(c&&u){let d=c.matchMedia?.("(pointer: coarse)").matches??!1,h=(u.maxTouchPoints??0)>1,m=u.userAgentData?u.userAgentData.mobile:/Mobi|Android/i.test(u.userAgent??"");e=h&&d||m}}catch{}let t=n.createElement("div");t.setAttribute("data-genex-guest-popover",""),t.style.cssText="position:fixed;top:calc(12px + env(safe-area-inset-top));right:calc(12px + env(safe-area-inset-right));z-index:2147483646;display:flex;justify-content:flex-end;pointer-events:none";let r=n.createElement("div");r.style.cssText=`display:flex;align-items:center;border-radius:12px;background:rgba(0,0,0,0.85);color:#fff;font-family:${Fu};box-shadow:0 4px 24px rgba(0,0,0,0.4);pointer-events:auto;user-select:none;`+(e?"gap:8px;padding:8px 8px 8px 12px;font-size:12px;max-width:calc(100vw - 88px)":"gap:12px;padding:10px 12px 10px 16px;font-size:13px"),t.appendChild(r);let s=n.createElement("span");s.textContent=!e&&rt?.name?`Playing as ${rt.name} \u2014 sign in to save progress`:"Sign in to save progress",e&&(s.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap"),r.appendChild(s);let i=n.createElement("button");i.textContent="Sign in",i.style.cssText="font-family:inherit;font-weight:500;border-radius:9px;border:none;cursor:pointer;background:#4b60bf;color:#fff;"+(e?"font-size:12px;padding:5px 12px":"font-size:13px;padding:6px 16px"),i.addEventListener("mouseenter",()=>{i.style.background="#3f51a8"}),i.addEventListener("mouseleave",()=>{i.style.background="#4b60bf"}),i.addEventListener("click",()=>{let c=Se();c&&(i.disabled=!0,$a(),Di(c))}),r.appendChild(i);let o=n.createElement("button");if(o.textContent="\xD7",o.setAttribute("aria-label","Dismiss"),o.style.cssText="font-size:16px;line-height:1;padding:6px 8px;border:none;cursor:pointer;background:transparent;color:rgba(255,255,255,0.6)",o.addEventListener("click",()=>{Em(),Ya()}),r.appendChild(o),e){let c=n.createElement("button");c.setAttribute("aria-label","Sign in to save progress"),c.style.cssText="display:none;width:44px;height:44px;border-radius:50%;border:none;cursor:pointer;background:rgba(0,0,0,0.55);color:#fff;align-items:center;justify-content:center;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);pointer-events:auto",c.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" y1="12" x2="3" y2="12"/></svg>',t.appendChild(c);let u=d=>{r.style.display=d?"none":"flex",c.style.display=d?"flex":"none"};Mn=setTimeout(()=>u(!0),5e3),r.addEventListener("pointerdown",()=>{Mn!==void 0&&clearTimeout(Mn),Mn=void 0}),c.addEventListener("click",()=>u(!1))}let a=()=>{n.body&&!t.isConnected&&n.body.appendChild(t)};return n.body?a():n.addEventListener?.("DOMContentLoaded",a),{root:t}}Zl({getShell:xm,isLocalTest:()=>{let n=Se();return!n||We()?!1:dr?hn:za(n,!1)},getConfig:()=>ue,getParentOrigin:()=>pn,getShellCaps:()=>Ru});var ml={};Ul(ml,{chatSend:()=>Ob,claim:()=>Pb,claimAsHost:()=>Mb,connect:()=>_b,destroy:()=>Nb,dispose:()=>Eb,drainEventsJson:()=>qb,leave:()=>cp,listen:()=>vb,objectsJson:()=>Hb,open:()=>wb,playersJson:()=>jb,release:()=>Db,reportEliminated:()=>Lb,reportFinish:()=>Ub,reportScore:()=>Bb,send:()=>Ab,sendInput:()=>Cb,serverNow:()=>Fb,sessionJson:()=>Vb,setIdentity:()=>mb,setMe:()=>Rb,setObject:()=>Tb,setRoomOpen:()=>Ib,setShared:()=>Sb,sharedJson:()=>Gb,snapMe:()=>xb,snapObject:()=>kb,timeUntil:()=>$b,version:()=>pb});var Ja={ready(n){let e=globalThis.__GENEX__;return n&&e&&typeof e.apiUrl=="string"&&Array.isArray(e.dashboardOrigins)&&Mi({slug:n,apiUrl:e.apiUrl,dashboardOrigins:e.dashboardOrigins.filter(t=>typeof t=="string")}),Va()},auth:()=>Su(),urls:()=>Tu()},rg=4096;function ae(n,e){n.q.length>=rg&&(n.overflowed?n.q.splice(1,1):(n.overflowed=!0,n.q.splice(0,2,{type:"warning",message:"genex bridge: event queue full; drain it every frame (oldest events dropped)"}))),n.q.push(e)}var Ka=n=>({type:"warning",message:`genex bridge: ${n}`});function sg(n){try{return JSON.stringify(n)}catch(e){let t=typeof n.kind=="string"?n.kind:n.type;return JSON.stringify(Ka(`event ${JSON.stringify(t)} dropped: JSON cannot carry it (${pr(e)})`))}}function Hu(n){return n.overflowed=!1,`[${n.q.splice(0).map(sg).join(",")}]`}var yt=n=>!!n&&typeof n=="object"&&!Array.isArray(n),Bi=n=>{let e=yt(n)||n instanceof Error?n.code:void 0;return typeof e=="number"&&Number.isFinite(e)?e:0},pr=n=>n instanceof Error?n.message:typeof n=="string"?n:"join failed";function cs(n,e){if(typeof n!="string")throw new TypeError(`genex bridge: ${e} must be a JSON string`);return JSON.parse(n)}function ls(n,e){let t=cs(n,e);if(!yt(t))throw new TypeError(`genex bridge: ${e} must be a JSON object`);return t}ArrayBuffer.isView||(ArrayBuffer.isView=n=>n!==null&&typeof n=="object"&&n.buffer instanceof ArrayBuffer);typeof globalThis>"u"&&typeof window<"u"&&(window.globalThis=window);typeof FormData>"u"&&(globalThis.FormData=class{});Kt();var Ot=class extends Error{constructor(t,r,s){super(r);l(this,"code");l(this,"headers");l(this,"status");l(this,"response");l(this,"data");this.name="ServerError",this.code=t,s&&(this.headers=s.headers,this.status=s.status,this.response=s.response,this.data=s.data)}};var us=class n extends Error{constructor(t,r){super(t);l(this,"code");this.code=r,this.name="MatchMakeError",Object.setPrototypeOf(this,n.prototype)}};Kt();qe();qe();qe();qe();qe();qe();qe();qe();var yf=256,Rc=5,Gn=class Gn{constructor(e,t={}){l(this,"instance");l(this,"mode");l(this,"historySize");l(this,"_desc");l(this,"_numFields");l(this,"_slots");l(this,"_slotLens");l(this,"_slotHead",0);l(this,"_slotCount",0);l(this,"_outBuffer");l(this,"_seq",0);l(this,"_encoder");this.instance=e,this.mode=t.mode??"reliable",this.historySize=this.mode==="unreliable"?Math.max(1,t.historySize??3):1,this._desc=pc(e);let r=this._desc.metadata?.[Ue];if(r===void 0)throw new Error(`InputEncoder: '${e.constructor.name}' has no fields`);this._numFields=r;for(let s=0;s<=r;s++)if(this._desc.names[s]!==void 0&&this._desc.encoders[s]===void 0)throw new Error(`InputEncoder: non-primitive field '${this._desc.names[s]}' on '${e.constructor.name}' is not supported. Use Encoder for state containing refs/collections.`);if(this.mode==="unreliable"){this._slots=new Array(this.historySize),this._slotLens=new Array(this.historySize).fill(0);for(let s=0;s<this.historySize;s++)this._slots[s]=new Uint8Array(yf);this._outBuffer=new Uint8Array((yf+Rc)*this.historySize)}this._encoder=new ws(e)}get seq(){return this._seq}encode(){let e=this._produceDelta();return this.mode==="reliable"?e:this._pushAndEmitRing(e)}reset(){this._slotHead=0,this._slotCount=0,this._encoder.discardChanges();let e=this.instance[_],t=this.instance[Fe];for(let r=0;r<=this._numFields;r++)t[r]===void 0||t[r]===null||e.markDirty(r)}copyInto(e){let t=this.instance[Fe],r=e[Fe];for(let s=0;s<=this._numFields;s++)r[s]=t[s]}_produceDelta(){let e=this._encoder.encode();return this._encoder.discardChanges(),e}_pushAndEmitRing(e){this._seq++;let t=this._slots[this._slotHead];return e.length>t.byteLength&&(t=this._slots[this._slotHead]=Gn._grow(t,e.length,"unreliable ring slot")),t.set(e),this._slotLens[this._slotHead]=e.length,this._slotHead=(this._slotHead+1)%this.historySize,this._slotCount<this.historySize&&this._slotCount++,this._emitRing()}_emitRing(){let e=this._seq-this._slotCount+1,t=Rc;for(let o=0;o<this._slotCount;o++)t+=this._slotLens[o]+Rc;let r=this._outBuffer;t>r.byteLength&&(r=this._outBuffer=Gn._grow(r,t,"unreliable output packet"));let s={offset:0};Q.number(r,e,s);let i=(this._slotHead-this._slotCount+this.historySize)%this.historySize;for(let o=0;o<this._slotCount;o++){let a=(i+o)%this.historySize,c=this._slotLens[a];Q.number(r,c,s),r.set(this._slots[a].subarray(0,c),s.offset),s.offset+=c}return r.subarray(0,s.offset)}static _grow(e,t,r){let s=Math.max(t,e.byteLength*2);return Gn._warned||(Gn._warned=!0,console.warn(`@colyseus/schema/input: InputEncoder buffer overflow in ${r}. Growing to ${s} bytes.`)),new Uint8Array(s)}};l(Gn,"_warned",!1);var fo=Gn;Kt();Sc();yo();var qn,At,Sr,Is,Os,Ps,Ms,Ds,Ns,Tr,Ls,bo,Ef,kr=class{constructor(e){he(this,bo);he(this,qn);he(this,At);he(this,Sr);he(this,Is);he(this,Os,!1);he(this,Ps);he(this,Ms,!1);he(this,Ds,!1);he(this,Ns);he(this,Tr);he(this,Ls);pe(this,qn,e)}get patchRate(){return q(this,Tr)}applyReflection(e,t,r){let s=kt.decode(e.subarray(0,r),t);kt.makeEncodable(s.state.constructor),pe(this,Ps,s.state.constructor),q(this,qn).clock===xr&&(q(this,qn).clock=new go)}applyOptions(e,t){let r=e[t.offset++];pe(this,Ms,(r&Ln.RENDER_TIME)!==0),pe(this,Ds,(r&Ln.RECKON_TIME)!==0),r&Ln.FIXED_TIMESTEP&&pe(this,Ns,te.number(e,t)),r&Ln.PATCH_RATE&&pe(this,Tr,te.number(e,t)),r&Ln.SUB_STEPS&&pe(this,Ls,te.number(e,t))}ackInput(e){return q(this,At)?q(this,At).ackInput(e):-1}reset(){q(this,At)?.reset()}handle(e){if(q(this,At))return e!==void 0&&Pn(this,bo,Ef).call(this,e),q(this,At);let t=e?.type??q(this,Ps);if(!t)throw new Error("room.input(): no input schema available. The server room must call `defineInput(YourInput)`, or you can pass `{ type: YourInput }` explicitly.");let r=new t,s=new fo(r,e);return pe(this,At,new Rr(q(this,qn),r,s,{stampRender:q(this,Ms),stampReckon:q(this,Ds),renderDelay:e?.renderDelay,allowRewind:e?.allowRewind,tickRate:q(this,Ns),patchRate:q(this,Tr),subSteps:q(this,Ls)})),pe(this,Sr,e),pe(this,Is,s),q(this,At)}};qn=new WeakMap,At=new WeakMap,Sr=new WeakMap,Is=new WeakMap,Os=new WeakMap,Ps=new WeakMap,Ms=new WeakMap,Ds=new WeakMap,Ns=new WeakMap,Tr=new WeakMap,Ls=new WeakMap,bo=new WeakSet,Ef=function(e){if(q(this,Os))return;let t=q(this,At),r=[];e.type!==void 0&&e.type!==t.data?.constructor&&r.push("type"),e.mode!==void 0&&e.mode!==t.mode&&r.push("mode"),e.historySize!==void 0&&t.mode==="unreliable"&&e.historySize!==q(this,Is).historySize&&r.push("historySize"),e.renderDelay!==void 0&&e.renderDelay!==q(this,Sr)?.renderDelay&&r.push("renderDelay"),e.allowRewind!==void 0!=(q(this,Sr)?.allowRewind!==void 0)&&r.push("allowRewind"),r.length!==0&&(pe(this,Os,!0),console.warn(`@colyseus/sdk: room.input() options ignored \u2014 the input handle was already created by an earlier call (first call wins). Differing: ${r.join(", ")}.`))};var kc;try{kc=new TextDecoder}catch{}var F,ft,w=0;var Pf=[],Ac=Pf,vc=0,de={},se,Rn,dt=0,Ft=0,Be,rn,Xe=[],re,Rf={useRecords:!1,mapsAsObjects:!0},Bs=class{},Ic=new Bs;Ic.name="MessagePack 0xC1";var xn=!1,xf=2;var Sn=class n{constructor(e){e&&(e.useRecords===!1&&e.mapsAsObjects===void 0&&(e.mapsAsObjects=!0),e.sequential&&e.trusted!==!1&&(e.trusted=!0,!e.structures&&e.useRecords!=!1&&(e.structures=[],e.maxSharedStructures||(e.maxSharedStructures=0))),e.structures?e.structures.sharedLength=e.structures.length:e.getStructures&&((e.structures=[]).uninitialized=!0,e.structures.sharedLength=0),e.int64AsNumber&&(e.int64AsType="number")),Object.assign(this,e)}unpack(e,t){if(F)return Bf(()=>(_o(),this?this.unpack(e,t):n.prototype.unpack.call(Rf,e,t)));!e.buffer&&e.constructor===ArrayBuffer&&(e=typeof Buffer<"u"?Buffer.from(e):new Uint8Array(e)),typeof t=="object"?(ft=t.end||e.length,w=t.start||0):(w=0,ft=t>-1?t:e.length),vc=0,Ft=0,Rn=null,Ac=Pf,Be=null,F=e;try{re=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(r){throw F=null,e instanceof Uint8Array?r:new Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof n){if(de=this,this.structures)return se=this.structures,wo(t);(!se||se.length>0)&&(se=[])}else de=Rf,(!se||se.length>0)&&(se=[]);return wo(t)}unpackMultiple(e,t){let r,s=0;try{xn=!0;let i=e.length,o=this?this.unpack(e,i):Ro.unpack(e,i);if(t){if(t(o,s,w)===!1)return;for(;w<i;)if(s=w,t(wo(),s,w)===!1)return}else{for(r=[o];w<i;)s=w,r.push(wo());return r}}catch(i){throw i.lastPosition=s,i.values=r,i}finally{xn=!1,_o()}}_mergeStructures(e,t){this._onLoadedStructures&&(e=this._onLoadedStructures(e)),e=e||[],Object.isFrozen(e)&&(e=e.map(r=>r.slice(0)));for(let r=0,s=e.length;r<s;r++){let i=e[r];i&&(i.isShared=!0,r>=32&&(i.highByte=r-32>>5))}e.sharedLength=e.length;for(let r in t||[])if(r>=0){let s=e[r],i=t[r];i&&(s&&((e.restoreStructures||(e.restoreStructures=[]))[r]=s),e[r]=i)}return this.structures=e}decode(e,t){return this.unpack(e,t)}};function wo(n){try{if(!de.trusted&&!xn){let t=se.sharedLength||0;t<se.length&&(se.length=t)}let e;if(de._readStruct&&F[w]<64&&F[w]>=32?(e=de._readStruct(F,w,ft),F=null,!(n&&n.lazy)&&e&&(e=e.toJSON()),w=ft):e=ke(),Be&&(w=Be.postBundlePosition,Be=null),xn&&(se.restoreStructures=null),w==ft)se&&se.restoreStructures&&Sf(),se=null,F=null,rn&&(rn=null);else{if(w>ft)throw new Error("Unexpected end of MessagePack data");if(!xn){let t;try{t=JSON.stringify(e,(r,s)=>typeof s=="bigint"?`${s}n`:s).slice(0,100)}catch(r){t="(JSON view not available "+r+")"}throw new Error("Data read, but end of buffer not reached "+t)}}return e}catch(e){throw se&&se.restoreStructures&&Sf(),_o(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")||w>ft)&&(e.incomplete=!0),e}}function Sf(){for(let n in se.restoreStructures)se[n]=se.restoreStructures[n];se.restoreStructures=null}function ke(){let n=F[w++];if(n<160)if(n<128){if(n<64)return n;{let e=se[n&63]||de.getStructures&&Mf()[n&63];return e?(e.read||(e.read=Oc(e,n&63)),e.read()):n}}else if(n<144)if(n-=128,de.mapsAsObjects){let e={};for(let t=0;t<n;t++){let r=Nf();r==="__proto__"&&(r="__proto_"),e[r]=ke()}return e}else{let e=new Map;for(let t=0;t<n;t++)e.set(ke(),ke());return e}else{n-=144;let e=new Array(n);for(let t=0;t<n;t++)e[t]=ke();return de.freezeData?Object.freeze(e):e}else if(n<192){let e=n-160;if(Ft>=w)return Rn.slice(w-dt,(w+=e)-dt);if(Ft==0&&ft<140){let t=e<16?Pc(e):Df(e);if(t!=null)return t}return Cc(e)}else{let e;switch(n){case 192:return null;case 193:return Be?(e=ke(),e>0?Be[1].slice(Be.position1,Be.position1+=e):Be[0].slice(Be.position0,Be.position0-=e)):Ic;case 194:return!1;case 195:return!0;case 196:if(e=F[w++],e===void 0)throw new Error("Unexpected end of buffer");return Tc(e);case 197:return e=re.getUint16(w),w+=2,Tc(e);case 198:return e=re.getUint32(w),w+=4,Tc(e);case 199:return zn(F[w++]);case 200:return e=re.getUint16(w),w+=2,zn(e);case 201:return e=re.getUint32(w),w+=4,zn(e);case 202:if(e=re.getFloat32(w),de.useFloat32>2){let t=Eo[(F[w]&127)<<1|F[w+1]>>7];return w+=4,(t*e+(e>0?.5:-.5)>>0)/t}return w+=4,e;case 203:return e=re.getFloat64(w),w+=8,e;case 204:return F[w++];case 205:return e=re.getUint16(w),w+=2,e;case 206:return e=re.getUint32(w),w+=4,e;case 207:return de.int64AsType==="number"?(e=re.getUint32(w)*4294967296,e+=re.getUint32(w+4)):de.int64AsType==="string"?e=re.getBigUint64(w).toString():de.int64AsType==="auto"?(e=re.getBigUint64(w),e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=re.getBigUint64(w),w+=8,e;case 208:return re.getInt8(w++);case 209:return e=re.getInt16(w),w+=2,e;case 210:return e=re.getInt32(w),w+=4,e;case 211:return de.int64AsType==="number"?(e=re.getInt32(w)*4294967296,e+=re.getUint32(w+4)):de.int64AsType==="string"?e=re.getBigInt64(w).toString():de.int64AsType==="auto"?(e=re.getBigInt64(w),e>=BigInt(-2)<<BigInt(52)&&e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=re.getBigInt64(w),w+=8,e;case 212:if(e=F[w++],e==114)return If(F[w++]&63);{let t=Xe[e];if(t)return t.read?(w++,t.read(ke())):t.noBuffer?(w++,t()):t(F.subarray(w,++w));throw new Error("Unknown extension "+e)}case 213:return e=F[w],e==114?(w++,If(F[w++]&63,F[w++])):zn(2);case 214:return zn(4);case 215:return zn(8);case 216:return zn(16);case 217:return e=F[w++],Ft>=w?Rn.slice(w-dt,(w+=e)-dt):Yy(e);case 218:return e=re.getUint16(w),w+=2,Ft>=w?Rn.slice(w-dt,(w+=e)-dt):Jy(e);case 219:return e=re.getUint32(w),w+=4,Ft>=w?Rn.slice(w-dt,(w+=e)-dt):Ky(e);case 220:return e=re.getUint16(w),w+=2,kf(e);case 221:return e=re.getUint32(w),w+=4,kf(e);case 222:return e=re.getUint16(w),w+=2,Af(e);case 223:return e=re.getUint32(w),w+=4,Af(e);default:if(n>=224)return n-256;if(n===void 0){let t=new Error("Unexpected end of MessagePack data");throw t.incomplete=!0,t}throw new Error("Unknown MessagePack token "+n)}}}var Wy=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function Oc(n,e){function t(){if(t.count++>xf){let s;try{s=n.read=new Function("r","return function(){return "+(de.freezeData?"Object.freeze":"")+"({"+n.map(i=>i==="__proto__"?"__proto_:r()":Wy.test(i)?i+":r()":"["+JSON.stringify(i)+"]:r()").join(",")+"})}")(ke)}catch{return xf=1/0,t()}return n.read0=s,n.highByte===0&&(n.read=Tf(e,n.read)),s()}let r={};for(let s=0,i=n.length;s<i;s++){let o=n[s];o==="__proto__"&&(o="__proto_"),r[o]=ke()}return de.freezeData?Object.freeze(r):r}return t.count=0,n.read0=t,n.highByte===0?Tf(e,t):t}var Tf=(n,e)=>function(){let t=F[w++];if(t===0)return e();let r=n<32?-(n+(t<<5)):n+(t<<5),s=se[r]||Mf()[r];if(!s)throw new Error("Record id is not defined for "+r);return s.read||(s.read=Oc(s,n)),s.read()};function Mf(){let n=Bf(()=>(F=null,de.getStructures()));return se=de._mergeStructures(n,se)}var Cc=Us,Yy=Us,Jy=Us,Ky=Us;function Us(n){let e;if(n<16&&(e=Pc(n)))return e;if(n>64&&kc)return kc.decode(F.subarray(w,w+=n));let t=w+n,r=[];for(e="";w<t;){let s=F[w++];if((s&128)===0)r.push(s);else if((s&224)===192){let i=F[w++]&63,o=(s&31)<<6|i;o<128?r.push(65533):r.push(o)}else if((s&240)===224){let i=F[w++]&63,o=F[w++]&63,a=(s&31)<<12|i<<6|o;a<2048||a>=55296&&a<=57343?r.push(65533):r.push(a)}else if((s&248)===240){let i=F[w++]&63,o=F[w++]&63,a=F[w++]&63,c=(s&7)<<18|i<<12|o<<6|a;c<65536||c>1114111?r.push(65533):(c>65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|c&1023),r.push(c))}else r.push(65533);r.length>=4096&&(e+=Le.apply(String,r),r.length=0)}return r.length>0&&(e+=Le.apply(String,r)),e}function kf(n){let e=new Array(n);for(let t=0;t<n;t++)e[t]=ke();return de.freezeData?Object.freeze(e):e}function Af(n){if(de.mapsAsObjects){let e={};for(let t=0;t<n;t++){let r=Nf();r==="__proto__"&&(r="__proto_"),e[r]=ke()}return e}else{let e=new Map;for(let t=0;t<n;t++)e.set(ke(),ke());return e}}var Le=String.fromCharCode;function Df(n){let e=w,t=new Array(n);for(let r=0;r<n;r++){let s=F[w++];if((s&128)>0){w=e;return}t[r]=s}return Le.apply(String,t)}function Pc(n){if(n<4)if(n<2){if(n===0)return"";{let e=F[w++];if((e&128)>1){w-=1;return}return Le(e)}}else{let e=F[w++],t=F[w++];if((e&128)>0||(t&128)>0){w-=2;return}if(n<3)return Le(e,t);let r=F[w++];if((r&128)>0){w-=3;return}return Le(e,t,r)}else{let e=F[w++],t=F[w++],r=F[w++],s=F[w++];if((e&128)>0||(t&128)>0||(r&128)>0||(s&128)>0){w-=4;return}if(n<6){if(n===4)return Le(e,t,r,s);{let i=F[w++];if((i&128)>0){w-=5;return}return Le(e,t,r,s,i)}}else if(n<8){let i=F[w++],o=F[w++];if((i&128)>0||(o&128)>0){w-=6;return}if(n<7)return Le(e,t,r,s,i,o);let a=F[w++];if((a&128)>0){w-=7;return}return Le(e,t,r,s,i,o,a)}else{let i=F[w++],o=F[w++],a=F[w++],c=F[w++];if((i&128)>0||(o&128)>0||(a&128)>0||(c&128)>0){w-=8;return}if(n<10){if(n===8)return Le(e,t,r,s,i,o,a,c);{let u=F[w++];if((u&128)>0){w-=9;return}return Le(e,t,r,s,i,o,a,c,u)}}else if(n<12){let u=F[w++],d=F[w++];if((u&128)>0||(d&128)>0){w-=10;return}if(n<11)return Le(e,t,r,s,i,o,a,c,u,d);let h=F[w++];if((h&128)>0){w-=11;return}return Le(e,t,r,s,i,o,a,c,u,d,h)}else{let u=F[w++],d=F[w++],h=F[w++],m=F[w++];if((u&128)>0||(d&128)>0||(h&128)>0||(m&128)>0){w-=12;return}if(n<14){if(n===12)return Le(e,t,r,s,i,o,a,c,u,d,h,m);{let g=F[w++];if((g&128)>0){w-=13;return}return Le(e,t,r,s,i,o,a,c,u,d,h,m,g)}}else{let g=F[w++],p=F[w++];if((g&128)>0||(p&128)>0){w-=14;return}if(n<15)return Le(e,t,r,s,i,o,a,c,u,d,h,m,g,p);let y=F[w++];if((y&128)>0){w-=15;return}return Le(e,t,r,s,i,o,a,c,u,d,h,m,g,p,y)}}}}}function vf(){let n=F[w++],e;if(n<192)e=n-160;else switch(n){case 217:e=F[w++];break;case 218:e=re.getUint16(w),w+=2;break;case 219:e=re.getUint32(w),w+=4;break;default:throw new Error("Expected string")}return Us(e)}function Tc(n){return de.copyBuffers?Uint8Array.prototype.slice.call(F,w,w+=n):F.subarray(w,w+=n)}function zn(n){let e=F[w++];if(Xe[e]){let t;return Xe[e](F.subarray(w,t=w+=n),r=>{w=r;try{return ke()}finally{w=t}})}else throw new Error("Unknown extension type "+e)}var Cf=new Array(4096);function Nf(){let n=F[w++];if(n>=160&&n<192){if(n=n-160,Ft>=w)return Rn.slice(w-dt,(w+=n)-dt);if(!(Ft==0&&ft<180))return Cc(n)}else return w--,Lf(ke());let e=(n<<5^(n>1?re.getUint16(w):n>0?F[w]:0))&4095,t=Cf[e],r=w,s=w+n-3,i,o=0;if(t&&t.bytes==n){for(;r<s;){if(i=re.getUint32(r),i!=t[o++]){r=1879048192;break}r+=4}for(s+=3;r<s;)if(i=F[r++],i!=t[o++]){r=1879048192;break}if(r===s)return w=r,t.string;s-=3,r=w}for(t=[],Cf[e]=t,t.bytes=n;r<s;)i=re.getUint32(r),t.push(i),r+=4;for(s+=3;r<s;)i=F[r++],t.push(i);let a=n<16?Pc(n):Df(n);return a!=null?t.string=a:t.string=Cc(n)}function Lf(n){if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean"||typeof n=="bigint")return n.toString();if(n==null)return n+"";if(de.allowArraysInMapKeys&&Array.isArray(n)&&n.flat().every(e=>["string","number","boolean","bigint"].includes(typeof e)))return n.flat().toString();throw new Error(`Invalid property type for record: ${typeof n}`)}var If=(n,e)=>{let t=ke().map(Lf),r=n;e!==void 0&&(n=n<32?-((e<<5)+n):(e<<5)+n,t.highByte=e);let s=se[n];return s&&(s.isShared||xn)&&((se.restoreStructures||(se.restoreStructures=[]))[n]=s),se[n]=t,t.read=Oc(t,r),(t.read0||t.read)()};Xe[0]=()=>{};Xe[0].noBuffer=!0;Xe[66]=n=>{let e=n.byteLength%8||8,t=BigInt(n[0]&128?n[0]-256:n[0]);for(let r=1;r<e;r++)t<<=BigInt(8),t+=BigInt(n[r]);if(n.byteLength!==e){let r=new DataView(n.buffer,n.byteOffset,n.byteLength),s=(i,o)=>{let a=o-i;if(a<=40){let h=r.getBigUint64(i);for(let m=i+8;m<o;m+=8)h<<=BigInt(64),h|=r.getBigUint64(m);return h}let c=i+(a>>4<<3),u=s(i,c),d=s(c,o);return u<<BigInt((o-c)*8)|d};t=t<<BigInt((r.byteLength-e)*8)|s(e,r.byteLength)}return t};var Of={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError=="function"?AggregateError:null};Xe[101]=()=>{let n=ke();if(!Of[n[0]]){let e=Error(n[1],{cause:n[2]});return e.name=n[0],e}return Of[n[0]](n[1],{cause:n[2]})};Xe[105]=n=>{if(de.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=re.getUint32(w-4);rn||(rn=new Map);let t=F[w],r;t>=144&&t<160||t==220||t==221?r=[]:t>=128&&t<144||t==222||t==223?r=new Map:(t>=199&&t<=201||t>=212&&t<=216)&&F[w+1]===115?r=new Set:r={};let s={target:r};rn.set(e,s);let i=ke();if(s.used)Object.assign(r,i);else return s.target=i;if(r instanceof Map)for(let[o,a]of i.entries())r.set(o,a);if(r instanceof Set)for(let o of Array.from(i))r.add(o);return r};Xe[112]=n=>{if(de.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=re.getUint32(w-4),t=rn.get(e);return t.used=!0,t.target};Xe[115]=()=>new Set(ke());var Mc=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(n=>n+"Array"),Xy=typeof globalThis=="object"?globalThis:window;Xe[116]=n=>{let e=n[0],t=Uint8Array.prototype.slice.call(n,1).buffer,r=Mc[e];if(!r){if(e===16)return t;if(e===17)return new DataView(t);throw new Error("Could not find typed array for code "+e)}return new Xy[r](t)};Xe[120]=()=>{let n=ke();return new RegExp(n[0],n[1])};var Qy=[];Xe[98]=n=>{let e=(n[0]<<24)+(n[1]<<16)+(n[2]<<8)+n[3],t=w;return w+=e-n.length,Be=Qy,Be=[vf(),vf()],Be.position0=0,Be.position1=0,Be.postBundlePosition=w,w=t,ke()};Xe[255]=n=>n.length==4?new Date((n[0]*16777216+(n[1]<<16)+(n[2]<<8)+n[3])*1e3):n.length==8?new Date(((n[0]<<22)+(n[1]<<14)+(n[2]<<6)+(n[3]>>2))/1e6+((n[3]&3)*4294967296+n[4]*16777216+(n[5]<<16)+(n[6]<<8)+n[7])*1e3):n.length==12?new Date(((n[0]<<24)+(n[1]<<16)+(n[2]<<8)+n[3])/1e6+((n[4]&128?-281474976710656:0)+n[6]*1099511627776+n[7]*4294967296+n[8]*16777216+(n[9]<<16)+(n[10]<<8)+n[11])*1e3):new Date("invalid");function Bf(n){de&&de._onSaveState&&de._onSaveState();let e=ft,t=w,r=vc,s=dt,i=Ft,o=Rn,a=Ac,c=rn,u=Be,d=new Uint8Array(F.slice(0,ft)),h=se,m=se.slice(0,se.length),g=de,p=xn,y=n();return ft=e,w=t,vc=r,dt=s,Ft=i,Rn=o,Ac=a,rn=c,Be=u,F=d,xn=p,se=h,se.splice(0,se.length,...m),de=g,re=new DataView(F.buffer,F.byteOffset,F.byteLength),y}function _o(){F=null,rn=null,se=null}var Eo=new Array(147);for(let n=0;n<256;n++)Eo[n]=+("1e"+Math.floor(45.15-n*.30103));var Ro=new Sn({useRecords:!1}),xo=Ro.unpack,Zy=Ro.unpackMultiple,e0=Ro.unpack,So={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},t0=new Float32Array(1),$E=new Uint8Array(t0.buffer,0,4);Sn.SUPPORTS_STRUCT_HOOKS=!0;var ko;try{ko=new TextEncoder}catch{}var Lc,Bc,vr=typeof Buffer<"u",To=vr?function(n){return Buffer.allocUnsafeSlow(n)}:Uint8Array,Vf=vr?Buffer:Uint8Array,Uf=vr?4294967296:2144337920,T,Fs,me,E=0,Ve,xe=null,n0=21760,r0=/[\u0080-\uFFFF]/,Ar=Symbol("record-id"),Tn=class extends Sn{constructor(e){super(e),this.offset=0;let t,r,s,i,o,a=Vf.prototype.utf8Write?function(S,U){return T.utf8Write(S,U,T.byteLength-U)}:ko&&ko.encodeInto?function(S,U){return ko.encodeInto(S,T.subarray(U)).written}:!1,c=this;e||(e={});let u=e&&e.sequential,d=e.structures||e.saveStructures,h=e.maxSharedStructures;if(h==null&&(h=d?32:0),h>8160)throw new Error("Maximum maxSharedStructure is 8160");e.structuredClone&&e.moreTypes==null&&(this.moreTypes=!0);let m=e.maxOwnStructures;m==null&&(m=d?32:64),!this.structures&&e.useRecords!=!1&&(this.structures=[]);let g=h>32||m+h>64,p=h+64,y=h+m+64;if(y>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let x=[],k=0,I=0;this.pack=this.encode=function(S,U){if(T||(T=new To(8192),me=T.dataView||(T.dataView=new DataView(T.buffer,0,8192)),E=0),Ve=T.length-10,Ve-E<2048?(T=new To(T.length),me=T.dataView||(T.dataView=new DataView(T.buffer,0,T.length)),Ve=T.length-10,E=0):E=E+7&2147483640,r=E,U&Cr&&(E+=U&255),o=c.structuredClone?new Map:null,c.bundleStrings&&typeof S!="string"?(xe=[],xe.size=1/0):xe=null,i=c.structures,i){i.uninitialized&&(i=c._mergeStructures(c.getStructures()));let D=i.sharedLength||0;if(D>h)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+i.sharedLength);if(!i.transitions){i.transitions=Object.create(null);for(let M=0;M<D;M++){let z=i[M];if(!z)continue;let W,H=i.transitions;for(let ce=0,K=z.length;ce<K;ce++){let Ze=z[ce];W=H[Ze],W||(W=H[Ze]=Object.create(null)),H=W}H[Ar]=M+64}this.lastNamedStructuresLength=D}u||(i.nextId=D+64)}s&&(s=!1);let L;try{c._writeStruct&&S&&typeof S=="object"?S.constructor===Object?Z(S):S.constructor!==Map&&!Array.isArray(S)&&!Bc.some(M=>S instanceof M)?Z(S.toJSON?S.toJSON():S):C(S):C(S);let D=xe;if(xe&&$f(r,C,0),o&&o.idsToInsert){let M=o.idsToInsert.sort((ce,K)=>ce.offset>K.offset?1:-1),z=M.length,W=-1;for(;D&&z>0;){let ce=M[--z].offset+r;ce<D.stringsPosition+r&&W===-1&&(W=0),ce>D.position+r?W>=0&&(W+=6):(W>=0&&(me.setUint32(D.position+r,me.getUint32(D.position+r)+W),W=-1),D=D.previous,z++)}W>=0&&D&&me.setUint32(D.position+r,me.getUint32(D.position+r)+W),E+=M.length*6,E>Ve&&ee(E),c.offset=E;let H=s0(T.subarray(r,E),M);return o=null,H}return c.offset=E,U&Hf?(T.start=r,T.end=E,T):T.subarray(r,E)}catch(D){throw L=D,D}finally{if(i&&(B(),s&&c.saveStructures)){let D=i.sharedLength||0,M=T.subarray(r,E),z=(c._prepareStructures||i0)(i,c);if(!L)return c.saveStructures(z,z.isCompatible)===!1?(i.uninitialized=!0,c.pack(S,U)):(c.lastNamedStructuresLength=D,T.length>1073741824&&(T=null),M)}T.length>1073741824&&(T=null),U&Gf&&(E=r)}};let B=()=>{I<10&&I++;let S=i.sharedLength||0;if(i.length>S&&!u&&(i.length=S),k>1e4)i.transitions=null,I=0,k=0,x.length>0&&(x=[]);else if(x.length>0&&!u){for(let U=0,L=x.length;U<L;U++)x[U][Ar]=0;x=[]}},N=S=>{var U=S.length;U<16?T[E++]=144|U:U<65536?(T[E++]=220,T[E++]=U>>8,T[E++]=U&255):(T[E++]=221,me.setUint32(E,U),E+=4);for(let L=0;L<U;L++)C(S[L])},C=S=>{E>Ve&&(T=ee(E));var U=typeof S,L;if(U==="string"){let D=S.length;if(xe&&D>=4&&D<4096){if((xe.size+=D)>n0){let H,ce=(xe[0]?xe[0].length*3+xe[1].length:0)+10;E+ce>Ve&&(T=ee(E+ce));let K;xe.position?(K=xe,T[E]=200,E+=3,T[E++]=98,H=E-r,E+=4,$f(r,C,0),me.setUint16(H+r-3,E-r-H)):(T[E++]=214,T[E++]=98,H=E-r,E+=4),xe=["",""],xe.previous=K,xe.size=0,xe.position=H}let W=r0.test(S);xe[W?0:1]+=S,T[E++]=193,C(W?-D:D);return}let M;D<32?M=1:D<256?M=2:D<65536?M=3:M=5;let z=D*3;if(E+z>Ve&&(T=ee(E+z)),D<64||!a){let W,H,ce,K=E+M;for(W=0;W<D;W++)H=S.charCodeAt(W),H<128?T[K++]=H:H<2048?(T[K++]=H>>6|192,T[K++]=H&63|128):(H&64512)===55296&&((ce=S.charCodeAt(W+1))&64512)===56320?(H=65536+((H&1023)<<10)+(ce&1023),W++,T[K++]=H>>18|240,T[K++]=H>>12&63|128,T[K++]=H>>6&63|128,T[K++]=H&63|128):(T[K++]=H>>12|224,T[K++]=H>>6&63|128,T[K++]=H&63|128);L=K-E-M}else L=a(S,E+M);L<32?T[E++]=160|L:L<256?(M<2&&T.copyWithin(E+2,E+1,E+1+L),T[E++]=217,T[E++]=L):L<65536?(M<3&&T.copyWithin(E+3,E+2,E+2+L),T[E++]=218,T[E++]=L>>8,T[E++]=L&255):(M<5&&T.copyWithin(E+5,E+3,E+3+L),T[E++]=219,me.setUint32(E,L),E+=4),E+=L}else if(U==="number")if(S>>>0===S)S<32||S<128&&this.useRecords===!1||S<64&&!this._writeStruct?T[E++]=S:S<256?(T[E++]=204,T[E++]=S):S<65536?(T[E++]=205,T[E++]=S>>8,T[E++]=S&255):(T[E++]=206,me.setUint32(E,S),E+=4);else if(S>>0===S)S>=-32?T[E++]=256+S:S>=-128?(T[E++]=208,T[E++]=S+256):S>=-32768?(T[E++]=209,me.setInt16(E,S),E+=2):(T[E++]=210,me.setInt32(E,S),E+=4);else{let D;if((D=this.useFloat32)>0&&S<4294967296&&S>=-2147483648){T[E++]=202,me.setFloat32(E,S);let M;if(D<4||(M=S*Eo[(T[E]&127)<<1|T[E+1]>>7])>>0===M){E+=4;return}else E--}T[E++]=203,me.setFloat64(E,S),E+=8}else if(U==="object"||U==="function")if(!S)T[E++]=192;else{if(o){let M=o.get(S);if(M){if(!M.id){let z=o.idsToInsert||(o.idsToInsert=[]);M.id=z.push(M)}T[E++]=214,T[E++]=112,me.setUint32(E,M.id),E+=4;return}else o.set(S,{offset:E-r})}let D=S.constructor;if(D===Object)V(S);else if(D===Array)N(S);else if(D===Map)if(this.mapAsEmptyObject)T[E++]=128;else{L=S.size,L<16?T[E++]=128|L:L<65536?(T[E++]=222,T[E++]=L>>8,T[E++]=L&255):(T[E++]=223,me.setUint32(E,L),E+=4);for(let[M,z]of S)C(M),C(z)}else{for(let M=0,z=Lc.length;M<z;M++){let W=Bc[M];if(S instanceof W){let H=Lc[M];if(H.write){H.type&&(T[E++]=212,T[E++]=H.type,T[E++]=0);let ln=H.write.call(this,S);ln===S?Array.isArray(S)?N(S):V(S):C(ln);return}let ce=T,K=me,Ze=E;T=null;let pt;try{pt=H.pack.call(this,S,ln=>(T=ce,ce=null,E+=ln,E>Ve&&ee(E),{target:T,targetView:me,position:E-ln}),C)}finally{ce&&(T=ce,me=K,E=Ze,Ve=T.length-10)}pt&&(pt.length+E>Ve&&ee(pt.length+E),E=Ff(pt,T,E,H.type));return}}if(Array.isArray(S))N(S);else{if(S.toJSON){let M=S.toJSON();if(M!==S)return C(M)}if(U==="function")return C(this.writeFunction&&this.writeFunction(S));V(S)}}}else if(U==="boolean")T[E++]=S?195:194;else if(U==="bigint"){if(S<9223372036854776e3&&S>=-9223372036854776e3)T[E++]=211,me.setBigInt64(E,S);else if(S<18446744073709552e3&&S>0)T[E++]=207,me.setBigUint64(E,S);else if(this.largeBigIntToFloat)T[E++]=203,me.setFloat64(E,Number(S));else{if(this.largeBigIntToString)return C(S.toString());if(this.useBigIntExtension||this.moreTypes){let D=S<0?BigInt(-1):BigInt(0),M;if(S>>BigInt(65536)===D){let z=BigInt(18446744073709552e3)-BigInt(1),W=[];for(;W.push(S&z),S>>BigInt(63)!==D;)S>>=BigInt(64);M=new Uint8Array(new BigUint64Array(W).buffer),M.reverse()}else{let z=S<0,W=(z?~S:S).toString(16);if(W.length%2?W="0"+W:parseInt(W.charAt(0),16)>=8&&(W="00"+W),vr)M=Buffer.from(W,"hex");else{M=new Uint8Array(W.length/2);for(let H=0;H<M.length;H++)M[H]=parseInt(W.slice(H*2,H*2+2),16)}if(z)for(let H=0;H<M.length;H++)M[H]=~M[H]}M.length+E>Ve&&ee(M.length+E),E=Ff(M,T,E,66);return}else throw new RangeError(S+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string")}E+=8}else if(U==="undefined")this.encodeUndefinedAsNil?T[E++]=192:(T[E++]=212,T[E++]=0,T[E++]=0);else throw new Error("Unknown type: "+U)},P=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?S=>{let U;if(this.skipValues){U=[];for(let M in S)(typeof S.hasOwnProperty!="function"||S.hasOwnProperty(M))&&!this.skipValues.includes(S[M])&&U.push(M)}else U=Object.keys(S);let L=U.length;L<16?T[E++]=128|L:L<65536?(T[E++]=222,T[E++]=L>>8,T[E++]=L&255):(T[E++]=223,me.setUint32(E,L),E+=4);let D;if(this.coercibleKeyAsNumber)for(let M=0;M<L;M++){D=U[M];let z=Number(D);C(isNaN(z)?D:z),C(S[D])}else for(let M=0;M<L;M++)C(D=U[M]),C(S[D])}:S=>{T[E++]=222;let U=E-r;E+=2;let L=0;for(let D in S)(typeof S.hasOwnProperty!="function"||S.hasOwnProperty(D))&&(C(D),C(S[D]),L++);if(L>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');T[U+++r]=L>>8,T[U+r]=L&255},v=this.useRecords===!1?P:e.progressiveRecords&&!g?S=>{let U,L=i.transitions||(i.transitions=Object.create(null)),D=E++-r,M;for(let z in S)if(typeof S.hasOwnProperty!="function"||S.hasOwnProperty(z)){if(U=L[z],U)L=U;else{let W=Object.keys(S),H=L;L=i.transitions;let ce=0;for(let K=0,Ze=W.length;K<Ze;K++){let pt=W[K];U=L[pt],U||(U=L[pt]=Object.create(null),ce++),L=U}D+r+1==E?(E--,Ae(L,W,ce)):Oe(L,W,D,ce),M=!0,L=H[z]}C(S[z])}if(!M){let z=L[Ar];z?T[D+r]=z:Oe(L,Object.keys(S),D,0)}}:S=>{let U,L=i.transitions||(i.transitions=Object.create(null)),D=0;for(let z in S)(typeof S.hasOwnProperty!="function"||S.hasOwnProperty(z))&&(U=L[z],U||(U=L[z]=Object.create(null),D++),L=U);let M=L[Ar];M?M>=96&&g?(T[E++]=((M-=96)&31)+96,T[E++]=M>>5):T[E++]=M:Ae(L,L.__keys__||Object.keys(S),D);for(let z in S)(typeof S.hasOwnProperty!="function"||S.hasOwnProperty(z))&&C(S[z])},O=typeof this.useRecords=="function"&&this.useRecords,V=O?S=>{O(S)?v(S):P(S)}:v,Z=S=>{let U=c._writeStruct(S,T,r,E,i,ee,(L,D,M)=>{if(M)return s=!0;E=D;let z=T;return C(L),B(),z!==T?{position:E,targetView:me,target:T}:E});if(U===0)return V(S);E=U},ee=S=>{let U;if(S>16777216){if(S-r>Uf)throw new Error("Packed buffer would be larger than maximum buffer size");U=Math.min(Uf,Math.round(Math.max((S-r)*(S>67108864?1.25:2),4194304)/4096)*4096)}else U=(Math.max(S-r<<2,T.length-1)>>12)+1<<12;let L=new To(U);return me=L.dataView||(L.dataView=new DataView(L.buffer,0,U)),S=Math.min(S,T.length),T.copy?T.copy(L,0,r,S):L.set(T.slice(r,S)),E-=r,r=0,Ve=L.length-10,T=L},Ae=(S,U,L)=>{let D=i.nextId;D||(D=64),D<p&&this.shouldShareStructure&&!this.shouldShareStructure(U)?(D=i.nextOwnId,D<y||(D=p),i.nextOwnId=D+1):(D>=y&&(D=p),i.nextId=D+1);let M=U.highByte=D>=96&&g?D-96>>5:-1;S[Ar]=D,S.__keys__=U,i[D-64]=U,D<p?(U.isShared=!0,i.sharedLength=D-63,s=!0,M>=0?(T[E++]=(D&31)+96,T[E++]=M):T[E++]=D):(M>=0?(T[E++]=213,T[E++]=114,T[E++]=(D&31)+96,T[E++]=M):(T[E++]=212,T[E++]=114,T[E++]=D),L&&(k+=I*L),x.length>=m&&(x.shift()[Ar]=0),x.push(S),C(U))},Oe=(S,U,L,D)=>{let M=T,z=E,W=Ve,H=r;T=Fs,E=0,r=0,T||(Fs=T=new To(8192)),Ve=T.length-10,Ae(S,U,D),Fs=T;let ce=E;if(T=M,E=z,Ve=W,r=H,ce>1){let K=E+ce-1;K>Ve&&ee(K);let Ze=L+r;T.copyWithin(Ze+ce,Ze+1,E),T.set(Fs.slice(0,ce),Ze),E=K}else T[L+r]=Fs[0]}}useBuffer(e){T=e,T.dataView||(T.dataView=new DataView(T.buffer,T.byteOffset,T.byteLength)),me=T.dataView,E=0}set position(e){E=e}get position(){return E}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}};Bc=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,Bs];Lc=[{pack(n,e,t){let r=n.getTime()/1e3;if((this.useTimestamp32||n.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:s,targetView:i,position:o}=e(6);s[o++]=214,s[o++]=255,i.setUint32(o,r)}else if(r>0&&r<4294967296){let{target:s,targetView:i,position:o}=e(10);s[o++]=215,s[o++]=255,i.setUint32(o,n.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),i.setUint32(o+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return e(0),t(this.onInvalidDate());let{target:s,targetView:i,position:o}=e(3);s[o++]=212,s[o++]=255,s[o++]=255}else{let{target:s,targetView:i,position:o}=e(15);s[o++]=199,s[o++]=12,s[o++]=255,i.setUint32(o,n.getMilliseconds()*1e6),i.setBigInt64(o+4,BigInt(Math.floor(r)))}}},{pack(n,e,t){if(this.setAsEmptyObject)return e(0),t({});let r=Array.from(n),{target:s,position:i}=e(this.moreTypes?3:0);this.moreTypes&&(s[i++]=212,s[i++]=115,s[i++]=0),t(r)}},{pack(n,e,t){let{target:r,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(r[s++]=212,r[s++]=101,r[s++]=0),t([n.name,n.message,n.cause])}},{pack(n,e,t){let{target:r,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(r[s++]=212,r[s++]=120,r[s++]=0),t([n.source,n.flags])}},{pack(n,e){this.moreTypes?Dc(n,16,e):Nc(vr?Buffer.from(n):new Uint8Array(n),e)}},{pack(n,e){let t=n.constructor;t!==Vf&&this.moreTypes?Dc(n,Mc.indexOf(t.name),e):Nc(n,e)}},{pack(n,e){this.moreTypes?Dc(n,17,e):Nc(vr?Buffer.from(n):new Uint8Array(n),e)}},{pack(n,e){let{target:t,position:r}=e(1);t[r]=193}}];function Dc(n,e,t,r){let s=n.byteLength;if(s+1<256){var{target:i,position:o}=t(4+s);i[o++]=199,i[o++]=s+1}else if(s+1<65536){var{target:i,position:o}=t(5+s);i[o++]=200,i[o++]=s+1>>8,i[o++]=s+1&255}else{var{target:i,position:o,targetView:a}=t(7+s);i[o++]=201,a.setUint32(o,s+1),o+=4}i[o++]=116,i[o++]=e,n.buffer||(n=new Uint8Array(n)),i.set(new Uint8Array(n.buffer,n.byteOffset,n.byteLength),o)}function Nc(n,e){let t=n.byteLength;var r,s;if(t<256){var{target:r,position:s}=e(t+2);r[s++]=196,r[s++]=t}else if(t<65536){var{target:r,position:s}=e(t+3);r[s++]=197,r[s++]=t>>8,r[s++]=t&255}else{var{target:r,position:s,targetView:i}=e(t+5);r[s++]=198,i.setUint32(s,t),s+=4}r.set(n,s)}function Ff(n,e,t,r){let s=n.length;switch(s){case 1:e[t++]=212;break;case 2:e[t++]=213;break;case 4:e[t++]=214;break;case 8:e[t++]=215;break;case 16:e[t++]=216;break;default:s<256?(e[t++]=199,e[t++]=s):s<65536?(e[t++]=200,e[t++]=s>>8,e[t++]=s&255):(e[t++]=201,e[t++]=s>>24,e[t++]=s>>16&255,e[t++]=s>>8&255,e[t++]=s&255)}return e[t++]=r,e.set(n,t),t+=s,t}function s0(n,e){let t,r=e.length*6,s=n.length-r;for(;t=e.pop();){let i=t.offset,o=t.id;n.copyWithin(i+r,i,s),r-=6;let a=i+r;n[a++]=214,n[a++]=105,n[a++]=o>>24,n[a++]=o>>16&255,n[a++]=o>>8&255,n[a++]=o&255,s=i}return n}function $f(n,e,t){if(xe.length>0){me.setUint32(xe.position+n,E+t-xe.position-n),xe.stringsPosition=E-n;let r=xe;xe=null,e(r[0]),e(r[1])}}function i0(n,e){return n.isCompatible=t=>{let r=!t||(e.lastNamedStructuresLength||0)===t.length;return r||e._mergeStructures(t),r},n}Tn.SUPPORTS_STRUCT_HOOKS=!0;var jf=new Tn({useRecords:!1}),o0=jf.pack,a0=jf.pack;var{NEVER:c0,ALWAYS:l0,DECIMAL_ROUND:u0,DECIMAL_FIT:d0}=So,Hf=512,Gf=1024,Cr=2048;qe();Kt();var f0=9,Ao=class{constructor(){l(this,"pending",new Uint8Array(0))}push(e){if(!e||e.byteLength===0)return[];let t=this.pending.byteLength===0?e:h0(this.pending,e),r=[],s=0;for(;s<t.byteLength;){let i={offset:s},o;try{o=te.number(t,i)}catch(c){if(t.byteLength-s<=f0)break;throw c}let a=i.offset+o;if(a>t.byteLength)break;r.push(t.subarray(i.offset,a)),s=a}return this.pending=s<t.byteLength?t.slice(s):new Uint8Array(0),r}};function h0(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}var $s=class{constructor(e){l(this,"wt");l(this,"url");l(this,"isOpen",!1);l(this,"events");l(this,"reader");l(this,"writer");l(this,"unreliableReader");l(this,"unreliableWriter");l(this,"lengthPrefixBuffer",new Uint8Array(9));l(this,"reliableReassembler",new Ao);l(this,"unreliableReassembler",new Ao);this.events=e}connect(e,t={}){this.url=e;let r=t.fingerprint&&{serverCertificateHashes:[{algorithm:"sha-256",value:new Uint8Array(t.fingerprint)}]}||void 0;this.wt=new WebTransport(e,r),this.wt.ready.then(s=>{console.log("WebTransport ready!",s),this.isOpen=!0,this.unreliableReader=this.wt.datagrams.readable.getReader();let i=this.wt.datagrams;this.unreliableWriter=(i.createWritable?i.createWritable():i.writable).getWriter(),this.wt.incomingBidirectionalStreams.getReader().read().then(a=>{this.reader=a.value.readable.getReader(),this.writer=a.value.writable.getWriter(),this.sendSeatReservation(t.roomId,t.sessionId,t.reconnectionToken,t.skipHandshake),this.readIncomingData(),this.readIncomingUnreliableData()}).catch(a=>{console.error("failed to read incoming stream",a),console.error("TODO: close the connection")})}).catch(s=>{console.log("WebTransport not ready!",s),this._close()}),this.wt.closed.then(s=>{console.log("WebTransport closed w/ success",s),this.events.onclose({code:s.closeCode,reason:s.reason})}).catch(s=>{console.log("WebTransport closed w/ error",s),this.events.onerror(s),this.events.onclose({code:s.closeCode,reason:s.reason})}).finally(()=>{this._close()})}send(e){this.writer.write(this.frame(e))}sendUnreliable(e){this.unreliableWriter.write(this.frame(e))}frame(e){let t=e instanceof Uint8Array?e:new Uint8Array(e),r=Q.number(this.lengthPrefixBuffer,t.length,{offset:0}),s=new Uint8Array(r+t.length);return s.set(this.lengthPrefixBuffer.subarray(0,r),0),s.set(t,r),s}close(e,t){this.isOpen=!1;try{let r=this.wt?.close({closeCode:e,reason:t});r&&typeof r.catch=="function"&&r.catch(()=>{})}catch{}}readIncomingData(){return this.readLoop(this.reader,this.reliableReassembler,"reliable")}readIncomingUnreliableData(){return this.readLoop(this.unreliableReader,this.unreliableReassembler,"unreliable")}async readLoop(e,t,r){for(;this.isOpen;){let s;try{s=await e.read()}catch(i){await this.onChannelFailure(r,i);return}if(s.done||!s.value)return;for(let i of t.push(s.value))this.events.onmessage({data:i})}}async onChannelFailure(e,t){await new Promise(r=>setTimeout(r,0)),this.isOpen&&(console.error(`H3Transport: stopped reading the ${e} channel while the session was open`,t),this.close(Ne.ABNORMAL_CLOSURE,`h3 ${e} channel failed`))}sendSeatReservation(e,t,r,s){let i={offset:0},o=[];Q.string(o,e,i),Q.string(o,t,i),r&&Q.string(o,r,i),s&&Q.boolean(o,1,i),this.writer.write(new Uint8Array(o).buffer)}_close(){this.isOpen=!1}};var Yf=Tp(zf(),1);Kt();var Uc=globalThis.WebSocket||Yf.default,Wf=!1,vo=class{constructor(e){l(this,"ws");l(this,"protocols");l(this,"events");this.events=e}send(e){this.ws.send(e)}sendUnreliable(e){Wf||(Wf=!0,console.warn('@colyseus/sdk: the WebSocket transport has no unreliable channel \u2014 sending `mode:"unreliable"` traffic reliably instead. Use @colyseus/h3-transport (WebTransport) for datagram delivery.')),this.send(e)}connect(e,t){try{this.ws=new Uc(e,{headers:t,protocols:this.protocols})}catch{this.ws=new Uc(e,this.protocols)}this.ws.binaryType="arraybuffer",this.ws.onopen=r=>this.events.onopen?.(r),this.ws.onmessage=r=>this.events.onmessage?.(r),this.ws.onclose=r=>this.events.onclose?.(r),this.ws.onerror=r=>this.events.onerror?.(r)}close(e,t){e===Ne.MAY_TRY_RECONNECT&&this.events.onclose&&(this.ws.onclose=null,this.events.onclose({code:e,reason:t})),this.ws.close(e,t)}get isOpen(){return this.ws.readyState===Uc.OPEN}};Kt();var Vs=[],Fc=typeof addEventListener=="function"&&typeof removeEventListener=="function";Fc&&addEventListener("offline",()=>{console.warn(`@colyseus/sdk: \u{1F6D1} Network offline. Closing ${Vs.length} connection(s)`),Vs.forEach(n=>n())},!1);var js,Ir=class{constructor(e){l(this,"transport");l(this,"events",{});l(this,"url");l(this,"options");he(this,js,Fc?()=>this.close(Ne.MAY_TRY_RECONNECT):null);e==="h3"?this.transport=new $s(this.events):this.transport=new vo(this.events)}connect(e,t){if(Fc){let r=this.events.onopen;this.events.onopen=i=>{Vs.push(q(this,js)),r?.(i)};let s=this.events.onclose;this.events.onclose=i=>{Vs.splice(Vs.indexOf(q(this,js)),1),s?.(i)}}this.url=e,this.options=t,this.transport.connect(e,t)}send(e){this.transport.send(e)}sendUnreliable(e){this.transport.sendUnreliable(e)}reconnect(e){if(this.transport instanceof $s){this.transport.connect(this.url,{...this.options,...e});return}let t=new URL(this.url);for(let r in e)t.searchParams.set(r,e[r]);this.transport.connect(t.toString(),this.options)}close(e,t){this.transport.close(e,t)}get isOpen(){return this.transport.isOpen}};js=new WeakMap;var Jf={};function $c(n,e){Jf[n]=e}function Vc(n){let e=Jf[n];if(!e)throw new Error("missing serializer: "+n);return e}var Co=()=>({emit(n,...e){let t=this.events[n]||[];for(let r=0,s=t.length;r<s;r++)t[r](...e)},events:{},on(n,e){return this.events[n]?.push(e)||(this.events[n]=[e]),()=>{this.events[n]=this.events[n]?.filter(t=>e!==t)}}});var Kf=new WeakMap,jc=class{constructor(){l(this,"handlers",[])}register(e,t=!1){return this.handlers.push(e),this}invoke(...e){let t=this.handlers;for(let r=0,s=t.length;r<s;r++)t[r].apply(this,e)}invokeAsync(...e){return Promise.all(this.handlers.map(t=>t.apply(this,e)))}remove(e){let t=this.handlers.indexOf(e);t===-1&&(t=this.handlers.findIndex(r=>Kf.get(r)===e)),t!==-1&&(this.handlers=this.handlers.filter((r,s)=>s!==t))}clear(){this.handlers=[]}};function Wn(){let n=new jc;function e(t){return n.register(t,this===null)}return e.once=t=>{let r=function(...s){n.remove(r),t.apply(this,s)};Kf.set(r,t),n.register(r)},e.remove=t=>n.remove(t),e.invoke=(...t)=>n.invoke(...t),e.invokeAsync=(...t)=>n.invokeAsync(...t),e.clear=()=>n.clear(),e}qe();function Hc(n){try{return eo(n.serializer.decoder)}catch{return}}var Or=class{constructor(){l(this,"state");l(this,"decoder")}setState(e,t){this.decoder.root.refs.size>1&&typeof this.decoder.decodeResync=="function"?this.decoder.decodeResync(e,t):this.decoder.decode(e,t)}getState(){return this.state}patch(e,t){return this.decoder.decode(e,t)}teardown(){this.decoder.root.clearRefs()}handshake(e,t){this.state?(kt.decode(e,t),this.decoder=new Tt(this.state)):(this.decoder=kt.decode(e,t),this.state=this.decoder.state)}};yo();function Xf(){return{enabled:!0,retryCount:0,maxRetries:15,delay:100,minDelay:100,maxDelay:5e3,minUptime:5e3,backoff:p0,maxEnqueuedMessages:10,enqueuedMessages:[],isReconnecting:!1}}var p0=(n,e)=>Math.floor(Math.pow(2,n)*e);function Io(n,e){n.reconnection.enqueuedMessages.push({data:e}),n.reconnection.enqueuedMessages.length>n.reconnection.maxEnqueuedMessages&&n.reconnection.enqueuedMessages.shift()}function Qf(n,e){if(!e){let r=new Error("request rejected");return r.name="rejected",r.reason=n,r}let t=new Error(n?.message??"request failed");return n?.name&&(t.name=n.name),n?.code!==void 0&&(t.code=n.code),t}Ts();var Gs,Pr,Mr,$t,Vt,Dr,jt,Zf,eh,th,nh,Oo=class Oo{constructor(e,t){he(this,jt);l(this,"roomId");l(this,"sessionId");l(this,"reconnectionToken");l(this,"name");l(this,"connection");l(this,"onStateChange",Wn());l(this,"onError",Wn());l(this,"onLeave",Wn());l(this,"onReconnect",Wn());l(this,"onDrop",Wn());l(this,"onJoin",Wn());l(this,"serializerId");l(this,"serializer");l(this,"reconnection",Xf());l(this,"joinedAtTime",0);l(this,"clock",xr);l(this,"onMessageHandlers",Co());l(this,"packr");l(this,"sharedBuffer");he(this,Gs,0);he(this,Pr);he(this,Mr,0);he(this,$t,new Map);he(this,Vt);he(this,Dr,0);if(this.name=e,this.packr=new Tn,this.sharedBuffer=new Uint8Array(8192),t){let r=new(Vc("schema"));this.serializer=r;let s=new t;r.state=s,r.decoder=new Tt(s)}this.onLeave(()=>{this.removeAllListeners(),this.destroy()})}connect(e,t,r){this.connection=new Ir(t.protocol),this.connection.events.onmessage=this.onMessageCallback.bind(this),this.connection.events.onclose=i=>{if(Pn(this,jt,th).call(this,"connection closed before a response was received."),this.joinedAtTime===0){console.warn?.(`Room connection was closed unexpectedly (${i.code}): ${i.reason}`),this.onError.invoke(i.code,i.reason);return}i.code===Ne.NO_STATUS_RECEIVED||i.code===Ne.ABNORMAL_CLOSURE||i.code===Ne.GOING_AWAY||i.code===Ne.MAY_TRY_RECONNECT?(this.onDrop.invoke(i.code,i.reason),this.handleReconnection(i.code,i.reason)):this.onLeave.invoke(i.code,i.reason)},this.connection.events.onerror=i=>{this.onError.invoke(i.code,i.reason)};let s=this.serializer?.getState()!==void 0;if(t.protocol==="h3"){let i=new URL(e);this.connection.connect(i.origin,{...t,skipHandshake:s})}else this.connection.connect(`${e}${s?"&skipHandshake=1":""}`,r)}leave(e=!0){return new Promise(t=>{this.onLeave(r=>t(r)),this.connection?e?(this.sharedBuffer[0]=_e.LEAVE_ROOM,this.connection.send(this.sharedBuffer.subarray(0,1))):this.connection.close():this.onLeave.invoke(Ne.CONSENTED)})}onMessage(e,t){return this.onMessageHandlers.on(this.getMessageHandlerKey(e),t)}ping(e){this.connection?.isOpen&&(pe(this,Gs,$e()),pe(this,Pr,e),this.sharedBuffer[0]=_e.PING,this.connection.send(this.sharedBuffer.subarray(0,1)))}send(e,t,r){if(r!==void 0){this.request(e,t).then(a=>r(a,void 0),a=>r(void 0,a));return}let s={offset:1};this.sharedBuffer[0]=_e.ROOM_DATA,typeof e=="string"?Q.string(this.sharedBuffer,e,s):Q.number(this.sharedBuffer,e,s);let i=s.offset,o;t!==void 0?(o=this.packr.pack(t,Cr|i),o.set(this.sharedBuffer.subarray(0,i),0)):o=this.sharedBuffer.subarray(0,i),this.connection.isOpen?this.connection.send(o):Io(this,new Uint8Array(o))}request(e,t,r){if(!this.connection.isOpen)return Promise.reject(new Error(`cannot send request "${e}": connection is not open.`));let s=r?.timeout??Oo.defaultRequestTimeout;return new Promise((i,o)=>{let a,c=this.sendRequest(e,t,{mode:r?.mode},(u,d,h)=>{clearTimeout(a),u?i(d):o(Qf(d,h))},u=>{clearTimeout(a),o(new Error(u))});a=setTimeout(()=>{this.cancelRequest(c),o(new Error(`request "${e}" timed out after ${s}ms.`))},s)})}sendRequest(e,t,r,s,i){let o=Pn(this,jt,Zf).call(this),a=Pn(this,jt,eh).call(this,o,e,t);if(r.mode==="unreliable"){if(!this.connection.isOpen)return-1;this.connection.sendUnreliable(a)}else this.connection.isOpen?this.connection.send(a):Io(this,new Uint8Array(a));return q(this,$t).set(o,{onReply:s,onClose:i}),o}cancelRequest(e){q(this,$t).delete(e)}sendUnreliable(e,t){if(!this.connection.isOpen)return;let r={offset:1};this.sharedBuffer[0]=_e.ROOM_DATA,typeof e=="string"?Q.string(this.sharedBuffer,e,r):Q.number(this.sharedBuffer,e,r);let s=r.offset,i;t!==void 0?(i=this.packr.pack(t,Cr|s),i.set(this.sharedBuffer.subarray(0,s),0)):i=this.sharedBuffer.subarray(0,s),this.connection.sendUnreliable(i)}sendBytes(e,t){let r={offset:1};this.sharedBuffer[0]=_e.ROOM_DATA_BYTES,typeof e=="string"?Q.string(this.sharedBuffer,e,r):Q.number(this.sharedBuffer,e,r);let s=r.offset;if(s+t.byteLength>this.sharedBuffer.byteLength){let i=new Uint8Array(s+t.byteLength);i.set(this.sharedBuffer.subarray(0,s)),this.sharedBuffer=i}this.sharedBuffer.set(t,s),this.connection.isOpen?this.connection.send(this.sharedBuffer.subarray(0,s+t.byteLength)):Io(this,this.sharedBuffer.subarray(0,s+t.byteLength))}input(e){return(q(this,Vt)??pe(this,Vt,new kr(this))).handle(e)}get state(){return this.serializer.getState()}removeAllListeners(){this.onJoin.clear(),this.onStateChange.clear(),this.onError.clear(),this.onLeave.clear(),this.onReconnect.clear(),this.onDrop.clear(),this.onMessageHandlers.events={},this.serializer instanceof Or&&(this.serializer.decoder.root.callbacks={})}onMessageCallback(e){Pn(this,jt,nh).call(this,new Uint8Array(e.data))}dispatchMessage(e,t){let r=this.getMessageHandlerKey(e);this.onMessageHandlers.events[r]?this.onMessageHandlers.emit(r,t):this.onMessageHandlers.events["*"]?this.onMessageHandlers.emit("*",e,t):r.startsWith("__")||console.warn?.(`@colyseus/sdk: onMessage() not registered for type '${e}'.`)}destroy(){this.serializer&&this.serializer.teardown()}getMessageHandlerKey(e){switch(typeof e){case"string":return e;case"number":return`i${e}`;default:throw new Error("invalid message type.")}}handleReconnection(e,t){if(!this.reconnection.enabled){this.onLeave.invoke(e,t);return}if(Date.now()-this.joinedAtTime<this.reconnection.minUptime){console.info(`[Colyseus reconnection]: ${String.fromCodePoint(10060)} Room has not been up for long enough for automatic reconnection. (min uptime: ${this.reconnection.minUptime}ms)`),this.onLeave.invoke(Ne.ABNORMAL_CLOSURE,"Room uptime too short for reconnection.");return}this.reconnection.isReconnecting||(this.reconnection.retryCount=0,this.reconnection.isReconnecting=!0,q(this,Vt)?.reset()),this.retryReconnection()}retryReconnection(){if(this.reconnection.retryCount>=this.reconnection.maxRetries){console.info(`[Colyseus reconnection]: ${String.fromCodePoint(10060)} \u274C Reconnection failed after ${this.reconnection.maxRetries} attempts.`),this.reconnection.isReconnecting=!1,this.onLeave.invoke(Ne.FAILED_TO_RECONNECT,"No more retries. Reconnection failed.");return}this.reconnection.retryCount++;let e=Math.min(this.reconnection.maxDelay,Math.max(this.reconnection.minDelay,this.reconnection.backoff(this.reconnection.retryCount,this.reconnection.delay)));console.info(`[Colyseus reconnection]: ${String.fromCodePoint(9203)} will retry in ${(e/1e3).toFixed(1)} seconds...`),setTimeout(()=>{try{console.info(`[Colyseus reconnection]: ${String.fromCodePoint(128260)} Re-establishing sessionId '${this.sessionId}' with roomId '${this.roomId}'... (attempt ${this.reconnection.retryCount} of ${this.reconnection.maxRetries})`),this.connection.reconnect({reconnectionToken:this.reconnectionToken.split(":")[1],skipHandshake:!0})}catch{this.retryReconnection()}},e)}};Gs=new WeakMap,Pr=new WeakMap,Mr=new WeakMap,$t=new WeakMap,Vt=new WeakMap,Dr=new WeakMap,jt=new WeakSet,Zf=function(){let e=q(this,Mr);return pe(this,Mr,q(this,Mr)+1>>>0),e},eh=function(e,t,r){let s={offset:1};this.sharedBuffer[0]=_e.ROOM_REQUEST,Q.number(this.sharedBuffer,e,s),typeof t=="string"?Q.string(this.sharedBuffer,t,s):Q.number(this.sharedBuffer,t,s);let i=s.offset;if(r!==void 0){let o=this.packr.pack(r,Cr|i);return o.set(this.sharedBuffer.subarray(0,i),0),o}return this.sharedBuffer.subarray(0,i)},th=function(e){if(q(this,$t).size!==0){for(let t of q(this,$t).values())t.onClose?.(e);q(this,$t).clear()}},nh=function(e){var i;let t={offset:1},r=e[0],s=r&Xa;if(r&mr.TIMED){let o=te.uint32(e,t),a=te.uint32(e,t),c=q(this,Vt)?q(this,Vt).ackInput(a):-1;this.clock.sample(o,c)}if(s===_e.JOIN_ROOM){let o=te.utf8Read(e,t,e[t.offset++]);if(this.serializerId=te.utf8Read(e,t,e[t.offset++]),!this.serializer){let u=Vc(this.serializerId);this.serializer=new u}let a=te.number(e,t);if(a>0&&this.serializer.handshake){let u=t.offset+a;this.serializer.handshake(e.subarray(0,u),t),t.offset=u}for(;t.offset<e.byteLength;){let u=e[t.offset++],d=te.number(e,t),h=t.offset+d;u===Fi.INPUT_REFLECTION?(q(this,Vt)??pe(this,Vt,new kr(this))).applyReflection(e,t,h):u===Fi.INPUT_OPTIONS&&(q(this,Vt)??pe(this,Vt,new kr(this))).applyOptions(e,t),t.offset=h}let c=q(this,Vt)?.patchRate;if(c!==void 0&&this.clock.setPatchInterval?.(c),this.joinedAtTime===0?(this.joinedAtTime=Date.now(),this.onJoin.invoke()):(console.info(`[Colyseus reconnection]: ${String.fromCodePoint(9989)} reconnection successful!`),this.reconnection.isReconnecting=!1,this.onReconnect.invoke()),this.reconnectionToken=`${this.roomId}:${o}`,this.sharedBuffer[0]=_e.JOIN_ROOM,this.connection.send(this.sharedBuffer.subarray(0,1)),this.reconnection.enqueuedMessages.length>0){for(let u of this.reconnection.enqueuedMessages)this.connection.send(u.data);this.reconnection.enqueuedMessages=[]}}else if(s===_e.ERROR){let o=te.number(e,t),a=te.string(e,t);this.onError.invoke(o,a)}else if(s===_e.LEAVE_ROOM)this.leave();else if(s===_e.ROOM_STATE)pe(this,Dr,0),this.serializer.setState(e,t),this.onStateChange.invoke(this.serializer.getState());else if(s===_e.ROOM_STATE_PATCH){if(r&mr.UNRELIABLE){let o=te.uint16(e,t);if(o-q(this,Dr)<<16>>16<=0)return;pe(this,Dr,o)}this.serializer.patch(e,t),this.onStateChange.invoke(this.serializer.getState())}else if(s===_e.ROOM_DATA){let o=te.stringCheck(e,t)?te.string(e,t):te.number(e,t),a=e.byteLength>t.offset?xo(e,{start:t.offset}):void 0;this.dispatchMessage(o,a)}else if(s===_e.ROOM_DATA_BYTES){let o=te.stringCheck(e,t)?te.string(e,t):te.number(e,t);this.dispatchMessage(o,e.subarray(t.offset))}else if(s===_e.ROOM_RESPONSE){let o=te.number(e,t),a=e[t.offset++],c=e.byteLength>t.offset?xo(e,{start:t.offset}):void 0,u=q(this,$t).get(o);u!==void 0&&(q(this,$t).delete(o),u.onReply(a===Ui.OK,c,a===Ui.ERROR))}else s===_e.PING&&((i=q(this,Pr))==null||i.call(this,Math.round($e()-q(this,Gs))),pe(this,Pr,void 0))},l(Oo,"defaultRequestTimeout",1e4);var Hs=Oo;function rh(n,e){return new Promise((t,r)=>{let s=new XMLHttpRequest,i=e?.method||"GET";s.open(i,n.toString()),s.withCredentials=e?.credentials==="include",e?.headers&&(e.headers instanceof Headers?e.headers:new Headers(e.headers)).forEach((a,c)=>{s.setRequestHeader(c,a)}),s.onload=()=>{let o=new Headers,a=s.getAllResponseHeaders().trim();if(a)for(let u of a.split(/[\r\n]+/)){let d=u.indexOf(": ");d>0&&o.append(u.substring(0,d),u.substring(d+2))}let c=s.response??s.responseText;t(new Gc(c,{status:s.status,statusText:s.statusText,headers:o}))},s.onerror=()=>r(new TypeError("Network request failed")),s.ontimeout=()=>r(new TypeError("Network request timed out")),s.send(e?.body??null)})}var Gc=class{constructor(e,t){l(this,"status");l(this,"statusText");l(this,"headers");l(this,"ok");l(this,"body");this.body=e,this.status=t.status,this.statusText=t.statusText,this.headers=t.headers,this.ok=t.status>=200&&t.status<300}async json(){return typeof this.body=="string"?JSON.parse(this.body):this.body}async text(){return typeof this.body=="string"?this.body:JSON.stringify(this.body)}async blob(){return new Blob([this.body])}};function m0(n){if(n===void 0)return!1;let e=typeof n;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(n)?!0:n.buffer?!1:n.constructor&&n.constructor.name==="Object"||typeof n.toJSON=="function"}function g0(n,e){let{params:t,query:r}=e||{},[s,i]=n.split("?"),o=s;if(t)if(Array.isArray(t)){let u=o.split("/").filter(d=>d.startsWith(":"));for(let[d,h]of u.entries()){let m=t[d];o=o.replace(h,m)}}else for(let[u,d]of Object.entries(t))o=o.replace(`:${u}`,String(d));let a=new URLSearchParams(i);if(r)for(let[u,d]of Object.entries(r))d!=null&&a.set(u,String(d));let c=a.toString();return c=c.length>0?`?${c}`.replace(/\+/g,"%20"):"",`${o}${c}`}var Po=class{constructor(e,t,r){l(this,"authToken");l(this,"options");l(this,"sdk");l(this,"_fetchFn");l(this,"del",this.delete);this.sdk=e,this.options=t,this._fetchFn=r}get fetchFn(){return this._fetchFn||(this._fetchFn=typeof globalThis.fetch<"u"?globalThis.fetch.bind(globalThis):rh),this._fetchFn}async request(e,t,r){return this.executeRequest(e,t,r)}get(e,t){return this.request("GET",e,t)}post(e,t){return this.request("POST",e,t)}delete(e,t){return this.request("DELETE",e,t)}patch(e,t){return this.request("PATCH",e,t)}put(e,t){return this.request("PUT",e,t)}async executeRequest(e,t,r){let s=this.options.body?{...this.options.body,...r?.body||{}}:r?.body,i=this.options.query?{...this.options.query,...r?.query||{}}:r?.query,o=this.options.params?{...this.options.params,...r?.params||{}}:r?.params,a=new Headers(this.options.headers?{...this.options.headers,...r?.headers||{}}:r?.headers);if(this.authToken&&!a.has("authorization")&&a.set("authorization",`Bearer ${this.authToken}`),m0(s)&&typeof s=="object"&&s!==null){a.has("content-type")||a.set("content-type","application/json");for(let[g,p]of Object.entries(s))p instanceof Date&&(s[g]=p.toISOString());s=JSON.stringify(s)}let c={credentials:r?.credentials||"include",...this.options,...r,query:i,params:o,headers:a,body:s,method:e},u=g0(this.sdk.getHttpEndpoint(t.toString()),c),d;try{d=await this.fetchFn(u,c)}catch(g){if(g.name==="AbortError")throw g;let p=new Ot(g.cause?.code||g.code,g.message);throw p.response=d,p.cause=g.cause,p}let h=d.headers.get("content-type"),m;if(h?.includes("json")?m=await d.json():h?.includes("text")?m=await d.text():m=await d.blob(),!d.ok)throw new Ot(d.status,m.message??m.error??d.statusText,{headers:d.headers,status:d.status,response:d,data:m});return{raw:d,data:m,headers:d.headers,status:d.status,statusText:d.statusText}}};var Yn;function zc(){if(!Yn)try{Yn=typeof cc<"u"&&cc.sys&&cc.sys.localStorage?cc.sys.localStorage:window.localStorage}catch{}return!Yn&&typeof globalThis.indexedDB<"u"&&(Yn=new qc),Yn||(Yn={cache:{},setItem:function(n,e){this.cache[n]=e},getItem:function(n){return this.cache[n]},removeItem:function(n){delete this.cache[n]}}),Yn}function sh(n,e){zc().setItem(n,e)}function ih(n){zc().removeItem(n)}function oh(n,e){let t=zc().getItem(n);typeof Promise>"u"||!(t instanceof Promise)?e(t):t.then(r=>e(r))}var qc=class{constructor(){l(this,"dbPromise",new Promise(e=>{let t=indexedDB.open("_colyseus_storage",1);t.onupgradeneeded=()=>t.result.createObjectStore("store"),t.onsuccess=()=>e(t.result)}))}async tx(e,t){let s=(await this.dbPromise).transaction("store",e).objectStore("store");return t(s)}setItem(e,t){return this.tx("readwrite",r=>r.put(t,e)).then()}async getItem(e){let t=await this.tx("readonly",r=>r.get(e));return new Promise(r=>{t.onsuccess=()=>r(t.result)})}removeItem(e){return this.tx("readwrite",t=>t.delete(e)).then()}};var zs,sn,Ws,qs=class{constructor(e){l(this,"settings",{path:"/auth",key:"colyseus-auth-token"});he(this,zs,!1);he(this,sn,null);he(this,Ws,Co());l(this,"http");this.http=e,oh(this.settings.key,t=>this.token=t)}set token(e){this.http.authToken=e}get token(){return this.http.authToken}onChange(e){let t=q(this,Ws).on("change",e);return q(this,zs)||this.getUserData().then(r=>{this.emitChange({...r,token:this.token})}).catch(r=>{this.emitChange({user:null,token:void 0})}),pe(this,zs,!0),t}async getUserData(){if(this.token)return(await this.http.get(`${this.settings.path}/userdata`)).data;throw new Error("missing auth.token")}async registerWithEmailAndPassword(e,t,r){let s=(await this.http.post(`${this.settings.path}/register`,{body:{email:e,password:t,options:r}})).data;return this.emitChange(s),s}async signInWithEmailAndPassword(e,t){let r=(await this.http.post(`${this.settings.path}/login`,{body:{email:e,password:t}})).data;return this.emitChange(r),r}async signInAnonymously(e){let t=(await this.http.post(`${this.settings.path}/anonymous`,{body:{options:e}})).data;return this.emitChange(t),t}async sendPasswordResetEmail(e){return(await this.http.post(`${this.settings.path}/forgot-password`,{body:{email:e}})).data}async signInWithProvider(e,t={}){return new Promise((r,s)=>{let i=t.width||480,o=t.height||768,a=this.token?`?token=${this.token}`:"",c=`Login with ${e[0].toUpperCase()+e.substring(1)}`,u=this.http.sdk.getHttpEndpoint(`${t.prefix||`${this.settings.path}/provider`}/${e}${a}`),d=screen.width/2-i/2,h=screen.height/2-o/2;pe(this,sn,window.open(u,c,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width="+i+", height="+o+", top="+h+", left="+d));let m=p=>{if(!(p.data.user===void 0&&p.data.token===void 0))if(clearInterval(g),q(this,sn)?.close(),pe(this,sn,null),window.removeEventListener("message",m),p.data.error!==void 0){let y=new Error(String(p.data.error));y.code=p.data.error,p.data.reason!==void 0&&(y.reason=p.data.reason),p.data.until!==void 0&&(y.until=p.data.until),s(y)}else r(p.data),this.emitChange(p.data)},g=setInterval(()=>{(!q(this,sn)||q(this,sn).closed)&&(pe(this,sn,null),s("cancelled"),window.removeEventListener("message",m))},200);window.addEventListener("message",m)})}async signOut(){this.emitChange({user:null,token:null})}emitChange(e){e.token!==void 0&&(this.token=e.token,e.token===null?ih(this.settings.key):sh(this.settings.key,e.token)),q(this,Ws).emit("change",e)}};zs=new WeakMap,sn=new WeakMap,Ws=new WeakMap;function ah(n){let e=window?.location?.hostname||"localhost",t=n.hostname.split("."),r=!n.hostname.includes("trycloudflare.com")&&!n.hostname.includes("discordsays.com")&&t.length>2?`/${t[0]}`:"";return n.pathname.startsWith("/.proxy")?`${n.protocol}//${e}${r}${n.pathname}${n.search}`:`${n.protocol}//${e}/.proxy/colyseus${r}${n.pathname}${n.search}`}ks();var ch=typeof window<"u"&&typeof window?.location?.hostname<"u"?`${window.location.protocol.replace("http","ws")}//${window.location.hostname}${window.location.port&&`:${window.location.port}`}`:"ws://127.0.0.1:2567",Do=class Do{constructor(e=ch,t){l(this,"http");l(this,"auth");l(this,"settings");l(this,"urlBuilder");if(typeof e=="string"){let r=e.startsWith("/")?new URL(e,ch):new URL(e),s=r.protocol==="https:"||r.protocol==="wss:",i=Number(r.port||(s?443:80));this.settings={hostname:r.hostname,pathname:r.pathname,port:i,secure:s,searchParams:r.searchParams.toString()||void 0}}else e.port===void 0&&(e.port=e.secure?443:80),e.pathname===void 0&&(e.pathname=""),this.settings=e;this.settings.pathname.endsWith("/")&&(this.settings.pathname=this.settings.pathname.slice(0,-1)),t?.protocol&&(this.settings.protocol=t.protocol),this.http=new Po(this,{headers:t?.headers||{}},t?.fetchFn),this.auth=new qs(this.http),this.urlBuilder=t?.urlBuilder,!this.urlBuilder&&typeof window<"u"&&window?.location?.hostname?.includes("discordsays.com")&&(this.urlBuilder=ah,console.log("Colyseus SDK: Discord Embedded SDK detected. Using custom URL builder."))}static async selectByLatency(e,t,r={}){let s=e.map(o=>new Do(o,t)),i=(await Promise.allSettled(s.map((o,a)=>o.getLatency(r).then(c=>{let u=s[a].settings;return console.log(`\u{1F6DC} Endpoint Latency: ${c}ms - ${u.hostname}:${u.port}${u.pathname}`),[a,c]})))).filter(o=>o.status==="fulfilled").map(o=>o.value);if(i.length===0)throw new Error("All endpoints failed to respond");return s[i.sort((o,a)=>o[1]-a[1])[0][0]]}async joinOrCreate(e,t={},r){return await this.createMatchMakeRequest("joinOrCreate",e,t,r)}async create(e,t={},r){return await this.createMatchMakeRequest("create",e,t,r)}async join(e,t={},r){return await this.createMatchMakeRequest("join",e,t,r)}async joinById(e,t={},r){return await this.createMatchMakeRequest("joinById",e,t,r)}async reconnect(e,t){if(typeof e=="string"&&typeof t=="string")throw new Error("DEPRECATED: .reconnect() now only accepts 'reconnectionToken' as argument.\nYou can get this token from previously connected `room.reconnectionToken`");let[r,s]=e.split(":");if(!r||!s)throw new Error(`Invalid reconnection token format.
|
|
13
|
+
The format should be roomId:reconnectionToken`);return await this.createMatchMakeRequest("reconnect",r,{reconnectionToken:s},t)}async consumeSeatReservation(e,t){let r=this.createRoom(e.name,t);r.roomId=e.roomId,r.sessionId=e.sessionId;let s={sessionId:r.sessionId};return e.reconnectionToken&&(s.reconnectionToken=e.reconnectionToken),r.connect(this.buildEndpoint(e,s),{...e,protocol:this.settings.protocol},this.http.options.headers),new Promise((i,o)=>{let a=(c,u)=>o(new Ot(c,u));r.onError.once(a),r.onJoin.once(()=>{r.onError.remove(a),ho("room",r),i(r)})})}getLatency(e={}){let t=e.protocol??"ws",r=e.pingCount??1,s=e.timeout??1500;return new Promise((i,o)=>{let a=new Ir(t),c=[],u=0,d=!1,h,m=p=>{if(!d){d=!0,clearTimeout(h);try{a.close()}catch{}p()}},g=p=>m(()=>o(new Ot(Ne.ABNORMAL_CLOSURE,`Failed to get latency: ${p}`)));h=setTimeout(()=>g(`timed out after ${s}ms`),s),a.events.onopen=()=>{u=Date.now(),a.send(new Uint8Array([_e.PING]))},a.events.onmessage=p=>{if(c.push(Date.now()-u),c.length<r)u=Date.now(),a.send(new Uint8Array([_e.PING]));else{let y=c.reduce((x,k)=>x+k,0)/c.length;m(()=>i(y))}},a.events.onclose=p=>g(`connection closed${p?.code?` (${p.code})`:""}${p?.reason?`: ${p.reason}`:""}`),a.events.onerror=p=>g(p.message);try{a.connect(this.getHttpEndpoint())}catch(p){g(p?.message??"failed to connect")}})}async createMatchMakeRequest(e,t,r={},s){try{if(!t)throw new Error("Must provide a room name");let o=(await this.http.post(`/matchmake/${e}/${t}`,{headers:{Accept:"application/json","Content-Type":"application/json"},body:r})).data;return e==="reconnect"&&(o.reconnectionToken=r.reconnectionToken),await this.consumeSeatReservation(o,s)}catch(i){throw i instanceof Ot?new us(i.message,i.code):i}}createRoom(e,t){return new Hs(e,t)}buildEndpoint(e,t={}){let r=this.settings.protocol||"ws",s=this.settings.searchParams||"";this.http.authToken&&(t._authToken=this.http.authToken);for(let a in t)t.hasOwnProperty(a)&&(s+=(s?"&":"")+`${a}=${t[a]}`);r==="h3"&&(r="http");let i=this.settings.secure?`${r}s://`:`${r}://`;e.publicAddress?i+=`${e.publicAddress}`:i+=`${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}`;let o=`${i}/${e.processId}/${e.roomId}?${s}`;return this.urlBuilder?this.urlBuilder(new URL(o)):o}getHttpEndpoint(e=""){let t=e.startsWith("/")?e:`/${e}`,r=`${this.settings.secure?"https":"http"}://${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}${t}`;return this.settings.searchParams&&(r+=`?${this.settings.searchParams}`),this.urlBuilder?this.urlBuilder(new URL(r)):r}getEndpointPort(){return this.settings.port!==80&&this.settings.port!==443?`:${this.settings.port}`:""}};l(Do,"VERSION","0.18");var Mo=Do,Nr=Mo;Kt();var No=class{setState(e){}getState(){return null}patch(e){}teardown(){}handshake(e){}};qe();tl();$o();Vo();Fo();$c("schema",Or);$c("none",No);var yS=Object.freeze({min:3,max:3}),bS=Object.freeze({min:4,max:4});var Wo={PLAY:"play",QUEUE:"queue",MATCH:"match",AUTHORITY:"authority"};var T0=["clients","preset","winCondition","config","matchmade"],wS=[...T0,"moduleSha","tickHz","maxPlayers","lagComp","seed","units","leaseId","region"],xh={BAD_OPTION:400,AUTH_REQUIRED:401,FORBIDDEN:403,PROTOCOL_UNSUPPORTED:426,NOT_ENTITLED:402,ROOM_QUOTA:429,MODULE_UNAVAILABLE:424,AUTHORITY_CAPACITY:503};var Y={STATE:"state",STATE_SNAP:"__state:snap",SHARED:"shared",CLAIM:"claim",RELEASE:"release",DESTROY:"destroy",OBJECT:"obj",OBJECT_SNAP:"__object:snap",INPUT:"__input",ROOM_OPEN:"__room:open",CHAT:"__chat",CHAT_HISTORY_REQUEST:"__chat:history:request",VOICE_ICE_REQUEST:"__voice:ice:request",VOICE_JOIN:"__voice:join",VOICE_LEAVE:"__voice:leave",VOICE_SIGNAL:"__voice:signal",MATCH_ELIMINATED:"match:eliminated",MATCH_SCORE:"match:score",MATCH_FINISH:"match:finish",POSE:"__pose",POSE_SNAP:"__pose:snap"},ne={OBJECT_RESULT:"__object:result",INPUT:"__input",ROOM_OPEN:"__room:open",CHAT:"__chat",CHAT_HISTORY:"__chat:history",VOICE_ICE:"__voice:ice",VOICE_SIGNAL:"__voice:signal",VOICE_REJECTED:"__voice:rejected",RATE_DROP:"rate:drop",SERVER_RESTART:"server:restart",MATCH_START:"match:start",MATCH_ENDED:"match:ended",MATCH_REQUEUE:"match:requeue",QUEUE:"queue",SEAT:"seat"},k0=["__","match:","server:","rate:"],A0=["state","shared","claim","release","destroy","obj","queue","seat"];function ti(n){return A0.includes(n)||k0.some(e=>n.startsWith(e))}var Yo="__",Gt="__t";var _S={[Y.STATE]:"state",[Y.STATE_SNAP]:"state",[Y.SHARED]:"bulk",[Y.CLAIM]:"control",[Y.RELEASE]:"control",[Y.DESTROY]:"control",[Y.OBJECT]:"bulk",[Y.OBJECT_SNAP]:"bulk",[Y.INPUT]:"input",[Y.ROOM_OPEN]:"control",[Y.CHAT]:"chat",[Y.CHAT_HISTORY_REQUEST]:"control",[Y.VOICE_ICE_REQUEST]:"voice",[Y.VOICE_JOIN]:"voice",[Y.VOICE_LEAVE]:"voice",[Y.VOICE_SIGNAL]:"voice",[Y.MATCH_ELIMINATED]:"bulk",[Y.MATCH_SCORE]:"bulk",[Y.MATCH_FINISH]:"bulk",[Y.POSE]:"pose",[Y.POSE_SNAP]:"pose"},nl={GOING_AWAY:1001,NO_STATUS:1005,ABNORMAL:1006,MAY_TRY_RECONNECT:4010,NORMAL:1e3,CONSENTED:4e3,MATCH_BOOT:4e3,SERVER_SHUTDOWN:4001,WITH_ERROR:4002,FAILED_TO_RECONNECT:4003,REVOKED:4401,SUPERSEDED:4409,MODULE_HALTED:4500,MODULE_FAULT:4501},An={ROOM_MAX_CLIENTS:64,MAX_NAME_CHARS:64,MAX_AVATAR_URL_CHARS:512,MAX_UID_CHARS:64,MAX_STATE_BYTES:16*1024,MAX_SHARED_KEY_CHARS:256,MAX_SHARED_VALUE_BYTES:64*1024,MAX_SHARED_KEYS:256,MAX_OBJECT_ID_CHARS:128,MAX_OBJECT_STATE_BYTES:64*1024,MAX_OBJECTS:128,MAX_REQUEST_ID_CHARS:96,MAX_EVENT_BYTES:16*1024,MAX_EVENT_TYPE_CHARS:128,MAX_JSON_DEPTH:32,MAX_JSON_NODES:4096,MAX_CHAT_CHARS:500,CHAT_HISTORY_MAX:50,CHAT_HISTORY_MAX_BYTES:8*1024,MAX_VOICE_PARTICIPANTS:6,MAX_VOICE_SIGNAL_BYTES:8*1024,MAX_SCORE_DELTA:1e3,CONTROL_RESULTS_PER_SESSION:128,CONTROL_RESULT_TTL_MS:6e4,MAX_TEAMS:8,MAX_ANIM_CHARS:64,MAX_POSE_ABS:1e9},ES={PATCH_INTERVAL_MS:1e3/30,RECONNECT_GRACE_S:30,GOING_AWAY_GRACE_S:5,HOST_FAILOVER_GRACE_MS:1500,MIN_OWNERSHIP_HOLD_MS:300,SHUTDOWN_DRAIN_MS:3e3,REQUEUE_GRACE_MS:5e3,SEAT_RESERVATION_S:15,QUEUE_TICK_MS:1e3,REVOCATION_SWEEP_MS:3e4};var qt={enabled:!0,minUptime:0,delay:125,minDelay:100,maxDelay:4e3,maxRetries:9,maxEnqueuedMessages:0,firstStateTimeoutMs:2e3},Sh=["x","y","z","yaw","vx","vy","vz","anim"],ye={RATIO:1.5,JITTER_SAFETY:1.25,MIN_MS:90,MAX_MS:300,DEFAULT_MS:100,EASE:.1,CLOCK_WINDOW:80,CLOCK_WINDOW_MS:5e3,CLOCK_WINDOW_MAX:4096,INTERVAL_WINDOW:30,MIN_GAP_MS:5,MAX_GAP_MS:2e3,HISTORY_MS:1500,MAX_EXTRAP_MS:250,ROT_EXTRAP_MS:150,SMOOTH_TAU_POS_MS:30,SMOOTH_TAU_ROT_MS:70,POISON_GUARD_MS:2e3,REBASE_AFTER_GAP_MS:1e3,MAX_HOST_TICK_DT_MS:250},an={HEARTBEAT_HZ:10,MIN_HEARTBEAT_HZ:5,MAX_HEARTBEAT_HZ:20,HEARTBEAT_DITHER:.15,RELAY_BUFFER:4,WARMUP_ACKS:30};var rl={SAMPLES:3,TIMEOUT_MS:4e3,GRACE_MS:1e3};async function Th(n,e={}){let t=n[0];if(t===void 0)throw new Error("genex multiplayer: `urls` must contain at least one relay URL");if(n.length===1)return t;let r=e.probe??v0,s=Math.max(1,e.samples??rl.SAMPLES),i=e.timeoutMs??rl.TIMEOUT_MS,o=e.graceMs??rl.GRACE_MS,a=n.map(()=>{});await new Promise(u=>{let d=n.length*s,h,m=setTimeout(g,i);function g(){clearTimeout(m),clearTimeout(h),u()}let p=()=>{--d===0&&g()};n.forEach((y,x)=>{for(let k=0;k<s;k++){let I;try{I=r(y,i)}catch(B){I=Promise.reject(B)}I.then(B=>{Number.isFinite(B)&&B>=0&&(a[x]=Math.min(a[x]??1/0,B),h??(h=setTimeout(g,o))),p()},p)}})});let c=-1;return a.forEach((u,d)=>{u!==void 0&&(c<0||u<a[c])&&(c=d)}),c<0?(console.warn(`genex multiplayer: no relay answered the latency probe \u2014 connecting to ${t}`),t):n[c]}var v0=(n,e)=>new Nr(n).getLatency({pingCount:1,timeout:e});var C0=n=>typeof n=="function"?n():n;async function ni(n){return n.url?new Nr(n.url):new Nr(await Th(n.urls))}function sl(n,e,t){return{gameId:n,name:e,embedToken:C0(t)?.embedToken,protocol:3}}var il=n=>!!n&&typeof n=="object"&&n.code===xh.PROTOCOL_UNSUPPORTED,ol=()=>console.error(`[multiplayer] the relay refused protocol ${3} (code 426) \u2014 this game was built with a @genex-ai/multiplayer that this relay no longer serves. Update the package and republish.`),kh=n=>{throw il(n)&&ol(),n};function Ah(n,e){let t=null,r=null;return{request(){return t||(t=new Promise(s=>{let i,o=a=>{r&&(r=null,t=null,i&&clearTimeout(i),s(a))};r=o,i=setTimeout(()=>o(null),e),n()}),t)},deliver(s){r?.(s)},get pending(){return t!==null}}}var vh=["x","y","z","yaw","vx","vy","vz"],Ch=[["x","vx"],["y","vy"],["z","vz"]],al=Math.PI*2,I0=n=>Sh.includes(n);function cl(n){if(!Number.isFinite(n))return 0;let e=n%al;return e<=-Math.PI?e+=al:e>Math.PI&&(e-=al),e}var Ih=n=>typeof n=="number"&&Number.isFinite(n)&&Math.abs(n)<=An.MAX_POSE_ABS;function Oh(n){let e={},t={},r=[];for(let s of Object.keys(n)){let i=n[s];if(!I0(s)){t[s]=i;continue}i!==void 0&&(s==="anim"?typeof i=="string"&&i.length<=An.MAX_ANIM_CHARS?e.anim=i:r.push(s):Ih(i)?e[s]=i:r.push(s))}return{pose:e,data:t,invalid:r}}function Ph(n){for(let e in n)if(n[e]!==void 0)return!0;return!1}function Mh(n,e,t){let r={...n},s={t:e},i=t?e-t.t:0,o=t!==void 0&&i>ye.MIN_GAP_MS&&i<ye.MAX_GAP_MS;for(let[a,c]of Ch){let u=n[a];if(u===void 0||(s[a]=u,n[c]!==void 0))continue;let d=t?.[a],h=o&&d!==void 0?(u-d)/i*1e3:0;r[c]=Ih(h)?h:0}return{pose:r,memory:s}}function Qo(n){let e=t=>typeof t=="number"&&Number.isFinite(t)?t:0;return{x:e(n.x),y:e(n.y),z:e(n.z),yaw:e(n.yaw),vx:e(n.vx),vy:e(n.vy),vz:e(n.vz),anim:typeof n.anim=="string"?n.anim:""}}var Yr=(n,e)=>{let t=n[e];return typeof t=="number"&&Number.isFinite(t)?t:0};function Dh(n,e){let t=n.length;if(t===0)return;let r=0;for(;r<t&&n[r].t<=e;)r++;if(r===0)return n[0].state;if(r>=t){let u=n[t-1],d={...u.state},h=Math.min(Math.max(0,e-u.t),ye.MAX_EXTRAP_MS)/1e3;for(let[m,g]of Ch)d[m]=Yr(u.state,m)+Yr(u.state,g)*h;if(t>=2){let m=n[t-2],g=u.t-m.t;if(g>0){let p=Math.min(Math.max(0,e-u.t),ye.ROT_EXTRAP_MS)/g,y=Yr(u.state,"yaw");d.yaw=y+cl(y-Yr(m.state,"yaw"))*p}}return d}let s=n[r-1],i=n[r],o=i.t-s.t,a=o>0?(e-s.t)/o:1,c={...s.state};for(let u of vh){let d=Yr(s.state,u),h=Yr(i.state,u);c[u]=u==="yaw"?d+cl(h-d)*a:d+(h-d)*a}return c}function Nh(n,e,t,r){let s={...e};for(let i of vh){let o=n[i],a=e[i];typeof o!="number"||typeof a!="number"||!Number.isFinite(o)||!Number.isFinite(a)||(s[i]=i==="yaw"?o+cl(a-o)*r:o+(a-o)*t)}return s}var Xo=class Xo{constructor(){l(this,"pending",[]);l(this,"current")}push(e,t){for(this.pending.push({t:e,state:t});this.pending.length>Xo.MAX_PENDING;)this.current=this.pending.shift()?.state}at(e){for(;this.pending.length>0;){let t=this.pending[0];if(this.current!==void 0&&e!==void 0&&t.t!==void 0&&t.t>e)break;this.current=t.state,this.pending.shift()}return this.current}flush(){this.at(void 0)}};l(Xo,"MAX_PENDING",64);var Ko=Xo;function Lh(n){try{let e=n.input();return e&&typeof e.send=="function"?e:null}catch{return null}}function Bh(n,e,t=an.HEARTBEAT_HZ,r=Math.random){let i=1e3/Math.min(an.MAX_HEARTBEAT_HZ,Math.max(an.MIN_HEARTBEAT_HZ,t)),o=1e3/an.MAX_HEARTBEAT_HZ,a=1e3/an.MIN_HEARTBEAT_HZ,c=!1,u=!1,d,h=()=>{if(u)return;if(e()){try{n.send()}catch{}!c&&n.lastProcessed>=an.WARMUP_ACKS&&(c=!0)}let m=i*(1+(r()*2-1)*an.HEARTBEAT_DITHER);d=setTimeout(h,Math.min(a,Math.max(o,m)))};return h(),{get synced(){return!c&&n.lastProcessed>=an.WARMUP_ACKS&&(c=!0),c},stop(){u=!0,d&&clearTimeout(d)}}}function Uh(n,e){return e.synced&&e.clockOrigin>0&&e.serverNow!==void 0&&Number.isFinite(e.serverNow)?n-e.clockOrigin-e.serverNow:n-e.wallNow}function ri(n){let e=n.reconnection;return e.enabled=qt.enabled,e.minUptime=qt.minUptime,e.delay=qt.delay,e.minDelay=qt.minDelay,e.maxDelay=qt.maxDelay,e.maxRetries=qt.maxRetries,e.maxEnqueuedMessages=qt.maxEnqueuedMessages,e.enqueuedMessages.length=0,n}function Fh(n){return n.reconnection.enabled=!1,n}function $h(n,e){return new Promise(t=>{let r=()=>{clearTimeout(s),t(!0)},s=setTimeout(()=>{n.onStateChange.remove(r),t(!1)},e);n.onStateChange.once(r)})}function Vh(n,e,t){return n!==e&&t!=null}var O0="The microphone was refused by the page that frames this game, not by the player: the frame was not given it, so the browser never asked. On its Genex page a build is given the microphone only when it declares it. An up-to-date genex CLI declares it at `genex preview` and `genex publish` when the game's own source calls voice.join(); to declare it by hand, add \"microphone\" to genex.capabilities in the game's package.json. Then preview or publish again.",ll=class extends Error{constructor(e){super(O0,{cause:e}),this.name="VoiceNotDelegatedError"}},jh=[{urls:"stun:stun.l.google.com:19302"}],P0=120,Hh=.02,M0=.6,Zo=class{constructor(e){l(this,"transport");l(this,"peers",new Map);l(this,"listeners",new Set);l(this,"roster",[]);l(this,"local",null);l(this,"audio",null);l(this,"localAnalyser",null);l(this,"levelTimer",null);l(this,"iceServers",jh);l(this,"spatial",!1);l(this,"threshold",Hh);l(this,"micOn",!0);l(this,"selfSpeaking",!1);l(this,"running",!1);l(this,"peeringHeld",!1);this.transport=e}get active(){return this.running}get micEnabled(){return this.micOn}get speaking(){return this.selfSpeaking}get participants(){return[...this.peers.values()].map(e=>({id:e.id,name:this.transport.nameOf(e.id),stream:e.stream,speaking:e.speaking,muted:e.muted,volume:e.volume,connection:e.connection}))}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async start(e={},t=!1){if(!this.running){this.peeringHeld=t,this.iceServers=e.iceServers?.length?e.iceServers:jh,this.spatial=e.spatial===!0,this.threshold=e.speakingThreshold??Hh,this.micOn=e.startMuted!==!0;try{this.local=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1})}catch(r){throw N0(r)}for(let r of this.local.getAudioTracks())r.enabled=this.micOn;this.audio=new AudioContext,this.localAnalyser=this.makeAnalyser(this.local),this.running=!0,this.levelTimer=setInterval(()=>this.pollLevels(),P0)}}stop(){this.running=!1,this.peeringHeld=!1,this.levelTimer&&(clearInterval(this.levelTimer),this.levelTimer=null);for(let e of[...this.peers.keys()])this.destroyPeer(e);for(let e of this.local?.getTracks()??[])e.stop();this.local=null,this.localAnalyser=null,this.audio?.close().catch(()=>{}),this.audio=null,this.roster=[],this.selfSpeaking=!1,this.emit()}setIceServers(e){if(e.length){this.iceServers=e;for(let t of this.peers.values())try{t.pc.setConfiguration({iceServers:e})}catch{}}}releasePeering(){this.peeringHeld&&(this.peeringHeld=!1,this.setRoster(this.roster))}setRoster(e){if(this.roster=e,!this.running||this.peeringHeld)return;let t=this.transport.selfId(),r=new Set(e.filter(s=>s!==t));for(let s of r)this.peers.has(s)||this.createPeer(s);for(let s of[...this.peers.keys()])r.has(s)||this.destroyPeer(s);this.emit()}setMicEnabled(e){this.micOn=e;for(let t of this.local?.getAudioTracks()??[])t.enabled=e;!e&&this.selfSpeaking&&(this.selfSpeaking=!1,this.emit())}mute(e){this.setMuted(e,!0)}unmute(e){this.setMuted(e,!1)}setVolume(e,t){let r=this.peers.get(e);r&&(r.volume=Math.max(0,Math.min(1,t)),r.el&&(r.el.volume=r.volume),this.emit())}async handleSignal(e,t){if(!this.running)return;let r=t;if(!r||typeof r!="object"||typeof r.t!="string")return;let s=this.peers.get(e)??(this.roster.includes(e)?this.createPeer(e):void 0);if(s)try{if(r.t==="offer"){await s.pc.setRemoteDescription(r.sdp),await this.flushIce(s);let i=await s.pc.createAnswer();await s.pc.setLocalDescription(i),this.transport.sendSignal(e,{t:"answer",sdp:i})}else if(r.t==="answer"){if(s.pc.signalingState!=="have-local-offer")return;await s.pc.setRemoteDescription(r.sdp),await this.flushIce(s)}else r.t==="ice"&&(s.pc.remoteDescription?await s.pc.addIceCandidate(r.c):s.pendingIce.push(r.c))}catch(i){console.warn(`[multiplayer] voice signaling failed with ${e}`,i)}}setMuted(e,t){let r=this.peers.get(e);!r||r.muted===t||(r.muted=t,r.el&&(r.el.muted=t||this.spatial),t&&r.speaking&&(r.speaking=!1),this.emit())}createPeer(e){let t=new RTCPeerConnection({iceServers:this.iceServers}),r={id:e,pc:t,el:null,stream:null,analyser:null,pendingIce:[],speaking:!1,muted:!1,volume:1,connection:"connecting"};this.peers.set(e,r);for(let s of this.local?.getAudioTracks()??[])this.local&&t.addTrack(s,this.local);return t.onicecandidate=s=>{s.candidate&&this.transport.sendSignal(e,{t:"ice",c:s.candidate.toJSON()})},t.ontrack=s=>{let i=s.streams[0]??new MediaStream([s.track]);r.stream=i,r.el=this.attachSink(i,r),r.analyser=this.makeAnalyser(i),this.emit()},t.onconnectionstatechange=()=>{let s=t.connectionState,i=s==="connected"?"connected":s==="failed"||s==="closed"?"failed":"connecting";if(i!==r.connection){if(r.connection=i,i==="failed"){let o=this.iceServers.some(a=>L0(a));console.warn(`[multiplayer] voice connection to ${e} failed`+(o?"":" \u2014 no TURN in the ICE list (relay offered none?)"))}this.emit()}},this.transport.selfId()<e&&this.offer(r),r}async offer(e){try{let t=await e.pc.createOffer();await e.pc.setLocalDescription(t),this.transport.sendSignal(e.id,{t:"offer",sdp:t})}catch(t){console.warn(`[multiplayer] voice offer to ${e.id} failed`,t)}}async flushIce(e){let t=e.pendingIce.splice(0);for(let r of t)try{await e.pc.addIceCandidate(r)}catch{}}destroyPeer(e){let t=this.peers.get(e);if(t){this.peers.delete(e),t.pc.onicecandidate=null,t.pc.ontrack=null,t.pc.onconnectionstatechange=null;try{t.pc.close()}catch{}t.el&&(t.el.srcObject=null,t.el.remove())}}attachSink(e,t){let r=document.createElement("audio");return r.autoplay=!0,r.srcObject=e,r.muted=this.spatial||t.muted,r.volume=t.volume,r.style.display="none",document.body.appendChild(r),r.play().catch(s=>{console.warn("[multiplayer] voice playback was blocked \u2014 join voice from a click/tap",s)}),r}makeAnalyser(e){if(!this.audio)return null;try{let t=this.audio.createMediaStreamSource(e),r=this.audio.createAnalyser();return r.fftSize=512,t.connect(r),r}catch{return null}}pollLevels(){let e=!1,t=this.micOn?Gh(this.localAnalyser):0,r=this.crossed(t,this.selfSpeaking);r!==this.selfSpeaking&&(this.selfSpeaking=r,e=!0);for(let s of this.peers.values()){let i=s.muted?!1:this.crossed(Gh(s.analyser),s.speaking);i!==s.speaking&&(s.speaking=i,e=!0)}e&&this.emit()}crossed(e,t){return e>=(t?this.threshold*M0:this.threshold)}emit(){for(let e of[...this.listeners])try{e()}catch(t){console.error("[multiplayer] a voice listener threw",t)}}};function D0(){try{return window.self!==window.top}catch{return!0}}function N0(n){if(n?.name!=="NotAllowedError")return n;try{if(!D0()||document.featurePolicy?.allowsFeature?.("microphone")!==!1)return n}catch{return n}return new ll(n)}function L0(n){return(Array.isArray(n.urls)?n.urls:[n.urls]).some(t=>typeof t=="string"&&t.startsWith("turn"))}function Gh(n){if(!n)return 0;let e=new Uint8Array(n.fftSize);n.getByteTimeDomainData(e);let t=0;for(let r=0;r<e.length;r++){let s=((e[r]??128)-128)/128;t+=s*s}return Math.sqrt(t/e.length)}var ul=Symbol("genex.roomRef"),cn=n=>n[ul]();var B0=ye.RATIO,U0=ye.MIN_MS,F0=ye.MAX_MS,ea=ye.DEFAULT_MS,$0=ye.JITTER_SAFETY,V0=ye.POISON_GUARD_MS,j0=ye.EASE,H0=ye.MAX_EXTRAP_MS,G0=ye.ROT_EXTRAP_MS,Wh=ye.CLOCK_WINDOW,q0=ye.CLOCK_WINDOW_MS,z0=ye.CLOCK_WINDOW_MAX,W0=ye.INTERVAL_WINDOW,Y0=ye.MIN_GAP_MS,J0=ye.MAX_GAP_MS,K0=ye.HISTORY_MS,X0=ye.SMOOTH_TAU_POS_MS,Q0=ye.SMOOTH_TAU_ROT_MS,Yh=ye.MAX_HOST_TICK_DT_MS,Z0=ye.REBASE_AFTER_GAP_MS,zt="obj:",eb=3e3,tb=5e3,nb=6e4,rb=2e3;function Xh(n){if(n==="predict")return{mode:"lerp"};if(n&&typeof n=="object"&&n.engine==="predict")return{mode:n.mode==="damped"?"damped":"lerp",delay:n.delay,smoothMs:n.smoothMs}}var ra=async n=>Xh(n)?Promise.resolve().then(()=>(zh(),qh)):void 0;function Jh(n){if(!n)return{state:{}};try{let e=JSON.parse(n);if(!e||typeof e!="object")return{state:{}};let t=e,r=t[Gt];if(typeof r=="number"&&Number.isFinite(r)){let s={...t};return delete s[Gt],{state:s,sendTime:r}}return{state:t}}catch{return{state:{}}}}function ta(n){if(n!=null)try{return JSON.parse(n)}catch{return}}var sb=(n,e)=>typeof e=="number"?Number.isFinite(e)?e:0:typeof e=="bigint"?Number(e):e;function Jr(n){return JSON.parse(JSON.stringify(n,sb))}var er=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function Qh(n,e,t){let[r,s,i,o]=e,[a,c,u,d]=n,h=a*r+c*s+u*i+d*o;if(h<0&&(r=-r,s=-s,i=-i,o=-o,h=-h),h>.9995){let x=a+(r-a)*t,k=c+(s-c)*t,I=u+(i-u)*t,B=d+(o-d)*t,N=Math.hypot(x,k,I,B)||1;return[x/N,k/N,I/N,B/N]}let m=Math.acos(h),g=Math.sin(m),p=Math.sin(m-m*t)/g,y=Math.sin(m*t)/g;return[a*p+r*y,c*p+s*y,u*p+i*y,d*p+o*y]}function na(n){return Array.isArray(n)&&n.length===4&&n.every(e=>typeof e=="number"&&Number.isFinite(e))}function Kh(n,e,t,r){let s={},i=t<1;for(let o in e){let a=n[o],c=e[o];typeof a=="number"&&typeof c=="number"&&Number.isFinite(a)&&Number.isFinite(c)?s[o]=a+(c-a)*t:na(a)&&na(c)?s[o]=Qh(a,c,r):s[o]=i&&o in n?a:c}return s}function ib(n,e,t,r){let s={};for(let i in e){let o=e[i],a=n[i];typeof a=="number"&&typeof o=="number"&&Number.isFinite(a)&&Number.isFinite(o)?s[i]=a+(o-a)*t:na(a)&&na(o)?s[i]=Qh(a,o,r):s[i]=o}return s}function ob(n,e){let t=n.length;if(t===0)return;if(t===1)return n[0].state;let r=0;for(;r<t&&n[r].t<=e;)r++;if(r===0)return n[0].state;if(r>=t){let c=n[t-2],u=n[t-1],d=u.t-c.t;if(d<=0)return u.state;let h=(Math.min(e,u.t+H0)-c.t)/d,m=(Math.min(e,u.t+G0)-c.t)/d;return Kh(c.state,u.state,h,m)}let s=n[r-1],i=n[r],o=i.t-s.t,a=o>0?(e-s.t)/o:1;return Kh(s.state,i.state,a,a)}function ab(n){if(n.length===0)return 66;let e=[...n].sort((t,r)=>t-r);return e[e.length>>1]}function cb(n,e){if(n.length===0)return 0;let t=[...n].sort((s,i)=>s-i),r=Math.min(t.length-1,Math.max(0,Math.round(e*(t.length-1))));return t[r]}async function Zh(n){let e=await ni(n),t=await ra(n.smoothing),r=ri(await e.joinOrCreate(Wo.PLAY,{...sl(n.room,n.name,n.auth),...n.options,protocol:3}).catch(kh));return dl(r,{pose:n.pose,smoothing:n.smoothing,predict:t})}var lb=n=>typeof n=="string"&&n.length>0&&n.length<=An.MAX_EVENT_TYPE_CHARS&&!ti(n),ub=new Set(["join","leave","change","shared","object","host","reconnecting","reconnected","disconnect","room:open","voice","voice:rejected"]),db=new Set([ne.OBJECT_RESULT,ne.INPUT,ne.ROOM_OPEN,ne.CHAT,ne.CHAT_HISTORY,ne.VOICE_ICE,ne.VOICE_SIGNAL,ne.VOICE_REJECTED,ne.RATE_DROP,...Object.values(Y)]),fb=[500,1e3,2e3,4e3,8e3];function dl(n,e={}){let t=new Map,r=new Map,s=new Map,i=new Map,o=new Map,a=new Map,c=new Set,u=new Map,d=new Map,h=new Map,m=new Map,g,p=new Map,y=new Map,x=new Map,k=new Map,I=new Map,B=new Map,N=new Map,C=new Map,P=new Set,v=new Map,O,V=0,Z=new Map,ee=f=>{for(let b of Z.values())if(b.id===f)return!0;return!1},Ae=typeof globalThis<"u"&&globalThis.__GENEX_MP_TEST_SKEW__||0,Oe=Ae?()=>er()+Ae:er,S=(f,b)=>{if(p.get(b)===n.sessionId)return!1;let A=`${f}:${b}`;return P.has(A)||(P.add(A),console.warn(`[multiplayer] objects.${f}('${b}') ignored because this session does not own the object \u2014 await objects.claimConfirmed('${b}') and check accepted before publishing`)),!0},U=(f,b,A,j)=>{let ie=Oe(),J=A,oe=ie-A,G=i.get(j);G||i.set(j,G={samples:[],mins:[],n:0});let ge=++G.n;for(G.samples.push({at:ie,n:ge});G.mins.length>0&&G.mins[G.mins.length-1].v>=oe;)G.mins.pop();for(G.mins.push({v:oe,n:ge});G.samples.length>z0||G.samples.length>Wh&&G.samples[0].at<ie-q0;)G.samples.shift();let Re=G.samples[0].n;for(;G.mins[0].n<Re;)G.mins.shift();s.set(j,G.mins[0].v);let et=o.get(f);et||o.set(f,et=[]),et.push(oe),et.length>Wh&&et.shift(),a.set(f,j);let mt=r.get(f);if(r.set(f,J),mt!=null){let tt=J-mt;if(tt>Y0&&tt<J0){let rr=h.get(f);rr||h.set(f,rr=[]),rr.push(tt),rr.length>W0&&rr.shift();let mp=et.length>=8?Math.max(0,cb(et,.9)-G.mins[0].v):0,gp=Math.min(F0,Math.max(U0,B0*ab(rr),$0*mp)),Ll=m.get(f)??ea;m.set(f,Ll+(gp-Ll)*j0)}}let ve=t.get(f);ve||t.set(f,ve=[]);let mi=v.get(f);if(mi&&ve.length===0){let tt=m.get(f)??ea;ve.push({t:J-Math.max(1,tt),state:mi})}v.delete(f),ve.push({t:J,state:b});let On=J-K0;for(;ve.length>2&&ve[0].t<On;)ve.shift();for(;ve.length>1&&ve[0].t>ve[ve.length-1].t+V0;)ve.shift()},L=(f,b)=>{let A=a.get(f),j=A===void 0?void 0:s.get(A);if(j!==void 0)return b-j-(m.get(f)??ea)},D=(f,b)=>{let A=t.get(f),j=L(f,b)??b-ea,ie=c.has(f),J=A&&(ie?Dh(A,j):ob(A,j));if(!J)return u.get(f);let oe=u.get(f),G;if(oe){let ge=Math.min(Yh,Math.max(0,b-(d.get(f)??b))),Re=1-Math.exp(-ge/X0),et=1-Math.exp(-ge/Q0);G=ie?Nh(oe,J,Re,et):ib(oe,J,Re,et)}else G=J;return u.set(f,G),d.set(f,b),G},M=f=>{t.delete(f),r.delete(f),a.delete(f),u.delete(f),d.delete(f),h.delete(f),m.delete(f),o.delete(f),v.delete(f)},z=f=>{t.delete(f),r.delete(f),a.delete(f),h.delete(f),m.delete(f),o.delete(f)},W=f=>{s.delete(f),i.delete(f)},H=new Map,ce=new Set,K=(f,...b)=>H.get(f)?.forEach(A=>{try{A(...b)}catch(j){console.error(`[multiplayer] a '${f}' listener threw:`,j)}}),Ze=new Map,pt=(f,b)=>{Ze.get(b)!==f&&(Ze.set(b,f),K("shared",b,ta(f)))},ln=f=>{let b=f||void 0;b!==O&&(O=b,K("host",O))},gl="",aa=()=>{let f=n.state?.voice?[...n.state.voice.keys()].sort():[],b=f.join(`
|
|
14
|
+
`);b!==gl&&(gl=b,be.setRoster(f),K("voice",be.participants))},yl=(f,b)=>{let A=zt+f,j=n.sessionId,ie=k.has(f),J=b.owner||void 0,oe=Number.isFinite(b.seq)?b.seq:0,G=Number.isFinite(b.epoch)?b.epoch:0,ge=Number.isFinite(b.t)?b.t:0,Re=typeof b.d=="string"?b.d:"",mt=J!==y.get(f)||ie&&oe!==k.get(f),ve=x.has(f)&&G!==x.get(f),mi=ge!==I.get(f);if(k.set(f,oe),x.set(f,G),I.set(f,ge),Re!==B.get(f)){B.set(f,Re);let tt=Re?ta(Re):void 0;tt&&typeof tt=="object"&&!Array.isArray(tt)&&N.set(f,tt)}J?y.set(f,J):y.delete(f),(mt||p.get(f)!==J&&!ee(f))&&(J?p.set(f,J):p.delete(f)),ve&&M(A),mt&&J!==j&&(C.delete(f),ve||z(A));let On=N.get(f);if(On&&J!==j){let tt=ge!==0&&mi&&J!==void 0;ve?(u.set(A,On),d.set(A,Oe()),tt&&U(A,On,ge,J)):(mt&&v.set(A,u.get(A)??On),tt&&U(A,On,ge,J))}(!ie||mt)&&K("object",f)},bl=f=>{let b=k.has(f)||p.has(f)||N.has(f)||C.has(f);M(zt+f),N.delete(f),p.delete(f),y.delete(f),x.delete(f),k.delete(f),I.delete(f),B.delete(f),C.delete(f),b&&K("object",f)},ca=new Map,Xr=new Map,la=new Map,lp=(f,b)=>{if(!b)return{};let A=ca.get(f);if(A&&A.raw===b)return A.state;let{state:j}=Jh(b);return ca.set(f,{raw:b,state:j}),j},ii=new Map,ua=new Map,tr=e.predict?Xh(e.smoothing):void 0,Ct,un=new Map,up=(f,b)=>{if(!tr||!e.predict)return;Ct??(Ct=e.predict.Predict.get(n));let A={mode:tr.mode,delay:tr.delay,smoothMs:tr.smoothMs};Ct.attach(b,{x:A,y:A,z:A,vx:A,vy:A,vz:A}),Ct.attach(b,{yaw:{...A,angle:!0}}),un.set(f,b)},wl=f=>{let b=un.get(f);b&&Ct&&Ct.detach(b),un.delete(f)},dp=f=>{let b=Ct;return{x:b.value(f,"x"),y:b.value(f,"y"),z:b.value(f,"z"),yaw:b.value(f,"yaw"),vx:b.value(f,"vx"),vy:b.value(f,"vy"),vz:b.value(f,"vz"),anim:f.anim??""}},It=!1,Wt=!1,Cn=!0,oi=!1,_l=0,ai=0,da=0,fa=new Set,ci=()=>fa.forEach(f=>f()),Qr=(f,b)=>{if(Z.delete(f.requestId),f.timeout&&clearTimeout(f.timeout),f.abort?.(),f.operation==="claim"&&f.optimistic&&!b.accepted){let A=b.owner??y.get(f.id);A?p.set(f.id,A):p.delete(f.id),A!==n.sessionId&&C.delete(f.id)}f.operation==="claim"&&b.accepted&&(p.set(f.id,n.sessionId),z(zt+f.id)),f.operation==="release"&&b.accepted&&(C.delete(f.id),p.get(f.id)===n.sessionId&&p.delete(f.id),z(zt+f.id)),f.operation==="remove"&&b.accepted&&(C.delete(f.id),N.delete(f.id),p.delete(f.id),M(zt+f.id)),f.resolve(b)},Zr=(f,b)=>{let A=n.state?.objects?.get(f.id);return{requestId:f.requestId,operation:f.operation,id:f.id,accepted:!1,owner:A?.owner||void 0,sequence:A&&Number.isFinite(A.seq)?A.seq:0,reason:b}},El=f=>{for(let b of[...Z.values()])Qr(b,Zr(b,f))},Rl=(f,b=!1)=>{if(!b&&!Cn)return;let A=f.operation==="claim"?Y.CLAIM:f.operation==="release"?Y.RELEASE:Y.DESTROY;De(A,f.payload)},nr=(f,b,A={})=>{let j=String(b),ie=`${n.sessionId.slice(0,12)}:${Date.now().toString(36)}:${(++V).toString(36)}`,J=Math.max(250,Math.min(A.timeoutMs??tb,nb));return new Promise(oe=>{let G={operation:f,id:j,requestId:ie,payload:{id:j,requestId:ie,...A.authority==="host"?{authority:"host"}:{}},optimistic:f==="claim"&&A.optimistic===!0,resolve:oe,timeout:null,abort:void 0};if(It||Wt){oe(Zr(G,It?"aborted":"disconnected"));return}if(G.optimistic&&p.set(j,n.sessionId),G.timeout=setTimeout(()=>Qr(G,Zr(G,"timeout")),J),A.signal){let ge=()=>Qr(G,Zr(G,"aborted"));A.signal.addEventListener("abort",ge,{once:!0}),G.abort=()=>A.signal?.removeEventListener("abort",ge)}if(Z.set(ie,G),A.signal?.aborted){Qr(G,Zr(G,"aborted"));return}Rl(G)})},li=0,De=(f,b,A=!1)=>{if(n.connection?.isOpen)try{return n.send(f,b),!0}catch{}return A&&li++,!1},ui,xl=0,Sl,Tl=new Set,kl=(f,b)=>{let{pose:A,data:j,invalid:ie}=Oh(f);for(let Re of ie)Tl.has(Re)||(Tl.add(Re),console.warn(`[multiplayer] me.set: '${Re}' is a typed pose key (pose: true) and its value is not a `+(Re==="anim"?`string of \u2264${An.MAX_ANIM_CHARS} chars`:"finite number")+" \u2014 it is not sent."));if(!Ph(A))return!1;let J=Oe(),oe=Mh(A,J,b?void 0:Sl);Sl=oe.memory;let G=JSON.stringify(j),ge=b||G!==ui||J-xl>=rb;return ge&&De(Y.STATE,JSON.stringify({...j,[Gt]:J}))?(ui=G,xl=J):ge&&(ui=void 0),De(b?Y.POSE_SNAP:Y.POSE,{...oe.pose,t:J})||(ui=void 0),!0},be=new Zo({selfId:()=>n.sessionId,nameOf:f=>n.state?.players?.get(f)?.name??"",sendSignal:(f,b)=>De(Y.VOICE_SIGNAL,{to:f,data:b},!0)});be.onChange(()=>K("voice",be.participants));let di=null,ha=Ah(()=>De(Y.VOICE_ICE_REQUEST,{},!0),eb),fi=()=>{di&&clearTimeout(di),di=null},Al=f=>{fi(),!(typeof f!="number"||!Number.isFinite(f)||f<=0)&&(di=setTimeout(()=>{be.active&&ha.request().then(b=>{!be.active||!b?.iceServers?.length||(be.setIceServers(b.iceServers),Al(b.ttl))})},Math.max(6e4,Math.floor(f*800))))},In=[],vl=new Set,pa=new Set,hi=new Set,fp=f=>!!f&&typeof f=="object"&&typeof f.id=="number"&&typeof f.from=="string"&&typeof f.name=="string"&&typeof f.text=="string",Cl=f=>{if(!fp(f)||vl.has(f.id)||hi.has(f.from))return;vl.add(f.id);let b=In[In.length-1];if(!b||f.id>b.id)In.push(f);else{let A=In.length;for(;A>0&&(In[A-1]?.id??0)>f.id;)A--;In.splice(A,0,f)}for(let A of[...pa])try{A(f)}catch(j){console.error("[multiplayer] a chat listener threw",j)}},lt=Hc(n);if(!lt)throw new Error("genex multiplayer: the relay room has no schema state");let Il=(f,b,A)=>{let j=f===n.sessionId,{state:ie,sendTime:J}=Jh(b.data),oe=Number.isFinite(b.epoch)?b.epoch:0,G=Xr.has(f)&&oe!==Xr.get(f);Xr.set(f,oe);let ge=A||b.data!==la.get(f);la.set(f,b.data);let Re=Number.isFinite(b.poseT)?b.poseT:0,et=Re!==(ua.get(f)??0);ua.set(f,Re);let mt=b.posed===!0;if(!j&&mt&&!c.has(f)&&(M(f),c.add(f),ii.set(f,new Ko)),!j&&G&&(M(f),un.has(f)&&wl(f)),K(A?"join":"change",f,mt?{...ie,...Qo(b)}:ie),!j){if(mt){let ve=ii.get(f);(ge||G)&&(ve.push(J,ie),(G||tr)&&ve.flush()),tr?un.has(f)||up(f,b):Re!==0&&(et||G)&&U(f,Qo(b),Re,f);return}(ge||G)&&Vh(f,n.sessionId,J)&&U(f,ie,J,f)}};lt(n.state).players.onAdd((f,b)=>{Il(b,f,!0),lt(f).onChange(()=>Il(b,f,!1))});let Ol=f=>{K("leave",f),M(f),W(f),wl(f),ca.delete(f),Xr.delete(f),la.delete(f),ua.delete(f),c.delete(f),ii.delete(f)};lt(n.state).players.onRemove((f,b)=>Ol(b)),lt(n.state).shared.onAdd(pt),lt(n.state).shared.onChange(pt),lt(n.state).objects.onAdd((f,b)=>{yl(b,f),lt(f).onChange(()=>yl(b,f))}),lt(n.state).objects.onRemove((f,b)=>bl(b)),lt(n.state).listen("host",f=>ln(f)),lt(n.state).voice.onAdd(aa),lt(n.state).voice.onRemove(aa);let hp=()=>{let f=n.state;if(f){for(let b of new Set([...p.keys(),...N.keys(),...k.keys()]))f.objects?.has(b)||bl(b);for(let b of[...Xr.keys()])f.players?.has(b)||Ol(b);ln(f.host),aa()}};n.onMessage(ne.VOICE_SIGNAL,f=>{f&&typeof f.from=="string"&&be.handleSignal(f.from,f.data)}),n.onMessage(ne.VOICE_REJECTED,f=>{fi(),be.stop(),K("voice:rejected",f??{reason:"full"})}),n.onMessage(ne.VOICE_ICE,f=>{ha.deliver(f??null)}),n.onMessage(ne.CHAT,f=>Cl(f)),n.onMessage(ne.CHAT_HISTORY,f=>{if(Array.isArray(f?.messages))for(let b of f.messages)Cl(b)}),n.onMessage(ne.OBJECT_RESULT,f=>{if(!f||typeof f.requestId!="string")return;let b=Z.get(f.requestId);!b||f.operation!==b.operation||f.id!==b.id||Qr(b,f)}),n.onMessage(ne.INPUT,f=>{f&&typeof f.from=="string"&&K(ne.INPUT,f.from,f.d)}),n.onMessage(ne.ROOM_OPEN,f=>{typeof f?.open=="boolean"&&K("room:open",{open:f.open})}),n.onMessage(ne.RATE_DROP,f=>{console.warn(`[multiplayer] the relay dropped ${f?.dropped??"some"} of your messages in the last second \u2014 you are publishing over budget. Publish idle/unchanged objects at \u22642Hz keepalive, not every tick (see the multiplayer skill's "message budget" section).`)}),n.onMessage(ne.SERVER_RESTART,()=>{}),De(Y.CHAT_HISTORY_REQUEST,{});let Pl=Lh(n),es=Pl?Bh(Pl,()=>!Wt&&!It):void 0,Ml=()=>es?n.clock.serverNow():void 0,pp=f=>Uh(f,{synced:es?.synced===!0,clockOrigin:Number.isFinite(n.state?.clockOrigin)?n.state?.clockOrigin:0,serverNow:Ml(),wallNow:Date.now()}),Dl=()=>{es?.stop(),Ct?.dispose(),Ct=void 0,un.clear()};n.onDrop(f=>{if(It||Wt)return;da++,oi||(oi=!0,_l=0,ai=er()),Cn=!1,ci();let{isReconnecting:b,retryCount:A,maxRetries:j}=n.reconnection;b&&A>=j||K("reconnecting",{attempt:++_l,code:f})}),n.onReconnect(()=>{if(Wt)return;if(It){n.leave().catch(()=>{});return}let f=da;if((ai?er()-ai:0)>Z0){for(let A of[...t.keys()])M(A);for(let A of[...i.keys()])W(A)}(async()=>{if(await $h(n,qt.firstStateTimeoutMs),!(f!==da||Wt||It)){hp();for(let A of[...Z.values()])Rl(A,!0);De(Y.CHAT_HISTORY_REQUEST,{}),oi=!1,ai=0,Cn=!0,ci(),K("reconnected"),li>0&&(console.warn(`[multiplayer] ${li} fire-and-forget event(s)/input(s) were dropped while reconnecting \u2014 they are not buffered; player/object state re-synced automatically.`),li=0)}})()}),n.onLeave(f=>{Wt||(Wt=!0,Cn=!1,oi=!1,Dl(),ci(),!It&&(El("disconnected"),K("disconnect",f??1006)))}),n.onError(()=>{});let Nl=((f,b)=>{let A=H.get(f);return A||H.set(f,A=new Set),A.add(b),!ub.has(f)&&!db.has(f)&&!ce.has(f)&&(ce.add(f),n.onMessage(f,j=>K(f,j))),()=>{A?.delete(b)}}),pi={id:n.sessionId,get players(){let f=new Map,b=Oe();return Ct&&un.size>0&&Ct.tick(er()),n.state?.players?.forEach((A,j)=>{let ie=lp(j,A.data),J=ie,oe=ie,G=ii.get(j);if(j!==n.sessionId&&G){let ge=Qo(A);if(oe={...ie,...ge},un.has(j))J={...G.at(void 0)??ie,...dp(A)};else{let Re=D(j,b)??ge;J={...G.at(L(j,b))??ie,...Re}}}else j===n.sessionId?g&&(J=g,oe=g):J=D(j,b)??ie;f.set(j,{id:j,name:A.name??"",avatarUrl:A.avatarUrl??"",connected:A.connected!==!1,uid:A.uid??"",team:Number.isFinite(A.team)?A.team:-1,state:J,stateRaw:oe})}),f},get activePlayers(){return new Map([...pi.players].filter(([,f])=>f.connected))},me:{set(f){Gt in f&&console.warn(`[multiplayer] '${Gt}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let b=Jr(f);g=b,!(e.pose&&kl(b,!1))&&De(Y.STATE,JSON.stringify({...b,[Gt]:Oe()}))},snap(f){Gt in f&&console.warn(`[multiplayer] '${Gt}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let b=Jr(f);g=b,!(e.pose&&kl(b,!0))&&De(Y.STATE_SNAP,JSON.stringify({...b,[Gt]:Oe()}))}},shared:{get(f){return ta(n.state?.shared?.get(f))},set(f,b){f.startsWith(Yo)||De(Y.SHARED,{key:f,value:JSON.stringify(Jr(b))})},keys(){return n.state?.shared?Array.from(n.state.shared.keys()):[]}},objects:{claim(f){nr("claim",f,{optimistic:!0})},claimConfirmed(f,b){return nr("claim",f,b)},release(f){let b=String(f);C.delete(b),p.get(b)===n.sessionId&&p.delete(b),z(zt+b),nr("release",b)},releaseConfirmed(f,b){return nr("release",f,b)},remove(f){let b=String(f);p.get(b)===n.sessionId&&(C.delete(b),N.delete(b),p.delete(b),M(zt+b)),nr("remove",b)},removeConfirmed(f,b){return nr("remove",f,b)},set(f,b){let A=String(f);if(S("set",A))return;let j=Jr(b);p.get(A)===n.sessionId&&C.set(A,j),De(Y.OBJECT,{id:A,d:j,t:Oe()})},snap(f,b){let A=String(f);if(S("snap",A))return;let j=Jr(b);p.get(A)===n.sessionId&&C.set(A,j),De(Y.OBJECT_SNAP,{id:A,d:j,t:Oe()})},get(f){let b=String(f),A=p.get(b),j=C.get(b);if(A===void 0&&!N.has(b)&&!j)return;let ie=A!==void 0&&A===n.sessionId,J,oe;return ie&&j?(J=j,oe=j,u.set(zt+b,j),d.set(zt+b,Oe())):(oe=N.get(b)??{},J=D(zt+b,Oe())??oe),{id:b,epoch:x.get(b)??0,owner:A,isMine:ie,state:J,stateRaw:oe}},ids(){return[...new Set([...p.keys(),...N.keys(),...C.keys()])]}},get isHost(){return Cn&&!It&&!Wt&&O!==void 0&&O===n.sessionId},get host(){return O},inputs:{send(f){De(Y.INPUT,Jr(f),!0)},on(f){let b=H.get(ne.INPUT);b||H.set(ne.INPUT,b=new Set);let A=(j,ie)=>f(j,ie);return b.add(A),()=>{b?.delete(A)}}},onHostTick(f,b){let A=null,j=0,ie=Number.isFinite(f)&&f>0?Math.min(f,100):20,J=Math.max(10,Math.round(1e3/ie)),oe=()=>{let ge=Cn&&!It&&!Wt&&O!==void 0&&O===n.sessionId;ge&&!A?(j=er(),A=setInterval(()=>{let Re=er();b(Math.min(Re-j,Yh)),j=Re},J)):!ge&&A&&(clearInterval(A),A=null)},G=Nl("host",oe);return fa.add(oe),oe(),()=>{G(),fa.delete(oe),A&&clearInterval(A),A=null}},on:Nl,send(f,b){if(!lb(f)){console.warn(`[multiplayer] send('${f}') collides with a relay-internal channel \u2014 use a different event name`);return}De(f,b,!0)},chat:{send(f){typeof f=="string"&&f.trim()&&De(Y.CHAT,{text:f},!0)},on(f){return pa.add(f),()=>pa.delete(f)},get history(){return[...In]},mute(f){typeof f=="string"&&f&&hi.add(f)},unmute(f){hi.delete(f)},get muted(){return[...hi]}},voice:{async join(f){if(await be.start(f,!0),!f?.iceServers?.length){let b=await ha.request();be.active&&b?.iceServers?.length&&(be.setIceServers(b.iceServers),Al(b.ttl))}be.active&&(De(Y.VOICE_JOIN,{},!0),be.releasePeering())},leave(){fi(),De(Y.VOICE_LEAVE,{},!0),be.stop()},get active(){return be.active},get participants(){return be.participants},setMicEnabled(f){be.setMicEnabled(f===!0)},get micEnabled(){return be.micEnabled},get speaking(){return be.speaking},mute(f){be.mute(f)},unmute(f){be.unmute(f)},setVolume(f,b){be.setVolume(f,b)},get muted(){return be.participants.filter(f=>f.muted).map(f=>f.id)}},setRoomOpen(f){De(Y.ROOM_OPEN,{open:f===!0})},leave(){It=!0,Dl(),be.stop(),fi(),Cn=!1,ci(),El("aborted"),n.reconnection.enabled=!1,n.leave().catch(()=>{})},serverNow:Ml,get rtt(){if(!es)return;let f=n.clock.smoothedRtt();return f>0?f:void 0},get clockSynced(){return es?.synced===!0},timeUntil:pp};return Object.defineProperty(pi,ul,{value:()=>n,enumerable:!1}),Object.defineProperty(pi,Symbol.for("genex.multiplayer.internals"),{enumerable:!1,value:{senderOf:f=>a.get(f),offsetOf:f=>{let b=a.get(f);return b===void 0?void 0:s.get(b)},offsetSamples:f=>i.get(f)?.samples.length??0,bufferLength:f=>t.get(f)?.length??0}}),pi}var hb=[1e3,2e3,4e3],fl=n=>sl(n.room,n.name,n.auth);function ep(n,e,t=r=>r-Date.now()){let r=n?.state?.match,s=r?ta(r):null,i=s&&typeof s=="object"?s:null;if(!i)return{status:n?"waiting":"searching",role:"player",queue:e,players:[],connectedPlayers:[],opponents:[],teams:{},myTeam:null,scores:{},config:{},winCondition:"lastStanding",championId:null,challengerId:null,roundId:0,winnerId:null,message:n?"Waiting for players\u2026":"Finding a match\u2026",startsAt:null,endsBy:null,startsInMs:null,endsInMs:null};let o=n?.sessionId,a=i.championId??null,c=i.challengerId??null,u=i.teams??{},d=Array.isArray(i.players)?i.players:[],h=i.connectedPlayers??d,m=o!=null&&d.includes(o),g=m?i.phase:"spectating",p=d.filter(P=>P!==o),y=o?Object.keys(u).find(P=>u[P]?.includes(o))??null:null,{winCondition:x,...k}=i.cfg??{},I=P=>typeof P=="number"&&Number.isFinite(P)&&P>0?P:null,B=I(i.startsAt),N=I(i.endsBy),C=P=>P===null?null:Math.max(0,t(P));return{status:g,role:m?"player":"spectator",queue:{position:0,size:0},players:d,connectedPlayers:h,opponents:p,teams:u,myTeam:y,scores:i.scores??{},config:k,winCondition:x?.type??"lastStanding",championId:a,challengerId:c,roundId:i.roundId??0,winnerId:i.winnerId??null,message:i.message??"",startsAt:B,endsBy:N,startsInMs:C(B),endsInMs:C(N)}}function Kr(n,e,t){if(n?.connection?.isOpen)try{n.send(e,t)}catch{}}async function tp(n){let e=await ni(n),t=await ra(n.smoothing),r=new Map,s=(P,...v)=>r.get(P)?.forEach(O=>O(...v)),i=((P,v)=>{let O=r.get(P);return O||r.set(P,O=new Set),O.add(v),()=>{O?.delete(v)}}),o=null,a=null,c=null,u={position:0,size:0},d=!1,h=!1,m=0,g=!1,p=!1,y=async()=>{if(d||h)return;h=!0;let P=++m;try{o=null,a=null;for(let v=0;;v++){c&&(c.leave(),c=null),u={position:0,size:0};let O;try{O=Fh(await e.joinOrCreate(Wo.QUEUE,fl(n)))}catch(V){if(d)return;let Z=il(V);Z&&ol();let ee=Z?void 0:hb[v];if(ee==null){if(v===0&&await new Promise(Ae=>setTimeout(Ae,0)),d)return;s("error",V);return}if(await new Promise(Ae=>setTimeout(Ae,ee)),d)return;continue}if(d||P!==m){O.leave();return}c=O,O.onMessage(ne.QUEUE,V=>{u={position:V.position,size:V.size},s("queue",V)}),O.onMessage(ne.SEAT,V=>{d||P!==m||c!==O||g||(g=!0,c=null,O.leave(),x(V.reservation,V.role,P))}),O.onLeave(()=>{d||c!==O||(c=null,(async()=>{for(let V of fb)if(await new Promise(Z=>setTimeout(Z,V)),d||c||o||(await y(),c||o))return})())}),s("searching");return}}finally{h=!1}},x=async(P,v,O)=>{try{let V=ri(await e.consumeSeatReservation(P));if(d||O!==m){V.leave();return}a=V;let Z=dl(V,{pose:n.pose,smoothing:n.smoothing,predict:t});o=Z,Z.on(ne.MATCH_START,ee=>s("matchStart",ee)),Z.on(ne.MATCH_ENDED,ee=>s("matchEnded",ee)),Z.on(ne.MATCH_REQUEUE,()=>{o===Z&&k()}),Z.on("disconnect",ee=>{if(!(d||o!==Z)){if(ee===nl.SUPERSEDED||ee===nl.REVOKED){m++,g=!1,a=null,o=null,s("disconnect",ee);return}k()}}),c&&(c.leave(),c=null),s("matched"),v==="spectator"&&s("spectate")}catch{!d&&O===m&&(g=!1,y())}finally{O===m&&(g=!1)}},k=async()=>{if(!(d||p)){p=!0;try{m++,g=!1,o?.leave(),a=null,o=null,await y()}finally{p=!1}}};y();let I=()=>o?cn(o):null,B=null,N=null,C=()=>{o!==B&&(B=o,N=null);let P=I(),v=!!P?.state?.match;if(!v&&o&&N)return N;let O=ep(P,u,o?o.timeUntil:void 0);return v&&(N=O),O};return{get session(){return o},get matchmaking(){return C()},on:i,eliminated(){Kr(I(),Y.MATCH_ELIMINATED,{})},score(P=1){Kr(I(),Y.MATCH_SCORE,{delta:P})},finish(){Kr(I(),Y.MATCH_FINISH,{})},retry(){d||h||c||a||y()},cancel(){d=!0,m++,g=!1,o?.leave(),!o&&a&&a.leave(),c&&c.leave(),a=null,c=null,o=null}}}function np(n,e){let t=new Map,r=(c,...u)=>t.get(c)?.forEach(d=>d(...u)),s=((c,u)=>{let d=t.get(c);return d||t.set(c,d=new Set),d.add(u),()=>{d?.delete(u)}}),i=!0,o=dl(n,e);o.on(ne.MATCH_START,c=>r("matchStart",c)),o.on(ne.MATCH_ENDED,c=>r("matchEnded",c)),o.on(ne.MATCH_REQUEUE,()=>{i=!1}),o.on("disconnect",()=>{i=!1});let a=()=>i?cn(o):null;return{get session(){return i?o:null},get matchmaking(){return ep(a(),{position:0,size:0},o.timeUntil)},on:s,eliminated(){Kr(a(),Y.MATCH_ELIMINATED,{})},score(c=1){Kr(a(),Y.MATCH_SCORE,{delta:c})},finish(){Kr(a(),Y.MATCH_FINISH,{})},retry(){},cancel(){o.leave(),i=!1}}}async function rp(n){let e=await ni(n),t=await ra(n.smoothing),r=ri(await e.create(Wo.MATCH,fl(n))),s=np(r,{pose:n.pose,smoothing:n.smoothing,predict:t});return Object.defineProperty(s,"code",{value:r.roomId,enumerable:!0}),s}async function sp(n,e){let t=await ni(e),r=await ra(e.smoothing),s=ri(await t.joinById(n,fl(e)));return np(s,{pose:e.pose,smoothing:e.smoothing,predict:r})}var pb=2,sa=Ja;function mb(n){sa=n??Ja}function gb(n){let e=JSON.parse(n);if(!yt(e))throw new TypeError("genex bridge: options must be a JSON object");let t=typeof e.gameId=="string"?e.gameId:"";if(!t)throw new TypeError("genex bridge: `gameId` (the game slug) is required");let r=Array.isArray(e.urls)?e.urls.filter(a=>typeof a=="string"&&a!==""):[],s="play";if(e.room==="queue"||e.room==="private")s=e.room;else if(yt(e.room)&&typeof e.room.joinById=="string"&&e.room.joinById)s={joinById:e.room.joinById};else if(e.room!==void 0&&e.room!==null&&e.room!=="play")throw new TypeError('genex bridge: `room` must be "play", "queue", "private" or {"joinById": code}');let i=typeof e.controlTimeoutMs=="number"&&Number.isFinite(e.controlTimeoutMs)?e.controlTimeoutMs:void 0,o=e.smoothing==="genex"||e.smoothing==="predict"||yt(e.smoothing)?e.smoothing:void 0;return{gameId:t,name:typeof e.name=="string"&&e.name?e.name:void 0,urls:r,room:s,pose:e.pose===!0,smoothing:o,controlTimeoutMs:i,options:yt(e.options)?e.options:void 0}}var hl=new Map,yb=1,pl=n=>n.closed?null:n.mm?n.mm.session:n.session;function si(n){n.closed=!0,n.connected=!1;for(let e of n.unwire.splice(0))e();n.wired=null,n.session=null,n.mm=null}function op(n,e){if(n.wired===e)return;for(let o of n.unwire.splice(0))o();n.wired=e,n.connected=!0,n.lastConnected.clear(),n.lastMatch="";let t=cn(e);n.sessionId=e.id,n.roomId=t.roomId;let r=n.unwire,s=o=>t.state?.players?.get(o)?.connected!==!1,i=o=>{let a=s(o),c=n.lastConnected.get(o);n.lastConnected.set(o,a),c!==void 0&&c!==a&&ae(n,{type:"playerConnection",id:o,connected:a})};ae(n,{type:"joined",sessionId:e.id}),t.state?.players?.forEach((o,a)=>{n.lastConnected.set(a,s(a)),ae(n,{type:"playerJoined",id:a})});for(let o of e.objects.ids())ae(n,{type:"objectChanged",id:o,owner:e.objects.get(o)?.owner??null});e.host!==void 0&&ae(n,{type:"hostChanged",host:e.host}),r.push(e.on("join",o=>{n.lastConnected.set(o,s(o)),ae(n,{type:"playerJoined",id:o})}),e.on("change",o=>{i(o),n.changed.has(o)||(n.changed.add(o),ae(n,{type:"playerChanged",id:o}))}),e.on("leave",o=>{n.lastConnected.delete(o),ae(n,{type:"playerLeft",id:o})}),e.on("host",o=>ae(n,{type:"hostChanged",host:o??null})),e.on("shared",(o,a)=>ae(n,{type:"sharedChanged",key:o,value:a??null})),e.on("object",o=>{let a=e.objects.get(o);ae(n,a?{type:"objectChanged",id:o,owner:a.owner??null}:{type:"objectRemoved",id:o})}),e.on("room:open",({open:o})=>ae(n,{type:"roomOpen",open:o})),e.on("reconnecting",({attempt:o,code:a})=>{n.connected=!1,ae(n,{type:"reconnecting",code:a,attempt:o})}),e.on("reconnected",()=>{n.connected=!0,ae(n,{type:"reconnected"})}),e.on("disconnect",o=>{n.connected=!1,n.opts.room!=="queue"&&(si(n),ae(n,{type:"disconnected",code:o,reason:""}))}),e.on(ne.SERVER_RESTART,()=>ae(n,{type:"serverRestart"})),e.on(ne.MATCH_START,o=>ae(n,{type:"matchStart",roundId:yt(o)&&typeof o.roundId=="number"?o.roundId:0})),e.on(ne.MATCH_ENDED,o=>ae(n,{type:"matchEnded",data:o??null})),e.on(ne.MATCH_REQUEUE,o=>ae(n,{type:"matchRequeue",reason:yt(o)&&typeof o.reason=="string"?o.reason:null})),e.inputs.on((o,a)=>ae(n,{type:"input",from:o,data:a??null})),e.chat.on(o=>ae(n,{type:"chat",id:o.id,from:o.from,name:o.name,text:o.text,at:o.at})),t.onMessage(ne.RATE_DROP,o=>ae(n,{type:"rateDrop",dropped:yt(o)&&typeof o.dropped=="number"?o.dropped:0})),t.onMessage("*",(o,a)=>{typeof o=="string"&&!ti(o)&&ae(n,{type:"message",kind:o,data:a??null})}))}function ia(n){let e=pl(n);e&&e!==n.wired&&op(n,e)}async function bb(n){let e=n.opts;if(await sa.ready(e.gameId),n.closed)return;let t=e.urls.length?e.urls:sa.urls();if(!t.length)throw Object.assign(new Error("genex bridge: no relay URL (pass urls, or run on a Genex page)"),{code:0});let r=()=>sa.auth(),s={urls:t,room:e.gameId,name:e.name,auth:r,pose:e.pose,smoothing:e.smoothing};if(e.room==="play"){let a=await Zh({...s,options:e.options});if(n.closed)return void a.leave();n.session=a,op(n,a);return}let i=s,o=e.room==="queue"?await tp(i):e.room==="private"?await rp(i):await sp(e.room.joinById,i);if(n.closed)return void o.cancel();n.mm=o,o.on("queue",a=>{yt(a)&&ae(n,{type:"queue",position:Number(a.position)||0,size:Number(a.size)||0})}),o.on("matched",()=>{ae(n,{type:"seated"}),ia(n)}),o.on("searching",()=>{if(n.wired){for(let a of n.unwire.splice(0))a();n.wired=null,n.connected=!1}}),o.on("error",a=>{let c=n.mm;si(n),c?.cancel(),ae(n,{type:"joinFailed",code:Bi(a),message:pr(a)})}),o.on("disconnect",a=>{si(n),ae(n,{type:"disconnected",code:typeof a=="number"?a:0,reason:""})}),ia(n)}function ap(n){let e=gb(n),t=yb++,r={opts:e,q:[],overflowed:!1,session:null,mm:null,wired:null,unwire:[],changed:new Set,lastConnected:new Map,lastMatch:"",sessionId:"",roomId:"",connected:!1,closed:!1};hl.set(t,r);let s=bb(r).catch(i=>{throw si(r),ae(r,{type:"joinFailed",code:Bi(i),message:pr(i)}),i});return{handle:t,done:s}}function wb(n){let{handle:e,done:t}=ap(n);return t.catch(()=>{}),e}async function _b(n){let{handle:e,done:t}=ap(n);try{await t}catch(r){let s=new Error(pr(r));throw s.code=Bi(r),s}return e}var vn=n=>hl.get(n),He=n=>{let e=vn(n);return e?(ia(e),pl(e)):null};function cp(n){let e=vn(n);if(!e||e.closed)return;let{mm:t,session:r}=e;si(e),t?t.cancel():r?.leave(),ae(e,{type:"disconnected",code:4e3,reason:"left"})}function Eb(n){cp(n),typeof n=="number"&&hl.delete(n)}function Rb(n,e){let t=ls(e,"state"),r=He(n);return r?(r.me.set(t),!0):!1}function xb(n,e){let t=ls(e,"state"),r=He(n);return r?(r.me.snap(t),!0):!1}function Sb(n,e,t){let r=cs(t,"value");if(typeof e!="string"||!e||e.startsWith(Yo))return!1;let s=He(n);return s?(s.shared.set(e,r),!0):!1}function Tb(n,e,t){let r=ls(t,"object state"),s=He(n);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.set(e,r),!0)}function kb(n,e,t){let r=ls(t,"object state"),s=He(n);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.snap(e,r),!0)}function Ab(n,e,t){let r=cs(t,"event data");if(typeof e!="string"||!e||e.length>An.MAX_EVENT_TYPE_CHARS||ti(e))return!1;let s=He(n);return s?(s.send(e,r),!0):!1}function vb(n,e){}function Cb(n,e){let t=cs(e,"input"),r=He(n);return r?(r.inputs.send(t),!0):!1}function Ib(n,e){let t=He(n);return t?(t.setRoomOpen(e===!0),!0):!1}function Ob(n,e){let t=He(n);return!t||typeof e!="string"?!1:(t.chat.send(e),!0)}function oa(n,e,t,r,s=!1){if(typeof t!="string"||!t)throw new TypeError("genex bridge: object id must be a non-empty string");let i=vn(n),o=He(n),a=d=>{if(!i)return;let h={type:"controlResult",requestId:String(r),operation:e,id:t,accepted:d.accepted,owner:d.owner??null,sequence:d.sequence,reason:d.reason};typeof d.retryAfterMs=="number"&&(h.retryAfterMs=d.retryAfterMs),ae(i,h)};if(!o){a({accepted:!1,sequence:0,reason:"disconnected"});return}let c={timeoutMs:i?.opts.controlTimeoutMs,...s?{authority:"host"}:{}};(e==="claim"?o.objects.claimConfirmed(t,c):e==="release"?o.objects.releaseConfirmed(t,c):o.objects.removeConfirmed(t,c)).then(a,()=>a({accepted:!1,sequence:0,reason:"disconnected"}))}function Pb(n,e,t){oa(n,"claim",e,t)}function Mb(n,e,t){oa(n,"claim",e,t,!0)}function Db(n,e,t){oa(n,"release",e,t)}function Nb(n,e,t){oa(n,"remove",e,t)}function Lb(n){let e=vn(n);return!e?.mm||e.closed?!1:(e.mm.eliminated(),!0)}function Bb(n,e=1){let t=vn(n);return!t?.mm||t.closed||typeof e!="number"||!Number.isFinite(e)?!1:(t.mm.score(e),!0)}function Ub(n){let e=vn(n);return!e?.mm||e.closed?!1:(e.mm.finish(),!0)}function Fb(n){return He(n)?.serverNow()??null}function $b(n,e){let t=He(n);return t?t.timeUntil(e):e-Date.now()}var ip=n=>typeof n=="number"&&Number.isFinite(n)?n:null;function Vb(n){let e=vn(n),t=He(n),r=t?cn(t):null,s=r?.state?.match,i=null;if(s)try{i=JSON.parse(s)}catch{i=null}return JSON.stringify({sessionId:t?.id??e?.sessionId??"",roomId:r?.roomId??e?.roomId??"",hostId:t?.host??null,isHost:t?.isHost??!1,connected:!!t&&!!e?.connected,closed:!e||e.closed,serverNow:ip(t?.serverNow()),rtt:ip(t?.rtt),clockSynced:t?.clockSynced??!1,clockOrigin:r?.state?.clockOrigin??0,matchState:i})}function jb(n){let e=He(n);if(!e)return"[]";let t=cn(e).state?.players,r=[];for(let[s,i]of e.players){let o=t?.get(s);r.push({id:s,name:i.name,uid:i.uid,team:i.team,connected:i.connected,avatarUrl:i.avatarUrl,state:i.state??{},stateRaw:i.stateRaw??{},epoch:o?.epoch??0,isMe:s===e.id,posed:o?.posed===!0})}return JSON.stringify(r)}function Hb(n){let e=He(n);if(!e)return"[]";let t=cn(e).state?.objects,r=[];for(let s of e.objects.ids()){let i=e.objects.get(s);i&&r.push({id:s,owner:i.owner??null,isMine:i.isMine,seq:t?.get(s)?.seq??0,epoch:i.epoch,state:i.state??null,stateRaw:i.stateRaw??null})}return JSON.stringify(r)}function Gb(n){let e=He(n),t={};if(e)for(let r of e.shared.keys())t[r]=e.shared.get(r)??null;return JSON.stringify(t)}function qb(n){let e=vn(n);if(!e)return"[]";try{ia(e);let t=pl(e);if(t){let r=cn(t).state?.match??"";if(r!==e.lastMatch){e.lastMatch=r;let s=null;try{s=r?JSON.parse(r):null}catch{s=null}ae(e,{type:"matchState",state:s})}}e.changed.clear()}catch(t){ae(e,Ka(pr(t)))}return Hu(e)}var zb=Object.freeze({...ml,initEmbed:Mi});globalThis.GenexMultiplayerBridge=zb;})();
|