@genex-ai/multiplayer 0.17.6 → 0.17.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/PROTOCOL.md +102 -31
  2. package/README.md +35 -14
  3. package/WORLD-GLTF.md +109 -0
  4. package/WORLD-SCENE.md +135 -0
  5. package/dist/authority/fast-udp.d.ts +4 -2
  6. package/dist/authority/fast-udp.js +8 -46
  7. package/dist/authority/fast-webtransport.d.ts +26 -4
  8. package/dist/authority/fast-webtransport.js +12 -115
  9. package/dist/authority/index.d.ts +379 -41
  10. package/dist/authority/index.js +247 -47
  11. package/dist/authority/module.d.ts +2 -1
  12. package/dist/authority/module.js +1 -1
  13. package/dist/bridge-authority.d.ts +3 -2
  14. package/dist/bridge-authority.global.js +10 -9
  15. package/dist/bridge-authority.js +11 -6
  16. package/dist/bridge.global.js +5 -5
  17. package/dist/bridge.js +3 -3
  18. package/dist/chunk-2NGXXQDS.js +1916 -0
  19. package/dist/{chunk-7QVOIHJF.js → chunk-DJ2XYETS.js} +2 -2
  20. package/dist/{chunk-Y6XHXDIK.js → chunk-MQYARUGU.js} +864 -539
  21. package/dist/{chunk-K3SF5VDS.js → chunk-OD6NRSX2.js} +3 -1
  22. package/dist/{chunk-UX3F6YTV.js → chunk-TEHGMFAG.js} +1 -1
  23. package/dist/chunk-TSYEWPVO.js +44 -0
  24. package/dist/chunk-TVTVIMIH.js +675 -0
  25. package/dist/{chunk-ZSWF4VCN.js → chunk-WEMRRIHH.js} +80 -2
  26. package/dist/chunk-YWQ3ALYY.js +69 -0
  27. package/dist/{chunk-5JGRFT2N.js → chunk-ZDGSUR6E.js} +879 -1898
  28. package/dist/{fast-client-CZ41v-oB.d.ts → fast-client--A88q0kk.d.ts} +85 -4
  29. package/dist/index.js +3 -3
  30. package/dist/level-build-CbRqrYJq.d.ts +140 -0
  31. package/dist/{module-DqtFb5wA.d.ts → module-CSpXrzFc.d.ts} +151 -400
  32. package/dist/{physics-predict-49udN3a1.d.ts → physics-predict-C7ZB1gDG.d.ts} +18 -3
  33. package/dist/protocol.d.ts +90 -2
  34. package/dist/protocol.js +17 -1
  35. package/dist/shot-world-D22tqOUT.d.ts +485 -0
  36. package/dist/world-fit/index.d.ts +549 -0
  37. package/dist/world-fit/index.js +4763 -0
  38. package/dist/world-fit/three.d.ts +77 -0
  39. package/dist/world-fit/three.js +140 -0
  40. package/package.json +15 -3
@@ -1,14 +1,15 @@
1
- "use strict";(()=>{var UE=Object.create;var Wc=Object.defineProperty;var VE=Object.getOwnPropertyDescriptor;var HE=Object.getOwnPropertyNames;var $E=Object.getPrototypeOf,jE=Object.prototype.hasOwnProperty;var am=t=>{throw TypeError(t)};var qE=(t,e,n)=>e in t?Wc(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var at=(t,e)=>()=>(t&&(e=t(t=0)),e);var GE=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Fd=(t,e)=>{for(var n in e)Wc(t,n,{get:e[n],enumerable:!0})},WE=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of HE(e))!jE.call(t,s)&&s!==n&&Wc(t,s,{get:()=>e[s],enumerable:!(r=VE(e,s))||r.enumerable});return t};var YE=(t,e,n)=>(n=t!=null?UE($E(t)):{},WE(e||!t||!t.__esModule?Wc(n,"default",{value:t,enumerable:!0}):n,t));var m=(t,e,n)=>qE(t,typeof e!="symbol"?e+"":e,n),zd=(t,e,n)=>e.has(t)||am("Cannot "+n);var ae=(t,e,n)=>(zd(t,e,"read from private field"),n?n.call(t):e.get(t)),ze=(t,e,n)=>e.has(t)?am("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),Ue=(t,e,n,r)=>(zd(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),ks=(t,e,n)=>(zd(t,e,"access private method"),n);var We,Lo,Sf,yu,gu,Ts,ft,hy=at(()=>{"use strict";We={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},Lo={TIMED:128,UNRELIABLE:64},Sf=31,yu={OK:0,REJECTED:1,ERROR:2},gu={INPUT_REFLECTION:1,INPUT_OPTIONS:2},Ts={RENDER_TIME:1,FIXED_TIMESTEP:2,PATCH_RATE:4,SUB_STEPS:8,RECKON_TIME:16},ft={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 yr=at(()=>{"use strict";hy()});function sg(t){Object.defineProperty(t,Symbol.metadata,{value:void 0,writable:!0,configurable:!0,enumerable:!1})}function cg(t,e,n){for(var r=0,s=0,o=e.length;s<o;s++)r=e.charCodeAt(s),r<128?t[n.offset++]=r:r<2048?(t[n.offset]=192|r>>6,t[n.offset+1]=128|r&63,n.offset+=2):r<55296||r>=57344?(t[n.offset]=224|r>>12,t[n.offset+1]=128|r>>6&63,t[n.offset+2]=128|r&63,n.offset+=3):(s++,r=65536+((r&1023)<<10|e.charCodeAt(s)&1023),t[n.offset]=240|r>>18,t[n.offset+1]=128|r>>12&63,t[n.offset+2]=128|r>>6&63,t[n.offset+3]=128|r&63,n.offset+=4)}function ug(t,e,n){t[n.offset++]=e&255}function OR(t,e,n){t[n.offset++]=e&255}function lg(t,e,n){t[n.offset++]=e&255,t[n.offset++]=e>>8&255}function If(t,e,n){t[n.offset++]=e&255,t[n.offset++]=e>>8&255}function xr(t,e,n){t[n.offset++]=e&255,t[n.offset++]=e>>8&255,t[n.offset++]=e>>16&255,t[n.offset++]=e>>24&255}function Os(t,e,n){let r=e>>24,s=e>>16,o=e>>8,i=e;t[n.offset++]=i&255,t[n.offset++]=o&255,t[n.offset++]=s&255,t[n.offset++]=r&255}function dg(t,e,n){let r=Math.floor(e/Math.pow(2,32)),s=e>>>0;Os(t,s,n),Os(t,r,n)}function fg(t,e,n){let r=e/Math.pow(2,32)>>0,s=e>>>0;Os(t,s,n),Os(t,r,n)}function IR(t,e,n){ig[0]=BigInt.asIntN(64,e),xr(t,Cs[0],n),xr(t,Cs[1],n)}function DR(t,e,n){ig[0]=BigInt.asIntN(64,e),xr(t,Cs[0],n),xr(t,Cs[1],n)}function pg(t,e,n){Pf[0]=e,xr(t,Cs[0],n)}function hg(t,e,n){MR[0]=e,xr(t,Cs[0],n),xr(t,Cs[1],n)}function BR(t,e,n){t[n.offset++]=e?1:0}function NR(t,e,n){e||(e="");let r=ag(e,"utf8"),s=0;if(r<32)t[n.offset++]=r|160,s=1;else if(r<256)t[n.offset++]=217,t[n.offset++]=r,s=2;else if(r<65536)t[n.offset++]=218,If(t,r,n),s=3;else if(r<4294967296)t[n.offset++]=219,Os(t,r,n),s=5;else throw new Error("String too long");return cg(t,e,n),s+r}function Af(t,e,n){if(isNaN(e))return Af(t,0,n);if(isFinite(e)){if(e!==(e|0))return Math.abs(e)<=34028235e31&&(Pf[0]=e,Math.abs(Math.abs(Pf[0])-Math.abs(e))<1e-4)?(t[n.offset++]=202,pg(t,e,n),5):(t[n.offset++]=203,hg(t,e,n),9)}else return Af(t,e>0?Number.MAX_SAFE_INTEGER:-Number.MAX_SAFE_INTEGER,n);return e>=0?e<128?(t[n.offset++]=e&255,1):e<256?(t[n.offset++]=204,t[n.offset++]=e&255,2):e<65536?(t[n.offset++]=205,If(t,e,n),3):e<4294967296?(t[n.offset++]=206,Os(t,e,n),5):(t[n.offset++]=207,fg(t,e,n),9):e>=-32?(t[n.offset++]=224|e+32,1):e>=-128?(t[n.offset++]=208,ug(t,e,n),2):e>=-32768?(t[n.offset++]=209,lg(t,e,n),3):e>=-2147483648?(t[n.offset++]=210,xr(t,e,n),5):(t[n.offset++]=211,dg(t,e,n),9)}function mg(t,e,n){n>t.length-e.offset&&(n=t.length-e.offset);for(var r="",s=0,o=e.offset,i=e.offset+n;o<i;o++){var a=t[o];if((a&128)===0){r+=String.fromCharCode(a);continue}if((a&224)===192){r+=String.fromCharCode((a&31)<<6|t[++o]&63);continue}if((a&240)===224){r+=String.fromCharCode((a&15)<<12|(t[++o]&63)<<6|(t[++o]&63)<<0);continue}if((a&248)===240){s=(a&7)<<18|(t[++o]&63)<<12|(t[++o]&63)<<6|(t[++o]&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 "+o+". Skip to end of string: "+(e.offset+n));break}return e.offset+=n,r}function yg(t,e){return ya(t,e)<<24>>24}function ya(t,e){return t[e.offset++]}function gg(t,e){return Bu(t,e)<<16>>16}function Bu(t,e){return t[e.offset++]|t[e.offset++]<<8}function On(t,e){return t[e.offset++]|t[e.offset++]<<8|t[e.offset++]<<16|t[e.offset++]<<24}function Uo(t,e){return On(t,e)>>>0}function bg(t,e){return Is[0]=On(t,e),LR[0]}function wg(t,e){return Is[0]=On(t,e),Is[1]=On(t,e),FR[0]}function xg(t,e){let n=Uo(t,e);return On(t,e)*Math.pow(2,32)+n}function Sg(t,e){let n=Uo(t,e);return Uo(t,e)*Math.pow(2,32)+n}function VR(t,e){return Is[0]=On(t,e),Is[1]=On(t,e),UR[0]}function HR(t,e){return Is[0]=On(t,e),Is[1]=On(t,e),zR[0]}function $R(t,e){return ya(t,e)>0}function jR(t,e){let n=t[e.offset++],r;return n<192?r=n&31:n===217?r=ya(t,e):n===218?r=Bu(t,e):n===219&&(r=Uo(t,e)),mg(t,e,r)}function qR(t,e){let n=t[e.offset++];if(n<128)return n;if(n===202)return bg(t,e);if(n===203)return wg(t,e);if(n===204)return ya(t,e);if(n===205)return Bu(t,e);if(n===206)return Uo(t,e);if(n===207)return Sg(t,e);if(n===208)return yg(t,e);if(n===209)return gg(t,e);if(n===210)return On(t,e);if(n===211)return xg(t,e);if(n>223)return(255-n+1)*-1}function GR(t,e){let n=t[e.offset];return n<192&&n>160||n===217||n===218||n===219}function Er(t,e){e.constructor&&(Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor[Symbol.metadata]==null&&sg(e.constructor),WR.set(e.constructor,t),Df[t]=e),e.encode&&(be[t]=e.encode),e.decode&&(Re[t]=e.decode)}function Eg(t){return Df[t]}function Sr(){return{pendingByView:new Map,sentByView:new Map,broadcastPending:new Set,sentBroadcast:new Set,broadcastDeletes:new Set,maxPerTick:32}}function Bf(t){return t._stream??(t._stream=Sr())}function Nu(t,e,n){e.activeViews.size===0&&Bf(t).broadcastPending.add(n)}function Lu(t,e,n,r){let s=t._stream;if(s===void 0)return!0;let o=!1;return s.broadcastPending.delete(r)?o=!0:s.sentBroadcast.delete(r)&&s.broadcastDeletes.add(r),e.forEachActiveView(i=>{let a=s.pendingByView.get(i.id);if(a?.has(r)){a.delete(r),o=!0;return}let c=s.sentByView.get(i.id);if(c?.has(r)){c.delete(r);let u=i.changes.get(n);u===void 0&&(u=new Map,i.changes.set(n,u)),u.set(r,B.DELETE)}}),o}function YR(t,e,n){let r=t._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 o=r.sentByView.get(s.id);if(o!==void 0&&o.size>0){let i=s.changes.get(n);i===void 0&&(i=new Map,s.changes.set(n,i));for(let a of o)i.set(a,B.DELETE);o.clear()}})}}function KR(t,e){let n=t._stream?.pendingByView;if(n===void 0)return!1;for(let[r,s]of n)if(s.size>0&&e.activeViews.get(r)?.deref()!==void 0)return!0;return!1}function XR(t){let e=t._stream;return e!==void 0&&(e.broadcastPending.size>0||e.broadcastDeletes.size>0)}function JR(t,e,n){let r=Bf(t),s=r.pendingByView.get(e);s===void 0&&(s=new Set,r.pendingByView.set(e,s)),s.add(n)}function Fu(t,e){let n=t._stream;n!==void 0&&(n.pendingByView.delete(e),n.sentByView.delete(e),n.priorityByView?.delete(e))}function Nf(t){if(t==null||typeof t!="object")throw new Error("t.quantized(): options object with { min, max } is required.");let{min:e,max:n}=t;if(typeof e!="number"||typeof n!="number"||!(n>e)||!Number.isFinite(e)||!Number.isFinite(n))throw new Error(`t.quantized(): require finite min < max (got min=${e}, max=${n}).`);let r=t.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=t.mode??"clamp";if(s!=="clamp"&&s!=="wrap")throw new Error(`t.quantized(): mode must be "clamp" or "wrap" (got ${JSON.stringify(s)}).`);let o=s==="wrap",i=Math.pow(2,r);return{min:e,max:n,bits:r,wrap:o,wire:ZR[r],range:n-e,span:o?i:e===-n?i-2:i-1}}function Ds(t){return t!==null&&typeof t=="object"&&t.quantized!==void 0}function Rg(t,e){if(t.wrap){if(!Number.isFinite(e))return 0;let r=t.range,s=(e-t.min)%r;s<0&&(s+=r);let o=t.span;return Math.floor(s/r*o+.5)%o}if(e!==e)return 0;let n=e<t.min?t.min:e>t.max?t.max:e;return Math.floor((n-t.min)/t.range*t.span+.5)}function kg(t,e){return t.min+e/t.span*t.range}function QR(t){let e=be[t.wire];return(n,r,s)=>e(n,Rg(t,r),s)}function ek(t,e,n){let r=Re[t.wire];return kg(t,r(e,n))}function tk(t){let e=typeof Object.keys(t)[0]=="string"&&Eg(Object.keys(t)[0]);return{complexTypeKlass:e,childType:e?Object.values(t)[0]:t}}function Vo(t){if(Array.isArray(t))return{array:Vo(t[0])};if(Ds(t))return typeof t.quantized.wire=="string"?t:{quantized:Nf(t.quantized)};if(typeof t.type<"u")return t.type;if(nk(t))return Object.keys(t).every(e=>typeof t[e]=="string")?"string":"number";if(typeof t=="object"&&t!==null){let e=Object.keys(t).find(n=>Df[n]!==void 0);if(e)return t[e]=Vo(t[e]),t}return t}function nk(t){if(typeof t=="function"&&t[Symbol.metadata])return!1;let e=Object.keys(t),n=e.filter(r=>/\d+/.test(r));return!!(n.length>0&&n.length===e.length/2&&t[t[n[0]]]==n[0]||e.length>0&&e.every(r=>typeof t[r]=="string"&&t[r]===r))}function wu(t,e,n){t[e]||Object.defineProperty(t,e,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[e].push(n)}function Pu(t){return t=t-(t>>>1&1431655765),t=(t&858993459)+(t>>>2&858993459),(t+(t>>>4)&252645135)*16843009>>>24}function xu(t){if(t===void 0)return 0;let e=0;for(let n=0,r=t.length;n<r;n++){let s=t[n];s<32&&(e|=1<<s)}return e}function sk(t){let e=[],n=[],r=[],s=[],o=t?.[bt];if(o===void 0)return{names:e,types:n,tags:r,encoders:s};let i=t[br];for(let a=0;a<=o;a++){let c=t[a];if(c===void 0){e[a]=void 0,n[a]=void 0,r[a]=void 0,s[a]=void 0;continue}e[a]=c.name,n[a]=c.type,r[a]=c.tag,s[a]=i?.[a]}return{names:e,types:n,tags:r,encoders:s}}function Lf(t){let e=t.constructor;if(Object.prototype.hasOwnProperty.call(e,aa))return e[aa];let n=e[Symbol.metadata],r=Ie.isValidInstance(t),s=(n?.[An]?.length??0)>0,o=sk(n),i=r&&!s?void 0:e[Ns],a={encoder:e[Qn],filter:i,metadata:n,isSchema:r,filterBitmask:r?xu(n?.[An]):0,hasAnyFullStateOnly:(n?.[zo]?.length??0)>0,hasAnyUnreliable:(n?.[Ms]?.length??0)>0,hasAnyStream:(n?.[nn]?.length??0)>0,hasAnyView:s,fullStateOnlyBitmask:xu(n?.[zo]),unreliableBitmask:xu(n?.[Ms]),streamBitmask:xu(n?.[nn]),names:o.names,types:o.types,tags:o.tags,encoders:o.encoders};return Object.defineProperty(e,aa,{value:a,enumerable:!1,writable:!0,configurable:!0}),a}function ok(t,e,n){if(t.parentRef){if(t.parentRef[I]===e[I]){t._parentIndex=n;return}if(Ag(t,(r,s)=>r[I]===e[I])){t._parentIndex=n;return}}t.parentRef===void 0?(t.parentRef=e,t._parentIndex=n):(t.extraParents={ref:t.parentRef,index:t._parentIndex,next:t.extraParents},t.parentRef=e,t._parentIndex=n)}function ik(t,e,n){if(t.extraParents===void 0){t._parentIndex=n;return}if(t.parentRef[I]===e[I]){t._parentIndex=n;return}for(let r=t.extraParents;r!==void 0;r=r.next)if(r.ref[I]===e[I]){r.index=n;return}}function ak(t,e){if(t.parentRef&&t.parentRef[I]===e[I])return t.extraParents?(t.parentRef=t.extraParents.ref,t._parentIndex=t.extraParents.index,t.extraParents=t.extraParents.next):(t.parentRef=void 0,t._parentIndex=void 0),!0;let n=t.extraParents,r=null;for(;n;){if(n.ref[I]===e[I])return r?r.next=n.next:t.extraParents=n.next,!0;r=n,n=n.next}return t.parentRef===void 0}function ck(t,e){if(t.parentRef!==void 0&&e(t.parentRef,t._parentIndex))return{ref:t.parentRef,index:t._parentIndex};for(let n=t.extraParents;n!==void 0;n=n.next)if(e(n.ref,n.index))return{ref:n.ref,index:n.index}}function Ag(t,e){if(t.parentRef!==void 0&&e(t.parentRef,t._parentIndex))return!0;for(let n=t.extraParents;n!==void 0;n=n.next)if(e(n.ref,n.index))return!0;return!1}function uk(t,e){if(t.parentRef&&t.parentRef[I]===e[I])return t._parentIndex;for(let n=t.extraParents;n!==void 0;n=n.next)if(n.ref[I]===e[I])return n.index}function lk(t){let e=[];t.parentRef&&e.push({ref:t.parentRef,index:t._parentIndex});let n=t.extraParents;for(;n;)e.push({ref:n.ref,index:n.index}),n=n.next;return e}function dk(t,e,n){let r=e.refTarget;if(e.isArray){let o=r.items,i=o[n];if(i!==void 0&&i[I]===t)return!0;for(let a=0,c=o.length;a<c;a++){let u=o[a];if(u!==void 0&&u[I]===t)return!0}return!1}let s=e.getValue(n);return s!==void 0&&s[I]===t}function pk(t,e){Ff(t,e,fk)}function Ff(t,e,n){let r=t.refTarget;if(r[ge]!==void 0){if(t.isPatchOnly)return;if(Array.isArray(r.items)){let s=r.items;for(let o=0,i=s.length;o<i;o++)s[o]!==void 0&&n(e,o)}else if(r.journal!==void 0)for(let[s,o]of r.journal.keyByIndex)r.$items.has(o)&&n(e,s);else if(r.$items!==void 0)for(let s of r.$items.keys())n(e,s)}else{let s=t.metadata;if(!s)return;let o=s[bt]??-1,i=s[ku],a=t.encDescriptor.names;for(let c=0;c<=o;c++){let u=a[c];if(u===void 0||i&&i.includes(c))continue;let l=r[u];l!=null&&n(e,c)}}}function Tg(t,e,n,r){hk(t,e,n),!t.isFullStateOnly&&(t.has()&&t.root?.enqueueChangeTree(t),t.unreliableRecorder?.has()&&t.root?.enqueueUnreliable(t),!t.has()&&!t.unreliableRecorder?.has()&&t.root?.enqueueChangeTree(t))}function hk(t,e,n){if(!e)return;let r=e[I],s=!r._isSchema,o;s?(e=r.parent,n=r.parentIndex,o=e?.[I].metadata):o=r.metadata;let i=(o?.[ua]?.includes(n)?ca:0)|(o?.[zo]?.includes(n)?Fo:0),a=r.flags&Pk|i,c=t.flags;if(t.flags=c|a,a&~c&Fo&&(t.reset(),t.unreliableRecorder?.reset()),!t.root?.types?.hasFilters)return;let d=o?.[An]?.includes(n)??!1,f=o?.[nn]?.includes(n)??!1,h=r.isFiltered||d||f;if(t.isFiltered=h,f&&!s){t.isStreamCollection=!0;let p=Bf(t.ref);if(p.priority===void 0){let g=Ie.getStreamPriority(o,n);g!==void 0&&(p.priority=g)}t.root?.registerStream(t.ref)}if(h){let p=Mg(t);t.isVisibilitySharedWithParent=r.isFiltered&&p&&!f&&(!d||s&&o[n].tag!==Hu)}}function gy(t){let e=t.pendingFilterRefresh;for(let n=0;n<e.length;n++){let r=e[n];(r.flags&la)!==0&&zf(r)}e.length=0}function Mg(t){return t._isSchema||typeof t.refTarget[ge]!="string"}function zf(t){t.flags&=~la;let e=t.root;if(e===void 0||t.parentRef===void 0)return;let n=Mg(t),r=by(t,t.parentRef,t._parentIndex,n);for(let o=t.extraParents;o!==void 0&&r!==mk;o=o.next)r|=by(t,o.ref,o.index,n);if(r===0)return;t.isVisibilitySharedWithParent=(r&vu)!==0;let s=(r&Au)===0;s!==t.isFiltered&&(t.isFiltered=s,!s&&!t.isFullStateOnly&&(t.forEachLiveWithCtx(t,vg),t.has()&&e.enqueueChangeTree(t),t.unreliableRecorder?.has()&&e.enqueueUnreliable(t)),t.forEachChildWithCtx(t,yk))}function by(t,e,n,r){let s=e[I];if(s.root!==t.root||!dk(t,s,n))return 0;s.flags&la&&zf(s);let o=Cg;if(s._isSchema)s.encDescriptor.tags[n]!==void 0||s.isFieldStream(n)||(s.isFiltered?r&&(o|=vu):o|=Au);else if(!s.isFiltered)o|=Au;else if(r&&!s.isStreamCollection){let i=s.parent?.[I];(i?._isSchema?i.encDescriptor.tags[s.parentIndex]:void 0)!==Hu&&(o|=vu)}return o}function gk(t,e,n,r){let s=t.subscribedViews;if(s===void 0)return;let o=t.isStreamCollection,i=o?t.ref:void 0,a=o?void 0:n[I];for(let c=0,u=s.length;c<u;c++){let l=s[c];for(;l!==0;){let d=l&-l;l^=d;let f=c*32+(31-Math.clz32(d)),p=r.activeViews.get(f)?.deref();if(p===void 0){s[c]&=~d;continue}o?JR(i,f,e):a!==void 0&&p.markVisible(a)}}}function bk(t,e){t.root=e;let n=e.add(t);Tg(t,t.parent,t.parentIndex),n&&ga(t,e,Ek)}function wk(t,e,n,r){if(t.addParent(e,r),!n)return;let s=n.add(t);n!==t.root&&(t.root=n,Tg(t,e,r));let o=e?.[I];if(o!==void 0&&o.subscribedViews!==void 0&&e[ge]!==void 0&&gk(o,r,t.ref,n),s){let i=wy[Su];i===void 0&&(i={parentRef:void 0,root:void 0},wy[Su]=i),i.parentRef=t.ref,i.root=n,Su++,ga(t,i,_k),Su--}}function xk(t,e){ga(t,e,Sk)}function Sk(t,e,n){t(e,n)}function ga(t,e,n){let r=t.refTarget;if(r[ge]){if(typeof r[ge]!="string"){let s=r.items;if(s!==void 0)for(let o=0,i=s.length;o<i;o++){let a=s[o];a&&n(e,a[I],o)}else{let o=r.$items,i=r._collectionIndexes;for(let a of o.keys()){let c=o.get(a);c&&n(e,c[I],i?.[a]??a)}}}}else{let o=t.metadata?.[Gr];if(!o)return;let i=t.encDescriptor.names;for(let a=0,c=o.length;a<c;a++){let u=o[a],l=r[i[u]];l&&n(e,l[I],u)}}}function Ek(t,e,n){e.root!==t?e.setRoot(t):t.add(e)}function _k(t,e,n){if(e.root===t.root){t.root.add(e),t.root.moveNextToParent(e);return}e.setParent(t.parentRef,t.root,n)}function Rk(t,e,n){let r=(n&3)<<3;return n<4?t>>>r&255:e>>>r&255}function xy(){return{next:void 0,tail:void 0,nextPosition:0}}function Ak(t){return new Mf(t)}function $o(t,e=t){Object.defineProperty(t,I,{value:Ak(e),enumerable:!1,writable:!0})}function zu(t,e,n,r,s,o,i){i!==void 0?i(e,r,o):typeof n=="string"?be[n]?.(e,r,o):n[Symbol.metadata]!=null?(be.number(e,r[Q],o),(s&B.ADD)===B.ADD&&t.tryEncodeTypeId(e,n,r.constructor,o)):be.number(e,r[Q],o)}function Og(t,e,n,r,s,o,i){let a=t.resyncVisited,c=a.get(t.currentRefId);if(c===void 0&&a.set(t.currentRefId,c=new Set),c.add(r),s!==void 0&&n===B.ADD&&s!==o){let u=s[Q];u!==void 0&&(t.root.removeRef(u),i?.push({ref:e,refId:t.currentRefId,op:B.DELETE,dynamicIndex:r,value:void 0,previousValue:s}))}}function Ck(t,e){let n=t.resyncVisited;n.has(e)||n.set(e,new Set)}function Ok(t,e){if(t.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}Hf(t,t.state,new Set,e)}function Hf(t,e,n,r){let s=e[Q];if(s===void 0||n.has(s))return;n.add(s);let o=e.constructor[Symbol.metadata],i=o?.[Gr];if(i===void 0)return;let a=o[ua];for(let c=0;c<i.length;c++){let u=i[c];if(a!==void 0&&a.includes(u))continue;let l=o[u],d=e[l.name];d&&(Ye.is(l.type)?Hf(t,d,n,r):Ik(t,d,n,r))}}function Ik(t,e,n,r){let s=e[rt]??e,o=s[Q];if(o===void 0||n.has(o))return;n.add(o);let i=t.resyncVisited.get(o);if(i===void 0)return;let a=t.root;s[Ho](i,(c,u)=>{r?.push({ref:e,refId:o,op:B.DELETE,dynamicIndex:u,value:void 0,previousValue:c});let l=c?.[Q];l!==void 0&&a.removeRef(l)},c=>{Ye.isSchema(c)&&Hf(t,c,n,r)})}function $f(t,e,n,r,s,o,i,a,c){let u=t.root,l;if((e&B.DELETE)===B.DELETE){let d=s?.[Q];d!==void 0&&u.removeRef(d),e!==B.DELETE_AND_ADD&&n[Cn](r),l=void 0}if(e!==B.DELETE)if(typeof o=="string")l=Re[o](i,a);else if(Ds(o))l=ek(o.quantized,i,a);else if(Ye.is(o)){let d=Re.number(i,a);if(l=u.refs.get(d),(e&B.ADD)===B.ADD){let f=t.getInstanceType(i,a,o);l||(l=t.createInstanceOfType(f)),u.addRef(d,l,l!==s||e===B.DELETE_AND_ADD&&l===s)}}else{let d=Eg(Object.keys(o)[0]),f=Re.number(i,a);t.resyncVisited!==null&&Ck(t,f);let h=u.refs.has(f)?s||u.refs.get(f):d.constructor.initializeForDecoder();if(l=h.clone(!0),l[ge]=Object.values(o)[0],s){let p=s[Q];if(p!==void 0&&f!==p){(e&B.DELETE)!==B.DELETE&&u.removeRef(p);let g=s.entries(),x;for(;(x=g.next())&&!x.done;){let[b,S]=x.value;typeof S=="object"&&(p=S[Q]),c?.push({ref:s,refId:p,op:B.DELETE,field:b,value:void 0,previousValue:S})}}}u.addRef(f,l,h!==s||e===B.DELETE_AND_ADD&&h===s)}return l}function Vu(t,e,n,r){if(!(t instanceof e))throw new da(`a '${e.name}' was expected, but '${t&&t.constructor.name}' was provided in ${n.constructor.name}#${r}`)}function Dg(t){return t!=null&&t[og]===!0}function Ot(t){return(()=>new er(t))}function ba(t){if(Dg(t)){let e=t._type,n=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 ${n}.`)}return t}function Ey(t){return new er({quantized:Nf(t)})}function $k(t=Hu){return function(e,n){let r=Ie.initialize(e.constructor);Ie.setTag(r,n,t)}}function jk(t,e){let n=Ie.initialize(t.constructor);Ie.setUnreliable(n,e)}function qk(t,e){let n=Ie.initialize(t.constructor);Ie.setPatchOnly(n,e)}function Wk(t,e,n){let r=Gk[n],s=n==="string",o=n==="boolean";return function(i){let a=this[kt],c=a[e];if(i!==c){if(i!=null){if(!o&&r!==void 0&&typeof i!==r&&!(s&&i===null)){let u=i&&i.constructor?` (${i.constructor.name})`:"";throw new da(`a '${r}' was expected, but '${JSON.stringify(i)}'${u} was provided in ${this.constructor.name}#${t}`)}this.constructor[Zn](this[I],e,B.ADD)}else c!=null&&this[I].delete(e);a[e]=i}}}function Yk(t,e,n){return function(r){let s=this[kt],o=s[e];if(r!==o){if(r!=null){Vu(r,n,this,t);let i=this[I],a=this.constructor;o!=null&&o[I]?(i.root?.remove(o[I]),a[Zn](i,e,B.DELETE_AND_ADD)):a[Zn](i,e,B.ADD),r[I]?.setParent(this,i.root,e)}else o!=null&&this[I].delete(e);s[e]=r}}}function Kk(t,e,n,r){let s=r.constructor===Wr,o=r.constructor===Yr;return function(i){let a=this[kt],c=a[e];if(i!==c){if(i!=null){if(s&&!(i instanceof Wr)){let d=new Wr;d[ge]=n,d.push(...i),i=d}else if(o&&!(i instanceof Yr)){let d=new Yr;if(d[ge]=n,i instanceof Map)i.forEach((f,h)=>d.set(h,f));else for(let f in i)d.set(f,i[f]);i=d}else i[ge]=n;let u=this[I],l=this.constructor;c!=null&&c[I]?(u.root?.remove(c[I]),l[Zn](u,e,B.DELETE_AND_ADD)):l[Zn](u,e,B.ADD),i[I]?.setParent(this,u.root,e)}else c!=null&&this[I].delete(e);a[e]=i}}}function Xk(t,e,n){return function(r){let s=this[kt],o=s[e];if(r!=null){if(typeof r!="number")throw new da(`a 'number' was expected, but '${JSON.stringify(r)}' was provided in ${this.constructor.name}#${t}`);if(r=kg(n,Rg(n,r)),r===o)return;this.constructor[Zn](this[I],e,B.ADD)}else{if(r===o)return;o!=null&&this[I].delete(e)}s[e]=r}}function Jk(t,e,n,r){let s;return r?s=Kk(t,e,n,r):typeof n=="string"?s=Wk(t,e,n):Ds(n)?s=Xk(t,e,n.quantized):s=Yk(t,e,n),{get:function(){return this[kt][e]},set:s,enumerable:!0,configurable:!0}}function Zk(t=!0){return function(e,n){let r=Ie.initialize(e.constructor);Ie.setDeprecated(r,n),t&&(r[tn]??(r[tn]={}),r[tn][n]={get:function(){throw new Error(`${n} is deprecated.`)},set:function(s){},enumerable:!1,configurable:!0},Object.defineProperty(e,n,r[tn][n]))}}function Qk(t){if(t&&typeof t=="object"){if(t.array!==void 0)return()=>new Wr;if(t.map!==void 0)return()=>new Yr;if(t.set!==void 0)return()=>new pa;if(t.collection!==void 0)return()=>new fa;if(t.stream!==void 0)return()=>new Mu}else if(typeof t=="function"&&Ye.is(t)&&(!t.prototype.initialize||t.prototype.initialize.length===0))return()=>new t}function It(t,e,n=Ye){if(t==null||typeof t!="object")throw new Error(`schema(): first argument must be a fields object (got ${typeof t}).`);let r={},s={},o={},i={},a=(M,O)=>{typeof O=="function"?i[M]=O:O&&typeof O.clone=="function"?i[M]=()=>O.clone():o[M]=O},c=(M,O)=>{if(O.hasDefault)a(M,O.default);else if(!O.optional){let z=Qk(O.type);z&&(i[M]=z)}},u={},l=[],d=[],f={},h=[],p=[],g={},x=[];for(let M in t){let O=t[M];if(Dg(O)){let z=O.toDefinition();if(z.noSync){if(z.view!==void 0||z.unreliable||z.patchOnly||z.fullStateOnly||z.stream)throw new Error(`schema(${e?`'${e}'`:""}): field '${M}' uses .noSync() together with a sync-only modifier (.view/.unreliable/.patchOnly/.fullStateOnly/.stream). A local-only field cannot be synchronized.`);c(M,z);continue}if(z.patchOnly&&z.fullStateOnly)throw new Error(`schema(${e?`'${e}'`:""}): field '${M}' 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 X=Vo(z.type);if(typeof X=="function"&&!Ye.is(X))throw new Error(`schema(${e?`'${e}'`:""}): field '${M}' is a synced ref to non-Schema class '${X.name||"(anonymous)"}' \u2014 use .noSync(), or Metadata.setFields().`);r[M]=X,z.view!==void 0&&(u[M]=z.view),z.unreliable&&l.push(M),z.patchOnly&&d.push(M),z.deprecated&&(f[M]=z.deprecatedThrows),z.fullStateOnly&&h.push(M),z.stream&&p.push(M),z.streamPriority!==void 0&&(g[M]=z.streamPriority),z.optional&&x.push(M),c(M,z)}else if(typeof O=="function")Ye.is(O)?(r[M]=Vo(O),(!O.prototype.initialize||O.prototype.initialize.length===0)&&(i[M]=()=>new O)):s[M]=O;else throw new Error(`schema(${e?`'${e}'`:""}): field '${M}' must be a t.* builder, Schema subclass, or method (got ${typeof O}).`)}let b=M=>{for(let O in o)M[O]=o[O];for(let O in i)M[O]=i[O]()},S=()=>{let M={};return b(M),M},_=M=>{let O=Object.keys(r),z={};for(let X in M)O.includes(X)||(z[X]=M[X]);return z},P=typeof s.initialize=="function",R=s.initialize??n._initialize,v=class extends n{constructor(...M){let O=M[0];O===void 0?(super(),b(this)):super(Object.assign(S(),P?_(O):O)),R&&new.target===v&&R.apply(this,M)}};e&&Object.defineProperty(v,"name",{value:e}),Ie.setFields(v,r),v._getDefaultValues=S,v._initialize=R,Object.assign(v.prototype,s);for(let M in u)$k(u[M])(v.prototype,M);for(let M of l)jk(v.prototype,M);for(let M of d)qk(v.prototype,M);for(let M in f)Zk(f[M])(v.prototype,M);if(h.length>0||p.length>0){let M=v[Symbol.metadata];for(let O of h)Ie.setFullStateOnly(M,O);for(let O of p)Ie.setStream(M,O);for(let O in g)Ie.setStreamPriority(M,O,g[O])}if(x.length>0){let M=v[Symbol.metadata];for(let O of x)M[M[O]].optional=!0}return v.extend=(M,O)=>It(M,O,v),v}function eP(t){return new Array(t).fill(0).map((e,n)=>n===t-1?"\u2514\u2500 ":" ").join("")}function tP(t,e){if(e===-1||e>=t.length)return!1;let n=t.length-1;for(let r=e;r<n;r++)t[r]=t[r+1];return t.length=n,!0}function nP(t,e,n){let r=~n,s=t.changeTrees;for(let o in s){let i=s[o],a=i.visibleViews;a!==void 0&&e<a.length&&(a[e]&=r);let c=i.subscribedViews;c!==void 0&&e<c.length&&(c[e]&=r);let u=i.tagViews;u!==void 0&&u.forEach(l=>{e<l.length&&(l[e]&=r)})}}function Ry(t){t.structSwitchEmitted||(t.shouldEmitSwitch&&(t.buffer[t.it.offset++]=255,be.number(t.buffer,t.ref[Q],t.it)),t.structSwitchEmitted=!0)}function sP(t,e){Ng(t,e,B.ADD)}function Bg(t,e){if(e._fullSyncGen===t.gen)return;if(e._fullSyncGen=t.gen,!t.hasView||t.view.isChangeTreeVisible(e)){let r=e.encDescriptor;t.changeTree=e,t.ref=e.ref,t.encoder=r.encoder,t.filter=r.filter,t.metadata=r.metadata,t.treeIsFiltered=e.isFiltered,t.isSchema=r.isSchema,t.filterBitmask=r.filterBitmask,t.tags=r.tags,t.structSwitchEmitted=!1,t.shouldEmitSwitch=t.hasView||t.it.offset>t.initialOffset||e!==t.rootChangeTree,e.isArray&&e.collDirty.size>0&&(e.flags|=Uf),Ff(e,t,sP)}ga(e,t,oP)}function oP(t,e,n){Bg(t,e)}function Ng(t,e,n){if(e<0){if(t.treeIsFiltered!==t.emitFiltered)return;Ry(t),t.buffer[t.it.offset++]=Math.abs(e)&255;return}if((t.isSchema?t.treeIsFiltered||(e<32?(t.filterBitmask&1<<e)!==0:t.tags[e]!==void 0):t.treeIsFiltered)!==t.emitFiltered)return;let s=t.isEncodeAll?B.ADD:n;s!==void 0&&(t.filter!==void 0&&!t.filter(t.ref,e,t.view)||(Ry(t),t.encoder(t.self,t.buffer,t.changeTree,e,s,t.it,t.isEncodeAll,t.hasView,t.metadata)))}function kf(t,e){let n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function Ou(t){let e=t.root,n=e.callbacks,r=new WeakMap,s;t.triggerChanges=function(a){let c=new Set;for(let u=0,l=a.length;u<l;u++){let d=a[u],f=d.refId,h=d.ref,p=n[f];if(p){if((d.op&B.DELETE)===B.DELETE&&Ye.isSchema(d.previousValue)){let g=n[d.previousValue[Q]]?.[B.DELETE];for(let x=g?.length-1;x>=0;x--)g[x]()}if(Ye.isSchema(h)){if(!c.has(f)){let g=p?.[B.REPLACE];for(let x=g?.length-1;x>=0;x--)g[x]()}if(p.hasOwnProperty(d.field)){let g=p[d.field];for(let x=g?.length-1;x>=0;x--)g[x](d.value,d.previousValue)}}else{if((d.op&B.DELETE)===B.DELETE){if(d.previousValue!==void 0){let g=p[B.DELETE];for(let x=g?.length-1;x>=0;x--)g[x](d.previousValue,d.dynamicIndex??d.field)}if((d.op&B.ADD)===B.ADD){let g=p[B.ADD];for(let x=g?.length-1;x>=0;x--)g[x](d.value,d.dynamicIndex??d.field)}}else if((d.op&B.ADD)===B.ADD&&d.previousValue!==d.value){let g=p[B.ADD];for(let x=g?.length-1;x>=0;x--)g[x](d.value,d.dynamicIndex??d.field)}if(d.value!==d.previousValue&&(d.value!==void 0||d.previousValue!==void 0)){let g=p[B.REPLACE];for(let x=g?.length-1;x>=0;x--)g[x](d.value,d.dynamicIndex??d.field)}}c.add(f)}}};function o(a,c){let u=c.instance?.constructor[Symbol.metadata]||a,l=c.instance&&typeof c.instance.forEach=="function"||a&&!Ye.is(a);if(u&&!l){let d=function(f,h,p,g){return g&&c.instance[h]!==void 0&&!r.has(s)&&p(c.instance[h],void 0),e.addCallback(f[Q],h,p)};return new Proxy({listen:function(h,p,g=!0){if(c.instance)return d(c.instance,h,p,g);{let x=()=>{};return c.onInstanceAvailable((b,S)=>{x=d(b,h,p,g&&S&&!r.has(s))}),()=>x()}},onChange:function(h){return e.addCallback(c.instance[Q],B.REPLACE,h)},bindTo:function(h,p){return p||(p=Object.keys(u).map(g=>u[g].name)),e.addCallback(c.instance[Q],B.REPLACE,()=>{p.forEach(g=>h[g]=c.instance[g])})}},{get(f,h){let p=u[u[h]];if(p){let g=c.instance?.[h],x=(b=>{let S=i(c.instance).listen(h,(_,P)=>{b(_,!1),S?.()},!1);g?.[Q]!==void 0&&b(g,!0)});return o(p.type,{instance:g?.[Q]!==void 0&&g,parentInstance:c.instance,onInstanceAvailable:x})}else return f[h]},has(f,h){return u[h]!==void 0},set(f,h,p){throw new Error("not allowed")},deleteProperty(f,h){throw new Error("not allowed")}})}else{let d=function(p,g,x){return x&&p.forEach((b,S)=>g(b,S)),e.addCallback(p[Q],B.ADD,(b,S)=>{r.set(g,!0),s=g,g(b,S),r.delete(g),s=void 0})},f=function(p,g){return e.addCallback(p[Q],B.DELETE,g)},h=function(p,g){return e.addCallback(p[Q],B.REPLACE,g)};return new Proxy({onAdd:function(p,g=!0){if(c.instance)return d(c.instance,p,g&&!r.has(s));if(c.onInstanceAvailable){let x=()=>{};return c.onInstanceAvailable((b,S)=>{x=d(b,p,g&&S&&!r.has(s))}),()=>x()}},onRemove:function(p){if(c.instance)return f(c.instance,p);if(c.onInstanceAvailable){let g=()=>{};return c.onInstanceAvailable(x=>{g=f(x,p)}),()=>g()}},onChange:function(p){if(c.instance)return h(c.instance,p);if(c.onInstanceAvailable){let g=()=>{};return c.onInstanceAvailable(x=>{g=h(x,p)}),()=>g()}}},{get(p,g){if(!p[g])throw new Error(`Can't access '${g}' through callback proxy. access the instance directly.`);return p[g]},has(p,g){return p[g]!==void 0},set(p,g,x){throw new Error("not allowed")},deleteProperty(p,g){throw new Error("not allowed")}})}}function i(a){return o(void 0,{instance:a})}return i}function iP(t,e){t.triggerChanges=e}var B,my,Q,Zn,Qn,Tn,Ns,Qe,Cn,Ho,I,ge,rt,qr,Mn,Ru,kt,og,tn,aa,br,bt,Gr,An,gr,Ms,ua,ku,zo,nn,bu,TR,Du,Cs,Pf,MR,ig,CR,ag,be,ma,Is,LR,FR,zR,UR,Re,Df,WR,_g,ZR,Kn,Bs,yy,rk,Ie,Pg,vf,Tf,vg,fk,Cg,Au,vu,mk,yk,wy,Su,kk,Ef,_f,ia,Rf,ca,Fo,_u,Eu,la,Uf,Pk,Kr,Mf,vk,Tk,Vf,Mk,Ig,vn,Dk,Uu,Bk,da,Nk,Sy,Py,Ay,vy,Ty,My,Cy,Oy,en,Wr,Tu,Iy,Dy,By,Ny,Ly,Xn,Yr,Fy,zy,Uy,Vy,Hy,$r,fa,$y,jy,qy,Gy,Wy,jr,pa,Yy,Ky,Xy,Jy,Zy,wr,Mu,Qy,er,Lk,Fk,zk,Uk,Vk,Hk,q,Hu,Gk,eg,tg,ng,rg,Pn,Ye,_y,Cf,FD,rP,Jn,ha,Cu,ky,Of,In,Lg,Fg,zg,Dn,Iu,jf,wt=at(()=>{"use strict";(function(t){t[t.ADD=128]="ADD",t[t.REPLACE=0]="REPLACE",t[t.DELETE=64]="DELETE",t[t.DELETE_AND_MOVE=96]="DELETE_AND_MOVE",t[t.MOVE_AND_ADD=160]="MOVE_AND_ADD",t[t.DELETE_AND_ADD=192]="DELETE_AND_ADD",t[t.CLEAR=10]="CLEAR",t[t.REVERSE=15]="REVERSE",t[t.MOVE=32]="MOVE",t[t.DELETE_BY_REFID=33]="DELETE_BY_REFID",t[t.ADD_BY_REFID=129]="ADD_BY_REFID"})(B||(B={}));Symbol.metadata??(Symbol.metadata=Symbol.for("Symbol.metadata"));my=(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 t="colyseus.symbolRegistry",e=my[t]||(my[t]=Object.create(null));Symbol.for=function(n){return e[n]||(e[n]=Symbol(n))},Symbol.keyFor=function(n){for(let r in e)if(e[r]===n)return r}}Q=Symbol.for("$refId"),Zn="~track",Qn="~encoder",Tn="~decoder",Ns="~filter",Qe="~getByIndex",Cn="~deleteByIndex",Ho="~resyncPrune",I=Symbol.for("$changes"),ge=Symbol.for("$childType"),rt=Symbol.for("$proxyTarget"),qr="~onEncodeEnd",Mn="~reset",Ru="~onDecodeEnd",kt=Symbol.for("$values"),og="~builder",tn="~descriptors",aa="~__encodeDescriptor",br="~encoders",bt="~__numFields",Gr="~__refTypeFieldIndexes",An="~__viewFieldIndexes",gr="$__fieldIndexesByViewTag",Ms="~__unreliableFieldIndexes",ua="~__patchOnlyFieldIndexes",ku="~__fullSyncSkipIndexes",zo="~__fullStateOnlyFieldIndexes",nn="~__streamFieldIndexes",bu="~__streamPriorities";try{TR=new TextEncoder}catch{}Du=new ArrayBuffer(8),Cs=new Int32Array(Du),Pf=new Float32Array(Du),MR=new Float64Array(Du),ig=new BigInt64Array(Du),CR=typeof Buffer<"u"&&Buffer.byteLength,ag=CR?Buffer.byteLength:function(t,e){for(var n=0,r=0,s=0,o=t.length;s<o;s++)n=t.charCodeAt(s),n<128?r+=1:n<2048?r+=2:n<55296||n>=57344?r+=3:(s++,r+=4);return r};be={int8:ug,uint8:OR,int16:lg,uint16:If,int32:xr,uint32:Os,int64:dg,uint64:fg,bigint64:IR,biguint64:DR,float32:pg,float64:hg,boolean:BR,string:NR,number:Af,utf8Write:cg,utf8Length:ag},ma=new ArrayBuffer(8),Is=new Int32Array(ma),LR=new Float32Array(ma),FR=new Float64Array(ma),zR=new BigUint64Array(ma),UR=new BigInt64Array(ma);Re={utf8Read:mg,int8:yg,uint8:ya,int16:gg,uint16:Bu,int32:On,uint32:Uo,float32:bg,float64:wg,int64:xg,uint64:Sg,bigint64:VR,biguint64:HR,boolean:$R,string:jR,number:qR,stringCheck:GR},Df={},WR=new Map;_g="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.";ZR={8:"uint8",16:"uint16",32:"uint32"};Kn=class Kn{constructor(e){m(this,"types",{});m(this,"schemas",new Map);m(this,"hasFilters",!1);e&&this.discoverTypes(e)}static register(e){let n=Object.getPrototypeOf(e);if(n!==Ye){let r=Kn.inheritedTypes.get(n);r||(r=new Set,Kn.inheritedTypes.set(n,r)),r.add(e)}}static cache(e){let n=Kn.cachedContexts.get(e);return n||(n=new Kn(e),Kn.cachedContexts.set(e,n)),n}has(e){return this.schemas.has(e)}get(e){return this.types[e]}add(e,n=this.schemas.size){return this.schemas.has(e)?!1:(this.types[n]=e,e[Symbol.metadata]==null&&Ie.initialize(e),this.schemas.set(e,n),!0)}getTypeId(e){return this.schemas.get(e)}discoverTypes(e){if(!this.add(e))return;Kn.inheritedTypes.get(e)?.forEach(s=>{this.discoverTypes(s)});let n=e;for(;(n=Object.getPrototypeOf(n))&&n!==Ye&&n!==Function.prototype;)this.discoverTypes(n);let r=e[Symbol.metadata];(r[An]||r[nn])&&(this.hasFilters=!0);for(let s in r){let i=r[s].type;if(typeof i!="string"&&!Ds(i))if(typeof i=="function")this.discoverTypes(i);else{let a=Object.values(i)[0];if(typeof a=="string")continue;this.discoverTypes(a)}}}debug(){return`TypeContext ->
1
+ "use strict";(()=>{var nE=Object.create;var cu=Object.defineProperty;var rE=Object.getOwnPropertyDescriptor;var sE=Object.getOwnPropertyNames;var oE=Object.getPrototypeOf,iE=Object.prototype.hasOwnProperty;var Um=t=>{throw TypeError(t)};var aE=(t,e,n)=>e in t?cu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var ht=(t,e)=>()=>(t&&(e=t(t=0)),e);var cE=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),of=(t,e)=>{for(var n in e)cu(t,n,{get:e[n],enumerable:!0})},uE=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of sE(e))!iE.call(t,s)&&s!==n&&cu(t,s,{get:()=>e[s],enumerable:!(r=rE(e,s))||r.enumerable});return t};var lE=(t,e,n)=>(n=t!=null?nE(oE(t)):{},uE(e||!t||!t.__esModule?cu(n,"default",{value:t,enumerable:!0}):n,t));var m=(t,e,n)=>aE(t,typeof e!="symbol"?e+"":e,n),af=(t,e,n)=>e.has(t)||Um("Cannot "+n);var de=(t,e,n)=>(af(t,e,"read from private field"),n?n.call(t):e.get(t)),He=(t,e,n)=>e.has(t)?Um("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),$e=(t,e,n,r)=>(af(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),zs=(t,e,n)=>(af(t,e,"access private method"),n);var Ke,Zo,Hf,Cu,Ou,$s,St,Gy=ht(()=>{"use strict";Ke={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},Zo={TIMED:128,UNRELIABLE:64},Hf=31,Cu={OK:0,REJECTED:1,ERROR:2},Ou={INPUT_REFLECTION:1,INPUT_OPTIONS:2},$s={RENDER_TIME:1,FIXED_TIMESTEP:2,PATCH_RATE:4,SUB_STEPS:8,RECKON_TIME:16},St={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 Pr=ht(()=>{"use strict";Gy()});function Lg(t){Object.defineProperty(t,Symbol.metadata,{value:void 0,writable:!0,configurable:!0,enumerable:!1})}function Vg(t,e,n){for(var r=0,s=0,o=e.length;s<o;s++)r=e.charCodeAt(s),r<128?t[n.offset++]=r:r<2048?(t[n.offset]=192|r>>6,t[n.offset+1]=128|r&63,n.offset+=2):r<55296||r>=57344?(t[n.offset]=224|r>>12,t[n.offset+1]=128|r>>6&63,t[n.offset+2]=128|r&63,n.offset+=3):(s++,r=65536+((r&1023)<<10|e.charCodeAt(s)&1023),t[n.offset]=240|r>>18,t[n.offset+1]=128|r>>12&63,t[n.offset+2]=128|r>>6&63,t[n.offset+3]=128|r&63,n.offset+=4)}function Hg(t,e,n){t[n.offset++]=e&255}function Yk(t,e,n){t[n.offset++]=e&255}function $g(t,e,n){t[n.offset++]=e&255,t[n.offset++]=e>>8&255}function ep(t,e,n){t[n.offset++]=e&255,t[n.offset++]=e>>8&255}function Cr(t,e,n){t[n.offset++]=e&255,t[n.offset++]=e>>8&255,t[n.offset++]=e>>16&255,t[n.offset++]=e>>24&255}function qs(t,e,n){let r=e>>24,s=e>>16,o=e>>8,i=e;t[n.offset++]=i&255,t[n.offset++]=o&255,t[n.offset++]=s&255,t[n.offset++]=r&255}function jg(t,e,n){let r=Math.floor(e/Math.pow(2,32)),s=e>>>0;qs(t,s,n),qs(t,r,n)}function Wg(t,e,n){let r=e/Math.pow(2,32)>>0,s=e>>>0;qs(t,s,n),qs(t,r,n)}function Kk(t,e,n){zg[0]=BigInt.asIntN(64,e),Cr(t,Ws[0],n),Cr(t,Ws[1],n)}function Xk(t,e,n){zg[0]=BigInt.asIntN(64,e),Cr(t,Ws[0],n),Cr(t,Ws[1],n)}function qg(t,e,n){Gf[0]=e,Cr(t,Ws[0],n)}function Gg(t,e,n){qk[0]=e,Cr(t,Ws[0],n),Cr(t,Ws[1],n)}function Jk(t,e,n){t[n.offset++]=e?1:0}function Zk(t,e,n){e||(e="");let r=Ug(e,"utf8"),s=0;if(r<32)t[n.offset++]=r|160,s=1;else if(r<256)t[n.offset++]=217,t[n.offset++]=r,s=2;else if(r<65536)t[n.offset++]=218,ep(t,r,n),s=3;else if(r<4294967296)t[n.offset++]=219,qs(t,r,n),s=5;else throw new Error("String too long");return Vg(t,e,n),s+r}function Yf(t,e,n){if(isNaN(e))return Yf(t,0,n);if(isFinite(e)){if(e!==(e|0))return Math.abs(e)<=34028235e31&&(Gf[0]=e,Math.abs(Math.abs(Gf[0])-Math.abs(e))<1e-4)?(t[n.offset++]=202,qg(t,e,n),5):(t[n.offset++]=203,Gg(t,e,n),9)}else return Yf(t,e>0?Number.MAX_SAFE_INTEGER:-Number.MAX_SAFE_INTEGER,n);return e>=0?e<128?(t[n.offset++]=e&255,1):e<256?(t[n.offset++]=204,t[n.offset++]=e&255,2):e<65536?(t[n.offset++]=205,ep(t,e,n),3):e<4294967296?(t[n.offset++]=206,qs(t,e,n),5):(t[n.offset++]=207,Wg(t,e,n),9):e>=-32?(t[n.offset++]=224|e+32,1):e>=-128?(t[n.offset++]=208,Hg(t,e,n),2):e>=-32768?(t[n.offset++]=209,$g(t,e,n),3):e>=-2147483648?(t[n.offset++]=210,Cr(t,e,n),5):(t[n.offset++]=211,jg(t,e,n),9)}function Yg(t,e,n){n>t.length-e.offset&&(n=t.length-e.offset);for(var r="",s=0,o=e.offset,i=e.offset+n;o<i;o++){var a=t[o];if((a&128)===0){r+=String.fromCharCode(a);continue}if((a&224)===192){r+=String.fromCharCode((a&31)<<6|t[++o]&63);continue}if((a&240)===224){r+=String.fromCharCode((a&15)<<12|(t[++o]&63)<<6|(t[++o]&63)<<0);continue}if((a&248)===240){s=(a&7)<<18|(t[++o]&63)<<12|(t[++o]&63)<<6|(t[++o]&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 "+o+". Skip to end of string: "+(e.offset+n));break}return e.offset+=n,r}function Kg(t,e){return Ma(t,e)<<24>>24}function Ma(t,e){return t[e.offset++]}function Xg(t,e){return Xu(t,e)<<16>>16}function Xu(t,e){return t[e.offset++]|t[e.offset++]<<8}function Ln(t,e){return t[e.offset++]|t[e.offset++]<<8|t[e.offset++]<<16|t[e.offset++]<<24}function ti(t,e){return Ln(t,e)>>>0}function Jg(t,e){return Gs[0]=Ln(t,e),Qk[0]}function Zg(t,e){return Gs[0]=Ln(t,e),Gs[1]=Ln(t,e),eA[0]}function Qg(t,e){let n=ti(t,e);return Ln(t,e)*Math.pow(2,32)+n}function eb(t,e){let n=ti(t,e);return ti(t,e)*Math.pow(2,32)+n}function rA(t,e){return Gs[0]=Ln(t,e),Gs[1]=Ln(t,e),nA[0]}function sA(t,e){return Gs[0]=Ln(t,e),Gs[1]=Ln(t,e),tA[0]}function oA(t,e){return Ma(t,e)>0}function iA(t,e){let n=t[e.offset++],r;return n<192?r=n&31:n===217?r=Ma(t,e):n===218?r=Xu(t,e):n===219&&(r=ti(t,e)),Yg(t,e,r)}function aA(t,e){let n=t[e.offset++];if(n<128)return n;if(n===202)return Jg(t,e);if(n===203)return Zg(t,e);if(n===204)return Ma(t,e);if(n===205)return Xu(t,e);if(n===206)return ti(t,e);if(n===207)return eb(t,e);if(n===208)return Kg(t,e);if(n===209)return Xg(t,e);if(n===210)return Ln(t,e);if(n===211)return Qg(t,e);if(n>223)return(255-n+1)*-1}function cA(t,e){let n=t[e.offset];return n<192&&n>160||n===217||n===218||n===219}function Ir(t,e){e.constructor&&(Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor[Symbol.metadata]==null&&Lg(e.constructor),uA.set(e.constructor,t),tp[t]=e),e.encode&&(Se[t]=e.encode),e.decode&&(Pe[t]=e.decode)}function tb(t){return tp[t]}function Or(){return{pendingByView:new Map,sentByView:new Map,broadcastPending:new Set,sentBroadcast:new Set,broadcastDeletes:new Set,maxPerTick:32}}function np(t){return t._stream??(t._stream=Or())}function Ju(t,e,n){e.activeViews.size===0&&np(t).broadcastPending.add(n)}function Zu(t,e,n,r){let s=t._stream;if(s===void 0)return!0;let o=!1;return s.broadcastPending.delete(r)?o=!0:s.sentBroadcast.delete(r)&&s.broadcastDeletes.add(r),e.forEachActiveView(i=>{let a=s.pendingByView.get(i.id);if(a?.has(r)){a.delete(r),o=!0;return}let c=s.sentByView.get(i.id);if(c?.has(r)){c.delete(r);let u=i.changes.get(n);u===void 0&&(u=new Map,i.changes.set(n,u)),u.set(r,N.DELETE)}}),o}function lA(t,e,n){let r=t._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 o=r.sentByView.get(s.id);if(o!==void 0&&o.size>0){let i=s.changes.get(n);i===void 0&&(i=new Map,s.changes.set(n,i));for(let a of o)i.set(a,N.DELETE);o.clear()}})}}function dA(t,e){let n=t._stream?.pendingByView;if(n===void 0)return!1;for(let[r,s]of n)if(s.size>0&&e.activeViews.get(r)?.deref()!==void 0)return!0;return!1}function fA(t){let e=t._stream;return e!==void 0&&(e.broadcastPending.size>0||e.broadcastDeletes.size>0)}function pA(t,e,n){let r=np(t),s=r.pendingByView.get(e);s===void 0&&(s=new Set,r.pendingByView.set(e,s)),s.add(n)}function Qu(t,e){let n=t._stream;n!==void 0&&(n.pendingByView.delete(e),n.sentByView.delete(e),n.priorityByView?.delete(e))}function rp(t){if(t==null||typeof t!="object")throw new Error("t.quantized(): options object with { min, max } is required.");let{min:e,max:n}=t;if(typeof e!="number"||typeof n!="number"||!(n>e)||!Number.isFinite(e)||!Number.isFinite(n))throw new Error(`t.quantized(): require finite min < max (got min=${e}, max=${n}).`);let r=t.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=t.mode??"clamp";if(s!=="clamp"&&s!=="wrap")throw new Error(`t.quantized(): mode must be "clamp" or "wrap" (got ${JSON.stringify(s)}).`);let o=s==="wrap",i=Math.pow(2,r);return{min:e,max:n,bits:r,wrap:o,wire:hA[r],range:n-e,span:o?i:e===-n?i-2:i-1}}function Ys(t){return t!==null&&typeof t=="object"&&t.quantized!==void 0}function rb(t,e){if(t.wrap){if(!Number.isFinite(e))return 0;let r=t.range,s=(e-t.min)%r;s<0&&(s+=r);let o=t.span;return Math.floor(s/r*o+.5)%o}if(e!==e)return 0;let n=e<t.min?t.min:e>t.max?t.max:e;return Math.floor((n-t.min)/t.range*t.span+.5)}function sb(t,e){return t.min+e/t.span*t.range}function mA(t){let e=Se[t.wire];return(n,r,s)=>e(n,rb(t,r),s)}function yA(t,e,n){let r=Pe[t.wire];return sb(t,r(e,n))}function gA(t){let e=typeof Object.keys(t)[0]=="string"&&tb(Object.keys(t)[0]);return{complexTypeKlass:e,childType:e?Object.values(t)[0]:t}}function ni(t){if(Array.isArray(t))return{array:ni(t[0])};if(Ys(t))return typeof t.quantized.wire=="string"?t:{quantized:rp(t.quantized)};if(typeof t.type<"u")return t.type;if(bA(t))return Object.keys(t).every(e=>typeof t[e]=="string")?"string":"number";if(typeof t=="object"&&t!==null){let e=Object.keys(t).find(n=>tp[n]!==void 0);if(e)return t[e]=ni(t[e]),t}return t}function bA(t){if(typeof t=="function"&&t[Symbol.metadata])return!1;let e=Object.keys(t),n=e.filter(r=>/\d+/.test(r));return!!(n.length>0&&n.length===e.length/2&&t[t[n[0]]]==n[0]||e.length>0&&e.every(r=>typeof t[r]=="string"&&t[r]===r))}function Du(t,e,n){t[e]||Object.defineProperty(t,e,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[e].push(n)}function Vu(t){return t=t-(t>>>1&1431655765),t=(t&858993459)+(t>>>2&858993459),(t+(t>>>4)&252645135)*16843009>>>24}function Nu(t){if(t===void 0)return 0;let e=0;for(let n=0,r=t.length;n<r;n++){let s=t[n];s<32&&(e|=1<<s)}return e}function SA(t){let e=[],n=[],r=[],s=[],o=t?.[At];if(o===void 0)return{names:e,types:n,tags:r,encoders:s};let i=t[vr];for(let a=0;a<=o;a++){let c=t[a];if(c===void 0){e[a]=void 0,n[a]=void 0,r[a]=void 0,s[a]=void 0;continue}e[a]=c.name,n[a]=c.type,r[a]=c.tag,s[a]=i?.[a]}return{names:e,types:n,tags:r,encoders:s}}function sp(t){let e=t.constructor;if(Object.prototype.hasOwnProperty.call(e,xa))return e[xa];let n=e[Symbol.metadata],r=De.isValidInstance(t),s=(n?.[On]?.length??0)>0,o=SA(n),i=r&&!s?void 0:e[Xs],a={encoder:e[cr],filter:i,metadata:n,isSchema:r,filterBitmask:r?Nu(n?.[On]):0,hasAnyFullStateOnly:(n?.[ei]?.length??0)>0,hasAnyUnreliable:(n?.[js]?.length??0)>0,hasAnyStream:(n?.[un]?.length??0)>0,hasAnyView:s,fullStateOnlyBitmask:Nu(n?.[ei]),unreliableBitmask:Nu(n?.[js]),streamBitmask:Nu(n?.[un]),names:o.names,types:o.types,tags:o.tags,encoders:o.encoders};return Object.defineProperty(e,xa,{value:a,enumerable:!1,writable:!0,configurable:!0}),a}function xA(t,e,n){if(t.parentRef){if(t.parentRef[I]===e[I]){t._parentIndex=n;return}if(ib(t,(r,s)=>r[I]===e[I])){t._parentIndex=n;return}}t.parentRef===void 0?(t.parentRef=e,t._parentIndex=n):(t.extraParents={ref:t.parentRef,index:t._parentIndex,next:t.extraParents},t.parentRef=e,t._parentIndex=n)}function _A(t,e,n){if(t.extraParents===void 0){t._parentIndex=n;return}if(t.parentRef[I]===e[I]){t._parentIndex=n;return}for(let r=t.extraParents;r!==void 0;r=r.next)if(r.ref[I]===e[I]){r.index=n;return}}function RA(t,e){if(t.parentRef&&t.parentRef[I]===e[I])return t.extraParents?(t.parentRef=t.extraParents.ref,t._parentIndex=t.extraParents.index,t.extraParents=t.extraParents.next):(t.parentRef=void 0,t._parentIndex=void 0),!0;let n=t.extraParents,r=null;for(;n;){if(n.ref[I]===e[I])return r?r.next=n.next:t.extraParents=n.next,!0;r=n,n=n.next}return t.parentRef===void 0}function EA(t,e){if(t.parentRef!==void 0&&e(t.parentRef,t._parentIndex))return{ref:t.parentRef,index:t._parentIndex};for(let n=t.extraParents;n!==void 0;n=n.next)if(e(n.ref,n.index))return{ref:n.ref,index:n.index}}function ib(t,e){if(t.parentRef!==void 0&&e(t.parentRef,t._parentIndex))return!0;for(let n=t.extraParents;n!==void 0;n=n.next)if(e(n.ref,n.index))return!0;return!1}function kA(t,e){if(t.parentRef&&t.parentRef[I]===e[I])return t._parentIndex;for(let n=t.extraParents;n!==void 0;n=n.next)if(n.ref[I]===e[I])return n.index}function AA(t){let e=[];t.parentRef&&e.push({ref:t.parentRef,index:t._parentIndex});let n=t.extraParents;for(;n;)e.push({ref:n.ref,index:n.index}),n=n.next;return e}function PA(t,e,n){let r=e.refTarget;if(e.isArray){let o=r.items,i=o[n];if(i!==void 0&&i[I]===t)return!0;for(let a=0,c=o.length;a<c;a++){let u=o[a];if(u!==void 0&&u[I]===t)return!0}return!1}let s=e.getValue(n);return s!==void 0&&s[I]===t}function vA(t,e){op(t,e,TA)}function op(t,e,n){let r=t.refTarget;if(r[be]!==void 0){if(t.isPatchOnly)return;if(Array.isArray(r.items)){let s=r.items;for(let o=0,i=s.length;o<i;o++)s[o]!==void 0&&n(e,o)}else if(r.journal!==void 0)for(let[s,o]of r.journal.keyByIndex)r.$items.has(o)&&n(e,s);else if(r.$items!==void 0)for(let s of r.$items.keys())n(e,s)}else{let s=t.metadata;if(!s)return;let o=s[At]??-1,i=s[Uu],a=t.encDescriptor.names;for(let c=0;c<=o;c++){let u=a[c];if(u===void 0||i&&i.includes(c))continue;let l=r[u];l!=null&&n(e,c)}}}function cb(t,e,n,r){MA(t,e,n),!t.isFullStateOnly&&(t.has()&&t.root?.enqueueChangeTree(t),t.unreliableRecorder?.has()&&t.root?.enqueueUnreliable(t),!t.has()&&!t.unreliableRecorder?.has()&&t.root?.enqueueChangeTree(t))}function MA(t,e,n){if(!e)return;let r=e[I],s=!r._isSchema,o;s?(e=r.parent,n=r.parentIndex,o=e?.[I].metadata):o=r.metadata;let i=(o?.[Ra]?.includes(n)?_a:0)|(o?.[ei]?.includes(n)?Qo:0),a=r.flags&HA|i,c=t.flags;if(t.flags=c|a,a&~c&Qo&&(t.reset(),t.unreliableRecorder?.reset()),!t.root?.types?.hasFilters)return;let d=o?.[On]?.includes(n)??!1,f=o?.[un]?.includes(n)??!1,h=r.isFiltered||d||f;if(t.isFiltered=h,f&&!s){t.isStreamCollection=!0;let p=np(t.ref);if(p.priority===void 0){let y=De.getStreamPriority(o,n);y!==void 0&&(p.priority=y)}t.root?.registerStream(t.ref)}if(h){let p=ub(t);t.isVisibilitySharedWithParent=r.isFiltered&&p&&!f&&(!d||s&&o[n].tag!==rl)}}function Xy(t){let e=t.pendingFilterRefresh;for(let n=0;n<e.length;n++){let r=e[n];(r.flags&Ea)!==0&&ip(r)}e.length=0}function ub(t){return t._isSchema||typeof t.refTarget[be]!="string"}function ip(t){t.flags&=~Ea;let e=t.root;if(e===void 0||t.parentRef===void 0)return;let n=ub(t),r=Jy(t,t.parentRef,t._parentIndex,n);for(let o=t.extraParents;o!==void 0&&r!==CA;o=o.next)r|=Jy(t,o.ref,o.index,n);if(r===0)return;t.isVisibilitySharedWithParent=(r&$u)!==0;let s=(r&Hu)===0;s!==t.isFiltered&&(t.isFiltered=s,!s&&!t.isFullStateOnly&&(t.forEachLiveWithCtx(t,ab),t.has()&&e.enqueueChangeTree(t),t.unreliableRecorder?.has()&&e.enqueueUnreliable(t)),t.forEachChildWithCtx(t,OA))}function Jy(t,e,n,r){let s=e[I];if(s.root!==t.root||!PA(t,s,n))return 0;s.flags&Ea&&ip(s);let o=lb;if(s._isSchema)s.encDescriptor.tags[n]!==void 0||s.isFieldStream(n)||(s.isFiltered?r&&(o|=$u):o|=Hu);else if(!s.isFiltered)o|=Hu;else if(r&&!s.isStreamCollection){let i=s.parent?.[I];(i?._isSchema?i.encDescriptor.tags[s.parentIndex]:void 0)!==rl&&(o|=$u)}return o}function IA(t,e,n,r){let s=t.subscribedViews;if(s===void 0)return;let o=t.isStreamCollection,i=o?t.ref:void 0,a=o?void 0:n[I];for(let c=0,u=s.length;c<u;c++){let l=s[c];for(;l!==0;){let d=l&-l;l^=d;let f=c*32+(31-Math.clz32(d)),p=r.activeViews.get(f)?.deref();if(p===void 0){s[c]&=~d;continue}o?pA(i,f,e):a!==void 0&&p.markVisible(a)}}}function DA(t,e){t.root=e;let n=e.add(t);cb(t,t.parent,t.parentIndex),n&&Ca(t,e,FA)}function NA(t,e,n,r){if(t.addParent(e,r),!n)return;let s=n.add(t);n!==t.root&&(t.root=n,cb(t,e,r));let o=e?.[I];if(o!==void 0&&o.subscribedViews!==void 0&&e[be]!==void 0&&IA(o,r,t.ref,n),s){let i=Zy[Bu];i===void 0&&(i={parentRef:void 0,root:void 0},Zy[Bu]=i),i.parentRef=t.ref,i.root=n,Bu++,Ca(t,i,zA),Bu--}}function BA(t,e){Ca(t,e,LA)}function LA(t,e,n){t(e,n)}function Ca(t,e,n){let r=t.refTarget;if(r[be]){if(typeof r[be]!="string"){let s=r.items;if(s!==void 0)for(let o=0,i=s.length;o<i;o++){let a=s[o];a&&n(e,a[I],o)}else{let o=r.$items,i=r._collectionIndexes;for(let a of o.keys()){let c=o.get(a);c&&n(e,c[I],i?.[a]??a)}}}}else{let o=t.metadata?.[ls];if(!o)return;let i=t.encDescriptor.names;for(let a=0,c=o.length;a<c;a++){let u=o[a],l=r[i[u]];l&&n(e,l[I],u)}}}function FA(t,e,n){e.root!==t?e.setRoot(t):t.add(e)}function zA(t,e,n){if(e.root===t.root){t.root.add(e),t.root.moveNextToParent(e);return}e.setParent(t.parentRef,t.root,n)}function UA(t,e,n){let r=(n&3)<<3;return n<4?t>>>r&255:e>>>r&255}function Qy(){return{next:void 0,tail:void 0,nextPosition:0}}function $A(t){return new Jf(t)}function si(t,e=t){Object.defineProperty(t,I,{value:$A(e),enumerable:!1,writable:!0})}function el(t,e,n,r,s,o,i){i!==void 0?i(e,r,o):typeof n=="string"?Se[n]?.(e,r,o):n[Symbol.metadata]!=null?(Se.number(e,r[Q],o),(s&N.ADD)===N.ADD&&t.tryEncodeTypeId(e,n,r.constructor,o)):Se.number(e,r[Q],o)}function db(t,e,n,r,s,o,i){let a=t.resyncVisited,c=a.get(t.currentRefId);if(c===void 0&&a.set(t.currentRefId,c=new Set),c.add(r),s!==void 0&&n===N.ADD&&s!==o){let u=s[Q];u!==void 0&&(t.root.removeRef(u),i?.push({ref:e,refId:t.currentRefId,op:N.DELETE,dynamicIndex:r,value:void 0,previousValue:s}))}}function GA(t,e){let n=t.resyncVisited;n.has(e)||n.set(e,new Set)}function YA(t,e){if(t.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}up(t,t.state,new Set,e)}function up(t,e,n,r){let s=e[Q];if(s===void 0||n.has(s))return;n.add(s);let o=e.constructor[Symbol.metadata],i=o?.[ls];if(i===void 0)return;let a=o[Ra];for(let c=0;c<i.length;c++){let u=i[c];if(a!==void 0&&a.includes(u))continue;let l=o[u],d=e[l.name];d&&(Xe.is(l.type)?up(t,d,n,r):KA(t,d,n,r))}}function KA(t,e,n,r){let s=e[lt]??e,o=s[Q];if(o===void 0||n.has(o))return;n.add(o);let i=t.resyncVisited.get(o);if(i===void 0)return;let a=t.root;s[ri](i,(c,u)=>{r?.push({ref:e,refId:o,op:N.DELETE,dynamicIndex:u,value:void 0,previousValue:c});let l=c?.[Q];l!==void 0&&a.removeRef(l)},c=>{Xe.isSchema(c)&&up(t,c,n,r)})}function lp(t,e,n,r,s,o,i,a,c){let u=t.root,l;if((e&N.DELETE)===N.DELETE){let d=s?.[Q];d!==void 0&&u.removeRef(d),e!==N.DELETE_AND_ADD&&n[Bn](r),l=void 0}if(e!==N.DELETE)if(typeof o=="string")l=Pe[o](i,a);else if(Ys(o))l=yA(o.quantized,i,a);else if(Xe.is(o)){let d=Pe.number(i,a);if(l=u.refs.get(d),(e&N.ADD)===N.ADD){let f=t.getInstanceType(i,a,o);l||(l=t.createInstanceOfType(f)),u.addRef(d,l,l!==s||e===N.DELETE_AND_ADD&&l===s)}}else{let d=tb(Object.keys(o)[0]),f=Pe.number(i,a);t.resyncVisited!==null&&GA(t,f);let h=u.refs.has(f)?s||u.refs.get(f):d.constructor.initializeForDecoder();if(l=h.clone(!0),l[be]=Object.values(o)[0],s){let p=s[Q];if(p!==void 0&&f!==p){(e&N.DELETE)!==N.DELETE&&u.removeRef(p);let y=s.entries(),S;for(;(S=y.next())&&!S.done;){let[b,x]=S.value;typeof x=="object"&&(p=x[Q]),c?.push({ref:s,refId:p,op:N.DELETE,field:b,value:void 0,previousValue:x})}}}u.addRef(f,l,h!==s||e===N.DELETE_AND_ADD&&h===s)}return l}function nl(t,e,n,r){if(!(t instanceof e))throw new ka(`a '${e.name}' was expected, but '${t&&t.constructor.name}' was provided in ${n.constructor.name}#${r}`)}function pb(t){return t!=null&&t[Fg]===!0}function Ft(t){return(()=>new ur(t))}function Oa(t){if(pb(t)){let e=t._type,n=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 ${n}.`)}return t}function tg(t){return new ur({quantized:rp(t)})}function oP(t=rl){return function(e,n){let r=De.initialize(e.constructor);De.setTag(r,n,t)}}function iP(t,e){let n=De.initialize(t.constructor);De.setUnreliable(n,e)}function aP(t,e){let n=De.initialize(t.constructor);De.setPatchOnly(n,e)}function uP(t,e,n){let r=cP[n],s=n==="string",o=n==="boolean";return function(i){let a=this[Mt],c=a[e];if(i!==c){if(i!=null){if(!o&&r!==void 0&&typeof i!==r&&!(s&&i===null)){let u=i&&i.constructor?` (${i.constructor.name})`:"";throw new ka(`a '${r}' was expected, but '${JSON.stringify(i)}'${u} was provided in ${this.constructor.name}#${t}`)}this.constructor[ar](this[I],e,N.ADD)}else c!=null&&this[I].delete(e);a[e]=i}}}function lP(t,e,n){return function(r){let s=this[Mt],o=s[e];if(r!==o){if(r!=null){nl(r,n,this,t);let i=this[I],a=this.constructor;o!=null&&o[I]?(i.root?.remove(o[I]),a[ar](i,e,N.DELETE_AND_ADD)):a[ar](i,e,N.ADD),r[I]?.setParent(this,i.root,e)}else o!=null&&this[I].delete(e);s[e]=r}}}function dP(t,e,n,r){let s=r.constructor===ds,o=r.constructor===fs;return function(i){let a=this[Mt],c=a[e];if(i!==c){if(i!=null){if(s&&!(i instanceof ds)){let d=new ds;d[be]=n,d.push(...i),i=d}else if(o&&!(i instanceof fs)){let d=new fs;if(d[be]=n,i instanceof Map)i.forEach((f,h)=>d.set(h,f));else for(let f in i)d.set(f,i[f]);i=d}else i[be]=n;let u=this[I],l=this.constructor;c!=null&&c[I]?(u.root?.remove(c[I]),l[ar](u,e,N.DELETE_AND_ADD)):l[ar](u,e,N.ADD),i[I]?.setParent(this,u.root,e)}else c!=null&&this[I].delete(e);a[e]=i}}}function fP(t,e,n){return function(r){let s=this[Mt],o=s[e];if(r!=null){if(typeof r!="number")throw new ka(`a 'number' was expected, but '${JSON.stringify(r)}' was provided in ${this.constructor.name}#${t}`);if(r=sb(n,rb(n,r)),r===o)return;this.constructor[ar](this[I],e,N.ADD)}else{if(r===o)return;o!=null&&this[I].delete(e)}s[e]=r}}function pP(t,e,n,r){let s;return r?s=dP(t,e,n,r):typeof n=="string"?s=uP(t,e,n):Ys(n)?s=fP(t,e,n.quantized):s=lP(t,e,n),{get:function(){return this[Mt][e]},set:s,enumerable:!0,configurable:!0}}function hP(t=!0){return function(e,n){let r=De.initialize(e.constructor);De.setDeprecated(r,n),t&&(r[cn]??(r[cn]={}),r[cn][n]={get:function(){throw new Error(`${n} is deprecated.`)},set:function(s){},enumerable:!1,configurable:!0},Object.defineProperty(e,n,r[cn][n]))}}function mP(t){if(t&&typeof t=="object"){if(t.array!==void 0)return()=>new ds;if(t.map!==void 0)return()=>new fs;if(t.set!==void 0)return()=>new Pa;if(t.collection!==void 0)return()=>new Aa;if(t.stream!==void 0)return()=>new Wu}else if(typeof t=="function"&&Xe.is(t)&&(!t.prototype.initialize||t.prototype.initialize.length===0))return()=>new t}function zt(t,e,n=Xe){if(t==null||typeof t!="object")throw new Error(`schema(): first argument must be a fields object (got ${typeof t}).`);let r={},s={},o={},i={},a=(k,M)=>{typeof M=="function"?i[k]=M:M&&typeof M.clone=="function"?i[k]=()=>M.clone():o[k]=M},c=(k,M)=>{if(M.hasDefault)a(k,M.default);else if(!M.optional){let B=mP(M.type);B&&(i[k]=B)}},u={},l=[],d=[],f={},h=[],p=[],y={},S=[];for(let k in t){let M=t[k];if(pb(M)){let B=M.toDefinition();if(B.noSync){if(B.view!==void 0||B.unreliable||B.patchOnly||B.fullStateOnly||B.stream)throw new Error(`schema(${e?`'${e}'`:""}): field '${k}' uses .noSync() together with a sync-only modifier (.view/.unreliable/.patchOnly/.fullStateOnly/.stream). A local-only field cannot be synchronized.`);c(k,B);continue}if(B.patchOnly&&B.fullStateOnly)throw new Error(`schema(${e?`'${e}'`:""}): field '${k}' 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 K=ni(B.type);if(typeof K=="function"&&!Xe.is(K))throw new Error(`schema(${e?`'${e}'`:""}): field '${k}' is a synced ref to non-Schema class '${K.name||"(anonymous)"}' \u2014 use .noSync(), or Metadata.setFields().`);r[k]=K,B.view!==void 0&&(u[k]=B.view),B.unreliable&&l.push(k),B.patchOnly&&d.push(k),B.deprecated&&(f[k]=B.deprecatedThrows),B.fullStateOnly&&h.push(k),B.stream&&p.push(k),B.streamPriority!==void 0&&(y[k]=B.streamPriority),B.optional&&S.push(k),c(k,B)}else if(typeof M=="function")Xe.is(M)?(r[k]=ni(M),(!M.prototype.initialize||M.prototype.initialize.length===0)&&(i[k]=()=>new M)):s[k]=M;else throw new Error(`schema(${e?`'${e}'`:""}): field '${k}' must be a t.* builder, Schema subclass, or method (got ${typeof M}).`)}let b=k=>{for(let M in o)k[M]=o[M];for(let M in i)k[M]=i[M]()},x=()=>{let k={};return b(k),k},R=k=>{let M=Object.keys(r),B={};for(let K in k)M.includes(K)||(B[K]=k[K]);return B},A=typeof s.initialize=="function",E=s.initialize??n._initialize,P=class extends n{constructor(...k){let M=k[0];M===void 0?(super(),b(this)):super(Object.assign(x(),A?R(M):M)),E&&new.target===P&&E.apply(this,k)}};e&&Object.defineProperty(P,"name",{value:e}),De.setFields(P,r),P._getDefaultValues=x,P._initialize=E,Object.assign(P.prototype,s);for(let k in u)oP(u[k])(P.prototype,k);for(let k of l)iP(P.prototype,k);for(let k of d)aP(P.prototype,k);for(let k in f)hP(f[k])(P.prototype,k);if(h.length>0||p.length>0){let k=P[Symbol.metadata];for(let M of h)De.setFullStateOnly(k,M);for(let M of p)De.setStream(k,M);for(let M in y)De.setStreamPriority(k,M,y[M])}if(S.length>0){let k=P[Symbol.metadata];for(let M of S)k[k[M]].optional=!0}return P.extend=(k,M)=>zt(k,M,P),P}function yP(t){return new Array(t).fill(0).map((e,n)=>n===t-1?"\u2514\u2500 ":" ").join("")}function gP(t,e){if(e===-1||e>=t.length)return!1;let n=t.length-1;for(let r=e;r<n;r++)t[r]=t[r+1];return t.length=n,!0}function bP(t,e,n){let r=~n,s=t.changeTrees;for(let o in s){let i=s[o],a=i.visibleViews;a!==void 0&&e<a.length&&(a[e]&=r);let c=i.subscribedViews;c!==void 0&&e<c.length&&(c[e]&=r);let u=i.tagViews;u!==void 0&&u.forEach(l=>{e<l.length&&(l[e]&=r)})}}function rg(t){t.structSwitchEmitted||(t.shouldEmitSwitch&&(t.buffer[t.it.offset++]=255,Se.number(t.buffer,t.ref[Q],t.it)),t.structSwitchEmitted=!0)}function SP(t,e){mb(t,e,N.ADD)}function hb(t,e){if(e._fullSyncGen===t.gen)return;if(e._fullSyncGen=t.gen,!t.hasView||t.view.isChangeTreeVisible(e)){let r=e.encDescriptor;t.changeTree=e,t.ref=e.ref,t.encoder=r.encoder,t.filter=r.filter,t.metadata=r.metadata,t.treeIsFiltered=e.isFiltered,t.isSchema=r.isSchema,t.filterBitmask=r.filterBitmask,t.tags=r.tags,t.structSwitchEmitted=!1,t.shouldEmitSwitch=t.hasView||t.it.offset>t.initialOffset||e!==t.rootChangeTree,e.isArray&&e.collDirty.size>0&&(e.flags|=ap),op(e,t,SP)}Ca(e,t,xP)}function xP(t,e,n){hb(t,e)}function mb(t,e,n){if(e<0){if(t.treeIsFiltered!==t.emitFiltered)return;rg(t),t.buffer[t.it.offset++]=Math.abs(e)&255;return}if((t.isSchema?t.treeIsFiltered||(e<32?(t.filterBitmask&1<<e)!==0:t.tags[e]!==void 0):t.treeIsFiltered)!==t.emitFiltered)return;let s=t.isEncodeAll?N.ADD:n;s!==void 0&&(t.filter!==void 0&&!t.filter(t.ref,e,t.view)||(rg(t),t.encoder(t.self,t.buffer,t.changeTree,e,s,t.it,t.isEncodeAll,t.hasView,t.metadata)))}function qf(t,e){let n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function Gu(t){let e=t.root,n=e.callbacks,r=new WeakMap,s;t.triggerChanges=function(a){let c=new Set;for(let u=0,l=a.length;u<l;u++){let d=a[u],f=d.refId,h=d.ref,p=n[f];if(p){if((d.op&N.DELETE)===N.DELETE&&Xe.isSchema(d.previousValue)){let y=n[d.previousValue[Q]]?.[N.DELETE];for(let S=y?.length-1;S>=0;S--)y[S]()}if(Xe.isSchema(h)){if(!c.has(f)){let y=p?.[N.REPLACE];for(let S=y?.length-1;S>=0;S--)y[S]()}if(p.hasOwnProperty(d.field)){let y=p[d.field];for(let S=y?.length-1;S>=0;S--)y[S](d.value,d.previousValue)}}else{if((d.op&N.DELETE)===N.DELETE){if(d.previousValue!==void 0){let y=p[N.DELETE];for(let S=y?.length-1;S>=0;S--)y[S](d.previousValue,d.dynamicIndex??d.field)}if((d.op&N.ADD)===N.ADD){let y=p[N.ADD];for(let S=y?.length-1;S>=0;S--)y[S](d.value,d.dynamicIndex??d.field)}}else if((d.op&N.ADD)===N.ADD&&d.previousValue!==d.value){let y=p[N.ADD];for(let S=y?.length-1;S>=0;S--)y[S](d.value,d.dynamicIndex??d.field)}if(d.value!==d.previousValue&&(d.value!==void 0||d.previousValue!==void 0)){let y=p[N.REPLACE];for(let S=y?.length-1;S>=0;S--)y[S](d.value,d.dynamicIndex??d.field)}}c.add(f)}}};function o(a,c){let u=c.instance?.constructor[Symbol.metadata]||a,l=c.instance&&typeof c.instance.forEach=="function"||a&&!Xe.is(a);if(u&&!l){let d=function(f,h,p,y){return y&&c.instance[h]!==void 0&&!r.has(s)&&p(c.instance[h],void 0),e.addCallback(f[Q],h,p)};return new Proxy({listen:function(h,p,y=!0){if(c.instance)return d(c.instance,h,p,y);{let S=()=>{};return c.onInstanceAvailable((b,x)=>{S=d(b,h,p,y&&x&&!r.has(s))}),()=>S()}},onChange:function(h){return e.addCallback(c.instance[Q],N.REPLACE,h)},bindTo:function(h,p){return p||(p=Object.keys(u).map(y=>u[y].name)),e.addCallback(c.instance[Q],N.REPLACE,()=>{p.forEach(y=>h[y]=c.instance[y])})}},{get(f,h){let p=u[u[h]];if(p){let y=c.instance?.[h],S=(b=>{let x=i(c.instance).listen(h,(R,A)=>{b(R,!1),x?.()},!1);y?.[Q]!==void 0&&b(y,!0)});return o(p.type,{instance:y?.[Q]!==void 0&&y,parentInstance:c.instance,onInstanceAvailable:S})}else return f[h]},has(f,h){return u[h]!==void 0},set(f,h,p){throw new Error("not allowed")},deleteProperty(f,h){throw new Error("not allowed")}})}else{let d=function(p,y,S){return S&&p.forEach((b,x)=>y(b,x)),e.addCallback(p[Q],N.ADD,(b,x)=>{r.set(y,!0),s=y,y(b,x),r.delete(y),s=void 0})},f=function(p,y){return e.addCallback(p[Q],N.DELETE,y)},h=function(p,y){return e.addCallback(p[Q],N.REPLACE,y)};return new Proxy({onAdd:function(p,y=!0){if(c.instance)return d(c.instance,p,y&&!r.has(s));if(c.onInstanceAvailable){let S=()=>{};return c.onInstanceAvailable((b,x)=>{S=d(b,p,y&&x&&!r.has(s))}),()=>S()}},onRemove:function(p){if(c.instance)return f(c.instance,p);if(c.onInstanceAvailable){let y=()=>{};return c.onInstanceAvailable(S=>{y=f(S,p)}),()=>y()}},onChange:function(p){if(c.instance)return h(c.instance,p);if(c.onInstanceAvailable){let y=()=>{};return c.onInstanceAvailable(S=>{y=h(S,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,S){throw new Error("not allowed")},deleteProperty(p,y){throw new Error("not allowed")}})}}function i(a){return o(void 0,{instance:a})}return i}function _P(t,e){t.triggerChanges=e}var N,Yy,Q,ar,cr,Dn,Xs,st,Bn,ri,I,be,lt,us,Nn,zu,Mt,Fg,cn,xa,vr,At,ls,On,Tr,js,Ra,Uu,ei,un,Iu,Wk,Ku,Ws,Gf,qk,zg,Gk,Ug,Se,va,Gs,Qk,eA,tA,nA,Pe,tp,uA,nb,hA,sr,Ks,Ky,wA,De,ob,Kf,Xf,ab,TA,lb,Hu,$u,CA,OA,Zy,Bu,VA,$f,jf,Sa,Wf,_a,Qo,Fu,Lu,Ea,ap,HA,ps,Jf,jA,WA,cp,qA,fb,In,XA,tl,JA,ka,ZA,eg,og,ig,ag,cg,ug,lg,dg,an,ds,ju,fg,pg,hg,mg,yg,or,fs,gg,bg,wg,Sg,xg,as,Aa,_g,Rg,Eg,kg,Ag,cs,Pa,Pg,Tg,vg,Mg,Cg,Mr,Wu,Og,ur,QA,eP,tP,nP,rP,sP,Y,rl,cP,Ig,Dg,Ng,Bg,Cn,Xe,ng,Zf,HB,wP,ir,Ta,qu,sg,Qf,Fn,yb,gb,bb,zn,Yu,dp,Pt=ht(()=>{"use strict";(function(t){t[t.ADD=128]="ADD",t[t.REPLACE=0]="REPLACE",t[t.DELETE=64]="DELETE",t[t.DELETE_AND_MOVE=96]="DELETE_AND_MOVE",t[t.MOVE_AND_ADD=160]="MOVE_AND_ADD",t[t.DELETE_AND_ADD=192]="DELETE_AND_ADD",t[t.CLEAR=10]="CLEAR",t[t.REVERSE=15]="REVERSE",t[t.MOVE=32]="MOVE",t[t.DELETE_BY_REFID=33]="DELETE_BY_REFID",t[t.ADD_BY_REFID=129]="ADD_BY_REFID"})(N||(N={}));Symbol.metadata??(Symbol.metadata=Symbol.for("Symbol.metadata"));Yy=(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 t="colyseus.symbolRegistry",e=Yy[t]||(Yy[t]=Object.create(null));Symbol.for=function(n){return e[n]||(e[n]=Symbol(n))},Symbol.keyFor=function(n){for(let r in e)if(e[r]===n)return r}}Q=Symbol.for("$refId"),ar="~track",cr="~encoder",Dn="~decoder",Xs="~filter",st="~getByIndex",Bn="~deleteByIndex",ri="~resyncPrune",I=Symbol.for("$changes"),be=Symbol.for("$childType"),lt=Symbol.for("$proxyTarget"),us="~onEncodeEnd",Nn="~reset",zu="~onDecodeEnd",Mt=Symbol.for("$values"),Fg="~builder",cn="~descriptors",xa="~__encodeDescriptor",vr="~encoders",At="~__numFields",ls="~__refTypeFieldIndexes",On="~__viewFieldIndexes",Tr="$__fieldIndexesByViewTag",js="~__unreliableFieldIndexes",Ra="~__patchOnlyFieldIndexes",Uu="~__fullSyncSkipIndexes",ei="~__fullStateOnlyFieldIndexes",un="~__streamFieldIndexes",Iu="~__streamPriorities";try{Wk=new TextEncoder}catch{}Ku=new ArrayBuffer(8),Ws=new Int32Array(Ku),Gf=new Float32Array(Ku),qk=new Float64Array(Ku),zg=new BigInt64Array(Ku),Gk=typeof Buffer<"u"&&Buffer.byteLength,Ug=Gk?Buffer.byteLength:function(t,e){for(var n=0,r=0,s=0,o=t.length;s<o;s++)n=t.charCodeAt(s),n<128?r+=1:n<2048?r+=2:n<55296||n>=57344?r+=3:(s++,r+=4);return r};Se={int8:Hg,uint8:Yk,int16:$g,uint16:ep,int32:Cr,uint32:qs,int64:jg,uint64:Wg,bigint64:Kk,biguint64:Xk,float32:qg,float64:Gg,boolean:Jk,string:Zk,number:Yf,utf8Write:Vg,utf8Length:Ug},va=new ArrayBuffer(8),Gs=new Int32Array(va),Qk=new Float32Array(va),eA=new Float64Array(va),tA=new BigUint64Array(va),nA=new BigInt64Array(va);Pe={utf8Read:Yg,int8:Kg,uint8:Ma,int16:Xg,uint16:Xu,int32:Ln,uint32:ti,float32:Jg,float64:Zg,int64:Qg,uint64:eb,bigint64:rA,biguint64:sA,boolean:oA,string:iA,number:aA,stringCheck:cA},tp={},uA=new Map;nb="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.";hA={8:"uint8",16:"uint16",32:"uint32"};sr=class sr{constructor(e){m(this,"types",{});m(this,"schemas",new Map);m(this,"hasFilters",!1);e&&this.discoverTypes(e)}static register(e){let n=Object.getPrototypeOf(e);if(n!==Xe){let r=sr.inheritedTypes.get(n);r||(r=new Set,sr.inheritedTypes.set(n,r)),r.add(e)}}static cache(e){let n=sr.cachedContexts.get(e);return n||(n=new sr(e),sr.cachedContexts.set(e,n)),n}has(e){return this.schemas.has(e)}get(e){return this.types[e]}add(e,n=this.schemas.size){return this.schemas.has(e)?!1:(this.types[n]=e,e[Symbol.metadata]==null&&De.initialize(e),this.schemas.set(e,n),!0)}getTypeId(e){return this.schemas.get(e)}discoverTypes(e){if(!this.add(e))return;sr.inheritedTypes.get(e)?.forEach(s=>{this.discoverTypes(s)});let n=e;for(;(n=Object.getPrototypeOf(n))&&n!==Xe&&n!==Function.prototype;)this.discoverTypes(n);let r=e[Symbol.metadata];(r[On]||r[un])&&(this.hasFilters=!0);for(let s in r){let i=r[s].type;if(typeof i!="string"&&!Ys(i))if(typeof i=="function")this.discoverTypes(i);else{let a=Object.values(i)[0];if(typeof a=="string")continue;this.discoverTypes(a)}}}debug(){return`TypeContext ->
2
2
  Schema types: ${this.schemas.size}
3
- hasFilters: ${this.hasFilters}`}};m(Kn,"inheritedTypes",new WeakMap),m(Kn,"cachedContexts",new WeakMap);Bs=Kn,yy=63;rk=[Gr,Ms,ua,ku,zo,nn,br];Ie={addField(t,e,n,r,s){if(e>=yy)throw new Error(`Can't define field '${n}'.
4
- Schema instances may only have up to ${yy} fields.`);t[e]=Object.assign(t[e]||{},{type:Vo(r),index:e,name:n}),Object.defineProperty(t,tn,{value:t[tn]||{},enumerable:!1,configurable:!0}),s?t[tn][n]=s:t[tn][n]={value:void 0,writable:!0,enumerable:!0,configurable:!0},Object.defineProperty(t,bt,{value:e,enumerable:!1,configurable:!0}),Object.defineProperty(t,n,{value:e,enumerable:!1,configurable:!0}),typeof t[e].type!="string"&&!Ds(t[e].type)&&(t[Gr]===void 0&&Object.defineProperty(t,Gr,{value:[],enumerable:!1,configurable:!0}),t[Gr].push(e));let o=t[e].type;if(o&&typeof o=="object"&&o.stream!==void 0){if(o.array!==void 0)throw new Error(_g);t[e].stream=!0,t[nn]||Object.defineProperty(t,nn,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[nn].includes(e)||t[nn].push(e);let i=r?.priority;typeof i=="function"&&Ie.setStreamPriority(t,n,i)}},setTag(t,e,n){let r=t[e],s=t[r];if(s.tag=n,t[An]||(Object.defineProperty(t,An,{value:[],enumerable:!1,configurable:!0}),Object.defineProperty(t,gr,{value:{},enumerable:!1,configurable:!0})),t[An].push(r),n<0)t[gr][n]||(t[gr][n]=[]),t[gr][n].push(r);else for(let o=n;o>0;o&=o-1){let i=o&-o;t[gr][i]||(t[gr][i]=[]),t[gr][i].push(r)}},setUnreliable(t,e){let n=t[e];if(typeof t[n].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".`);t[n].unreliable=!0,t[Ms]||Object.defineProperty(t,Ms,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[Ms].push(n)},setPatchOnly(t,e){let n=t[e];if(t[n].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.`);t[n].patchOnly=!0,wu(t,ua,n),wu(t,ku,n)},setDeprecated(t,e){let n=t[e];t[n].deprecated=!0,wu(t,ku,n),Object.defineProperty(t,n,{value:t[n],enumerable:!1,configurable:!0})},setFullStateOnly(t,e){let n=t[e];if(t[n].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.`);t[n].fullStateOnly=!0,wu(t,zo,n)},setStream(t,e){let n=t[e];t[n].stream=!0,t[nn]||Object.defineProperty(t,nn,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[nn].push(n)},setStreamPriority(t,e,n){let r=t[e];t[bu]||Object.defineProperty(t,bu,{value:{},enumerable:!1,configurable:!0,writable:!0}),t[bu][r]=n},getStreamPriority(t,e){return t?.[bu]?.[e]},defineField(t,e,n,r,s){let o=Vo(s),{complexTypeKlass:i,childType:a}=tk(o);Ie.addField(e,n,r,o,Jk(r,n,a,i)),e[tn][r]&&Object.defineProperty(t.prototype,r,e[tn][r]),(typeof o=="string"||Ds(o))&&(e[br]||Object.defineProperty(e,br,{value:[],enumerable:!1,configurable:!0,writable:!0}),e[br][n]=typeof o=="string"?be[o]:QR(o.quantized))},setFields(t,e){let n=t.prototype.constructor;Bs.register(n);let r=Object.getPrototypeOf(n),s=r&&r[Symbol.metadata],o=Ie.initialize(n);n[Zn]||(n[Zn]=Ye[Zn]),n[Qn]||(n[Qn]=Ye[Qn]),n[Tn]||(n[Tn]=Ye[Tn]),n.prototype.toJSON||(n.prototype.toJSON=Ye.prototype.toJSON);let i=o[bt]??(s&&s[bt])??-1;i++,o[br]||Object.defineProperty(o,br,{value:s?.[br]?[...s[br]]:[],enumerable:!1,configurable:!0,writable:!0});for(let a in e){if(o[a]!==void 0)throw new Error(`@colyseus/schema: Duplicate '${a}' definition on '${n.name||"(anonymous)"}'.`);Ie.defineField(n,o,i,a,e[a]),i++}return t},isDeprecated(t,e){return t[e].deprecated===!0},initialize(t){let e=Object.getPrototypeOf(t),n=e[Symbol.metadata],r=t[Symbol.metadata]??Object.create(null);if(e!==Ye&&r===n&&(r=Object.create(null),n)){Object.setPrototypeOf(r,n),Object.defineProperty(r,bt,{value:n[bt],enumerable:!1,configurable:!0,writable:!0}),n[An]!==void 0&&(Object.defineProperty(r,An,{value:[...n[An]],enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(r,gr,{value:{...n[gr]},enumerable:!1,configurable:!0,writable:!0}));for(let s of rk){let o=n[s];o!==void 0&&Object.defineProperty(r,s,{value:[...o],enumerable:!1,configurable:!0,writable:!0})}Object.defineProperty(r,tn,{value:{...n[tn]},enumerable:!1,configurable:!0,writable:!0})}return Object.defineProperty(t,Symbol.metadata,{value:r,writable:!1,configurable:!0}),r},isValidInstance(t){return t.constructor[Symbol.metadata]&&Object.prototype.hasOwnProperty.call(t.constructor[Symbol.metadata],bt)},getFields(t){let e=t[Symbol.metadata],n={};for(let r=0;r<=e[bt];r++)n[e[r].name]=e[r].type;return n},hasViewTagAtIndex(t,e){return t?.[An]?.includes(e)},hasUnreliableAtIndex(t,e){return t?.[Ms]?.includes(e)},hasPatchOnlyAtIndex(t,e){return t?.[ua]?.includes(e)},hasFullStateOnlyAtIndex(t,e){return t?.[zo]?.includes(e)},hasStreamAtIndex(t,e){return t?.[nn]?.includes(e)}},Pg=(t,e,n)=>t(e,n),vf=class{constructor(e){m(this,"dirtyLow",0);m(this,"dirtyHigh",0);m(this,"ops");this.ops=new Uint8Array(Math.max(e+1,1))}record(e,n){let r=this.ops[e];r===0?this.ops[e]=n:r===B.DELETE?this.ops[e]=B.DELETE_AND_ADD:r===B.ADD&&n===B.DELETE_AND_ADD&&(this.ops[e]=B.DELETE_AND_ADD),e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}recordDelete(e,n){this.ops[e]=n,e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}recordRaw(e,n){this.record(e,n)}operationAt(e){let n=this.ops[e];return n===0?void 0:n}setOperationAt(e,n){this.ops[e]=n}forEach(e){this.forEachWithCtx(e,Pg)}forEachWithCtx(e,n){let r=this.dirtyLow,s=this.dirtyHigh,o=this.ops;for(;r!==0;){let i=r&-r,a=31-Math.clz32(i);r^=i,n(e,a,o[a])}for(;s!==0;){let i=s&-s,a=31-Math.clz32(i)+32;s^=i,n(e,a,o[a])}}size(){return Pu(this.dirtyLow)+Pu(this.dirtyHigh)}has(){return(this.dirtyLow|this.dirtyHigh)!==0}reset(){this.dirtyLow=0,this.dirtyHigh=0,this.ops.fill(0)}},Tf=class{constructor(){m(this,"dirty",new Map);m(this,"pureOps",[])}record(e,n){let r=this.dirty.get(e);r===void 0?this.dirty.set(e,n):r===B.DELETE?this.dirty.set(e,B.DELETE_AND_ADD):r===B.ADD&&n===B.DELETE_AND_ADD&&this.dirty.set(e,B.DELETE_AND_ADD)}recordDelete(e,n){this.dirty.set(e,n)}recordRaw(e,n){this.dirty.set(e,n)}recordPure(e){this.pureOps.push([this.dirty.size,e])}operationAt(e){return this.dirty.get(e)}setOperationAt(e,n){this.dirty.has(e)&&this.dirty.set(e,n)}forEach(e){this.forEachWithCtx(e,Pg)}forEachWithCtx(e,n){let r=this.pureOps;if(r.length>0){let s=0,o=0;for(let[i,a]of this.dirty){for(;s<r.length&&r[s][0]<=o;){let c=r[s++][1];n(e,-c,c)}n(e,i,a),o++}for(;s<r.length;){let i=r[s++][1];n(e,-i,i)}}else for(let[s,o]of this.dirty)n(e,s,o)}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 n=new Map;for(let[r,s]of this.dirty)n.set(r+e,s);this.dirty=n}};vg=(t,e)=>{t.isFieldUnreliable(e)?t.ensureUnreliableRecorder().record(e,B.ADD):t.record(e,B.ADD)},fk=(t,e)=>t(e);Cg=1,Au=2,vu=4,mk=Cg|Au|vu;yk=(t,e,n)=>{zf(e)};wy=[],Su=0;kk=(t,e,n)=>t(e,n);Ef=1,_f=2,ia=4,Rf=8,ca=16,Fo=32,_u=64,Eu=128,la=256,Uf=512,Pk=ca|Fo,Kr=class{constructor(e,n=e){m(this,"ref");m(this,"refTarget");m(this,"metadata");m(this,"encDescriptor");m(this,"root");m(this,"parentRef");m(this,"_parentIndex");m(this,"extraParents");m(this,"flags",ia);m(this,"_fullSyncGen",0);m(this,"_isSchema",!1);m(this,"dirtyLow",0);m(this,"dirtyHigh",0);m(this,"opsLow",0);m(this,"opsHigh",0);m(this,"ops");m(this,"collDirty");m(this,"collPureOps");m(this,"unreliableRecorder");m(this,"paused",!1);m(this,"changesNode");m(this,"unreliableChangesNode");m(this,"visibleViews");m(this,"tagViews");m(this,"subscribedViews");this.ref=e,this.refTarget=n;let r=Lf(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 o=this.metadata?.[bt]??0;o>7&&(this.ops=new Uint8Array(o+1))}else this.collDirty=new Map}get isArray(){return this.refTarget!==this.ref}get isFiltered(){return(this.flags&Ef)!==0}set isFiltered(e){this.flags=e?this.flags|Ef:this.flags&~Ef}get isVisibilitySharedWithParent(){return(this.flags&_f)!==0}set isVisibilitySharedWithParent(e){this.flags=e?this.flags|_f:this.flags&~_f}get isNew(){return(this.flags&ia)!==0}set isNew(e){this.flags=e?this.flags|ia:this.flags&~ia}get isUnreliable(){return(this.flags&Rf)!==0}set isUnreliable(e){this.flags=e?this.flags|Rf:this.flags&~Rf}get isPatchOnly(){return(this.flags&ca)!==0}set isPatchOnly(e){this.flags=e?this.flags|ca:this.flags&~ca}get isFullStateOnly(){return(this.flags&Fo)!==0}set isFullStateOnly(e){this.flags=e?this.flags|Fo:this.flags&~Fo}get isStreamCollection(){return(this.flags&_u)!==0}set isStreamCollection(e){this.flags=e?this.flags|_u:this.flags&~_u}get needsRestage(){return(this.flags&Eu)!==0}set needsRestage(e){this.flags=e?this.flags|Eu:this.flags&~Eu}get hasFilteredFields(){return this.isFiltered||this.encDescriptor.hasAnyView}ensureUnreliableRecorder(){return this.unreliableRecorder===void 0&&(this.unreliableRecorder=this._isSchema?new vf(this.metadata?.[bt]??0):new Tf),this.unreliableRecorder}isFieldUnreliable(e){let n=this.encDescriptor;return n.hasAnyUnreliable?e<32?(n.unreliableBitmask&1<<e)!==0:Ie.hasUnreliableAtIndex(this.metadata,e):!1}isFieldFullStateOnly(e){if(this.isFullStateOnly)return!0;let n=this.encDescriptor;return n.hasAnyFullStateOnly?e<32?(n.fullStateOnlyBitmask&1<<e)!==0:Ie.hasFullStateOnlyAtIndex(this.metadata,e):!1}isFieldStream(e){let n=this.encDescriptor;return n.hasAnyStream?e<32?(n.streamBitmask&1<<e)!==0:Ie.hasStreamAtIndex(this.metadata,e):!1}_opAt(e){let n=this.ops;if(n!==void 0)return n[e];let r=(e&3)<<3;return e<4?this.opsLow>>>r&255:this.opsHigh>>>r&255}_opPut(e,n){let r=this.ops;if(r!==void 0){r[e]=n;return}let s=(e&3)<<3,o=~(255<<s);e<4?this.opsLow=this.opsLow&o|n<<s:this.opsHigh=this.opsHigh&o|n<<s}_markDirty(e){e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}record(e,n){if(this._isSchema){let r=this._opAt(e);r===0?this._opPut(e,n):r===B.DELETE?this._opPut(e,B.DELETE_AND_ADD):r===B.ADD&&n===B.DELETE_AND_ADD&&this._opPut(e,B.DELETE_AND_ADD),this._markDirty(e)}else{let r=this.collDirty,s=r.get(e),o;s===void 0?o=n:s===B.DELETE||s===B.ADD&&n===B.DELETE_AND_ADD?o=B.DELETE_AND_ADD:o=s,r.set(e,o)}}recordDelete(e,n){this._isSchema?(this._opPut(e,n),this._markDirty(e)):this.collDirty.set(e,n)}recordRaw(e,n){this._isSchema?(this._opPut(e,n),this._markDirty(e)):this.collDirty.set(e,n)}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 n=this._opAt(e);return n===0?void 0:n}return this.collDirty.get(e)}setOperationAt(e,n){if(this._isSchema)this._opPut(e,n);else{let r=this.collDirty;r.has(e)&&r.set(e,n)}}forEach(e){this.forEachWithCtx(e,kk)}forEachWithCtx(e,n){if(this._isSchema){let o=this.dirtyLow,i=this.dirtyHigh,a=this.ops;if(a!==void 0){for(;o!==0;){let c=o&-o,u=31-Math.clz32(c);o^=c,n(e,u,a[u])}for(;i!==0;){let c=i&-i,u=31-Math.clz32(c)+32;i^=c,n(e,u,a[u])}}else{let c=this.opsLow,u=this.opsHigh;for(;o!==0;){let l=o&-o,d=31-Math.clz32(l);o^=l,n(e,d,Rk(c,u,d))}}return}let r=this.collDirty,s=this.collPureOps;if(s!==void 0&&s.length>0){let o=0,i=0;for(let[a,c]of r){for(;o<s.length&&s[o][0]<=i;){let u=s[o++][1];n(e,-u,u)}n(e,a,c),i++}for(;o<s.length;){let a=s[o++][1];n(e,-a,a)}}else for(let[o,i]of r)n(e,o,i)}size(){return this._isSchema?Pu(this.dirtyLow)+Pu(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&=~Uf}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=ia|Eu,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,n){if(this._isSchema)throw new Error("ChangeTree (Schema): insertAt is not supported");let r=this.collDirty,s=new Map,o=!this.paused&&!this.isFullStateOnly;if(e>0)for(let[i,a]of r)i<e&&s.set(i,a);if(o)for(let i=0;i<n;i++)s.set(e+i,B.ADD);for(let[i,a]of r)i>=e&&s.set(i+n,a);this.collDirty=s,o&&this.root?.enqueueChangeTree(this)}removeAt(e,n){if(this._isSchema)throw new Error("ChangeTree (Schema): removeAt is not supported");let r=this.collDirty,s=e+n,o=!1;for(let a of r.keys())if(a>=s){o=!0;break}if(!o){for(let a=e;a<s;a++)r.delete(a);return}let i=new Map;for(let[a,c]of r)a<e?i.set(a,c):a>=s&&i.set(a-n,c);this.collDirty=i}unshift(e){this.insertAt(0,e)}setRoot(e){bk(this,e)}setParent(e,n,r){wk(this,e,n,r)}forEachChild(e){xk(this,e)}forEachChildWithCtx(e,n){ga(this,e,n)}forEachLive(e){pk(this,e)}forEachLiveWithCtx(e,n){Ff(this,e,n)}operation(e){this.paused||this.isFullStateOnly||(this.recordPure(e),this.root?.enqueueChangeTree(this))}_routeAndRecord(e,n,r){if(!(this.paused||this.isFieldFullStateOnly(e))){if(this.isFieldUnreliable(e)&&!this.isNew){let s=this.ensureUnreliableRecorder();r?s.recordRaw(e,n):s.record(e,n),this.root?.enqueueUnreliable(this);return}r?this.recordRaw(e,n):this.record(e,n),this.root?.enqueueChangeTree(this)}}change(e,n=B.ADD){this._routeAndRecord(e,n,!1)}indexedOperation(e,n){this._routeAndRecord(e,n,!0)}getChange(e){return this.operationAt(e)}pause(){this.paused=!0}resume(){this.paused=!1}untracked(e){let n=this.paused;this.paused=!0;try{return e()}finally{this.paused=n}}markDirty(e,n=B.ADD){let r=this.paused;this.paused=!1;try{this.change(e,n)}finally{this.paused=r}}getValue(e,n=!1){return this.refTarget[Qe](e,n)}delete(e,n){if(e===void 0){try{throw new Error(`@colyseus/schema ${this.ref.constructor.name}: trying to delete non-existing index '${e}'`)}catch(o){console.warn(o)}return}if(this.paused||this.isFieldFullStateOnly(e))return this.getValue(e);let r=this.isFieldUnreliable(e)&&!this.isNew;r?this.ensureUnreliableRecorder().recordDelete(e,n??B.DELETE):this.recordDelete(e,n??B.DELETE);let s=this.getValue(e);return s&&s[I]&&this.root?.remove(s[I]),r?this.root?.enqueueUnreliable(this):this.root?.enqueueChangeTree(this),s}endEncode(){this.reset(),this.changesNode=void 0,this._isSchema||this.refTarget[qr]?.(),this.isNew=!1}endEncodeUnreliable(){this.unreliableRecorder?.reset(),this.unreliableChangesNode=void 0,this._isSchema||this.refTarget[qr]?.()}discard(){this._isSchema||this.refTarget[qr]?.(),this.reset(),this.unreliableRecorder?.reset()}discardAll(){let e=n=>{if(n<0)return;let r=this.getValue(n);r&&r[I]&&r[I].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,n){ok(this,e,n)}setParentIndex(e,n){ik(this,e,n)}removeParent(e=this.parent){return ak(this,e)}findParent(e){return ck(this,e)}hasParent(e){return Ag(this,e)}indexInParent(e){return uk(this,e)}getAllParents(){return lk(this)}},Mf=class{constructor(e){m(this,"ref");m(this,"root");m(this,"parentRef");m(this,"paused",!1);m(this,"isNew",!1);m(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 n=this.ref;if(n[ge]){if(typeof n[ge]!="string")for(let[i,a]of n.entries())a&&e(a[I],n._collectionIndexes?.[i]??i);return}let s=n.constructor?.[Symbol.metadata];if(!s)return;let o=s[Gr]??[];for(let i=0;i<o.length;i++){let a=o[i],c=n[s[a].name];c&&e(c[I],a)}}forEachChildWithCtx(e,n){this.forEachChild((r,s)=>n(e,r,s))}forEachLive(){}forEachLiveWithCtx(){}forEach(){}};vk=function(t,e,n,r,s,o,i,a){if(e[o.offset++]=(r|s)&255,s===B.DELETE)return;let c=n.encDescriptor,u=n.ref,l=u[kt][r]??u[c.names[r]];zu(t,e,c.types[r],l,s,o,c.encoders[r])},Tk=function(t,e,n,r,s,o){if(e[o.offset++]=s&255,be.number(e,r,o),s===B.DELETE)return;let i=n.ref;if((s&B.ADD)===B.ADD){let a=i.$indexes.get(r);be.string(e,a,o)}zu(t,e,i[ge],i[Qe](r),s,o)},Vf=function(t,e,n,r,s,o){if(e[o.offset++]=s&255,be.number(e,r,o),s===B.DELETE)return;let i=n.ref;zu(t,e,i[ge],i[Qe](r),s,o)},Mk=function(t,e,n,r,s,o,i,a){let c=n.refTarget,u=c[ge],l=typeof u!="string",d=a&&n.isFiltered&&l,f;if(d){let p=c.tmpItems[r];if(!p)return;if(f=p[Q],s===B.DELETE)s=B.DELETE_BY_REFID;else if((s&B.ADD)===B.ADD)s=B.ADD_BY_REFID;else if((s&B.MOVE)===B.MOVE)return}else if(s===B.DELETE&&l){let p=c.tmpItems[r];if(!p)return;f=p[Q],s=B.DELETE_BY_REFID}else f=r;if(e[o.offset++]=s&255,be.number(e,f,o),s===B.DELETE||s===B.DELETE_BY_REFID)return;let h=c[Qe](r,i);zu(t,e,u,h,s,o)};Ig=-1,vn={Map:1,Array:2,Set:3,Collection:4,Stream:5};Dk=function(t,e,n,r,s){let o=e[n.offset++],i=r.constructor[Symbol.metadata],a=o>>6<<6,c=o%(a||255),u=i[c];if(u===void 0)return console.warn("@colyseus/schema: field not defined at",{index:c,ref:r.constructor.name,metadata:i}),Ig;let l=u.deprecated===!0,d=l?void 0:r[Qe](c),f=$f(t,a,r,c,d,u.type,e,n,s);l||(f!=null&&(r[u.name]=f),d!==f&&s?.push({ref:r,refId:t.currentRefId,op:a,field:u.name,value:f,previousValue:d}))},Uu=function(t,e,n,r,s){let o=r[rt]??r,i=e[n.offset++];if(i===B.CLEAR){t.removeChildRefs(o,s),o.clear();return}let a=Re.number(e,n),c=o[ge],u=o.constructor.COLLECTION_KIND,l;(i&B.ADD)===B.ADD?u===vn.Map?(l=Re.string(e,n),o.setIndex(a,l)):l=a:l=o.getIndex(a);let d=o[Qe](a),f=$f(t,i,r,a,d,c,e,n,s);if(t.resyncVisited!==null&&Og(t,r,i,l,d,f,s),f!=null)switch(u){case vn.Map:o.$items.set(l,f);break;case vn.Array:o.$setAt(a,f,t.resyncVisited!==null&&i===B.ADD?B.REPLACE:i);break;case vn.Set:case vn.Collection:case vn.Stream:o.$items.has(a)||(o.$items.set(a,f),typeof o.$refId=="number"&&a>=o.$refId&&(o.$refId=a+1));break;default:console.warn(`@colyseus/schema: missing COLLECTION_KIND on ${o.constructor?.name} \u2014 item at index ${a} was not stored.`);break}d!==f&&s?.push({ref:r,refId:t.currentRefId,op:i,dynamicIndex:l,value:f,previousValue:d})},Bk=function(t,e,n,r,s){let o=r[rt]??r,i=e[n.offset++],a;if(i===B.CLEAR){t.removeChildRefs(o,s),o.clear();return}else if(i===B.REVERSE){o.items.reverse();return}else if(i===B.DELETE_BY_REFID){let f=Re.number(e,n),h=t.root.refs.get(f);if(h===void 0||(t.root.removeRef(f),a=o.findIndex(p=>p===h),a===-1))return;o[Cn](a),s?.push({ref:r,refId:t.currentRefId,op:B.DELETE,dynamicIndex:a,value:void 0,previousValue:h});return}else if(i===B.ADD_BY_REFID){let f=Re.number(e,n),h=t.root.refs.get(f);h&&(a=o.findIndex(p=>p===h)),(a===-1||a===void 0)&&(a=o.length)}else a=Re.number(e,n);let c=o[ge],u=a,l=o.items[a],d=$f(t,i,r,a,l,c,e,n,s);t.resyncVisited!==null&&Og(t,r,i,a,l,d,s),d!=null&&d!==l&&o.$setAt(a,d,t.resyncVisited!==null&&i===B.ADD?B.REPLACE:i),l!==d&&s?.push({ref:r,refId:t.currentRefId,op:i,dynamicIndex:u,value:d,previousValue:l})},da=class extends Error{};Nk=(t,e)=>{let n=t.toString(),r=e.toString();return n<r?-1:n>r?1:0},Sy={get:(t,e)=>typeof e!="symbol"&&!isNaN(e)?t.items[e]:Reflect.get(t,e),set:(t,e,n)=>{if(typeof e!="symbol"&&!isNaN(e)){if(n==null)t.$deleteAt(e);else{let r;if(n[I]){Vu(n,t[ge],t,e);let s=t.items[e];t.isMovingItems?(r=t.$wireIndex(Number(e)),s!==void 0?n[I].isNew?t[I].indexedOperation(r,B.MOVE_AND_ADD):(t[I].getChange(r)&B.DELETE)===B.DELETE?t[I].indexedOperation(r,B.DELETE_AND_MOVE):t[I].indexedOperation(r,B.MOVE):n[I].isNew&&t[I].indexedOperation(r,B.ADD),n[I].setParent(t,t[I].root,r)):r=t.$changeAt(Number(e),n),s!==void 0&&s[I].root?.remove(s[I])}else r=t.$changeAt(Number(e),n);t.items[e]=n,r!==void 0&&(t.tmpItems[r]=n)}return!0}return Reflect.set(t,e,n)},deleteProperty:(t,e)=>(typeof e=="number"?t.$deleteAt(e):delete t[e],!0),has:(t,e)=>typeof e!="symbol"&&!isNaN(Number(e))?Reflect.has(t.items,e):Reflect.has(t,e)},en=class en{constructor(...e){m(this,Oy);m(this,Cy);m(this,My);m(this,Ty);m(this,"items",[]);m(this,"tmpItems",[]);m(this,"deletedIndexes",[]);m(this,"isMovingItems",!1);m(this,"_needsCompaction",!1);m(this,Py);this[ge]=void 0,this[rt]=this;let n=new Proxy(this,Sy);return Object.defineProperty(this,I,{value:new Kr(n,this),enumerable:!1,writable:!0}),e.length>0&&this.push(...e),n}static[(Oy=I,Cy=Q,My=rt,Ty=ge,vy=Qn,Ay=Tn,Ns)](e,n,r){if(!r)return!0;let s=e[rt]??e;return typeof s[ge]=="string"||r.isChangeTreeVisible(s.tmpItems[n]?.[I])}static is(e){return Array.isArray(e)||e.array!==void 0}static from(e){return new en(...Array.from(e))}static initializeForDecoder(){let e=Object.create(en.prototype);e.items=[],e.isMovingItems=!1,e._needsCompaction=!1,e[ge]=void 0,e[rt]=e;let n=new Proxy(e,Sy);return $o(e,n),n}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[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}push(...e){let n=this[rt],r=n.items,s=n.tmpItems,o=n[I],i=n[ge],a=s.length;for(let c=0,u=e.length;c<u;c++,a++){let l=e[c];if(l==null)return;typeof l=="object"&&i&&Vu(l,i,n,c),o.indexedOperation(a,B.ADD),r.push(l),s.push(l),l[I]?.setParent(this,o.root,a)}return a}pop(){let e=this[rt],n=e.tmpItems,r=e.deletedIndexes,s=-1;for(let i=n.length-1;i>=0;i--)if(r[i]!==!0){s=i;break}if(s<0)return;let o=e.$isUnsentAdd(s);return e[I].delete(s),o?e.$cancelAdd(s):r[s]=!0,e.items.pop()}at(e){return e<0&&(e+=this.length),this.items[e]}$wireIndex(e){let n=this.deletedIndexes;if(n.length===0)return e;let r=this.tmpItems,s=0;for(let o=0;o<r.length;o++)if(n[o]!==!0){if(s===e)return o;s++}return r.length+(e-s)}$isUnsentAdd(e){let n=this[I];return(n.flags&(Uf|_u))===0&&!n.paused&&typeof this[ge]!="string"&&n.operationAt(e)===B.ADD}$cancelAdd(e,n=!0){let r=this[I],s=this.tmpItems[e];this.tmpItems.splice(e,1),this.deletedIndexes.length>0&&this.deletedIndexes.splice(e,1),r.removeAt(e,1);let o=s?.[I];o!==void 0&&o.root===void 0&&o.removeParent(this),n&&this.$reindexChildren(e)}$reindexChildren(e,n){if(!this[I].hasFilteredFields||typeof this[ge]=="string")return;let r=this.tmpItems,s=r.length;if(n!==void 0)for(;e<s&&r[e]===n[e];)e++;for(let o=e;o<s;o++)r[o]?.[I]?.setParentIndex(this,o)}$changeAt(e,n){if(n==null){console.error("ArraySchema items cannot be null nor undefined; Use `splice(index, 1)` instead.");return}if(this.items[e]===n)return;let r=this.items[e]!==void 0?typeof n=="object"?B.DELETE_AND_ADD:B.REPLACE:B.ADD,s=this.$wireIndex(e),o=this[I];return o.change(s,r),n[I]?.setParent(this,o.root,s),s}$deleteAt(e,n){this[I].delete(this.$wireIndex(e),n)}$setAt(e,n,r){r===B.ADD&&this.items[e]!==void 0?this.items.splice(e,0,n):r===B.DELETE_AND_MOVE?(this.items.splice(e,1),this.items[e]=n):(e>this.items.length&&(this._needsCompaction=!0),this.items[e]=n)}clear(){let e=this[rt];if(e.items.length===0)return;let n=e[I];n.forEachChild((r,s)=>{n.root?.remove(r)}),n.discard(),n.operation(B.CLEAR),e.items.length=0,e.tmpItems.length=0}[Mn](){let e=this[rt]??this,n=e[I];if(n.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]?.[Mn]?.();e.items.length=0,e.tmpItems.length=0,e.deletedIndexes.length=0,n.recycle(),e[Q]=void 0}concat(...e){return new en(...this.items.concat(...e))}join(e){return this.items.join(e)}reverse(){let e=this[rt],n=e[I];if(n.has()||e.deletedIndexes.length>0){let r=e.items.slice().reverse();return this.clear(),this.push(...r),this}return n.operation(B.REVERSE),e.items.reverse(),e.tmpItems.reverse(),e.$reindexChildren(0),this}shift(){let e=this[rt],n=e.items;if(n.length===0)return;let r=e[I],s=e.deletedIndexes,o=0;for(;s[o]===!0;)o++;let i=e.$isUnsentAdd(o);return r.delete(o,B.DELETE),i?e.$cancelAdd(o):s[o]=!0,n.shift()}slice(e,n){let r=new en;return r.push(...this.items.slice(e,n)),r}sort(e=Nk){let n=this[rt];n.isMovingItems=!0;let r=n[I];return n.items.sort(e).forEach((o,i)=>r.change(i,B.REPLACE)),n.tmpItems.sort(e),n.$reindexChildren(0),n.isMovingItems=!1,this}splice(e,n,...r){let s=this[rt],o=s[I],i=s.items,a=s.tmpItems,c=s.deletedIndexes,u=i.length,l=a.length,d=r.length,f=[];for(let p=0;p<l;p++)c[p]!==!0&&f.push(p);let h;if(u>e){n===void 0&&(n=u-e);for(let p=e;p<e+n;p++){let g=f[p],x=s.$isUnsentAdd(g);o.delete(g,B.DELETE),x?(h??(h=[])).push(g):c[g]=!0}}else n=0;if(d>0){let p=f[e]??u,g=Math.min(d,n);for(let b=0;b<g;b++){let S=p+b,_,P=h!==void 0?h.indexOf(S):-1;P!==-1?(h.splice(P,1),_=B.ADD):_=c[S]?B.DELETE_AND_ADD:B.ADD,o.indexedOperation(S,_),a[S]=r[b],c[S]=!1,r[b][I]?.setParent(this,o.root,S)}let x=d-g;if(x>0){let b=p+g;o.insertAt(b,x);for(let S=0;S<x;S++)r[g+S][I]?.setParent(this,o.root,b+S);c.length>0&&c.splice(b,0,...new Array(x).fill(!1)),a.splice(b,0,...r.slice(g)),s.$reindexChildren(b+x)}}if(h!==void 0&&h.length>0){for(let p=h.length-1;p>=0;p--)s.$cancelAdd(h[p],!1);s.$reindexChildren(h[0])}return o.root?.enqueueChangeTree(o),i.splice(e,n,...r)}unshift(...e){let n=this[rt],r=n[I];r.unshift(e.length);for(let o=0;o<e.length;o++)e[o]?.[I]?.setParent(this,r.root,o);let s=n.deletedIndexes;return s.length>0&&s.unshift(...new Array(e.length).fill(!1)),n.tmpItems.unshift(...e),n.$reindexChildren(e.length),n.items.unshift(...e)}indexOf(e,n){return this.items.indexOf(e,n)}lastIndexOf(e,n=this.length-1){return this.items.lastIndexOf(e,n)}every(e,n){return this.items.every(e,n)}some(e,n){return this.items.some(e,n)}forEach(e,n){return this.items.forEach(e,n)}map(e,n){return this.items.map(e,n)}filter(e,n){return this.items.filter(e,n)}reduce(e,n){return this.items.reduce.apply(this.items,arguments)}reduceRight(e,n){return this.items.reduceRight.apply(this.items,arguments)}find(e,n){return this.items.find(e,n)}findIndex(e,n){return this.items.findIndex(e,n)}fill(e,n,r){throw new Error("ArraySchema#fill() not implemented")}copyWithin(e,n,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 en}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}includes(e,n){return this.items.includes(e,n)}flatMap(e,n){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,n){let r=this.items.slice();return e<0&&(e+=this.length),r[e]=n,new en(...r)}toReversed(){return this.items.slice().reverse()}toSorted(e){return this.items.slice().sort(e)}toSpliced(e,n,...r){let s=this.items.slice();return s.splice.apply(s,arguments),s}shuffle(){return this.move(e=>{let n=this.items.length;for(;n!=0;){let r=Math.floor(Math.random()*n);n--,[this[n],this[r]]=[this[r],this[n]]}})}move(e){return this.isMovingItems=!0,e(this),this.isMovingItems=!1,this}[(Py=Symbol.unscopables,Qe)](e,n=!1){let r=this[rt]??this;return n||r.deletedIndexes[e]?r.items[e]:r.tmpItems[e]||r.items[e]}[Cn](e){let n=this[rt]??this;n.items[e]=void 0,n._needsCompaction=!0}[qr](){let e=this.tmpItems;this.tmpItems=this.items.slice(),this.deletedIndexes.length>0&&(this.$reindexChildren(0,e),this.deletedIndexes.length=0)}[Ru](){let e=this[rt]??this;e._needsCompaction&&(e._needsCompaction=!1,e.items=e.items.filter(n=>n!==void 0))}[Ho](e,n,r){let s=this[rt]??this,o=s.items,i=!1;for(let a=0;a<o.length;a++){let c=o[a];if(e.has(a)){r(c);continue}i=!0,n(c,a),s[Cn](a)}i&&s[Ru]()}toArray(){return this.items.slice(0)}toJSON(){return this.toArray().map(e=>typeof e.toJSON=="function"?e.toJSON():e)}clone(e){let n;return e?(n=new en,n.push(...this.items)):n=new en(...this.map(r=>r[I]?r.clone():r)),n}};m(en,vy,Mk),m(en,Ay,Bk),m(en,"COLLECTION_KIND",vn.Array);Wr=en;Er("array",{constructor:Wr});Tu=class{constructor(){m(this,"keyByIndex",new Map);m(this,"indexByKey",Object.create(null));m(this,"nextIndex",0);m(this,"snapshots")}indexOf(e){let n=this.indexByKey[e];return n===void 0?void 0:n}assign(e){let n=this.nextIndex++;return this.indexByKey[e]=n,this.keyByIndex.set(n,e),n}snapshot(e,n){(this.snapshots??(this.snapshots=new Map)).set(e,n)}forgetSnapshot(e){this.snapshots?.delete(e)}snapshotAt(e){return this.snapshots?.get(e)}setIndex(e,n){this.keyByIndex.set(e,n),this.indexByKey[n]=e}keyOf(e){return this.keyByIndex.get(e)}cleanupAfterEncode(){if(this.snapshots!==void 0){for(let[e]of this.snapshots){let n=this.keyByIndex.get(e);n!==void 0&&(delete this.indexByKey[n],this.keyByIndex.delete(e))}this.snapshots.clear()}}reset(){this.indexByKey=Object.create(null),this.keyByIndex.clear(),this.snapshots?.clear(),this.nextIndex=0}},Xn=class Xn{constructor(e){m(this,Ly);m(this,Ny);m(this,"childType");m(this,By);m(this,"$items",new Map);m(this,"journal",new Tu);m(this,"_stream");if(Object.defineProperty(this,I,{value:new Kr(this),enumerable:!1,writable:!0}),this[ge]=void 0,e)if(e instanceof Map||e instanceof Xn)e.forEach((n,r)=>this.set(r,n));else for(let n in e)this.set(n,e[n])}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Sr())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Sr())).priority=e}get $indexes(){return this.journal.keyByIndex}get _collectionIndexes(){return this.journal.indexByKey}static[(Ly=I,Ny=Q,By=ge,Dy=Qn,Iy=Tn,Ns)](e,n,r){if(!r||typeof e[ge]=="string")return!0;let s=e[Qe](n)??e.journal.snapshotAt(n);return r.isChangeTreeVisible(s[I])}static is(e){return e.map!==void 0}static initializeForDecoder(){let e=Object.create(Xn.prototype);return e.$items=new Map,e.journal=new Tu,e[ge]=void 0,$o(e),e}[Symbol.iterator](){return this.$items[Symbol.iterator]()}get[Symbol.toStringTag](){return this.$items[Symbol.toStringTag]}static get[Symbol.species](){return Xn}set(e,n){if(n==null)throw new Error(`MapSchema#set('${e}', ${n}): trying to set ${n} value on '${e}'.`);typeof n=="object"&&this[ge]&&Vu(n,this[ge],this,e),e=e.toString();let r=this[I],s=n[I]!==void 0,o=this.journal,i=o.indexOf(e),a;if(i!==void 0){a=B.REPLACE;let c=this.$items.get(e);if(c===n)return;s&&(a=B.DELETE_AND_ADD,c!==void 0&&c[I].root?.remove(c[I])),o.snapshotAt(i)!==void 0&&o.forgetSnapshot(i)}else i=o.assign(e),a=B.ADD;return this.$items.set(e,n),a===B.ADD&&r.isStreamCollection?r.root!==void 0&&Nu(this,r.root,i):r.change(i,a),s&&n[I].setParent(this,r.root,i),this}get(e){return this.$items.get(e)}getOrInsert(e,n){return this.$items.has(e)?this.$items.get(e):(this.set(e,n),n)}getOrInsertComputed(e,n){if(this.$items.has(e))return this.$items.get(e);let r=n(e);return this.set(e,r),r}delete(e){if(!this.$items.has(e))return!1;let n=this.journal.indexOf(e),r=this.$items.get(e),s=this[I];if(s.isStreamCollection){let o=s.root,i=!1;return o!==void 0&&(i=Lu(this,o,this[Q],n)),r?.[I]!==void 0&&o?.remove(r[I]),this.$items.delete(e),i||this.journal.snapshot(n,r),!0}return this.journal.snapshot(n,r),s.delete(n),this.$items.delete(e)}clear(){let e=this[I];e.discard(),e.forEachChild((n,r)=>{e.root?.remove(n)}),this.journal.reset(),this.$items.clear(),e.operation(B.CLEAR)}[Mn](){let e=this[I];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed MapSchema (pooling not supported).");this.$items.forEach(n=>n?.[Mn]?.()),this.$items.clear(),this.journal.reset(),e.recycle(),this[Q]=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[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}setIndex(e,n){this.journal.setIndex(e,n)}getIndex(e){return this.journal.keyOf(e)}[Qe](e){let n=this.journal.keyOf(e);return n!==void 0?this.$items.get(n):void 0}[Cn](e){let n=this.journal.keyOf(e);n!==void 0&&(this.$items.delete(n),this.journal.keyByIndex.delete(e))}[Ho](e,n,r){let s=null;if(this.$items.forEach((o,i)=>{if(e.has(i)){r(o);return}(s??(s=new Set)).add(i),n(o,i)}),s!==null){s.forEach(i=>{this.$items.delete(i),delete this.journal.indexByKey[i]});let o=[];this.journal.keyByIndex.forEach((i,a)=>{s.has(i)&&o.push(a)});for(let i=0;i<o.length;i++)this.journal.keyByIndex.delete(o[i])}}[qr](){this.journal.cleanupAfterEncode()}_dropView(e){Fu(this,e)}_unregister(){}toJSON(){return Object.fromEntries(Array.from(this,([n,r])=>[n,typeof r.toJSON=="function"?r.toJSON():r]))}clone(e){let n;return e?n=Object.assign(new Xn,this):(n=new Xn,this.forEach((r,s)=>{r[I]?n.set(s,r.clone()):n.set(s,r)})),n}};m(Xn,Dy,Tk),m(Xn,Iy,Uu),m(Xn,"COLLECTION_KIND",vn.Map);Yr=Xn;Er("map",{constructor:Yr});$r=class $r{constructor(e){m(this,Hy);m(this,Vy);m(this,Uy);m(this,"$items",new Map);m(this,"deletedItems",{});m(this,"$refId",0);m(this,"_stream");Object.defineProperty(this,I,{value:new Kr(this),enumerable:!1,writable:!0}),this[ge]=void 0,e&&e.forEach(n=>this.add(n))}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Sr())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Sr())).priority=e}static[(Hy=I,Vy=Q,Uy=ge,zy=Qn,Fy=Tn,Ns)](e,n,r){return!r||typeof e[ge]=="string"||r.isChangeTreeVisible((e[Qe](n)??e.deletedItems[n])[I])}static is(e){return e.collection!==void 0}static initializeForDecoder(){let e=Object.create($r.prototype);return e.$items=new Map,e.deletedItems={},e.$refId=0,e[ge]=void 0,$o(e),e}add(e){let n=this.$refId++,r=this[I];return this.$items.set(n,e),r.isStreamCollection?r.root!==void 0&&Nu(this,r.root,n):r.change(n),e[I]!==void 0&&e[I].setParent(this,r.root,n),n}at(e){let n=Array.from(this.$items.keys())[e];return this.$items.get(n)}entries(){return this.$items.entries()}delete(e){let n=this.$items.entries(),r,s;for(;(s=n.next())&&!s.done;)if(e===s.value[1]){r=s.value[0];break}if(r===void 0)return!1;let o=this[I];if(o.isStreamCollection){let i=o.root,a=this.$items.get(r);return i!==void 0&&Lu(this,i,this[Q],r),a?.[I]!==void 0&&i?.remove(a[I]),this.deletedItems[r]=a,this.$items.delete(r)}return this.deletedItems[r]=o.delete(r),this.$items.delete(r)}clear(){let e=this[I];e.discard(),e.forEachChild((n,r)=>{e.root?.remove(n)}),this.$items.clear(),e.operation(B.CLEAR)}[Mn](){let e=this[I];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed CollectionSchema (pooling not supported).");this.$items.forEach(n=>n?.[Mn]?.()),this.$items.clear(),this.deletedItems={},this.$refId=0,e.recycle(),this[Q]=void 0}has(e){return Array.from(this.$items.values()).some(n=>n===e)}forEach(e){this.$items.forEach((n,r,s)=>e(n,r,this))}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}[Symbol.iterator](){return this.$items.values()}setIndex(e,n){}getIndex(e){return e}[Qe](e){return this.$items.get(e)}[Cn](e){this.$items.delete(e)}[Ho](e,n,r){let s=null;if(this.$items.forEach((o,i)=>{if(e.has(i)){r(o);return}(s??(s=[])).push(i),n(o,i)}),s!==null)for(let o=0;o<s.length;o++)this[Cn](s[o])}[qr](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){Fu(this,e)}_unregister(){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach((n,r)=>{e.push(typeof n.toJSON=="function"?n.toJSON():n)}),e}clone(e){let n;return e?n=Object.assign(new $r,this):(n=new $r,this.forEach(r=>{r[I]?n.add(r.clone()):n.add(r)})),n}};m($r,zy,Vf),m($r,Fy,Uu),m($r,"COLLECTION_KIND",vn.Collection);fa=$r;Er("collection",{constructor:fa});jr=class jr{constructor(e){m(this,Wy);m(this,Gy);m(this,qy);m(this,"$items",new Map);m(this,"deletedItems",{});m(this,"$refId",0);m(this,"_stream");Object.defineProperty(this,I,{value:new Kr(this),enumerable:!1,writable:!0}),this[ge]=void 0,e&&e.forEach(n=>this.add(n))}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Sr())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Sr())).priority=e}static[(Wy=I,Gy=Q,qy=ge,jy=Qn,$y=Tn,Ns)](e,n,r){return!r||typeof e[ge]=="string"||r.isVisible((e[Qe](n)??e.deletedItems[n])[I])}static is(e){return e.set!==void 0}static initializeForDecoder(){let e=Object.create(jr.prototype);return e.$items=new Map,e.deletedItems={},e.$refId=0,e[ge]=void 0,$o(e),e}add(e){if(this.has(e))return!1;let n=this.$refId++,r=this[I];return this.$items.set(n,e),r.isStreamCollection?r.root!==void 0&&Nu(this,r.root,n):r.change(n,B.ADD),e[I]!==void 0&&e[I].setParent(this,r.root,n),n}entries(){return this.$items.entries()}delete(e){let n=this.$items.entries(),r,s;for(;(s=n.next())&&!s.done;)if(e===s.value[1]){r=s.value[0];break}if(r===void 0)return!1;let o=this[I];if(o.isStreamCollection){let i=o.root,a=this.$items.get(r);return i!==void 0&&Lu(this,i,this[Q],r),a?.[I]!==void 0&&i?.remove(a[I]),this.deletedItems[r]=a,this.$items.delete(r)}return this.deletedItems[r]=o.delete(r),this.$items.delete(r)}clear(){let e=this[I];e.discard(),this.$items.clear(),e.operation(B.CLEAR)}[Mn](){let e=this[I];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed SetSchema (pooling not supported).");this.$items.forEach(n=>n?.[Mn]?.()),this.$items.clear(),this.deletedItems={},this.$refId=0,e.recycle(),this[Q]=void 0}has(e){let n=this.$items.values(),r=!1,s;for(;(s=n.next())&&!s.done;)if(e===s.value){r=!0;break}return r}forEach(e){this.$items.forEach((n,r,s)=>e(n,r,this))}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}[Symbol.iterator](){return this.$items.values()}setIndex(e,n){}getIndex(e){return e}[Qe](e){return this.$items.get(e)}[Cn](e){this.$items.delete(e)}[Ho](e,n,r){let s=null;if(this.$items.forEach((o,i)=>{if(e.has(i)){r(o);return}(s??(s=[])).push(i),n(o,i)}),s!==null)for(let o=0;o<s.length;o++)this[Cn](s[o])}[qr](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){Fu(this,e)}_unregister(){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach((n,r)=>{e.push(typeof n.toJSON=="function"?n.toJSON():n)}),e}clone(e){let n;return e?n=Object.assign(new jr,this):(n=new jr,this.forEach(r=>{r[I]?n.add(r.clone()):n.add(r)})),n}};m(jr,jy,Vf),m(jr,$y,Uu),m(jr,"COLLECTION_KIND",vn.Set);pa=jr;Er("set",{constructor:pa});wr=class wr{constructor(){m(this,Zy);m(this,Jy);m(this,Xy);m(this,"$items",new Map);m(this,"$nextPosition",0);m(this,"_itemIndex",new Map);m(this,"_stream");Object.defineProperty(this,I,{value:new Kr(this),enumerable:!1,writable:!0}),this[ge]=void 0}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Sr())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Sr())).priority=e}static[(Zy=I,Jy=Q,Xy=ge,Ky=Qn,Yy=Tn,Ns)](e,n,r){if(!r)return!0;let s=e[Qe](n);return s===void 0?!1:r.isVisible(s[I])}static is(e){return e&&e.stream!==void 0}static initializeForDecoder(){let e=Object.create(wr.prototype);return e.$items=new Map,e.$nextPosition=0,e._itemIndex=new Map,e[ge]=void 0,$o(e),e}add(e){if(this._itemIndex.has(e))return-1;let n=this.$nextPosition++;this.$items.set(n,e),this._itemIndex.set(e,n);let s=this[I].root;return e[I]!==void 0&&e[I].setParent(this,s,n),s!==void 0&&Nu(this,s,n),n}remove(e){let n=this._itemIndex.get(e);if(n===void 0)return!1;this._itemIndex.delete(e),this.$items.delete(n);let r=this[I].root;return r!==void 0&&(Lu(this,r,this[Q],n),e[I]!==void 0&&r.remove(e[I])),!0}has(e){return this._itemIndex.has(e)}clear(){let e=this[I].root;if(e!==void 0){YR(this,e,this[Q]);for(let n of this.$items.values())n[I]!==void 0&&e.remove(n[I])}this.$items.clear(),this._itemIndex.clear()}forEach(e){for(let[n,r]of this.$items)e(r,n,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,n){}getIndex(e){return e}[Qe](e){return this.$items.get(e)}[Cn](e){let n=this.$items.get(e);n!==void 0&&(this._itemIndex.delete(n),this.$items.delete(e))}[Ho](){}[qr](){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach(n=>{e.push(typeof n?.toJSON=="function"?n.toJSON():n)}),e}clone(e){if(e)return Object.assign(new wr,this);let n=new wr;return n.maxPerTick=this.maxPerTick,this.forEach(r=>{n.add(typeof r?.clone=="function"?r.clone():r)}),n}_dropView(e){Fu(this,e)}_unregister(){}};m(wr,"$isStream",!0),m(wr,Ky,Vf),m(wr,Yy,Uu),m(wr,"COLLECTION_KIND",vn.Stream);Mu=wr;Er("stream",{constructor:Mu});Qy=og;er=class{constructor(e){m(this,Qy,!0);m(this,"_type");m(this,"_default");m(this,"_hasDefault",!1);m(this,"_view");m(this,"_unreliable",!1);m(this,"_patchOnly",!1);m(this,"_deprecated",!1);m(this,"_deprecatedThrows",!0);m(this,"_fullStateOnly",!1);m(this,"_stream",!1);m(this,"_optional",!1);m(this,"_noSync",!1);m(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(_g);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}}};Lk=(t=>new er({array:ba(t)})),Fk=(t=>new er({map:ba(t)})),zk=(t=>new er({set:ba(t)})),Uk=(t=>new er({collection:ba(t)})),Vk=(t=>{let e=new er({stream:ba(t)});return e._stream=!0,e}),Hk=(t=>new er(t));q=Object.freeze({string:Ot("string"),number:Ot("number"),boolean:Ot("boolean"),int8:Ot("int8"),uint8:Ot("uint8"),int16:Ot("int16"),uint16:Ot("uint16"),int32:Ot("int32"),uint32:Ot("uint32"),int64:Ot("int64"),uint64:Ot("uint64"),float32:Ot("float32"),float64:Ot("float64"),bigint64:Ot("bigint64"),biguint64:Ot("biguint64"),ref:Hk,array:Lk,map:Fk,set:zk,collection:Uk,stream:Vk,quantized:Ey,angle:t=>Ey({min:0,max:Math.PI*2,mode:"wrap",bits:t?.bits??16})}),Hu=-1;Gk={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"};Pn=class Pn{constructor(e){m(this,tg);m(this,eg);Pn.initialize(this),e&&Pn.assignProps(this,e)}static initialize(e){Object.defineProperty(e,I,{value:new Kr(e),enumerable:!1,writable:!0}),e[kt]=[]}static initializeForDecoder(){let e=Object.create(this.prototype);return $o(e),e[kt]=[],e}static reset(e){let n=e?.[I];if(n===void 0||typeof n.recycle!="function")throw new Error("@colyseus/schema: Schema.reset() requires a tracked (encoder-side) instance.");if(n.extraParents!==void 0)throw new Error(`@colyseus/schema: cannot reset a shared instance (${e.constructor.name}) with multiple parents.`);e[Mn]()}[(rg=Qn,ng=Tn,tg=Q,eg=kt,Mn)](){let n=this.constructor[Symbol.metadata]?.[Gr]??[],r=this[kt];for(let s=0;s<n.length;s++)r[n[s]]?.[Mn]?.();this[I].recycle(),this[Q]=void 0}static is(e){let n=e[Symbol.metadata];return typeof n=="object"&&n!==null}static isSchema(e){return typeof e?.assign=="function"}static[Zn](e,n,r=B.ADD){e.change(n,r)}static[Ns](e,n,r){let o=e.constructor[Symbol.metadata][n]?.tag;return r===void 0?o===void 0:o===void 0?!0:o===Hu?r.isChangeTreeVisible(e[I]):r.hasTagOnTree(e[I],o)}assign(e){return Pn.assignProps(this,e),this}static assignProps(e,n){let r=e.constructor[Symbol.metadata];if(r&&r[bt]!==void 0)for(let o=0;o<=r[bt];o++){let i=r[o];if(!i)continue;let a=n[i.name];a!==void 0&&(e[i.name]=a)}let s=Object.keys(n);for(let o=0;o<s.length;o++){let i=s[o];r&&r[i]!==void 0||(e[i]=n[i])}}restore(e){let n=this.constructor[Symbol.metadata];for(let r in n){let s=n[r],o=s.name,i=s.type,a=e[o];if(a!=null){if(typeof i=="string")this[o]=a;else if(Pn.is(i)){let c=new i;c.restore(a),this[o]=c}else if(typeof i=="object"){let c=Object.keys(i)[0],u=i[c];if(c==="map"){let l=this[o];for(let d in a)if(Pn.is(u)){let f=new u;f.restore(a[d]),l.set(d,f)}else l.set(d,a[d])}else if(c==="array"){let l=this[o];for(let d=0;d<a.length;d++)if(Pn.is(u)){let f=new u;f.restore(a[d]),l.push(f)}else l.push(a[d])}}}}return this}setDirty(e,n){let r=this.constructor[Symbol.metadata];this[I].change(r[r[e]].index,n)}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}clone(){let e=Object.create(this.constructor.prototype);Pn.initialize(e);let n=this.constructor[Symbol.metadata];for(let r in n){let s=n[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={},n=this.constructor[Symbol.metadata];for(let r in n){let s=n[r],o=s.name;!s.deprecated&&this[o]!==null&&typeof this[o]<"u"&&(e[o]=typeof this[o].toJSON=="function"?this[o].toJSON():this[o])}return e}discardAllChanges(){this[I].discardAll()}[Qe](e){let n=this.constructor[Symbol.metadata];return this[n[e].name]}[Cn](e){let n=this.constructor[Symbol.metadata];this[n[e].name]=void 0}static debugRefIds(e,n=!1,r=0,s,o=""){let i=n?` - ${JSON.stringify(e.toJSON())}`:"",a=e[I],c=e[Q],u=s?s.root:a.root,l=u?.refCount?.[c]>1?` [\xD7${u.refCount[c]}]`:"",d=`${eP(r)}${o}${e.constructor.name} (refId: ${c})${l}${i}
5
- `;return a.forEachChild((f,h)=>{let p=h;typeof h=="number"&&e.$indexes&&(p=e.$indexes.get(h)??h);let g=e.forEach!==void 0&&p!==void 0?`["${p}"]: `:"";d+=this.debugRefIds(f.ref,n,r+1,s,g)}),d}static debugRefIdEncodingOrder(e,n="allChanges"){let r=[],s=e[I];if(n==="changes"){let c=s.root.changes?.next;for(;c;)c.changeTree&&r.push(c.changeTree.ref[Q]),c=c.next;return r}let o=n==="allFilteredChanges",i=new Set,a=c=>{i.has(c)||(i.add(c),c.isFiltered===o&&r.push(c.ref[Q]),c.forEachChild((u,l)=>a(u)))};return a(s),r}static debugRefIdsFromDecoder(e){return this.debugRefIds(e.state,!1,0,e)}static debugChanges(e,n=!1){let r=e[I],s=n?"allChanges":"changes",o=`${e.constructor.name} (${e[Q]}) -> .${s}:
3
+ hasFilters: ${this.hasFilters}`}};m(sr,"inheritedTypes",new WeakMap),m(sr,"cachedContexts",new WeakMap);Ks=sr,Ky=63;wA=[ls,js,Ra,Uu,ei,un,vr];De={addField(t,e,n,r,s){if(e>=Ky)throw new Error(`Can't define field '${n}'.
4
+ Schema instances may only have up to ${Ky} fields.`);t[e]=Object.assign(t[e]||{},{type:ni(r),index:e,name:n}),Object.defineProperty(t,cn,{value:t[cn]||{},enumerable:!1,configurable:!0}),s?t[cn][n]=s:t[cn][n]={value:void 0,writable:!0,enumerable:!0,configurable:!0},Object.defineProperty(t,At,{value:e,enumerable:!1,configurable:!0}),Object.defineProperty(t,n,{value:e,enumerable:!1,configurable:!0}),typeof t[e].type!="string"&&!Ys(t[e].type)&&(t[ls]===void 0&&Object.defineProperty(t,ls,{value:[],enumerable:!1,configurable:!0}),t[ls].push(e));let o=t[e].type;if(o&&typeof o=="object"&&o.stream!==void 0){if(o.array!==void 0)throw new Error(nb);t[e].stream=!0,t[un]||Object.defineProperty(t,un,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[un].includes(e)||t[un].push(e);let i=r?.priority;typeof i=="function"&&De.setStreamPriority(t,n,i)}},setTag(t,e,n){let r=t[e],s=t[r];if(s.tag=n,t[On]||(Object.defineProperty(t,On,{value:[],enumerable:!1,configurable:!0}),Object.defineProperty(t,Tr,{value:{},enumerable:!1,configurable:!0})),t[On].push(r),n<0)t[Tr][n]||(t[Tr][n]=[]),t[Tr][n].push(r);else for(let o=n;o>0;o&=o-1){let i=o&-o;t[Tr][i]||(t[Tr][i]=[]),t[Tr][i].push(r)}},setUnreliable(t,e){let n=t[e];if(typeof t[n].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".`);t[n].unreliable=!0,t[js]||Object.defineProperty(t,js,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[js].push(n)},setPatchOnly(t,e){let n=t[e];if(t[n].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.`);t[n].patchOnly=!0,Du(t,Ra,n),Du(t,Uu,n)},setDeprecated(t,e){let n=t[e];t[n].deprecated=!0,Du(t,Uu,n),Object.defineProperty(t,n,{value:t[n],enumerable:!1,configurable:!0})},setFullStateOnly(t,e){let n=t[e];if(t[n].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.`);t[n].fullStateOnly=!0,Du(t,ei,n)},setStream(t,e){let n=t[e];t[n].stream=!0,t[un]||Object.defineProperty(t,un,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[un].push(n)},setStreamPriority(t,e,n){let r=t[e];t[Iu]||Object.defineProperty(t,Iu,{value:{},enumerable:!1,configurable:!0,writable:!0}),t[Iu][r]=n},getStreamPriority(t,e){return t?.[Iu]?.[e]},defineField(t,e,n,r,s){let o=ni(s),{complexTypeKlass:i,childType:a}=gA(o);De.addField(e,n,r,o,pP(r,n,a,i)),e[cn][r]&&Object.defineProperty(t.prototype,r,e[cn][r]),(typeof o=="string"||Ys(o))&&(e[vr]||Object.defineProperty(e,vr,{value:[],enumerable:!1,configurable:!0,writable:!0}),e[vr][n]=typeof o=="string"?Se[o]:mA(o.quantized))},setFields(t,e){let n=t.prototype.constructor;Ks.register(n);let r=Object.getPrototypeOf(n),s=r&&r[Symbol.metadata],o=De.initialize(n);n[ar]||(n[ar]=Xe[ar]),n[cr]||(n[cr]=Xe[cr]),n[Dn]||(n[Dn]=Xe[Dn]),n.prototype.toJSON||(n.prototype.toJSON=Xe.prototype.toJSON);let i=o[At]??(s&&s[At])??-1;i++,o[vr]||Object.defineProperty(o,vr,{value:s?.[vr]?[...s[vr]]:[],enumerable:!1,configurable:!0,writable:!0});for(let a in e){if(o[a]!==void 0)throw new Error(`@colyseus/schema: Duplicate '${a}' definition on '${n.name||"(anonymous)"}'.`);De.defineField(n,o,i,a,e[a]),i++}return t},isDeprecated(t,e){return t[e].deprecated===!0},initialize(t){let e=Object.getPrototypeOf(t),n=e[Symbol.metadata],r=t[Symbol.metadata]??Object.create(null);if(e!==Xe&&r===n&&(r=Object.create(null),n)){Object.setPrototypeOf(r,n),Object.defineProperty(r,At,{value:n[At],enumerable:!1,configurable:!0,writable:!0}),n[On]!==void 0&&(Object.defineProperty(r,On,{value:[...n[On]],enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(r,Tr,{value:{...n[Tr]},enumerable:!1,configurable:!0,writable:!0}));for(let s of wA){let o=n[s];o!==void 0&&Object.defineProperty(r,s,{value:[...o],enumerable:!1,configurable:!0,writable:!0})}Object.defineProperty(r,cn,{value:{...n[cn]},enumerable:!1,configurable:!0,writable:!0})}return Object.defineProperty(t,Symbol.metadata,{value:r,writable:!1,configurable:!0}),r},isValidInstance(t){return t.constructor[Symbol.metadata]&&Object.prototype.hasOwnProperty.call(t.constructor[Symbol.metadata],At)},getFields(t){let e=t[Symbol.metadata],n={};for(let r=0;r<=e[At];r++)n[e[r].name]=e[r].type;return n},hasViewTagAtIndex(t,e){return t?.[On]?.includes(e)},hasUnreliableAtIndex(t,e){return t?.[js]?.includes(e)},hasPatchOnlyAtIndex(t,e){return t?.[Ra]?.includes(e)},hasFullStateOnlyAtIndex(t,e){return t?.[ei]?.includes(e)},hasStreamAtIndex(t,e){return t?.[un]?.includes(e)}},ob=(t,e,n)=>t(e,n),Kf=class{constructor(e){m(this,"dirtyLow",0);m(this,"dirtyHigh",0);m(this,"ops");this.ops=new Uint8Array(Math.max(e+1,1))}record(e,n){let r=this.ops[e];r===0?this.ops[e]=n:r===N.DELETE?this.ops[e]=N.DELETE_AND_ADD:r===N.ADD&&n===N.DELETE_AND_ADD&&(this.ops[e]=N.DELETE_AND_ADD),e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}recordDelete(e,n){this.ops[e]=n,e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}recordRaw(e,n){this.record(e,n)}operationAt(e){let n=this.ops[e];return n===0?void 0:n}setOperationAt(e,n){this.ops[e]=n}forEach(e){this.forEachWithCtx(e,ob)}forEachWithCtx(e,n){let r=this.dirtyLow,s=this.dirtyHigh,o=this.ops;for(;r!==0;){let i=r&-r,a=31-Math.clz32(i);r^=i,n(e,a,o[a])}for(;s!==0;){let i=s&-s,a=31-Math.clz32(i)+32;s^=i,n(e,a,o[a])}}size(){return Vu(this.dirtyLow)+Vu(this.dirtyHigh)}has(){return(this.dirtyLow|this.dirtyHigh)!==0}reset(){this.dirtyLow=0,this.dirtyHigh=0,this.ops.fill(0)}},Xf=class{constructor(){m(this,"dirty",new Map);m(this,"pureOps",[])}record(e,n){let r=this.dirty.get(e);r===void 0?this.dirty.set(e,n):r===N.DELETE?this.dirty.set(e,N.DELETE_AND_ADD):r===N.ADD&&n===N.DELETE_AND_ADD&&this.dirty.set(e,N.DELETE_AND_ADD)}recordDelete(e,n){this.dirty.set(e,n)}recordRaw(e,n){this.dirty.set(e,n)}recordPure(e){this.pureOps.push([this.dirty.size,e])}operationAt(e){return this.dirty.get(e)}setOperationAt(e,n){this.dirty.has(e)&&this.dirty.set(e,n)}forEach(e){this.forEachWithCtx(e,ob)}forEachWithCtx(e,n){let r=this.pureOps;if(r.length>0){let s=0,o=0;for(let[i,a]of this.dirty){for(;s<r.length&&r[s][0]<=o;){let c=r[s++][1];n(e,-c,c)}n(e,i,a),o++}for(;s<r.length;){let i=r[s++][1];n(e,-i,i)}}else for(let[s,o]of this.dirty)n(e,s,o)}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 n=new Map;for(let[r,s]of this.dirty)n.set(r+e,s);this.dirty=n}};ab=(t,e)=>{t.isFieldUnreliable(e)?t.ensureUnreliableRecorder().record(e,N.ADD):t.record(e,N.ADD)},TA=(t,e)=>t(e);lb=1,Hu=2,$u=4,CA=lb|Hu|$u;OA=(t,e,n)=>{ip(e)};Zy=[],Bu=0;VA=(t,e,n)=>t(e,n);$f=1,jf=2,Sa=4,Wf=8,_a=16,Qo=32,Fu=64,Lu=128,Ea=256,ap=512,HA=_a|Qo,ps=class{constructor(e,n=e){m(this,"ref");m(this,"refTarget");m(this,"metadata");m(this,"encDescriptor");m(this,"root");m(this,"parentRef");m(this,"_parentIndex");m(this,"extraParents");m(this,"flags",Sa);m(this,"_fullSyncGen",0);m(this,"_isSchema",!1);m(this,"dirtyLow",0);m(this,"dirtyHigh",0);m(this,"opsLow",0);m(this,"opsHigh",0);m(this,"ops");m(this,"collDirty");m(this,"collPureOps");m(this,"unreliableRecorder");m(this,"paused",!1);m(this,"changesNode");m(this,"unreliableChangesNode");m(this,"visibleViews");m(this,"tagViews");m(this,"subscribedViews");this.ref=e,this.refTarget=n;let r=sp(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 o=this.metadata?.[At]??0;o>7&&(this.ops=new Uint8Array(o+1))}else this.collDirty=new Map}get isArray(){return this.refTarget!==this.ref}get isFiltered(){return(this.flags&$f)!==0}set isFiltered(e){this.flags=e?this.flags|$f:this.flags&~$f}get isVisibilitySharedWithParent(){return(this.flags&jf)!==0}set isVisibilitySharedWithParent(e){this.flags=e?this.flags|jf:this.flags&~jf}get isNew(){return(this.flags&Sa)!==0}set isNew(e){this.flags=e?this.flags|Sa:this.flags&~Sa}get isUnreliable(){return(this.flags&Wf)!==0}set isUnreliable(e){this.flags=e?this.flags|Wf:this.flags&~Wf}get isPatchOnly(){return(this.flags&_a)!==0}set isPatchOnly(e){this.flags=e?this.flags|_a:this.flags&~_a}get isFullStateOnly(){return(this.flags&Qo)!==0}set isFullStateOnly(e){this.flags=e?this.flags|Qo:this.flags&~Qo}get isStreamCollection(){return(this.flags&Fu)!==0}set isStreamCollection(e){this.flags=e?this.flags|Fu:this.flags&~Fu}get needsRestage(){return(this.flags&Lu)!==0}set needsRestage(e){this.flags=e?this.flags|Lu:this.flags&~Lu}get hasFilteredFields(){return this.isFiltered||this.encDescriptor.hasAnyView}ensureUnreliableRecorder(){return this.unreliableRecorder===void 0&&(this.unreliableRecorder=this._isSchema?new Kf(this.metadata?.[At]??0):new Xf),this.unreliableRecorder}isFieldUnreliable(e){let n=this.encDescriptor;return n.hasAnyUnreliable?e<32?(n.unreliableBitmask&1<<e)!==0:De.hasUnreliableAtIndex(this.metadata,e):!1}isFieldFullStateOnly(e){if(this.isFullStateOnly)return!0;let n=this.encDescriptor;return n.hasAnyFullStateOnly?e<32?(n.fullStateOnlyBitmask&1<<e)!==0:De.hasFullStateOnlyAtIndex(this.metadata,e):!1}isFieldStream(e){let n=this.encDescriptor;return n.hasAnyStream?e<32?(n.streamBitmask&1<<e)!==0:De.hasStreamAtIndex(this.metadata,e):!1}_opAt(e){let n=this.ops;if(n!==void 0)return n[e];let r=(e&3)<<3;return e<4?this.opsLow>>>r&255:this.opsHigh>>>r&255}_opPut(e,n){let r=this.ops;if(r!==void 0){r[e]=n;return}let s=(e&3)<<3,o=~(255<<s);e<4?this.opsLow=this.opsLow&o|n<<s:this.opsHigh=this.opsHigh&o|n<<s}_markDirty(e){e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}record(e,n){if(this._isSchema){let r=this._opAt(e);r===0?this._opPut(e,n):r===N.DELETE?this._opPut(e,N.DELETE_AND_ADD):r===N.ADD&&n===N.DELETE_AND_ADD&&this._opPut(e,N.DELETE_AND_ADD),this._markDirty(e)}else{let r=this.collDirty,s=r.get(e),o;s===void 0?o=n:s===N.DELETE||s===N.ADD&&n===N.DELETE_AND_ADD?o=N.DELETE_AND_ADD:o=s,r.set(e,o)}}recordDelete(e,n){this._isSchema?(this._opPut(e,n),this._markDirty(e)):this.collDirty.set(e,n)}recordRaw(e,n){this._isSchema?(this._opPut(e,n),this._markDirty(e)):this.collDirty.set(e,n)}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 n=this._opAt(e);return n===0?void 0:n}return this.collDirty.get(e)}setOperationAt(e,n){if(this._isSchema)this._opPut(e,n);else{let r=this.collDirty;r.has(e)&&r.set(e,n)}}forEach(e){this.forEachWithCtx(e,VA)}forEachWithCtx(e,n){if(this._isSchema){let o=this.dirtyLow,i=this.dirtyHigh,a=this.ops;if(a!==void 0){for(;o!==0;){let c=o&-o,u=31-Math.clz32(c);o^=c,n(e,u,a[u])}for(;i!==0;){let c=i&-i,u=31-Math.clz32(c)+32;i^=c,n(e,u,a[u])}}else{let c=this.opsLow,u=this.opsHigh;for(;o!==0;){let l=o&-o,d=31-Math.clz32(l);o^=l,n(e,d,UA(c,u,d))}}return}let r=this.collDirty,s=this.collPureOps;if(s!==void 0&&s.length>0){let o=0,i=0;for(let[a,c]of r){for(;o<s.length&&s[o][0]<=i;){let u=s[o++][1];n(e,-u,u)}n(e,a,c),i++}for(;o<s.length;){let a=s[o++][1];n(e,-a,a)}}else for(let[o,i]of r)n(e,o,i)}size(){return this._isSchema?Vu(this.dirtyLow)+Vu(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&=~ap}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=Sa|Lu,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,n){if(this._isSchema)throw new Error("ChangeTree (Schema): insertAt is not supported");let r=this.collDirty,s=new Map,o=!this.paused&&!this.isFullStateOnly;if(e>0)for(let[i,a]of r)i<e&&s.set(i,a);if(o)for(let i=0;i<n;i++)s.set(e+i,N.ADD);for(let[i,a]of r)i>=e&&s.set(i+n,a);this.collDirty=s,o&&this.root?.enqueueChangeTree(this)}removeAt(e,n){if(this._isSchema)throw new Error("ChangeTree (Schema): removeAt is not supported");let r=this.collDirty,s=e+n,o=!1;for(let a of r.keys())if(a>=s){o=!0;break}if(!o){for(let a=e;a<s;a++)r.delete(a);return}let i=new Map;for(let[a,c]of r)a<e?i.set(a,c):a>=s&&i.set(a-n,c);this.collDirty=i}unshift(e){this.insertAt(0,e)}setRoot(e){DA(this,e)}setParent(e,n,r){NA(this,e,n,r)}forEachChild(e){BA(this,e)}forEachChildWithCtx(e,n){Ca(this,e,n)}forEachLive(e){vA(this,e)}forEachLiveWithCtx(e,n){op(this,e,n)}operation(e){this.paused||this.isFullStateOnly||(this.recordPure(e),this.root?.enqueueChangeTree(this))}_routeAndRecord(e,n,r){if(!(this.paused||this.isFieldFullStateOnly(e))){if(this.isFieldUnreliable(e)&&!this.isNew){let s=this.ensureUnreliableRecorder();r?s.recordRaw(e,n):s.record(e,n),this.root?.enqueueUnreliable(this);return}r?this.recordRaw(e,n):this.record(e,n),this.root?.enqueueChangeTree(this)}}change(e,n=N.ADD){this._routeAndRecord(e,n,!1)}indexedOperation(e,n){this._routeAndRecord(e,n,!0)}getChange(e){return this.operationAt(e)}pause(){this.paused=!0}resume(){this.paused=!1}untracked(e){let n=this.paused;this.paused=!0;try{return e()}finally{this.paused=n}}markDirty(e,n=N.ADD){let r=this.paused;this.paused=!1;try{this.change(e,n)}finally{this.paused=r}}getValue(e,n=!1){return this.refTarget[st](e,n)}delete(e,n){if(e===void 0){try{throw new Error(`@colyseus/schema ${this.ref.constructor.name}: trying to delete non-existing index '${e}'`)}catch(o){console.warn(o)}return}if(this.paused||this.isFieldFullStateOnly(e))return this.getValue(e);let r=this.isFieldUnreliable(e)&&!this.isNew;r?this.ensureUnreliableRecorder().recordDelete(e,n??N.DELETE):this.recordDelete(e,n??N.DELETE);let s=this.getValue(e);return s&&s[I]&&this.root?.remove(s[I]),r?this.root?.enqueueUnreliable(this):this.root?.enqueueChangeTree(this),s}endEncode(){this.reset(),this.changesNode=void 0,this._isSchema||this.refTarget[us]?.(),this.isNew=!1}endEncodeUnreliable(){this.unreliableRecorder?.reset(),this.unreliableChangesNode=void 0,this._isSchema||this.refTarget[us]?.()}discard(){this._isSchema||this.refTarget[us]?.(),this.reset(),this.unreliableRecorder?.reset()}discardAll(){let e=n=>{if(n<0)return;let r=this.getValue(n);r&&r[I]&&r[I].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,n){xA(this,e,n)}setParentIndex(e,n){_A(this,e,n)}removeParent(e=this.parent){return RA(this,e)}findParent(e){return EA(this,e)}hasParent(e){return ib(this,e)}indexInParent(e){return kA(this,e)}getAllParents(){return AA(this)}},Jf=class{constructor(e){m(this,"ref");m(this,"root");m(this,"parentRef");m(this,"paused",!1);m(this,"isNew",!1);m(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 n=this.ref;if(n[be]){if(typeof n[be]!="string")for(let[i,a]of n.entries())a&&e(a[I],n._collectionIndexes?.[i]??i);return}let s=n.constructor?.[Symbol.metadata];if(!s)return;let o=s[ls]??[];for(let i=0;i<o.length;i++){let a=o[i],c=n[s[a].name];c&&e(c[I],a)}}forEachChildWithCtx(e,n){this.forEachChild((r,s)=>n(e,r,s))}forEachLive(){}forEachLiveWithCtx(){}forEach(){}};jA=function(t,e,n,r,s,o,i,a){if(e[o.offset++]=(r|s)&255,s===N.DELETE)return;let c=n.encDescriptor,u=n.ref,l=u[Mt][r]??u[c.names[r]];el(t,e,c.types[r],l,s,o,c.encoders[r])},WA=function(t,e,n,r,s,o){if(e[o.offset++]=s&255,Se.number(e,r,o),s===N.DELETE)return;let i=n.ref;if((s&N.ADD)===N.ADD){let a=i.$indexes.get(r);Se.string(e,a,o)}el(t,e,i[be],i[st](r),s,o)},cp=function(t,e,n,r,s,o){if(e[o.offset++]=s&255,Se.number(e,r,o),s===N.DELETE)return;let i=n.ref;el(t,e,i[be],i[st](r),s,o)},qA=function(t,e,n,r,s,o,i,a){let c=n.refTarget,u=c[be],l=typeof u!="string",d=a&&n.isFiltered&&l,f;if(d){let p=c.tmpItems[r];if(!p)return;if(f=p[Q],s===N.DELETE)s=N.DELETE_BY_REFID;else if((s&N.ADD)===N.ADD)s=N.ADD_BY_REFID;else if((s&N.MOVE)===N.MOVE)return}else if(s===N.DELETE&&l){let p=c.tmpItems[r];if(!p)return;f=p[Q],s=N.DELETE_BY_REFID}else f=r;if(e[o.offset++]=s&255,Se.number(e,f,o),s===N.DELETE||s===N.DELETE_BY_REFID)return;let h=c[st](r,i);el(t,e,u,h,s,o)};fb=-1,In={Map:1,Array:2,Set:3,Collection:4,Stream:5};XA=function(t,e,n,r,s){let o=e[n.offset++],i=r.constructor[Symbol.metadata],a=o>>6<<6,c=o%(a||255),u=i[c];if(u===void 0)return console.warn("@colyseus/schema: field not defined at",{index:c,ref:r.constructor.name,metadata:i}),fb;let l=u.deprecated===!0,d=l?void 0:r[st](c),f=lp(t,a,r,c,d,u.type,e,n,s);l||(f!=null&&(r[u.name]=f),d!==f&&s?.push({ref:r,refId:t.currentRefId,op:a,field:u.name,value:f,previousValue:d}))},tl=function(t,e,n,r,s){let o=r[lt]??r,i=e[n.offset++];if(i===N.CLEAR){t.removeChildRefs(o,s),o.clear();return}let a=Pe.number(e,n),c=o[be],u=o.constructor.COLLECTION_KIND,l;(i&N.ADD)===N.ADD?u===In.Map?(l=Pe.string(e,n),o.setIndex(a,l)):l=a:l=o.getIndex(a);let d=o[st](a),f=lp(t,i,r,a,d,c,e,n,s);if(t.resyncVisited!==null&&db(t,r,i,l,d,f,s),f!=null)switch(u){case In.Map:o.$items.set(l,f);break;case In.Array:o.$setAt(a,f,t.resyncVisited!==null&&i===N.ADD?N.REPLACE:i);break;case In.Set:case In.Collection:case In.Stream:o.$items.has(a)||(o.$items.set(a,f),typeof o.$refId=="number"&&a>=o.$refId&&(o.$refId=a+1));break;default:console.warn(`@colyseus/schema: missing COLLECTION_KIND on ${o.constructor?.name} \u2014 item at index ${a} was not stored.`);break}d!==f&&s?.push({ref:r,refId:t.currentRefId,op:i,dynamicIndex:l,value:f,previousValue:d})},JA=function(t,e,n,r,s){let o=r[lt]??r,i=e[n.offset++],a;if(i===N.CLEAR){t.removeChildRefs(o,s),o.clear();return}else if(i===N.REVERSE){o.items.reverse();return}else if(i===N.DELETE_BY_REFID){let f=Pe.number(e,n),h=t.root.refs.get(f);if(h===void 0||(t.root.removeRef(f),a=o.findIndex(p=>p===h),a===-1))return;o[Bn](a),s?.push({ref:r,refId:t.currentRefId,op:N.DELETE,dynamicIndex:a,value:void 0,previousValue:h});return}else if(i===N.ADD_BY_REFID){let f=Pe.number(e,n),h=t.root.refs.get(f);h&&(a=o.findIndex(p=>p===h)),(a===-1||a===void 0)&&(a=o.length)}else a=Pe.number(e,n);let c=o[be],u=a,l=o.items[a],d=lp(t,i,r,a,l,c,e,n,s);t.resyncVisited!==null&&db(t,r,i,a,l,d,s),d!=null&&d!==l&&o.$setAt(a,d,t.resyncVisited!==null&&i===N.ADD?N.REPLACE:i),l!==d&&s?.push({ref:r,refId:t.currentRefId,op:i,dynamicIndex:u,value:d,previousValue:l})},ka=class extends Error{};ZA=(t,e)=>{let n=t.toString(),r=e.toString();return n<r?-1:n>r?1:0},eg={get:(t,e)=>typeof e!="symbol"&&!isNaN(e)?t.items[e]:Reflect.get(t,e),set:(t,e,n)=>{if(typeof e!="symbol"&&!isNaN(e)){if(n==null)t.$deleteAt(e);else{let r;if(n[I]){nl(n,t[be],t,e);let s=t.items[e];t.isMovingItems?(r=t.$wireIndex(Number(e)),s!==void 0?n[I].isNew?t[I].indexedOperation(r,N.MOVE_AND_ADD):(t[I].getChange(r)&N.DELETE)===N.DELETE?t[I].indexedOperation(r,N.DELETE_AND_MOVE):t[I].indexedOperation(r,N.MOVE):n[I].isNew&&t[I].indexedOperation(r,N.ADD),n[I].setParent(t,t[I].root,r)):r=t.$changeAt(Number(e),n),s!==void 0&&s[I].root?.remove(s[I])}else r=t.$changeAt(Number(e),n);t.items[e]=n,r!==void 0&&(t.tmpItems[r]=n)}return!0}return Reflect.set(t,e,n)},deleteProperty:(t,e)=>(typeof e=="number"?t.$deleteAt(e):delete t[e],!0),has:(t,e)=>typeof e!="symbol"&&!isNaN(Number(e))?Reflect.has(t.items,e):Reflect.has(t,e)},an=class an{constructor(...e){m(this,dg);m(this,lg);m(this,ug);m(this,cg);m(this,"items",[]);m(this,"tmpItems",[]);m(this,"deletedIndexes",[]);m(this,"isMovingItems",!1);m(this,"_needsCompaction",!1);m(this,og);this[be]=void 0,this[lt]=this;let n=new Proxy(this,eg);return Object.defineProperty(this,I,{value:new ps(n,this),enumerable:!1,writable:!0}),e.length>0&&this.push(...e),n}static[(dg=I,lg=Q,ug=lt,cg=be,ag=cr,ig=Dn,Xs)](e,n,r){if(!r)return!0;let s=e[lt]??e;return typeof s[be]=="string"||r.isChangeTreeVisible(s.tmpItems[n]?.[I])}static is(e){return Array.isArray(e)||e.array!==void 0}static from(e){return new an(...Array.from(e))}static initializeForDecoder(){let e=Object.create(an.prototype);e.items=[],e.isMovingItems=!1,e._needsCompaction=!1,e[be]=void 0,e[lt]=e;let n=new Proxy(e,eg);return si(e,n),n}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[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}push(...e){let n=this[lt],r=n.items,s=n.tmpItems,o=n[I],i=n[be],a=s.length;for(let c=0,u=e.length;c<u;c++,a++){let l=e[c];if(l==null)return;typeof l=="object"&&i&&nl(l,i,n,c),o.indexedOperation(a,N.ADD),r.push(l),s.push(l),l[I]?.setParent(this,o.root,a)}return a}pop(){let e=this[lt],n=e.tmpItems,r=e.deletedIndexes,s=-1;for(let i=n.length-1;i>=0;i--)if(r[i]!==!0){s=i;break}if(s<0)return;let o=e.$isUnsentAdd(s);return e[I].delete(s),o?e.$cancelAdd(s):r[s]=!0,e.items.pop()}at(e){return e<0&&(e+=this.length),this.items[e]}$wireIndex(e){let n=this.deletedIndexes;if(n.length===0)return e;let r=this.tmpItems,s=0;for(let o=0;o<r.length;o++)if(n[o]!==!0){if(s===e)return o;s++}return r.length+(e-s)}$isUnsentAdd(e){let n=this[I];return(n.flags&(ap|Fu))===0&&!n.paused&&typeof this[be]!="string"&&n.operationAt(e)===N.ADD}$cancelAdd(e,n=!0){let r=this[I],s=this.tmpItems[e];this.tmpItems.splice(e,1),this.deletedIndexes.length>0&&this.deletedIndexes.splice(e,1),r.removeAt(e,1);let o=s?.[I];o!==void 0&&o.root===void 0&&o.removeParent(this),n&&this.$reindexChildren(e)}$reindexChildren(e,n){if(!this[I].hasFilteredFields||typeof this[be]=="string")return;let r=this.tmpItems,s=r.length;if(n!==void 0)for(;e<s&&r[e]===n[e];)e++;for(let o=e;o<s;o++)r[o]?.[I]?.setParentIndex(this,o)}$changeAt(e,n){if(n==null){console.error("ArraySchema items cannot be null nor undefined; Use `splice(index, 1)` instead.");return}if(this.items[e]===n)return;let r=this.items[e]!==void 0?typeof n=="object"?N.DELETE_AND_ADD:N.REPLACE:N.ADD,s=this.$wireIndex(e),o=this[I];return o.change(s,r),n[I]?.setParent(this,o.root,s),s}$deleteAt(e,n){this[I].delete(this.$wireIndex(e),n)}$setAt(e,n,r){r===N.ADD&&this.items[e]!==void 0?this.items.splice(e,0,n):r===N.DELETE_AND_MOVE?(this.items.splice(e,1),this.items[e]=n):(e>this.items.length&&(this._needsCompaction=!0),this.items[e]=n)}clear(){let e=this[lt];if(e.items.length===0)return;let n=e[I];n.forEachChild((r,s)=>{n.root?.remove(r)}),n.discard(),n.operation(N.CLEAR),e.items.length=0,e.tmpItems.length=0}[Nn](){let e=this[lt]??this,n=e[I];if(n.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]?.[Nn]?.();e.items.length=0,e.tmpItems.length=0,e.deletedIndexes.length=0,n.recycle(),e[Q]=void 0}concat(...e){return new an(...this.items.concat(...e))}join(e){return this.items.join(e)}reverse(){let e=this[lt],n=e[I];if(n.has()||e.deletedIndexes.length>0){let r=e.items.slice().reverse();return this.clear(),this.push(...r),this}return n.operation(N.REVERSE),e.items.reverse(),e.tmpItems.reverse(),e.$reindexChildren(0),this}shift(){let e=this[lt],n=e.items;if(n.length===0)return;let r=e[I],s=e.deletedIndexes,o=0;for(;s[o]===!0;)o++;let i=e.$isUnsentAdd(o);return r.delete(o,N.DELETE),i?e.$cancelAdd(o):s[o]=!0,n.shift()}slice(e,n){let r=new an;return r.push(...this.items.slice(e,n)),r}sort(e=ZA){let n=this[lt];n.isMovingItems=!0;let r=n[I];return n.items.sort(e).forEach((o,i)=>r.change(i,N.REPLACE)),n.tmpItems.sort(e),n.$reindexChildren(0),n.isMovingItems=!1,this}splice(e,n,...r){let s=this[lt],o=s[I],i=s.items,a=s.tmpItems,c=s.deletedIndexes,u=i.length,l=a.length,d=r.length,f=[];for(let p=0;p<l;p++)c[p]!==!0&&f.push(p);let h;if(u>e){n===void 0&&(n=u-e);for(let p=e;p<e+n;p++){let y=f[p],S=s.$isUnsentAdd(y);o.delete(y,N.DELETE),S?(h??(h=[])).push(y):c[y]=!0}}else n=0;if(d>0){let p=f[e]??u,y=Math.min(d,n);for(let b=0;b<y;b++){let x=p+b,R,A=h!==void 0?h.indexOf(x):-1;A!==-1?(h.splice(A,1),R=N.ADD):R=c[x]?N.DELETE_AND_ADD:N.ADD,o.indexedOperation(x,R),a[x]=r[b],c[x]=!1,r[b][I]?.setParent(this,o.root,x)}let S=d-y;if(S>0){let b=p+y;o.insertAt(b,S);for(let x=0;x<S;x++)r[y+x][I]?.setParent(this,o.root,b+x);c.length>0&&c.splice(b,0,...new Array(S).fill(!1)),a.splice(b,0,...r.slice(y)),s.$reindexChildren(b+S)}}if(h!==void 0&&h.length>0){for(let p=h.length-1;p>=0;p--)s.$cancelAdd(h[p],!1);s.$reindexChildren(h[0])}return o.root?.enqueueChangeTree(o),i.splice(e,n,...r)}unshift(...e){let n=this[lt],r=n[I];r.unshift(e.length);for(let o=0;o<e.length;o++)e[o]?.[I]?.setParent(this,r.root,o);let s=n.deletedIndexes;return s.length>0&&s.unshift(...new Array(e.length).fill(!1)),n.tmpItems.unshift(...e),n.$reindexChildren(e.length),n.items.unshift(...e)}indexOf(e,n){return this.items.indexOf(e,n)}lastIndexOf(e,n=this.length-1){return this.items.lastIndexOf(e,n)}every(e,n){return this.items.every(e,n)}some(e,n){return this.items.some(e,n)}forEach(e,n){return this.items.forEach(e,n)}map(e,n){return this.items.map(e,n)}filter(e,n){return this.items.filter(e,n)}reduce(e,n){return this.items.reduce.apply(this.items,arguments)}reduceRight(e,n){return this.items.reduceRight.apply(this.items,arguments)}find(e,n){return this.items.find(e,n)}findIndex(e,n){return this.items.findIndex(e,n)}fill(e,n,r){throw new Error("ArraySchema#fill() not implemented")}copyWithin(e,n,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 an}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}includes(e,n){return this.items.includes(e,n)}flatMap(e,n){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,n){let r=this.items.slice();return e<0&&(e+=this.length),r[e]=n,new an(...r)}toReversed(){return this.items.slice().reverse()}toSorted(e){return this.items.slice().sort(e)}toSpliced(e,n,...r){let s=this.items.slice();return s.splice.apply(s,arguments),s}shuffle(){return this.move(e=>{let n=this.items.length;for(;n!=0;){let r=Math.floor(Math.random()*n);n--,[this[n],this[r]]=[this[r],this[n]]}})}move(e){return this.isMovingItems=!0,e(this),this.isMovingItems=!1,this}[(og=Symbol.unscopables,st)](e,n=!1){let r=this[lt]??this;return n||r.deletedIndexes[e]?r.items[e]:r.tmpItems[e]||r.items[e]}[Bn](e){let n=this[lt]??this;n.items[e]=void 0,n._needsCompaction=!0}[us](){let e=this.tmpItems;this.tmpItems=this.items.slice(),this.deletedIndexes.length>0&&(this.$reindexChildren(0,e),this.deletedIndexes.length=0)}[zu](){let e=this[lt]??this;e._needsCompaction&&(e._needsCompaction=!1,e.items=e.items.filter(n=>n!==void 0))}[ri](e,n,r){let s=this[lt]??this,o=s.items,i=!1;for(let a=0;a<o.length;a++){let c=o[a];if(e.has(a)){r(c);continue}i=!0,n(c,a),s[Bn](a)}i&&s[zu]()}toArray(){return this.items.slice(0)}toJSON(){return this.toArray().map(e=>typeof e.toJSON=="function"?e.toJSON():e)}clone(e){let n;return e?(n=new an,n.push(...this.items)):n=new an(...this.map(r=>r[I]?r.clone():r)),n}};m(an,ag,qA),m(an,ig,JA),m(an,"COLLECTION_KIND",In.Array);ds=an;Ir("array",{constructor:ds});ju=class{constructor(){m(this,"keyByIndex",new Map);m(this,"indexByKey",Object.create(null));m(this,"nextIndex",0);m(this,"snapshots")}indexOf(e){let n=this.indexByKey[e];return n===void 0?void 0:n}assign(e){let n=this.nextIndex++;return this.indexByKey[e]=n,this.keyByIndex.set(n,e),n}snapshot(e,n){(this.snapshots??(this.snapshots=new Map)).set(e,n)}forgetSnapshot(e){this.snapshots?.delete(e)}snapshotAt(e){return this.snapshots?.get(e)}setIndex(e,n){this.keyByIndex.set(e,n),this.indexByKey[n]=e}keyOf(e){return this.keyByIndex.get(e)}cleanupAfterEncode(){if(this.snapshots!==void 0){for(let[e]of this.snapshots){let n=this.keyByIndex.get(e);n!==void 0&&(delete this.indexByKey[n],this.keyByIndex.delete(e))}this.snapshots.clear()}}reset(){this.indexByKey=Object.create(null),this.keyByIndex.clear(),this.snapshots?.clear(),this.nextIndex=0}},or=class or{constructor(e){m(this,yg);m(this,mg);m(this,"childType");m(this,hg);m(this,"$items",new Map);m(this,"journal",new ju);m(this,"_stream");if(Object.defineProperty(this,I,{value:new ps(this),enumerable:!1,writable:!0}),this[be]=void 0,e)if(e instanceof Map||e instanceof or)e.forEach((n,r)=>this.set(r,n));else for(let n in e)this.set(n,e[n])}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Or())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Or())).priority=e}get $indexes(){return this.journal.keyByIndex}get _collectionIndexes(){return this.journal.indexByKey}static[(yg=I,mg=Q,hg=be,pg=cr,fg=Dn,Xs)](e,n,r){if(!r||typeof e[be]=="string")return!0;let s=e[st](n)??e.journal.snapshotAt(n);return r.isChangeTreeVisible(s[I])}static is(e){return e.map!==void 0}static initializeForDecoder(){let e=Object.create(or.prototype);return e.$items=new Map,e.journal=new ju,e[be]=void 0,si(e),e}[Symbol.iterator](){return this.$items[Symbol.iterator]()}get[Symbol.toStringTag](){return this.$items[Symbol.toStringTag]}static get[Symbol.species](){return or}set(e,n){if(n==null)throw new Error(`MapSchema#set('${e}', ${n}): trying to set ${n} value on '${e}'.`);typeof n=="object"&&this[be]&&nl(n,this[be],this,e),e=e.toString();let r=this[I],s=n[I]!==void 0,o=this.journal,i=o.indexOf(e),a;if(i!==void 0){a=N.REPLACE;let c=this.$items.get(e);if(c===n)return;s&&(a=N.DELETE_AND_ADD,c!==void 0&&c[I].root?.remove(c[I])),o.snapshotAt(i)!==void 0&&o.forgetSnapshot(i)}else i=o.assign(e),a=N.ADD;return this.$items.set(e,n),a===N.ADD&&r.isStreamCollection?r.root!==void 0&&Ju(this,r.root,i):r.change(i,a),s&&n[I].setParent(this,r.root,i),this}get(e){return this.$items.get(e)}getOrInsert(e,n){return this.$items.has(e)?this.$items.get(e):(this.set(e,n),n)}getOrInsertComputed(e,n){if(this.$items.has(e))return this.$items.get(e);let r=n(e);return this.set(e,r),r}delete(e){if(!this.$items.has(e))return!1;let n=this.journal.indexOf(e),r=this.$items.get(e),s=this[I];if(s.isStreamCollection){let o=s.root,i=!1;return o!==void 0&&(i=Zu(this,o,this[Q],n)),r?.[I]!==void 0&&o?.remove(r[I]),this.$items.delete(e),i||this.journal.snapshot(n,r),!0}return this.journal.snapshot(n,r),s.delete(n),this.$items.delete(e)}clear(){let e=this[I];e.discard(),e.forEachChild((n,r)=>{e.root?.remove(n)}),this.journal.reset(),this.$items.clear(),e.operation(N.CLEAR)}[Nn](){let e=this[I];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed MapSchema (pooling not supported).");this.$items.forEach(n=>n?.[Nn]?.()),this.$items.clear(),this.journal.reset(),e.recycle(),this[Q]=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[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}setIndex(e,n){this.journal.setIndex(e,n)}getIndex(e){return this.journal.keyOf(e)}[st](e){let n=this.journal.keyOf(e);return n!==void 0?this.$items.get(n):void 0}[Bn](e){let n=this.journal.keyOf(e);n!==void 0&&(this.$items.delete(n),this.journal.keyByIndex.delete(e))}[ri](e,n,r){let s=null;if(this.$items.forEach((o,i)=>{if(e.has(i)){r(o);return}(s??(s=new Set)).add(i),n(o,i)}),s!==null){s.forEach(i=>{this.$items.delete(i),delete this.journal.indexByKey[i]});let o=[];this.journal.keyByIndex.forEach((i,a)=>{s.has(i)&&o.push(a)});for(let i=0;i<o.length;i++)this.journal.keyByIndex.delete(o[i])}}[us](){this.journal.cleanupAfterEncode()}_dropView(e){Qu(this,e)}_unregister(){}toJSON(){return Object.fromEntries(Array.from(this,([n,r])=>[n,typeof r.toJSON=="function"?r.toJSON():r]))}clone(e){let n;return e?n=Object.assign(new or,this):(n=new or,this.forEach((r,s)=>{r[I]?n.set(s,r.clone()):n.set(s,r)})),n}};m(or,pg,WA),m(or,fg,tl),m(or,"COLLECTION_KIND",In.Map);fs=or;Ir("map",{constructor:fs});as=class as{constructor(e){m(this,xg);m(this,Sg);m(this,wg);m(this,"$items",new Map);m(this,"deletedItems",{});m(this,"$refId",0);m(this,"_stream");Object.defineProperty(this,I,{value:new ps(this),enumerable:!1,writable:!0}),this[be]=void 0,e&&e.forEach(n=>this.add(n))}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Or())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Or())).priority=e}static[(xg=I,Sg=Q,wg=be,bg=cr,gg=Dn,Xs)](e,n,r){return!r||typeof e[be]=="string"||r.isChangeTreeVisible((e[st](n)??e.deletedItems[n])[I])}static is(e){return e.collection!==void 0}static initializeForDecoder(){let e=Object.create(as.prototype);return e.$items=new Map,e.deletedItems={},e.$refId=0,e[be]=void 0,si(e),e}add(e){let n=this.$refId++,r=this[I];return this.$items.set(n,e),r.isStreamCollection?r.root!==void 0&&Ju(this,r.root,n):r.change(n),e[I]!==void 0&&e[I].setParent(this,r.root,n),n}at(e){let n=Array.from(this.$items.keys())[e];return this.$items.get(n)}entries(){return this.$items.entries()}delete(e){let n=this.$items.entries(),r,s;for(;(s=n.next())&&!s.done;)if(e===s.value[1]){r=s.value[0];break}if(r===void 0)return!1;let o=this[I];if(o.isStreamCollection){let i=o.root,a=this.$items.get(r);return i!==void 0&&Zu(this,i,this[Q],r),a?.[I]!==void 0&&i?.remove(a[I]),this.deletedItems[r]=a,this.$items.delete(r)}return this.deletedItems[r]=o.delete(r),this.$items.delete(r)}clear(){let e=this[I];e.discard(),e.forEachChild((n,r)=>{e.root?.remove(n)}),this.$items.clear(),e.operation(N.CLEAR)}[Nn](){let e=this[I];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed CollectionSchema (pooling not supported).");this.$items.forEach(n=>n?.[Nn]?.()),this.$items.clear(),this.deletedItems={},this.$refId=0,e.recycle(),this[Q]=void 0}has(e){return Array.from(this.$items.values()).some(n=>n===e)}forEach(e){this.$items.forEach((n,r,s)=>e(n,r,this))}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}[Symbol.iterator](){return this.$items.values()}setIndex(e,n){}getIndex(e){return e}[st](e){return this.$items.get(e)}[Bn](e){this.$items.delete(e)}[ri](e,n,r){let s=null;if(this.$items.forEach((o,i)=>{if(e.has(i)){r(o);return}(s??(s=[])).push(i),n(o,i)}),s!==null)for(let o=0;o<s.length;o++)this[Bn](s[o])}[us](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){Qu(this,e)}_unregister(){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach((n,r)=>{e.push(typeof n.toJSON=="function"?n.toJSON():n)}),e}clone(e){let n;return e?n=Object.assign(new as,this):(n=new as,this.forEach(r=>{r[I]?n.add(r.clone()):n.add(r)})),n}};m(as,bg,cp),m(as,gg,tl),m(as,"COLLECTION_KIND",In.Collection);Aa=as;Ir("collection",{constructor:Aa});cs=class cs{constructor(e){m(this,Ag);m(this,kg);m(this,Eg);m(this,"$items",new Map);m(this,"deletedItems",{});m(this,"$refId",0);m(this,"_stream");Object.defineProperty(this,I,{value:new ps(this),enumerable:!1,writable:!0}),this[be]=void 0,e&&e.forEach(n=>this.add(n))}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Or())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Or())).priority=e}static[(Ag=I,kg=Q,Eg=be,Rg=cr,_g=Dn,Xs)](e,n,r){return!r||typeof e[be]=="string"||r.isVisible((e[st](n)??e.deletedItems[n])[I])}static is(e){return e.set!==void 0}static initializeForDecoder(){let e=Object.create(cs.prototype);return e.$items=new Map,e.deletedItems={},e.$refId=0,e[be]=void 0,si(e),e}add(e){if(this.has(e))return!1;let n=this.$refId++,r=this[I];return this.$items.set(n,e),r.isStreamCollection?r.root!==void 0&&Ju(this,r.root,n):r.change(n,N.ADD),e[I]!==void 0&&e[I].setParent(this,r.root,n),n}entries(){return this.$items.entries()}delete(e){let n=this.$items.entries(),r,s;for(;(s=n.next())&&!s.done;)if(e===s.value[1]){r=s.value[0];break}if(r===void 0)return!1;let o=this[I];if(o.isStreamCollection){let i=o.root,a=this.$items.get(r);return i!==void 0&&Zu(this,i,this[Q],r),a?.[I]!==void 0&&i?.remove(a[I]),this.deletedItems[r]=a,this.$items.delete(r)}return this.deletedItems[r]=o.delete(r),this.$items.delete(r)}clear(){let e=this[I];e.discard(),this.$items.clear(),e.operation(N.CLEAR)}[Nn](){let e=this[I];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed SetSchema (pooling not supported).");this.$items.forEach(n=>n?.[Nn]?.()),this.$items.clear(),this.deletedItems={},this.$refId=0,e.recycle(),this[Q]=void 0}has(e){let n=this.$items.values(),r=!1,s;for(;(s=n.next())&&!s.done;)if(e===s.value){r=!0;break}return r}forEach(e){this.$items.forEach((n,r,s)=>e(n,r,this))}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}[Symbol.iterator](){return this.$items.values()}setIndex(e,n){}getIndex(e){return e}[st](e){return this.$items.get(e)}[Bn](e){this.$items.delete(e)}[ri](e,n,r){let s=null;if(this.$items.forEach((o,i)=>{if(e.has(i)){r(o);return}(s??(s=[])).push(i),n(o,i)}),s!==null)for(let o=0;o<s.length;o++)this[Bn](s[o])}[us](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){Qu(this,e)}_unregister(){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach((n,r)=>{e.push(typeof n.toJSON=="function"?n.toJSON():n)}),e}clone(e){let n;return e?n=Object.assign(new cs,this):(n=new cs,this.forEach(r=>{r[I]?n.add(r.clone()):n.add(r)})),n}};m(cs,Rg,cp),m(cs,_g,tl),m(cs,"COLLECTION_KIND",In.Set);Pa=cs;Ir("set",{constructor:Pa});Mr=class Mr{constructor(){m(this,Cg);m(this,Mg);m(this,vg);m(this,"$items",new Map);m(this,"$nextPosition",0);m(this,"_itemIndex",new Map);m(this,"_stream");Object.defineProperty(this,I,{value:new ps(this),enumerable:!1,writable:!0}),this[be]=void 0}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Or())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Or())).priority=e}static[(Cg=I,Mg=Q,vg=be,Tg=cr,Pg=Dn,Xs)](e,n,r){if(!r)return!0;let s=e[st](n);return s===void 0?!1:r.isVisible(s[I])}static is(e){return e&&e.stream!==void 0}static initializeForDecoder(){let e=Object.create(Mr.prototype);return e.$items=new Map,e.$nextPosition=0,e._itemIndex=new Map,e[be]=void 0,si(e),e}add(e){if(this._itemIndex.has(e))return-1;let n=this.$nextPosition++;this.$items.set(n,e),this._itemIndex.set(e,n);let s=this[I].root;return e[I]!==void 0&&e[I].setParent(this,s,n),s!==void 0&&Ju(this,s,n),n}remove(e){let n=this._itemIndex.get(e);if(n===void 0)return!1;this._itemIndex.delete(e),this.$items.delete(n);let r=this[I].root;return r!==void 0&&(Zu(this,r,this[Q],n),e[I]!==void 0&&r.remove(e[I])),!0}has(e){return this._itemIndex.has(e)}clear(){let e=this[I].root;if(e!==void 0){lA(this,e,this[Q]);for(let n of this.$items.values())n[I]!==void 0&&e.remove(n[I])}this.$items.clear(),this._itemIndex.clear()}forEach(e){for(let[n,r]of this.$items)e(r,n,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,n){}getIndex(e){return e}[st](e){return this.$items.get(e)}[Bn](e){let n=this.$items.get(e);n!==void 0&&(this._itemIndex.delete(n),this.$items.delete(e))}[ri](){}[us](){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach(n=>{e.push(typeof n?.toJSON=="function"?n.toJSON():n)}),e}clone(e){if(e)return Object.assign(new Mr,this);let n=new Mr;return n.maxPerTick=this.maxPerTick,this.forEach(r=>{n.add(typeof r?.clone=="function"?r.clone():r)}),n}_dropView(e){Qu(this,e)}_unregister(){}};m(Mr,"$isStream",!0),m(Mr,Tg,cp),m(Mr,Pg,tl),m(Mr,"COLLECTION_KIND",In.Stream);Wu=Mr;Ir("stream",{constructor:Wu});Og=Fg;ur=class{constructor(e){m(this,Og,!0);m(this,"_type");m(this,"_default");m(this,"_hasDefault",!1);m(this,"_view");m(this,"_unreliable",!1);m(this,"_patchOnly",!1);m(this,"_deprecated",!1);m(this,"_deprecatedThrows",!0);m(this,"_fullStateOnly",!1);m(this,"_stream",!1);m(this,"_optional",!1);m(this,"_noSync",!1);m(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(nb);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}}};QA=(t=>new ur({array:Oa(t)})),eP=(t=>new ur({map:Oa(t)})),tP=(t=>new ur({set:Oa(t)})),nP=(t=>new ur({collection:Oa(t)})),rP=(t=>{let e=new ur({stream:Oa(t)});return e._stream=!0,e}),sP=(t=>new ur(t));Y=Object.freeze({string:Ft("string"),number:Ft("number"),boolean:Ft("boolean"),int8:Ft("int8"),uint8:Ft("uint8"),int16:Ft("int16"),uint16:Ft("uint16"),int32:Ft("int32"),uint32:Ft("uint32"),int64:Ft("int64"),uint64:Ft("uint64"),float32:Ft("float32"),float64:Ft("float64"),bigint64:Ft("bigint64"),biguint64:Ft("biguint64"),ref:sP,array:QA,map:eP,set:tP,collection:nP,stream:rP,quantized:tg,angle:t=>tg({min:0,max:Math.PI*2,mode:"wrap",bits:t?.bits??16})}),rl=-1;cP={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"};Cn=class Cn{constructor(e){m(this,Dg);m(this,Ig);Cn.initialize(this),e&&Cn.assignProps(this,e)}static initialize(e){Object.defineProperty(e,I,{value:new ps(e),enumerable:!1,writable:!0}),e[Mt]=[]}static initializeForDecoder(){let e=Object.create(this.prototype);return si(e),e[Mt]=[],e}static reset(e){let n=e?.[I];if(n===void 0||typeof n.recycle!="function")throw new Error("@colyseus/schema: Schema.reset() requires a tracked (encoder-side) instance.");if(n.extraParents!==void 0)throw new Error(`@colyseus/schema: cannot reset a shared instance (${e.constructor.name}) with multiple parents.`);e[Nn]()}[(Bg=cr,Ng=Dn,Dg=Q,Ig=Mt,Nn)](){let n=this.constructor[Symbol.metadata]?.[ls]??[],r=this[Mt];for(let s=0;s<n.length;s++)r[n[s]]?.[Nn]?.();this[I].recycle(),this[Q]=void 0}static is(e){let n=e[Symbol.metadata];return typeof n=="object"&&n!==null}static isSchema(e){return typeof e?.assign=="function"}static[ar](e,n,r=N.ADD){e.change(n,r)}static[Xs](e,n,r){let o=e.constructor[Symbol.metadata][n]?.tag;return r===void 0?o===void 0:o===void 0?!0:o===rl?r.isChangeTreeVisible(e[I]):r.hasTagOnTree(e[I],o)}assign(e){return Cn.assignProps(this,e),this}static assignProps(e,n){let r=e.constructor[Symbol.metadata];if(r&&r[At]!==void 0)for(let o=0;o<=r[At];o++){let i=r[o];if(!i)continue;let a=n[i.name];a!==void 0&&(e[i.name]=a)}let s=Object.keys(n);for(let o=0;o<s.length;o++){let i=s[o];r&&r[i]!==void 0||(e[i]=n[i])}}restore(e){let n=this.constructor[Symbol.metadata];for(let r in n){let s=n[r],o=s.name,i=s.type,a=e[o];if(a!=null){if(typeof i=="string")this[o]=a;else if(Cn.is(i)){let c=new i;c.restore(a),this[o]=c}else if(typeof i=="object"){let c=Object.keys(i)[0],u=i[c];if(c==="map"){let l=this[o];for(let d in a)if(Cn.is(u)){let f=new u;f.restore(a[d]),l.set(d,f)}else l.set(d,a[d])}else if(c==="array"){let l=this[o];for(let d=0;d<a.length;d++)if(Cn.is(u)){let f=new u;f.restore(a[d]),l.push(f)}else l.push(a[d])}}}}return this}setDirty(e,n){let r=this.constructor[Symbol.metadata];this[I].change(r[r[e]].index,n)}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}clone(){let e=Object.create(this.constructor.prototype);Cn.initialize(e);let n=this.constructor[Symbol.metadata];for(let r in n){let s=n[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={},n=this.constructor[Symbol.metadata];for(let r in n){let s=n[r],o=s.name;!s.deprecated&&this[o]!==null&&typeof this[o]<"u"&&(e[o]=typeof this[o].toJSON=="function"?this[o].toJSON():this[o])}return e}discardAllChanges(){this[I].discardAll()}[st](e){let n=this.constructor[Symbol.metadata];return this[n[e].name]}[Bn](e){let n=this.constructor[Symbol.metadata];this[n[e].name]=void 0}static debugRefIds(e,n=!1,r=0,s,o=""){let i=n?` - ${JSON.stringify(e.toJSON())}`:"",a=e[I],c=e[Q],u=s?s.root:a.root,l=u?.refCount?.[c]>1?` [\xD7${u.refCount[c]}]`:"",d=`${yP(r)}${o}${e.constructor.name} (refId: ${c})${l}${i}
5
+ `;return a.forEachChild((f,h)=>{let p=h;typeof h=="number"&&e.$indexes&&(p=e.$indexes.get(h)??h);let y=e.forEach!==void 0&&p!==void 0?`["${p}"]: `:"";d+=this.debugRefIds(f.ref,n,r+1,s,y)}),d}static debugRefIdEncodingOrder(e,n="allChanges"){let r=[],s=e[I];if(n==="changes"){let c=s.root.changes?.next;for(;c;)c.changeTree&&r.push(c.changeTree.ref[Q]),c=c.next;return r}let o=n==="allFilteredChanges",i=new Set,a=c=>{i.has(c)||(i.add(c),c.isFiltered===o&&r.push(c.ref[Q]),c.forEachChild((u,l)=>a(u)))};return a(s),r}static debugRefIdsFromDecoder(e){return this.debugRefIds(e.state,!1,0,e)}static debugChanges(e,n=!1){let r=e[I],s=n?"allChanges":"changes",o=`${e.constructor.name} (${e[Q]}) -> .${s}:
6
6
  `;return n?r.forEachLive(i=>{o+=`- [${i}]: ADD (${JSON.stringify(r.getValue(Number(i),!0))})
7
- `}):r.forEach((i,a)=>{i<0||!a||(o+=`- [${i}]: ${B[a]} (${JSON.stringify(r.getValue(Number(i),!1))})
8
- `)}),o}};m(Pn,rg,vk),m(Pn,ng,Dk);Ye=Pn;sg(Ye);_y={value:0,enumerable:!1,writable:!0},Cf=class{constructor(e,n=0){m(this,"types");m(this,"nextUniqueId",0);m(this,"refCount",{});m(this,"changeTrees",{});m(this,"changes",xy());m(this,"unreliableChanges",xy());m(this,"pendingFilterRefresh",[]);m(this,"_nodePool",[]);m(this,"_nextViewId",0);m(this,"_freeViewIds",[]);m(this,"activeViews",new Map);m(this,"streamTrees",new Set);this.types=e,this.nextUniqueId=n}enqueueFilterRefresh(e){this.types.hasFilters&&(e.flags&la||(e.flags|=la,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 n=e.id;for(let r of this.streamTrees)r._dropView(n)}forEachActiveView(e){for(let[n,r]of this.activeViews){let s=r.deref();if(s===void 0){this.activeViews.delete(n);for(let o of this.streamTrees)o._dropView(n);continue}e(s)}}registerStream(e){this.streamTrees.add(e)}unregisterStream(e){this.streamTrees.delete(e)}add(e){let n=e.ref;n[Q]===void 0&&(_y.value=this.nextUniqueId++,Object.defineProperty(n,Q,_y));let r=n[Q],s=this.changeTrees[r]===void 0;s&&(this.changeTrees[r]=e);let o=this.refCount[r];return(o===0||e.needsRestage)&&(e.needsRestage=!1,e.forEachLiveWithCtx(e,vg)),this.refCount[r]=(o||0)+1,o>0&&this.enqueueFilterRefresh(e),s}remove(e){let n=e.ref[Q],r=this.refCount[n]-1;if(r<=0){if(e.root=void 0,delete this.changeTrees[n],e.isStreamCollection){let s=e.ref;s._unregister?.(),this.unregisterStream(s)}this.removeFromQueue(e),this.removeFromUnreliableQueue(e),this.refCount[n]=0,e.forEachChild((s,o)=>{s.removeParent(e.ref)&&(s.parentRef===void 0||s.parentRef&&this.refCount[s.ref[Q]]>0?this.remove(s):s.parentRef&&this.moveNextToParent(s))})}else this.refCount[n]=r,this.enqueueFilterRefresh(e),this.recursivelyMoveNextToParent(e);return r}recursivelyMoveNextToParent(e){this.moveNextToParent(e),e.forEachChild((n,r)=>this.recursivelyMoveNextToParent(n))}moveNextToParent(e){e.changesNode&&this._moveNextToParentInList(this.changes,e,e.changesNode,"changesNode"),e.unreliableChangesNode&&this._moveNextToParentInList(this.unreliableChanges,e,e.unreliableChangesNode,"unreliableChangesNode")}_moveNextToParentInList(e,n,r,s){let o=n.parent;if(!o||!o[I])return;let i=o[I][s];!i||i===r||r.position>i.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,n=e.changesNode){n||(e.changesNode=this._appendToList(this.changes,e))}enqueueUnreliable(e,n=e.unreliableChangesNode){n||(e.unreliableChangesNode=this._appendToList(this.unreliableChanges,e))}_appendToList(e,n){let r=this._nodePool,s;return r.length>0?(s=r.pop(),s.changeTree=n,s.next=void 0,s.prev=void 0):s={changeTree:n,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,n,r,s){return!r||r.changeTree!==n?!1:(r.prev?r.prev.next=r.next:e.next=r.next,r.next?r.next.prev=r.prev:e.tail=r.prev,n[s]=void 0,this.releaseNode(r),!0)}};FD=new FinalizationRegistry(({root:t,id:e,slot:n,bit:r})=>{nP(t,n,r),t.activeViews.delete(e);for(let s of t.streamTrees)s._dropView(e);t.releaseViewId(e)}),rP=-1;Jn=class Jn{constructor(e,n){m(this,"sharedBuffer",new Uint8Array(Jn.BUFFER_SIZE));m(this,"context");m(this,"state");m(this,"root");m(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});m(this,"_fullSyncGen",0);this.context=Bs.cache(e.constructor),this.root=n??new Cf(this.context),this.setState(e)}setState(e){this.state=e,this.state[I].setRoot(this.root)}encode(e={offset:0},n,r=this.sharedBuffer,s=e.offset){return this._encodeChannel(e,n,r,s,!1)}encodeUnreliable(e={offset:0},n,r=this.sharedBuffer,s=e.offset){return this._encodeChannel(e,n,r,s,!0)}_encodeChannel(e,n,r,s,o){this.root.pendingFilterRefresh.length>0&&gy(this.root);let i=n!==void 0,a=this.state[I],c=this._encodeCtx;c.self=this,c.buffer=r,c.it=e,c.view=n,c.isEncodeAll=!1,c.hasView=i,c.emitFiltered=i;let l=o?this.root.unreliableChanges:this.root.changes;for(;l=l.next;){let d=l.changeTree;if(i&&!n.isChangeTreeVisible(d))continue;let f=o?d.unreliableRecorder:d;if(!f||!f.has())continue;let h=d.encDescriptor;c.changeTree=d,c.ref=d.ref,c.encoder=h.encoder,c.filter=h.filter,c.metadata=h.metadata,c.treeIsFiltered=d.isFiltered,c.isSchema=h.isSchema,c.filterBitmask=h.filterBitmask,c.tags=h.tags,c.structSwitchEmitted=!1,c.isRootTree=d===a,c.shouldEmitSwitch=i||e.offset>s||!c.isRootTree,f.forEachWithCtx(c,Ng)}return!o&&!i&&this._isStreamBroadcastMode&&this._emitStreamBroadcast(r,e),e.offset>r.byteLength?(r=this._resizeBuffer(r,e.offset),e.offset=s,this._encodeChannel(e,n,r,s,o)):r.subarray(0,e.offset)}encodeFullSync(e,n,r,s,o=e.offset){this.root.pendingFilterRefresh.length>0&&gy(this.root);let i=s!==void 0,a=this.state[I],c=this._encodeCtx;return c.self=this,c.buffer=n,c.it=e,c.view=s,c.isEncodeAll=!0,c.hasView=i,c.emitFiltered=r,c.gen=++this._fullSyncGen,c.initialOffset=o,c.rootChangeTree=a,Bg(c,a),e.offset>n.byteLength?(n=this._resizeBuffer(n,e.offset),e.offset=o,this.encodeFullSync(e,n,r,s,o)):n.subarray(0,e.offset)}_resizeBuffer(e,n){let r=Math.ceil(n/Jn.BUFFER_SIZE)*Jn.BUFFER_SIZE;console.warn(`@colyseus/schema buffer overflow. Encoded state is higher than default BUFFER_SIZE. Use the following to increase default BUFFER_SIZE:
7
+ `}):r.forEach((i,a)=>{i<0||!a||(o+=`- [${i}]: ${N[a]} (${JSON.stringify(r.getValue(Number(i),!1))})
8
+ `)}),o}};m(Cn,Bg,jA),m(Cn,Ng,XA);Xe=Cn;Lg(Xe);ng={value:0,enumerable:!1,writable:!0},Zf=class{constructor(e,n=0){m(this,"types");m(this,"nextUniqueId",0);m(this,"refCount",{});m(this,"changeTrees",{});m(this,"changes",Qy());m(this,"unreliableChanges",Qy());m(this,"pendingFilterRefresh",[]);m(this,"_nodePool",[]);m(this,"_nextViewId",0);m(this,"_freeViewIds",[]);m(this,"activeViews",new Map);m(this,"streamTrees",new Set);this.types=e,this.nextUniqueId=n}enqueueFilterRefresh(e){this.types.hasFilters&&(e.flags&Ea||(e.flags|=Ea,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 n=e.id;for(let r of this.streamTrees)r._dropView(n)}forEachActiveView(e){for(let[n,r]of this.activeViews){let s=r.deref();if(s===void 0){this.activeViews.delete(n);for(let o of this.streamTrees)o._dropView(n);continue}e(s)}}registerStream(e){this.streamTrees.add(e)}unregisterStream(e){this.streamTrees.delete(e)}add(e){let n=e.ref;n[Q]===void 0&&(ng.value=this.nextUniqueId++,Object.defineProperty(n,Q,ng));let r=n[Q],s=this.changeTrees[r]===void 0;s&&(this.changeTrees[r]=e);let o=this.refCount[r];return(o===0||e.needsRestage)&&(e.needsRestage=!1,e.forEachLiveWithCtx(e,ab)),this.refCount[r]=(o||0)+1,o>0&&this.enqueueFilterRefresh(e),s}remove(e){let n=e.ref[Q],r=this.refCount[n]-1;if(r<=0){if(e.root=void 0,delete this.changeTrees[n],e.isStreamCollection){let s=e.ref;s._unregister?.(),this.unregisterStream(s)}this.removeFromQueue(e),this.removeFromUnreliableQueue(e),this.refCount[n]=0,e.forEachChild((s,o)=>{s.removeParent(e.ref)&&(s.parentRef===void 0||s.parentRef&&this.refCount[s.ref[Q]]>0?this.remove(s):s.parentRef&&this.moveNextToParent(s))})}else this.refCount[n]=r,this.enqueueFilterRefresh(e),this.recursivelyMoveNextToParent(e);return r}recursivelyMoveNextToParent(e){this.moveNextToParent(e),e.forEachChild((n,r)=>this.recursivelyMoveNextToParent(n))}moveNextToParent(e){e.changesNode&&this._moveNextToParentInList(this.changes,e,e.changesNode,"changesNode"),e.unreliableChangesNode&&this._moveNextToParentInList(this.unreliableChanges,e,e.unreliableChangesNode,"unreliableChangesNode")}_moveNextToParentInList(e,n,r,s){let o=n.parent;if(!o||!o[I])return;let i=o[I][s];!i||i===r||r.position>i.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,n=e.changesNode){n||(e.changesNode=this._appendToList(this.changes,e))}enqueueUnreliable(e,n=e.unreliableChangesNode){n||(e.unreliableChangesNode=this._appendToList(this.unreliableChanges,e))}_appendToList(e,n){let r=this._nodePool,s;return r.length>0?(s=r.pop(),s.changeTree=n,s.next=void 0,s.prev=void 0):s={changeTree:n,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,n,r,s){return!r||r.changeTree!==n?!1:(r.prev?r.prev.next=r.next:e.next=r.next,r.next?r.next.prev=r.prev:e.tail=r.prev,n[s]=void 0,this.releaseNode(r),!0)}};HB=new FinalizationRegistry(({root:t,id:e,slot:n,bit:r})=>{bP(t,n,r),t.activeViews.delete(e);for(let s of t.streamTrees)s._dropView(e);t.releaseViewId(e)}),wP=-1;ir=class ir{constructor(e,n){m(this,"sharedBuffer",new Uint8Array(ir.BUFFER_SIZE));m(this,"context");m(this,"state");m(this,"root");m(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});m(this,"_fullSyncGen",0);this.context=Ks.cache(e.constructor),this.root=n??new Zf(this.context),this.setState(e)}setState(e){this.state=e,this.state[I].setRoot(this.root)}encode(e={offset:0},n,r=this.sharedBuffer,s=e.offset){return this._encodeChannel(e,n,r,s,!1)}encodeUnreliable(e={offset:0},n,r=this.sharedBuffer,s=e.offset){return this._encodeChannel(e,n,r,s,!0)}_encodeChannel(e,n,r,s,o){this.root.pendingFilterRefresh.length>0&&Xy(this.root);let i=n!==void 0,a=this.state[I],c=this._encodeCtx;c.self=this,c.buffer=r,c.it=e,c.view=n,c.isEncodeAll=!1,c.hasView=i,c.emitFiltered=i;let l=o?this.root.unreliableChanges:this.root.changes;for(;l=l.next;){let d=l.changeTree;if(i&&!n.isChangeTreeVisible(d))continue;let f=o?d.unreliableRecorder:d;if(!f||!f.has())continue;let h=d.encDescriptor;c.changeTree=d,c.ref=d.ref,c.encoder=h.encoder,c.filter=h.filter,c.metadata=h.metadata,c.treeIsFiltered=d.isFiltered,c.isSchema=h.isSchema,c.filterBitmask=h.filterBitmask,c.tags=h.tags,c.structSwitchEmitted=!1,c.isRootTree=d===a,c.shouldEmitSwitch=i||e.offset>s||!c.isRootTree,f.forEachWithCtx(c,mb)}return!o&&!i&&this._isStreamBroadcastMode&&this._emitStreamBroadcast(r,e),e.offset>r.byteLength?(r=this._resizeBuffer(r,e.offset),e.offset=s,this._encodeChannel(e,n,r,s,o)):r.subarray(0,e.offset)}encodeFullSync(e,n,r,s,o=e.offset){this.root.pendingFilterRefresh.length>0&&Xy(this.root);let i=s!==void 0,a=this.state[I],c=this._encodeCtx;return c.self=this,c.buffer=n,c.it=e,c.view=s,c.isEncodeAll=!0,c.hasView=i,c.emitFiltered=r,c.gen=++this._fullSyncGen,c.initialOffset=o,c.rootChangeTree=a,hb(c,a),e.offset>n.byteLength?(n=this._resizeBuffer(n,e.offset),e.offset=o,this.encodeFullSync(e,n,r,s,o)):n.subarray(0,e.offset)}_resizeBuffer(e,n){let r=Math.ceil(n/ir.BUFFER_SIZE)*ir.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},n=this.sharedBuffer){return this.encodeFullSync(e,n,!1)}encodeAllView(e,n,r,s=this.sharedBuffer){let o=r.offset;return s=this.encodeFullSync(r,s,!0,e,o),kf(s.subarray(0,n),s.subarray(o,r.offset))}ensureCapacity(e,n){if(n+Jn.BUFFER_SIZE<=e.byteLength)return e;let r=Math.ceil((n+Jn.BUFFER_SIZE)/Jn.BUFFER_SIZE)*Jn.BUFFER_SIZE,s=new Uint8Array(r);return s.set(e.subarray(0,n)),e===this.sharedBuffer&&(this.sharedBuffer=s),s}encodeView(e,n,r,s=this.sharedBuffer){let o=r.offset;this._emitStreamPriority(e);for(let i of e.changes.keys()){let a=e.changes.get(i),c=this.root.changeTrees[i];if(c===void 0){e.changes.delete(i);continue}if(a.size===0)continue;let u=c.encDescriptor,l=u.encoder,d=u.metadata,f=c.ref,h=c.refTarget;s=this.ensureCapacity(s,r.offset),s[r.offset++]=255,be.number(s,f[Q],r);for(let[p,g]of a){let x;if(p===rP){let _=h.tmpItems,P=h.deletedIndexes;for(let R=0;R<_.length;R++)_[R]===void 0||P[R]===!0||l(this,s,c,R,B.ADD,r,!1,!0,d);continue}if(typeof p=="number")x=p;else{let _=p.indexInParent(f);if(_===void 0)continue;if(x=_,g===B.ADD&&c.getChange(x)===B.DELETE){e.changes.delete(p.ref[Q]);continue}}let S=h[Qe](x)!==void 0&&g||B.DELETE;l(this,s,c,x,S,r,!1,!0,d)}}return e.changes.clear(),s=this.encode(r,e,s),kf(s.subarray(0,n),s.subarray(o,r.offset))}encodeUnreliableView(e,n,r,s=this.sharedBuffer){let o=r.offset;return s=this.encodeUnreliable(r,e,s,o),kf(s.subarray(0,n),s.subarray(o,r.offset))}_emitStreamBroadcast(e,n){let r=this.root.streamTrees;for(let s of r){let o=s,i=o[I],a=o[Q];if(a===void 0)continue;let c=o._stream,u=c.broadcastDeletes,l=c.broadcastPending,d=c.sentBroadcast,f=u.size>0,h=l.size>0,p=i.encDescriptor,g=p.encoder,x=p.metadata;if(f||h){if(e[n.offset++]=255,be.number(e,a,n),f){for(let R of u)g(this,e,i,R,B.DELETE,n,!1,!1,x);u.clear()}let b=c.maxPerTick,S=[],_=0,P=[];for(let R of l){if(_>=b)break;let v=o[Qe](R);if(v===void 0){P.push(R);continue}g(this,e,i,R,B.ADD,n,!1,!1,x),d.add(R),S.push(v),P.push(R),_++}for(let R of P)l.delete(R);for(let R of S){let v=R[I];if(v===void 0)continue;let M=R[Q];if(M===void 0)continue;e[n.offset++]=255,be.number(e,M,n);let O=v.encDescriptor,z=O.encoder,X=O.metadata;v.forEachLive(N=>{Ie.hasUnreliableAtIndex(X,N)||z(this,e,v,N,B.ADD,n,!1,!1,X)})}}for(let b of d){let S=o[Qe](b);if(S===void 0)continue;let _=S[I];if(_===void 0||!_.has())continue;let P=S[Q];if(P===void 0)continue;e[n.offset++]=255,be.number(e,P,n);let R=_.encDescriptor,v=R.encoder,M=R.metadata;_.forEach((O,z)=>{O<0||Ie.hasUnreliableAtIndex(M,O)||v(this,e,_,O,z,n,!1,!1,M)})}}}_emitStreamPriority(e){let n=this.root.streamTrees;if(n.size===0)return;let r=e.id;for(let s of n){let o=s,i=o._stream,a=i.pendingByView.get(r);if(a===void 0||a.size===0)continue;let c=i.priorityByView?.get(r),u=c!==void 0,l=i.priority,d=i.maxPerTick,f=[],h=[];if(u||l!==void 0){let x=[],b=[],S=0;for(let _ of a){let P=o[Qe](_);if(P===void 0){h.push(_);continue}let R=u?c(P):l(e,P);if(S<d){let v=S++;for(;v>0&&b[v-1]<R;)b[v]=b[v-1],x[v]=x[v-1],v--;b[v]=R,x[v]=_}else if(R>b[d-1]){let v=d-1;for(;v>0&&b[v-1]<R;)b[v]=b[v-1],x[v]=x[v-1],v--;b[v]=R,x[v]=_}}for(let _=0;_<S;_++)f.push(x[_])}else for(let x of a){if(f.length>=d)break;f.push(x)}for(let x of h)a.delete(x);let p=f.length,g=i.sentByView.get(r);g===void 0&&(g=new Set,i.sentByView.set(r,g));for(let x=0;x<p;x++){let b=f[x],S=o[Qe](b);if(S===void 0){a.delete(b);continue}e._addImmediate(S);let _=S[I];if(_!==void 0){let P=S[Q],R=e.changes.get(P);R===void 0&&(R=new Map,e.changes.set(P,R));let v=_.metadata;_.forEachLive(M=>{Ie.hasUnreliableAtIndex(v,M)||R.set(M,B.ADD)})}a.delete(b),g.add(b)}}}discardChanges(){let e=this.root.changes,n=e.next,r=this.root;for(;n;){let s=n.next;n.changeTree.endEncode(),r.releaseNode(n),n=s}e.next=void 0,e.tail=void 0}discardUnreliableChanges(){let e=this.root.unreliableChanges,n=e.next,r=this.root;for(;n;){let s=n.next;n.changeTree.endEncodeUnreliable(),r.releaseNode(n),n=s}e.next=void 0,e.tail=void 0}tryEncodeTypeId(e,n,r,s){let o=this.context.getTypeId(n),i=this.context.getTypeId(r);if(i===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}o!==i&&(e[s.offset++]=213,be.number(e,i,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 n=e.activeViews.size===0;for(let r of e.streamTrees)if(n?XR(r):KR(r,e))return!0;return!1}get hasUnreliableChanges(){return this.root.unreliableChanges.next!==void 0}};m(Jn,"BUFFER_SIZE",16*1024);ha=Jn,Cu=class extends Error{constructor(e){super(e),this.name="DecodingWarning"}},ky={value:0,enumerable:!1,writable:!0},Of=class{constructor(){m(this,"refs",new Map);m(this,"refCount",{});m(this,"deletedRefs",new Set);m(this,"callbacks",{});m(this,"nextUniqueId",0)}getNextUniqueId(){return this.nextUniqueId++}addRef(e,n,r=!0){this.refs.set(e,n),n[Q]===void 0?(ky.value=e,Object.defineProperty(n,Q,ky)):n[Q]!==e&&(n[Q]=e),r&&(this.refCount[e]=(this.refCount[e]||0)+1),this.deletedRefs.has(e)&&this.deletedRefs.delete(e)}removeRef(e){let n=this.refCount[e];if(n===void 0){try{throw new Cu("trying to remove refId that doesn't exist: "+e)}catch(r){console.warn(r)}return}if(n===0){try{let r=this.refs.get(e);throw new Cu(`trying to remove refId '${e}' with 0 refCount (${r.constructor.name}: ${JSON.stringify(r)})`)}catch(r){console.warn(r)}return}(this.refCount[e]=n-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 n=this.refs.get(e),r=n.constructor[Symbol.metadata];if(r!=null)for(let s in r){let o=r[s].name,i=n[o];if(typeof i=="object"&&i){let a=i[Q];a!==void 0&&!this.deletedRefs.has(a)&&this.removeRef(a)}}else typeof n[ge]=="function"&&Array.from(n.values()).forEach(s=>{let o=s[Q];o!==void 0&&!this.deletedRefs.has(o)&&this.removeRef(o)});this.refs.delete(e),delete this.refCount[e],delete this.callbacks[e]}),this.deletedRefs.clear()}addCallback(e,n,r){if(e===void 0){let s=typeof n=="number"?B[n]:n;throw new Error(`Can't addCallback on '${s}' (refId is undefined)`)}return this.callbacks[e]||(this.callbacks[e]={}),this.callbacks[e][n]||(this.callbacks[e][n]=[]),this.callbacks[e][n].push(r),()=>this.removeCallback(e,n,r)}removeCallback(e,n,r){let s=this.callbacks?.[e]?.[n]?.indexOf(r);s!==void 0&&s!==-1&&tP(this.callbacks[e][n],s)}},In=class{constructor(e,n){m(this,"context");m(this,"state");m(this,"root");m(this,"currentRefId",0);m(this,"triggerChanges");m(this,"resyncVisited",null);m(this,"resyncDamaged",!1);this.setState(e),this.context=n||new Bs(e.constructor)}setState(e){this.state=e,this.root=new Of,this.root.addRef(0,e)}decode(e,n={offset:0},r=this.state){let s=this.triggerChanges!==void 0?[]:null,o=this.root,i=e.byteLength,a=r.constructor[Tn];for(this.currentRefId=0;n.offset<i;){if(e[n.offset]==255){n.offset++,r[Ru]?.();let u=Re.number(e,n),l=o.refs.get(u);l?(r=l,a=r.constructor[Tn],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,n,i));continue}if(a(this,e,n,r,s)===Ig){console.warn("@colyseus/schema: definition mismatch"),this.skipCurrentStructure(e,n,i);continue}}return r[Ru]?.(),this.resyncVisited!==null&&Ok(this,s),s!==null&&this.triggerChanges?.(s),o.garbageCollectDeletedRefs(),s}decodeResync(e,n={offset:0}){this.resyncVisited=new Map,this.resyncDamaged=!1;try{return this.decode(e,n)}finally{this.resyncVisited=null}}skipCurrentStructure(e,n,r){this.resyncVisited!==null&&(this.resyncDamaged=!0);let s={offset:n.offset};for(;n.offset<r&&!(e[n.offset]===255&&(s.offset=n.offset+1,this.root.refs.has(Re.number(e,s))));)n.offset++}getInstanceType(e,n,r){let s;if(e[n.offset]===213){n.offset++;let o=Re.number(e,n);s=this.context.get(o)}return s||r}createInstanceOfType(e){return e.initializeForDecoder()}removeChildRefs(e,n){let r=typeof e[ge]!="string",s=e[Q];e.forEach((o,i)=>{n?.push({ref:e,refId:s,op:B.DELETE,field:i,value:void 0,previousValue:o}),r&&this.root.removeRef(o[Q])})}},Lg=It({min:q.float64(),max:q.float64(),bits:q.uint8(),mode:q.uint8()},"QuantizedDescriptor"),Fg=It({name:q.string(),type:q.string(),referencedType:q.number(),childPrimitive:q.string(),quantized:q.ref(Lg).optional()},"ReflectionField"),zg=It({id:q.number(),extendsId:q.number(),fields:q.array(Fg)},"ReflectionType"),Dn=It({types:q.array(zg),rootType:q.number()},"Reflection");Dn.encode=function(t,e={offset:0}){let n=t.context,r=new Dn,s=new ha(r),o=n.schemas.get(t.state.constructor);o>0&&(r.rootType=o);let i=new Set,a={},c=l=>{if(l.extendsId===void 0||i.has(l.extendsId)){i.add(l.id),r.types.push(l);let d=a[l.id];d!==void 0&&(delete a[l.id],d.forEach(f=>c(f)))}else a[l.extendsId]===void 0&&(a[l.extendsId]=[]),a[l.extendsId].push(l)};n.schemas.forEach((l,d)=>{let f=new zg;f.id=Number(l);let h=Object.getPrototypeOf(d);h!==Ye&&(f.extendsId=n.schemas.get(h));let p=d[Symbol.metadata];if(p!==h[Symbol.metadata]){let g=p[bt]??-1;for(let x=0;x<=g;x++){let b=p[x];if(b===void 0)continue;let S=b.name;if(!Object.prototype.hasOwnProperty.call(p,S))continue;let _=new Fg;_.name=S;let P;if(typeof b.type=="string")P=b.type;else if(Ds(b.type)){let R=b.type.quantized;P="quantized";let v=new Lg;v.min=R.min,v.max=R.max,v.bits=R.bits,v.mode=R.wrap?1:0,_.quantized=v}else{let R;Ye.is(b.type)?(P="ref",R=b.type):(P=Object.keys(b.type)[0],typeof b.type[P]=="string"?_.childPrimitive=b.type[P]:R=b.type[P]),_.referencedType=R?n.getTypeId(R):-1}_.type=P,f.fields.push(_)}}c(f)});for(let l in a)a[l].forEach(d=>r.types.push(d));return s.encodeAll(e).slice(0,e.offset)};Dn.decode=function(t,e){let n=new Dn;new In(n).decode(t,e);let s=new Bs;n.types.forEach(a=>{let c=s.get(a.extendsId)??Ye,u=class extends c{};Bs.register(u),s.add(u,a.id)},{});let o=(a,c,u)=>{c.fields.forEach((l,d)=>{let f=u+d;if(l.quantized!==void 0){let h=l.quantized;Ie.addField(a,f,l.name,{quantized:Nf({min:h.min,max:h.max,bits:h.bits,mode:h.mode===1?"wrap":"clamp"})})}else if(l.referencedType!==void 0){let h=l.type,p=s.get(l.referencedType)??l.childPrimitive;h==="ref"?Ie.addField(a,f,l.name,p):Ie.addField(a,f,l.name,{[h]:p})}else Ie.addField(a,f,l.name,l.type)})};n.types.forEach(a=>{let c=s.get(a.id),u=Ie.initialize(c),l=[],d=a;do l.push(d),d=n.types.find(h=>h.id===d.extendsId);while(d);let f=0;l.reverse().forEach(h=>{o(u,h,f),f+=h.fields.length})});let i=new(s.get(n.rootType||0));return new In(i,s)};Dn.makeEncodable=function(t){let e=t[Symbol.metadata];if(!e)return t;let n=e[bt];if(n===void 0)return t;for(let r=0;r<=n;r++){let s=e[r];s&&Ie.defineField(t,e,r,s.name,s.type)}return Object.prototype.hasOwnProperty.call(t,aa)&&delete t[aa],t};Iu=class{constructor(e){m(this,"decoder");m(this,"uniqueRefIds",new Set);m(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,n,r){return this.decoder.root.addCallback(e,n,r)}addCallbackOrWaitCollectionAvailable(e,n,r,s,o=!0){let i=()=>{},a=()=>i(),c=e[n];if(!c||c[Q]===void 0){let u;return u=this.addCallback(e[Q],n,(l,d)=>{l!=null&&(u(),i=this.addCallback(l[Q],r,s))}),i=u,a}else return o=o&&this.isTriggering===!1,r===B.ADD&&o&&c.forEach((u,l)=>{s(u,l)}),this.addCallback(c[Q],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,n,r,s=!0){s=s&&this.isTriggering===!1;let o=e[n];return s&&o!==null&&o!==void 0&&r(o,void 0),this.addCallback(e[Q],n,r)}onChange(...e){if(e.length===2&&typeof e[0]!="string"){let n=e[0],r=e[1];return this.addCallback(n[Q],B.REPLACE,r)}return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],B.REPLACE,e[1]):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],B.REPLACE,e[2])}onAdd(...e){return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],B.ADD,e[1],e[2]!==!1):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],B.ADD,e[2],e[3]!==!1)}onRemove(...e){return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],B.DELETE,e[1]):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],B.DELETE,e[2])}bindTo(e,n,r,s=!0){let o=e.constructor[Symbol.metadata];r||(r=Object.keys(o).filter(a=>!isNaN(Number(a))).map(a=>o[a].name));let i=()=>{for(let a of r){let c=e[a];c!==void 0&&(n[a]=c)}};return s&&i(),this.addCallback(e[Q],B.REPLACE,i)}triggerChanges(e){this.uniqueRefIds.clear(),this.isTriggering=!0;for(let n=0,r=e.length;n<r;n++){let s=e[n],o=s.refId,i=s.ref,a=this.callbacks[o];if(a){if((s.op&B.DELETE)===B.DELETE&&Ye.isSchema(s.previousValue)){let c=s.previousValue[Q],u=this.callbacks[c]?.[B.DELETE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l]()}catch(d){console.error(d)}}if(Ye.isSchema(i)){if(!this.uniqueRefIds.has(o)){let u=a[B.REPLACE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l]()}catch(d){console.error(d)}}let c=a[s.field];if(c)for(let u=c.length-1;u>=0;u--)try{c[u](s.value,s.previousValue)}catch(l){console.error(l)}}else{let c=s.dynamicIndex??s.field;if((s.op&B.DELETE)===B.DELETE){if(s.previousValue!==void 0){let u=a[B.DELETE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](s.previousValue,c)}catch(d){console.error(d)}}if((s.op&B.ADD)===B.ADD){let u=a[B.ADD];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](s.value,c)}catch(d){console.error(d)}}}else if((s.op&B.ADD)===B.ADD&&s.previousValue!==s.value){let u=a[B.ADD];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](s.value,c)}catch(d){console.error(d)}}if(s.value!==s.previousValue){let u=a[B.REPLACE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](c,s.value)}catch(d){console.error(d)}}}this.uniqueRefIds.add(o)}}this.isTriggering=!1}},jf={get(t){if(t instanceof In)return new Iu(t);if("decoder"in t.serializer)return new Iu(t.serializer.decoder);throw new Error("Invalid room or decoder")},getLegacy(t){if(t instanceof In)return Ou(t);if("decoder"in t.serializer)return Ou(t.serializer.decoder);throw new Error("Invalid room or decoder")},getRawChanges(t,e){return iP(t,e)}};Er("map",{constructor:Yr});Er("array",{constructor:Wr});Er("set",{constructor:pa});Er("collection",{constructor:fa})});function Pt(){return typeof performance<"u"?performance.now():Date.now()}var wa=at(()=>{"use strict"});function ju(t,e){let n=globalThis,r=n.__colyseusDebug;if(!r){let s=[];r=n.__colyseusDebug={__buffer:s,publish(o,i){s.push([o,aP(i)]),s.length>cP&&s.shift()}}}r.publish(t,e)}function qu(){if(typeof globalThis>"u")return!1;let t=globalThis.__colyseusDebug;return t!=null&&t.__buffer===void 0}var aP,cP,xa=at(()=>{"use strict";aP=typeof WeakRef<"u"?t=>new WeakRef(t):t=>({deref:()=>t}),cP=64});function zt(t){return t[Q]}function tr(t){return t.constructor[uP]}function Sa(t,e){let n=tr(t)?.[e];return typeof n=="number"?n:-1}function Vg(t){let e=tr(t);if(!e)return[];let n=[];for(let r=0;;r++){let s=e[r];if(!s||typeof s.name!="string")break;typeof s.type=="string"&&n.push(s.name)}return n}function Ea(t){let e=tr(t),n=[],r=[];if(e)for(let s=0;;s++){let o=e[s];if(!o||typeof o.name!="string")break;typeof o.type=="string"&&(n.push(o.name),lP[o.type]===void 0&&r.push(o.name))}return{fields:n,numeric:r}}function fP(t){if(Number.isNaN(t))return 0;if(!Number.isFinite(t))return t>0?Number.MAX_SAFE_INTEGER:-Number.MAX_SAFE_INTEGER;if(t!==(t|0)&&Math.abs(t)<=34028235e31){let e=Math.fround(t);if(Math.abs(Math.abs(e)-Math.abs(t))<1e-4)return e}return t}function Hg(t,e){let n=tr(t),r=n?.[e];switch((typeof r=="number"?n[r]:void 0)?.type){case"float32":return Math.fround;case"number":return fP;default:return dP}}function $g(t){if(t.length>pP){let b=t;return S=>{let _={};for(let P=0;P<b.length;P++)_[b[P]]=S[b[P]];return _}}let e=t[0],n=t[1],r=t[2],s=t[3],o=t[4],i=t[5],a=t[6],c=t[7],u=t[8],l=t[9],d=t[10],f=t[11],h=t[12],p=t[13],g=t[14],x=t[15];return b=>{let S={};return e!==void 0&&(S[e]=b[e]),n!==void 0&&(S[n]=b[n]),r!==void 0&&(S[r]=b[r]),s!==void 0&&(S[s]=b[s]),o!==void 0&&(S[o]=b[o]),i!==void 0&&(S[i]=b[i]),a!==void 0&&(S[a]=b[a]),c!==void 0&&(S[c]=b[c]),u!==void 0&&(S[u]=b[u]),l!==void 0&&(S[l]=b[l]),d!==void 0&&(S[d]=b[d]),f!==void 0&&(S[f]=b[f]),h!==void 0&&(S[h]=b[h]),p!==void 0&&(S[p]=b[p]),g!==void 0&&(S[g]=b[g]),x!==void 0&&(S[x]=b[x]),S}}var uP,Gu,lP,dP,pP,_a=at(()=>{"use strict";wt();uP=Symbol.metadata??Symbol.for("Symbol.metadata"),Gu=kt;lP={string:!0,boolean:!0,bigint64:!0,biguint64:!0};dP=t=>t;pP=16});var Gf,hP,mP,Ut,jo,Wf=at(()=>{"use strict";wt();yr();wa();xa();_a();Gf=9,hP=Gf,mP=(t,e)=>(e?2:1)*(Gf+4+Gf*t),Ut=class Ut{constructor(e,n,r,s){m(this,"data");m(this,"_host");m(this,"_encoder");m(this,"_scratch",new Uint8Array(2048));m(this,"_framed",null);m(this,"_sentCount",0);m(this,"_lastProcessed",0);m(this,"_epoch",0);m(this,"_sendTimes");m(this,"_inputBufferSize");m(this,"_inputBuffer",null);m(this,"_reckonTimes",null);m(this,"_pendingReckon",0);m(this,"_lastStamp",0);m(this,"_stampRing",null);m(this,"_renderDeltaRing",null);m(this,"_ringSlots",0);m(this,"_warnedUnknownKeys",null);m(this,"_stampRender",!1);m(this,"_stampReckon",!1);m(this,"_allowRewind");m(this,"_sendListeners",null);m(this,"_renderDelay",0);m(this,"_renderDelayExplicit",!1);m(this,"_renderDelayProvider");m(this,"_tickRate");m(this,"_patchRate");m(this,"_subSteps",1);this._host=e,this.data=n,this._encoder=r,this._stampRender=s?.stampRender??!1,this._stampReckon=s?.stampReckon??!1,this._allowRewind=s?.allowRewind,this._allowRewind!==void 0&&r.mode==="unreliable"&&!Ut._warnedAllowRewindIgnored&&(Ut._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 o=this._tickRate?1e3/this._tickRate:1e3/60,i=Ut.BUFFER_RTT_BUDGET_MS+(this._patchRate??0);this._inputBufferSize=Math.max(Ut.BUFFER_FLOOR,Math.ceil(i/o*Ut.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){Ut._warnedBufferOverflow||(Ut._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=tr(this.data);if(e)for(let n of Object.keys(this.data))e[n]!==void 0||this._warnedUnknownKeys?.has(n)||((this._warnedUnknownKeys??(this._warnedUnknownKeys=new Set)).add(n),console.warn(`@colyseus/sdk input: "${n}" 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;qu()&&this._warnUnknownFields();let n=this._encoder.encode(),r=this._encoder.mode==="reliable",s=this._stampReckon||this._stampRender,o=s&&r&&(this._allowRewind===void 0||this._allowRewind(this.data)),i=s&&!r,a=this._stampReckon&&this._stampRender,u=1+(o?hP+(a?2:0):i?mP(this._encoder.historySize,a):0)+n.length;u>this._scratch.byteLength&&(this._scratch=new Uint8Array(Math.max(u,this._scratch.byteLength*2)),this._framed=null),this._scratch[0]=(r?We.ROOM_INPUT_RELIABLE:We.ROOM_INPUT_UNRELIABLE)|(o||i?Lo.TIMED:0);let l={offset:1};if(i)this._writeRingStamps(l);else if(o){let{stamp:p,renderDelta:g}=this._sampleStamp();be.number(this._scratch,p-this._lastStamp,l),this._lastStamp=p,a&&be.uint16(this._scratch,g,l)}else this._pendingReckon=0;this._scratch.set(n,l.offset);let d=l.offset+n.length;(this._framed===null||this._framed.byteLength!==d)&&(this._framed=this._scratch.subarray(0,d));let f=this._framed,h;return r?(e.send(f),h=++this._sentCount):(e.sendUnreliable(f),h=this._sentCount=this._encoder.seq),this._recordSent(h),h}_writeRingStamps(e){let{stamp:n,renderDelta:r}=this._sampleStamp(),s=this._encoder.historySize,o=this._encoder.seq,i=this._ringSlots=Math.min(this._ringSlots+1,s),a=this._stampRing??(this._stampRing=new Float64Array(s));if(a[o%s]=n,be.number(this._scratch,i,e),be.uint32(this._scratch,n,e),this._writeSeriesDeltas(a,o,i,e),this._stampReckon&&this._stampRender){let c=this._renderDeltaRing??(this._renderDeltaRing=new Uint16Array(s));c[o%s]=r,be.uint16(this._scratch,r,e),this._writeSeriesDeltas(c,o,i,e)}}_writeSeriesDeltas(e,n,r,s){let o=e.length;for(let i=1;i<r;i++)be.number(this._scratch,e[(n-i+1)%o]-e[(n-i)%o],s)}_sampleStamp(){let e=this._host.clock,n=(e?.lastServerTime?.()??0)>0,r=n?Math.max(0,Math.round(e.serverNow()))>>>0:0,s=n?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]=Pt(),this._stampReckon&&((this._reckonTimes??(this._reckonTimes=new Float64Array(this._inputBufferSize)))[e%this._inputBufferSize]=this._pendingReckon);let n=this._sendListeners;if(n!==null)for(let r=0;r<n.length;r++)n[r](e)}onSend(e){let n=this._sendListeners;return this._sendListeners=n!==null?[...n,e]:[e],()=>{let r=this._sendListeners;if(r===null)return;let s=r.indexOf(e);if(s<0)return;let o=r.slice();o.splice(s,1),this._sendListeners=o.length>0?o:null}}ackInput(e){if(e<=this._lastProcessed)return-1;let n=this._sentCount-e>=this._inputBufferSize;if(this._lastProcessed=e,n)return-1;let r=this._sendTimes[e%this._inputBufferSize];return r>0?Pt()-r:-1}};m(Ut,"BUFFER_FLOOR",64),m(Ut,"BUFFER_RTT_BUDGET_MS",1e3),m(Ut,"BUFFER_HEADROOM",1.5),m(Ut,"_warnedBufferOverflow",!1),m(Ut,"_warnedAllowRewindIgnored",!1);jo=Ut});var qo,st,Wu,Yu=at(()=>{"use strict";wa();qo=Object.freeze({now:()=>Pt(),serverNow:()=>Pt(),renderNow:()=>Pt(),rtt:()=>0,smoothedRtt:()=>0,jitter:()=>0,lastServerTime:()=>0,patchInterval:()=>0,setPatchInterval:t=>{},sample:(t,e)=>{}}),st=class st{constructor(){m(this,"_clockOffset",0);m(this,"_clockHasSample",!1);m(this,"_offsetCount",0);m(this,"_rttFloorT",[]);m(this,"_rttFloorV",[]);m(this,"_rtt",0);m(this,"_smoothedRtt",0);m(this,"_rttHasSample",!1);m(this,"_jitter",0);m(this,"_lastRecvTime",-1);m(this,"_lastServerTime",0);m(this,"_patchInterval",0);m(this,"_renderTau",st.RENDER_TAU);m(this,"_renderSn",0);m(this,"_renderSnAt",0)}serverNow(){return Pt()+this._clockOffset}renderNow(){let e=this.serverNow();if(this._renderTau<=0)return e;let n=Pt();if(this._renderSn===0)return this._renderSn=e,this._renderSnAt=n,this._renderSn;let r=Math.min(n-this._renderSnAt,100);return r<.5?this._renderSn:(this._renderSnAt=n,this._renderSn+=r,Math.abs(e-this._renderSn)>st.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 Pt()}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,n){let r=Pt(),s=st.EMA_ALPHA,o=this._patchInterval;if(this._lastRecvTime>=0&&o>0){let a=r-this._lastRecvTime,c=Math.round(a/o);c>=1&&c<=st.JITTER_STALL_X&&(this._jitter+=(Math.abs(a-c*o)-this._jitter)*st.JITTER_GAIN)}this._lastRecvTime=r,this._lastServerTime=e,(n<0||this._smoothedRtt>0&&n>this._smoothedRtt*st.RTT_OUTLIER_X)&&(n=-1);let i=n>=0?e+n/2-r:e-r;if(!this._clockHasSample)this._clockOffset=i,this._clockHasSample=!0,n>=0&&(this.pushRttFloor(n,r),this._offsetCount=1);else if(n>=0){let a=this.pushRttFloor(n,r),c=this._offsetCount<st.RTT_GATE_WARMUP;this._offsetCount++,(c||n<=a*st.RTT_GATE_FACTOR)&&(this._clockOffset=this._clockOffset*(1-s)+i*s)}n>=0&&(this._rtt=n,this._rttHasSample?this._smoothedRtt=this._smoothedRtt*(1-s)+n*s:(this._smoothedRtt=n,this._rttHasSample=!0))}pushRttFloor(e,n){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(n);let o=n-st.RTT_GATE_WINDOW;for(;r.length>0&&r[0]<o;)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}};m(st,"EMA_ALPHA",.1),m(st,"RENDER_TAU",250),m(st,"RENDER_SNAP",250),m(st,"RTT_OUTLIER_X",4),m(st,"JITTER_GAIN",1/16),m(st,"JITTER_STALL_X",4),m(st,"RTT_GATE_FACTOR",1.2),m(st,"RTT_GATE_WINDOW",1e4),m(st,"RTT_GATE_WARMUP",30);Wu=st});var mb=GE(($B,hb)=>{"use strict";hb.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});function UP(t,e){return{now:()=>t?.serverNow()??performance.now(),ttlMs:typeof e=="function"?()=>e(t?.smoothedRtt()??0):e}}var $a,pl,mp=at(()=>{"use strict";$a=t=>Math.max(t*2,600),pl=class t{constructor(){m(this,"entries",new Map);m(this,"accepted",new Set);m(this,"cfg",{});m(this,"dead",!1)}static get(e,n={}){let r=new t;return r.configure(UP(e.clock??null,n.ttlMs??$a)),n.onReject&&r.configure({onReject:n.onReject}),r}configure(e){this.cfg={...this.cfg,...e}}predict(e,n){return this.entries.set(e,n??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,n){let r=e??this.cfg.now?.()??performance.now(),s=this.cfg.ttlMs,o=n??(typeof s=="function"?s():s)??1/0;for(let[i,a]of this.entries)this.accepted.has(i)||r-a>o&&(this.entries.delete(i),this.cfg.onReject?.(i))}clear(){this.entries.clear(),this.accepted.clear()}get size(){return this.entries.size}dispose(){this.dead=!0,this.entries.clear(),this.accepted.clear()}}});function Ib(){return{ema:0,peak:0}}function yp(t,e){t.ema+=(e-t.ema)*.1,t.peak=Math.max(e,t.peak*.9)}function Db(t){t.ema=0,t.peak=0}function ri(t,e){let n=e!==void 0&&e>Ob?e:Ob;return t.ema>=n?"diverging":t.peak>=n?"jitter":"matched"}var Ob,hl=at(()=>{"use strict";Ob=.001});function ja(){return qu()}function Nb(){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 Lb(t,e){console.warn(e===""?`@colyseus/sdk predict: two key-less ctx.memo calls ran in one step (input seq ${t}) \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 ${t}) \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 Fb(t,e,n,r){let s=Pt();if(s-Bb<VP)return;Bb=s;let o="",i=-1;for(let c in e){let u=e[c],l=u<0?-u:u;l>i&&(i=l,o=c)}let a=o?e[o]:n;console.warn(`@colyseus/sdk predict: prediction is diverging at input seq ${t} \u2014 rolling drift ${n.toFixed(3)} \u2265 tolerance ${r}; "${o}" 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 Bb,VP,gp=at(()=>{"use strict";wa();xa();Bb=-1/0,VP=1e3});function zb(){return wp>0}var bp,wp,si,ml=at(()=>{"use strict";hl();gp();bp=class{constructor(){m(this,"byTick",new Map);m(this,"diagTick",-1);m(this,"diagKeys",new Set);m(this,"warnedKeys",new Set)}run(e,n,r,s){if(n)return this.byTick.get(e)?.get(r);ja()&&(e!==this.diagTick?(this.diagTick=e,this.diagKeys.clear()):this.diagKeys.has(r)&&!this.warnedKeys.has(r)&&(this.warnedKeys.add(r),Lb(e,r)),this.diagKeys.add(r));let o=s();if(o!==void 0){let i=this.byTick.get(e);i===void 0&&(i=new Map,this.byTick.set(e,i)),i.set(r,o)}return o}prune(e){for(let n of this.byTick.keys())n<=e&&this.byTick.delete(n)}clear(){this.byTick.clear(),this.diagTick=-1,this.diagKeys.clear()}},wp=0;si=class{constructor(e){m(this,"lastCorrection",{});m(this,"lastCorrectionMag",0);m(this,"reconcileSeq",0);m(this,"drift",Ib());m(this,"error",{});m(this,"prev",{});m(this,"renderedBefore",{});m(this,"lastTick",-1);m(this,"lastAcked",0);m(this,"lastEpoch");m(this,"replayFrom",0);m(this,"predictedSeq",0);m(this,"catching",!1);m(this,"unsubscribeSend",()=>{});m(this,"renderAcc",0);m(this,"tickSeq",0);m(this,"clampedReadTick",-1);m(this,"warnedStaleRead",!1);m(this,"stepCtx");m(this,"ackWatermark",()=>this.input_.lastProcessed);m(this,"memos",new bp);m(this,"smoothMs");m(this,"snapThreshold");m(this,"stepMs");m(this,"input_");m(this,"onReconcile");m(this,"warnTolerance");m(this,"clock");m(this,"dead",!1);m(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 n=e.stepMs??this.input_.stepMs??(e.stepSeconds!==void 0?e.stepSeconds*1e3:void 0);if(n===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=n;let r=e.stepSeconds??this.input_.stepSeconds??n/1e3,s=e.subSteps??this.input_.subSteps??1;this.stepCtx={dt:r,dtMs:n,tick:0,isReplay:!1,reckonTime:0,lagCompActive:!1,subSteps:s,subDt:r/s,subDtMs:n/s,memo:(o,i)=>typeof o=="string"?this.memos.run(this.stepCtx.tick,this.stepCtx.isReplay,o,i):this.memos.run(this.stepCtx.tick,this.stepCtx.isReplay,"",o),predict:(o,i)=>{this.stepCtx.isReplay||o._predictFromSim(this.stepCtx.tick,i,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 n=this.lastTick<0?0:e-this.lastTick;this.lastTick=e,n>0&&this.stepMs>0&&(this.renderAcc+=n);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(),n<=0)return;let o=this.smoothMs<=0?1:1-Math.exp(-n/this.smoothMs);for(let i of this.smoothedFields())this.error[i]-=this.error[i]*o}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,Nb()),this.catching=!0,this.stepCtx.isReplay=!1;for(let n=this.predictedSeq+1;n<=e;n++){let r=this.input_.at(n);r!==void 0&&(this.snapshotPrev(),this.runStep(n,r),this.refreshRender(),this.renderAcc-=this.stepMs,this.renderAcc<0?this.renderAcc=0:this.renderAcc>=this.stepMs&&(this.renderAcc%=this.stepMs)),this.predictedSeq=n}this.catching=!1}}runStep(e,n){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(n)}reconcile(e){let n=this.warnTolerance!==void 0||ja();if(this.truthMatchesAt(e)){if(n){for(let u of this.smoothedFields())this.lastCorrection[u]=0;this.lastCorrectionMag=0,yp(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,wp++;try{for(let u=s+1;u<=this.input_.sentCount;u++){let l=this.input_.at(u);l!==void 0&&this.runStep(u,l)}}finally{wp--}this.catching=!1,this.refreshRender(),this.predictedSeq=this.input_.sentCount;let o=this.smoothMs<=0,i=n||this.snapThreshold>0,a=0;for(let u of this.smoothedFields()){let l=r[u]-this.readCurrent(u);if(this.error[u]=o?0:l,i){let d=l<0?-l:l;d>a&&(a=d)}n&&(this.lastCorrection[u]=l)}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++,n&&(this.lastCorrectionMag=a,c||(yp(this.drift,a),this.warnTolerance!==void 0&&ri(this.drift,this.warnTolerance)==="diverging"&&Fb(e,this.lastCorrection,this.drift.ema,this.warnTolerance))),this.memos.prune(e),this.onReconcile?.(e)}get pendingCount(){return this.input_.pendingCount}reset(){this.reseedState(),Db(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 HP,xp,oi,Sp=at(()=>{"use strict";mp();ml();HP=0,xp=10,oi=class{constructor(e,n){m(this,"opts");m(this,"store");m(this,"entries",new Map);m(this,"now");m(this,"cooldownUntil",-1/0);m(this,"warnedReplayPredict",!1);m(this,"dead",!1);m(this,"teardowns",[]);this.opts=e,this.now=()=>n?.serverNow()??performance.now(),this.store=pl.get({clock:n},{ttlMs:e.ttlMs??$a,onReject:r=>{let s=this.entries.get(r);this.entries.delete(r),s&&this.opts.onReject?.(s.payload)}})}_predictFromSim(e,n,r){this.add(e,n,r)}predict(e){if(zb()){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,n,r){let s=this.opts.uniqueBy!==void 0?this.opts.uniqueBy(n):typeof n=="string"||typeof n=="number"?n:HP;if(this.entries.has(s))return;let o=this.now();if(this.opts.cooldownMs!==void 0){if(o<this.cooldownUntil)return;this.cooldownUntil=o+this.opts.cooldownMs}let i=this.store.predict(s,o);r!==void 0&&i.accept(),this.entries.set(s,{payload:n,seq:e,acked:r}),this.opts.onPredict?.(n)}has(e){return e===void 0?this.entries.size>0:this.entries.has(e)}get pendingCount(){return this.entries.size}confirm(e){let n=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),n++)}return n===0&&this.opts.onUnpredicted?.(e),n}reject(e){let n=0;for(let r of this.settleKeys(e))this.entries.has(r)&&(this.store.reject(r),n++);return n}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??xp;for(let[n,r]of[...this.entries])r.acked!==void 0&&r.acked()>=r.seq+e&&this.store.reject(n)}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 Hs,yl=at(()=>{"use strict";mp();Hs=class{constructor(e={},n=null){m(this,"opts");m(this,"clock");m(this,"correlate");m(this,"ttl");m(this,"byId",new Map);m(this,"byServer",new Map);m(this,"nextId",1);m(this,"lastTickAt");m(this,"detach");m(this,"dead",!1);m(this,"handleAdd",(e,n)=>{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)}});m(this,"handleRemove",(e,n)=>{let r=this.byServer.get(e);r&&(this.byServer.delete(e),this.byId.delete(r.id))});m(this,"readServer",(e,n)=>e[n]);this.opts=e,this.clock=n,this.correlate=e.correlate??"fifo",this.ttl=e.ttl??$a}attach(e){this.detach?.(),this.detach=e(this.handleAdd,this.handleRemove)}spawn(e){let n=this.nextId++,r=this.makeData(),s={id:n,server:void 0,local:e,state:"pending",at:this.now(),leadMs:0,accepted:!1,data:r};return this.byId.set(n,s),{id:n,local:e,data:r,cancel:()=>{let o=this.byId.get(n);o&&o.state==="pending"&&this.byId.delete(n)},accept:()=>{let o=this.byId.get(n);o&&(o.accepted=!0)}}}confirmEntry(e,n){e.server=n,e.state="confirmed";let r=this.opts.spawnTime;r!==void 0&&e.at!==void 0&&(e.leadMs=r(n)-e.at),this.byServer.set(n,e)}takeMatch(e){let n=this.correlate;if(typeof n!="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"&&n(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 n=this.opts.step,r=this.clock!==null?this.clock.serverNow():e;if(n!==void 0&&this.lastTickAt!==void 0){let s=Math.max(0,(r-this.lastTickAt)/1e3);if(s>0)for(let o of this.byId.values())o.state==="pending"&&n(o.local,s)}this.lastTickAt=r}prune(){if(this.byId.size===0)return;let e=this.now(),n=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>n&&(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,n){return e.server!==void 0?this.readServer(e.server,n):e.local[n]}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 Ub,$s,gl=at(()=>{"use strict";ml();_a();gp();Ub=t=>typeof t=="number"?t:typeof t=="boolean"?t?1:0:NaN,$s=class extends si{constructor(n,r){super(r);m(this,"local",{});m(this,"fields");m(this,"numericFields",[]);m(this,"step");m(this,"instance");m(this,"wireRound",[]);m(this,"history");m(this,"historySeq");m(this,"historySize");m(this,"historyOn");m(this,"undeclared",null);m(this,"devView",null);this.instance=n;let s=r.fields,o=s??Ea(n).fields;if(s===void 0&&o.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=o,this.step=r.step;let i=this.fields.length>0;for(let a of this.fields){let c=n[a];this.local[a]=c,typeof c=="number"?(this.numericFields.push(a),this.prev[a]=c,this.error[a]=0):typeof c!="boolean"&&(i=!1),this.wireRound.push(Hg(n,a))}if(this.historyOn=i,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=Ea(n).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(n){this.noteRenderRead();let r=this.local[n];if(typeof r!="number")return r;let s=r+(this.error[n]??0),o=this.prev[n]??s;return o+(s-o)*this.renderAlpha()}smoothedFields(){return this.numericFields}readCurrent(n){return this.local[n]}applyStep(n){let r=this.undeclared!==null&&ja()?this.stepView():this.local;if(this.step(this.stepCtx,r,n),this.historyOn){let s=this.stepCtx.tick,o=s%this.historySize,i=o*this.fields.length;for(let a=0;a<this.fields.length;a++)this.history[i+a]=Ub(this.local[this.fields[a]]);this.historySeq[o]=s}}stepView(){if(this.devView!==null)return this.devView;let n=this.undeclared,r=new Set,s=(o,i)=>{typeof i!="string"||!n.has(i)||r.has(i)||(r.add(i),console.warn(`@colyseus/sdk predict: step ${o} "${i}" \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 "${i}" 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(o,i,a){return s("read",i),Reflect.get(o,i,a)},set(o,i,a,c){return s("wrote",i),Reflect.set(o,i,a,c)}}),this.devView}truthMatchesAt(n){if(!this.historyOn)return!1;let r=n%this.historySize;if(this.historySeq[r]!==n)return!1;let s=r*this.fields.length,o=this.instance;for(let i=0;i<this.fields.length;i++)if(this.wireRound[i](this.history[s+i])!==Ub(o[this.fields[i]]))return!1;return!0}snapshotPrev(){for(let n of this.numericFields)this.prev[n]=this.local[n]+this.error[n]}adoptTruth(){let n=this.instance;for(let r of this.fields)this.local[r]=n[r]}reseedState(){let n=this.instance;for(let r of this.fields)this.local[r]=n[r];for(let r of this.numericFields)this.prev[r]=this.local[r],this.error[r]=0;this.historySeq.fill(-1)}}});var js,bl=at(()=>{"use strict";ml();_a();js=class extends si{constructor(n){super(n);m(this,"worldHandle");m(this,"bindings",[]);m(this,"curPose",{});m(this,"poseFields",[]);m(this,"customFields",[]);m(this,"fieldsReady",!1);m(this,"poseA",{});m(this,"poseB",{});m(this,"renderPose",{});m(this,"poseDirty",!0);m(this,"step");m(this,"adopt");m(this,"readPose");m(this,"interpolate");let r=n.world;for(let s of Object.keys(r)){let o=r[s];if(o===null||typeof o!="object")continue;if(zt(o)===void 0){if(tr(o)!==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:i,numeric:a}=Ea(o);if(i.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 l of i)c[l]=o[l];r[s]=c;let u=a.map(l=>`${s}.${l}`);this.bindings.push({source:o,mirror:c,fields:i,numeric:a,poseKeys:u})}if(this.bindings.length===0&&n.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=n.world,this.step=n.step,this.adopt=n.adopt,this.readPose=n.pose,this.interpolate=n.interpolate,this.refreshPose();for(let s of this.poseFields)this.prev[s]=this.curPose[s],this.error[s]=0}refreshPose(){let n=this.curPose;for(let r of this.bindings){let{mirror:s,numeric:o,poseKeys:i}=r;for(let a=0;a<o.length;a++)n[i[a]]=s[o[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)n[s]=r[s]}if(!this.fieldsReady){let r=[];for(let s of this.bindings)for(let o of s.poseKeys)r.push(o);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(n=>({source:n.source,fields:n.numeric,poseKeys:n.poseKeys}))}value(n){if(this.noteRenderRead(),this.interpolate)return this.pose()[n];let r=this.curPose[n]+(this.error[n]??0),s=this.prev[n]??r;return s+(r-s)*this.renderAlpha()}pose(){if(this.noteRenderRead(),!this.poseDirty)return this.renderPose;let n=this.renderAlpha(),r=this.poseA,s=this.poseB;for(let o of this.poseFields)r[o]=this.prev[o]??this.curPose[o],s[o]=this.curPose[o]+(this.error[o]??0);if(this.interpolate){let o=this.interpolate(r,s,n);for(let i of this.poseFields)this.renderPose[i]=o[i]}else for(let o of this.poseFields)this.renderPose[o]=r[o]+(s[o]-r[o])*n;return this.poseDirty=!1,this.renderPose}smoothedFields(){return this.poseFields}readCurrent(n){return this.curPose[n]}applyStep(n){this.step(this.stepCtx,this.worldHandle,n)}adoptTruth(){for(let n of this.bindings){let{source:r,mirror:s,fields:o}=n;for(let i=0;i<o.length;i++)s[o[i]]=r[o[i]]}this.adopt?.(this.worldHandle)}refreshRender(){this.refreshPose()}markDirty(){this.poseDirty=!0}snapshotPrev(){for(let n of this.poseFields)this.prev[n]=this.curPose[n]+this.error[n]}reseedState(){this.adoptTruth(),this.refreshPose();for(let n of this.poseFields)this.prev[n]=this.curPose[n],this.error[n]=0}}});function Vb(t,e,n,r){let s=[];if(n.field!==void 0){let o=new Map;s.push(t.onAdd(n.collection,(i,a)=>{o.has(i)||o.set(i,t.listen(i,n.field,c=>{c===n.equals&&e.confirm(a)},!1))})),s.push(t.onRemove(n.collection,i=>{o.get(i)?.(),o.delete(i)})),s.push(()=>{for(let i of o.values())i();o.clear()})}else n.event==="remove"?s.push(t.onRemove(n.collection,(o,i)=>{e.confirm(i)})):s.push(t.onAdd(n.collection,o=>{n.mine!==void 0&&o[n.mine]!==r?.()||e.confirm()},!1));return()=>{for(let o of s.splice(0))o?.()}}var Hb=at(()=>{"use strict"});function jb(t){return t===null||typeof t!="object"?!1:Array.isArray(t.fields)}function WP(){qb||(qb=!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 ct,rn,mn,kr,Nn,qa,Ga,ii,ai,ci,Wa,vt,$P,jP,$b,Ht,ui,qs,Gs,li,di,fi,pi,ir,Ya,Sl,El,_l,qP,wl,Ep,ts,xl,GP,qb,hi,Ws,_p=at(()=>{"use strict";wt();Sp();yl();gl();bl();Wf();hl();Yu();xa();_a();Hb();ct=16,rn=0,mn=1,kr=2,Nn=3,qa=4,Ga=5,ii=6,ai=7,ci=8,Wa=9,vt=Wa+ct*2,$P=3,jP=1.5,$b=250,Ht=7,ui=0,qs=1,Gs=2,li=3,di=4,fi=5,pi=6,ir=0,Ya=0,Sl=1,El=2,_l=3,qP=4,wl=5,Ep={lerp:Ya,extrapolate:Sl,damped:El,reckon:_l,raw:qP},ts={mode:"lerp",delay:100,smoothMs:50,maxExtrapolate:200,tickInterval:0,snap:0,angle:!1},xl={step:void 0,smoothMs:50,substep:16,snap:0};GP=0,qb=!1;hi=class hi{constructor(e,n){m(this,"callbacks");m(this,"sessionSource");m(this,"slotBuf",new Float64Array(64*vt));m(this,"slotCount",0);m(this,"slotDetach",[]);m(this,"slotAngle",[]);m(this,"freeSlots",[]);m(this,"slotByRef",new Map);m(this,"simByRef",new Map);m(this,"boundBySlot",new Map);m(this,"boundProfileIdx",-1);m(this,"renderTime",0);m(this,"defaultMode");m(this,"reckonDefaults");m(this,"clock");m(this,"useRenderClock",!1);m(this,"fixedStepMs");m(this,"stepAcc",0);m(this,"lastFrameNow",-1);m(this,"profileBuf",new Float64Array(8*Ht));m(this,"profileCount",0);m(this,"profileKeys",new Map);m(this,"profileLabels",[]);m(this,"profileComputers",[]);m(this,"trackListeners",[]);m(this,"name");m(this,"disposeListeners",[]);m(this,"driven",[]);m(this,"computeDamped",e=>{let n=this.slotBuf,r=e*vt,s=this.profileBuf,o=(n[r+Nn]|0)*Ht,i=this.renderTime,a=n[r+rn],c=n[r+kr],u=i-c;n[r+kr]=i;let l=n[r+mn];if(u>0){let d=s[o+Gs],f=d>0?1-Math.exp(-u/d):1;l+=(a-l)*f,n[r+mn]=l}return l});m(this,"computeLerp",e=>{let n=this.computeLerpRaw(e),r=this.slotBuf,s=e*vt,o=this.profileBuf[(r[s+Nn]|0)*Ht+pi],i=this.renderTime;if(o<=0)return r[s+mn]=n,r[s+ci]=n,r[s+kr]=i,n;let a=r[s+kr],c=i-a;if(c<=0)return r[s+mn];let u=r[s+ci],l=r[s+mn],d=c/o,f=(n-u)/d,h=n-f+(l-u+f)*Math.exp(-d);return r[s+mn]=h,r[s+ci]=n,r[s+kr]=i,h});m(this,"computeExtrapolate",e=>{let n=this.slotBuf,r=e*vt,s=this.profileBuf,o=(n[r+Nn]|0)*Ht,i=this.renderTime,a=n[r+ai]|0;if(a===0)return n[r+rn];let c=n[r+ii]|0,u=r+Wa,l=(c-a+ct)%ct,d=(l+a-1)%ct,f=u+d*2,h=n[f],p=n[f+1],g;if(a===1)g=p;else{let P=a>=3?2:1,R=(l+a-1-P+ct)%ct,v=u+R*2,M=n[v],O=n[v+1],z=h-M;if(z<=0)g=p;else{let X=(p-O)/z,N=s[o+li],Y=i-h;Y<0?Y=0:Y>N&&(Y=N),g=p+X*Y}}let x=n[r+kr];n[r+kr]=i;let b=s[o+Gs];if(b<=0)return n[r+mn]=g,g;let S=i-x,_=n[r+mn];if(S>0){let P=1-Math.exp(-S/b);_+=(g-_)*P,n[r+mn]=_}return _});m(this,"computeReckon",e=>{let n=this.slotBuf,r=e*vt,s=n[r+qa],o=n[r+Ga]|0,i=this.simByRef.get(s);if(i!==void 0){let a=o<i.posOf.length?i.posOf[o]:-1;if(a>=0)return this.applySimulation(i,a)}return n[r+rn]});m(this,"computeRaw",e=>this.slotBuf[e*vt+rn]);m(this,"computeBound",e=>{let n=this.boundBySlot.get(e);return n!==void 0?n.ctrl.value(n.key):this.slotBuf[e*vt+rn]});this.callbacks=jf.get(e),this.sessionSource=e;let{clock:r,...s}=n;this.defaultMode=s.mode??"lerp";let o=this.defaultMode!=="reckon"&&this.defaultMode!=="raw",i=o?(()=>{let u=s;return{mode:u.mode??ts.mode,delay:u.delay??ts.delay,smoothMs:u.smoothMs??ts.smoothMs,maxExtrapolate:u.maxExtrapolate??ts.maxExtrapolate,tickInterval:u.tickInterval??ts.tickInterval,snap:u.snap??ts.snap,angle:u.angle??ts.angle}})():{...ts},a=o?s.smoothMs??0:0;if(this.allocProfile(this.defaultMode,i.delay,i.smoothMs,a,i.maxExtrapolate,i.tickInterval,i.snap,!1)!==ir)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??xl.smoothMs,substep:u.substep??xl.substep,snap:u.snap??xl.snap}}else this.reckonDefaults={...xl};this.clock=r??e.clock??void 0,this.useRenderClock=s.renderPresent!==!1,this.clock===qo&&WP(),this.name=s.name??`predict#${++GP}`,ju("predict",this.makeCoreHandle())}static get(e,n={}){return new hi(e,n)}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,n)=>this.setProfile(e,n),onTrack:e=>(this.trackListeners.push(e),()=>{let n=this.trackListeners.indexOf(e);n>=0&&this.trackListeners.splice(n,1)}),onDispose:e=>(this.disposeListeners.push(e),()=>{let n=this.disposeListeners.indexOf(e);n>=0&&this.disposeListeners.splice(n,1)})}}snapshotReconcilers(){let e=[],n=0;for(let r of this.driven){let s=r;if(!s.drift)continue;let o=s.warnTolerance;e.push({label:`reconciler #${n++}`,status:ri(s.drift,o),severity:o!==void 0&&o>0?s.drift.ema/o: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,n=ir*Ht,r=e[n+ui]|0;return{mode:r===Ya?"lerp":r===Sl?"extrapolate":r===El?"damped":r===_l?"reckon":"raw",delay:e[n+qs],smoothMs:e[n+Gs],lerpSmoothMs:e[n+pi],maxExtrapolate:e[n+li],tickInterval:e[n+di],snap:e[n+fi]}}allocProfile(e,n,r,s,o,i,a,c,u){let l=typeof e=="number"?e:Ep[e],d="";if(c){d=`${u??""}|${l}|${n}|${r}|${s}|${o}|${i}|${a}`;let g=this.profileKeys.get(d);if(g!==void 0)return g}let f=this.profileCount++;if((f+1)*Ht>this.profileBuf.length){let g=new Float64Array(this.profileBuf.length*2);g.set(this.profileBuf),this.profileBuf=g}let p=f*Ht;return this.profileBuf[p+ui]=l,this.profileBuf[p+qs]=n,this.profileBuf[p+Gs]=r,this.profileBuf[p+pi]=s,this.profileBuf[p+li]=o,this.profileBuf[p+di]=i,this.profileBuf[p+fi]=a,this.profileLabels[f]=u,this.profileComputers[f]=this.computerForMode(l),c&&this.profileKeys.set(d,f),f}computerForMode(e){return e===Ya?this.computeLerp:e===Sl?this.computeExtrapolate:e===El?this.computeDamped:e===_l?this.computeReckon:e===wl?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 ir;let n=this.readSmoothingDefaults(),r=e.mode??n.mode,s=e.delay??n.delay,o=e.smoothMs??n.smoothMs,i=e.smoothMs??n.lerpSmoothMs,a=e.maxExtrapolate??n.maxExtrapolate,c=e.tickInterval??n.tickInterval,u=e.snap??n.snap;return r===n.mode&&s===n.delay&&o===n.smoothMs&&i===n.lerpSmoothMs&&a===n.maxExtrapolate&&c===n.tickInterval&&u===n.snap?ir:this.allocProfile(r,s,o,i,a,c,u,!0)}groupProfile(e,n){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,n)}setDefaults(e){let n=e.mode;if(n!==void 0){this.defaultMode=n;let a=ir*Ht,c=Ep[n];this.profileBuf[a+ui]=c,this.profileComputers[ir]=this.computerForMode(c)}let r=e,s=ir*Ht,o=this.profileBuf;r.delay!==void 0&&(o[s+qs]=r.delay),r.smoothMs!==void 0&&(o[s+Gs]=r.smoothMs,o[s+pi]=r.smoothMs),r.maxExtrapolate!==void 0&&(o[s+li]=r.maxExtrapolate),r.tickInterval!==void 0&&(o[s+di]=r.tickInterval),r.snap!==void 0&&(o[s+fi]=r.snap,this.reckonDefaults.snap=r.snap);let i=e;i.step!==void 0&&(this.reckonDefaults.step=i.step),i.smoothMs!==void 0&&(this.reckonDefaults.smoothMs=i.smoothMs),i.substep!==void 0&&(this.reckonDefaults.substep=i.substep)}snapshotProfiles(){let e=[];for(let n=0;n<this.profileCount;n++){let r=n*Ht,s=this.profileBuf[r+ui]|0;if(s===wl)continue;let o=s===Ya?"lerp":s===Sl?"extrapolate":s===El?"damped":s===_l?"reckon":"raw";e.push({id:n,isDefault:n===ir,label:this.profileLabels[n],mode:o,delay:this.profileBuf[r+qs],smoothMs:this.profileBuf[r+(s===Ya?pi:Gs)],maxExtrapolate:this.profileBuf[r+li],tickInterval:this.profileBuf[r+di],snap:this.profileBuf[r+fi]})}return e}setProfile(e,n){if(e<0||e>=this.profileCount)return;let r=e*Ht,s=this.profileBuf;if((s[r+ui]|0)!==wl){if(n.mode!==void 0){let o=Ep[n.mode];s[r+ui]=o,this.profileComputers[e]=this.computerForMode(o),e===ir&&(this.defaultMode=n.mode)}n.delay!==void 0&&(s[r+qs]=n.delay),n.smoothMs!==void 0&&(s[r+Gs]=n.smoothMs,s[r+pi]=n.smoothMs),n.maxExtrapolate!==void 0&&(s[r+li]=n.maxExtrapolate),n.tickInterval!==void 0&&(s[r+di]=n.tickInterval),n.snap!==void 0&&(s[r+fi]=n.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,n,r={}){return this.trackWithProfile(e,n,this.profileFromOpts(r),r.angle??!1)}trackWithProfile(e,n,r,s=!1){let o=zt(e);if(o===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 i=Sa(e,n),a=e[n]??0,c,u=this.slotByRef.get(o)?.get(n);u!==void 0&&(c=this.boundBySlot.get(u),c!==void 0?this.freeStash(c):this.untrackSlot(o,n));let l=this.allocSlot(),d=this.slotBuf,f=l*vt;if(d[f+rn]=a,d[f+mn]=a,d[f+kr]=performance.now(),d[f+ci]=a,d[f+Nn]=r,d[f+qa]=o,d[f+Ga]=i,d[f+ii]=0,d[f+ai]=0,this.slotAngle[l]=s,c!==void 0)c.stash=l;else{let p=this.slotByRef.get(o);p===void 0&&(p=new Map,this.slotByRef.set(o,p)),p.set(n,l)}for(let p=0;p<this.trackListeners.length;p++)this.trackListeners[p](r,n);let h=this.callbacks.listen(e,n,p=>{let g=this.clock&&this.clock.lastServerTime()>0?this.clock.lastServerTime():performance.now(),x=this.slotBuf,b=l*vt;if(s){let N=x[b+rn];p=N+Math.atan2(Math.sin(p-N),Math.cos(p-N))}let S=(x[b+Nn]|0)*Ht,_=this.profileBuf[S+di],P=x[b+ii]|0,R=x[b+ai]|0,v=this.profileBuf[S+fi];v>0&&R>0&&Math.abs(p-x[b+rn])>v&&(P=0,R=0,x[b+mn]=p,x[b+ci]=p);let M=R===0?Number.NEGATIVE_INFINITY:x[b+Wa+(P===0?ct-1:P-1)*2],O=g;if(_>0&&isFinite(M)){let N=g-M,Y=N>0?Math.max(1,Math.round(N/_)):1;O=M+Y*_;let he=g+_;O>he&&(O=he)}x[b+rn]=p;let z=b+Wa;if(R>=2&&isFinite(M)){let N=P===0?ct-1:P-1,Y=N===0?ct-1:N-1,he=M-x[z+Y*2],A=this.clock?.patchInterval?this.clock.patchInterval():0,W=A>0?A:he,G=A>0?jP*A:$P*he;if(W>0&&O-M>G){let $=W<$b?W:$b,j=z+P*2;x[j]=O-$,x[j+1]=x[z+N*2+1],P=P+1>=ct?0:P+1,R<ct&&R++}}let X=z+P*2;x[X]=O,x[X+1]=p,x[b+ii]=P+1>=ct?0:P+1,R<ct&&(x[b+ai]=R+1)},!0);return this.slotDetach[l]=h,()=>this.untrackSlot(o,n)}untrack(e,n){let r=zt(e);r!==void 0&&this.untrackSlot(r,n)}untrackSlot(e,n){let r=this.slotByRef.get(e),s=r?.get(n);if(s===void 0)return;let o=this.boundBySlot.get(s);if(o!==void 0){this.freeStash(o);return}this.slotDetach[s]?.(),this.slotDetach[s]=void 0,this.freeSlots.push(s),r.delete(n),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)*vt>this.slotBuf.length){let r=new Float64Array(this.slotBuf.length*2);r.set(this.slotBuf),this.slotBuf=r}return e}registerBound(e,n,r,s,o){let i=zt(n),a=this.slotByRef.get(i);a===void 0&&(a=new Map,this.slotByRef.set(i,a));let c=[];for(let u=0;u<r.length;u++){let l=r[u],d=a.get(l),f=-1;if(d!==void 0){let b=this.boundBySlot.get(d);b!==void 0?(console.warn(`@colyseus/sdk Predict: "${l}" (refId ${i}) is already bound to a controller \u2014 the newer registration wins.`),f=b.stash,this.boundBySlot.delete(d),this.freeSlots.push(d)):f=d}let h=this.allocSlot(),p=this.slotBuf,g=h*vt,x=n[l]??0;p[g+rn]=x,p[g+mn]=x,p[g+kr]=0,p[g+ci]=x,p[g+Nn]=o,p[g+qa]=i,p[g+Ga]=Sa(n,l),p[g+ii]=0,p[g+ai]=0,this.slotAngle[h]=!1,this.boundBySlot.set(h,{ctrl:e,key:s[u],stash:f}),a.set(l,h),c.push(h);for(let b=0;b<this.trackListeners.length;b++)this.trackListeners[b](o,l)}return()=>{for(let u=0;u<c.length;u++){let l=c[u],d=this.boundBySlot.get(l);if(d===void 0||d.ctrl!==e)continue;this.boundBySlot.delete(l),this.freeSlots.push(l);let f=this.slotByRef.get(i);f?.get(r[u])===l&&(d.stash>=0?f.set(r[u],d.stash):(f.delete(r[u]),f.size===0&&this.slotByRef.delete(i)))}}}installBoundOverlay(e){let n=[];for(let r of e.boundRegistrations)r.fields.length===0||zt(r.source)===void 0||(this.boundProfileIdx<0&&(this.boundProfileIdx=this.allocProfile(wl,0,0,0,0,0,0,!1,"bound")),n.push(this.registerBound(e,r.source,r.fields,r.poseKeys,this.boundProfileIdx)));n.length>0&&e.onDisposed(()=>{for(let r of n)r()})}trackStepped(e,n){let r=n.substep??16,s=n.fields,o=s.map(p=>Sa(e,p)),i=n.step,a=this.clock,c=this.presentFn(),u=n.forwardMs??(c?()=>{let p=a.lastServerTime();return p>0?Math.max(0,c()-p):0}:()=>0),l=n.elapsedMs??c??(()=>performance.now()),d=e[Gu],f=n.snapshot===void 0&&Array.isArray(d)&&o.every(p=>p>=0&&p<d.length),h;if(f){let p=new e.constructor,g=p[Gu];h=(x,b,S,_)=>{let P=x[Gu];for(let M=0;M<P.length;M++)g[M]=P[M];let R=b,v=_-b;for(;R>0;){let M=R<r?R:r;v+=M,i(p,M/1e3,v),R-=M}for(let M=0;M<o.length;M++)S[M]=g[o[M]]}}else{let p=Vg(e),g=n.snapshot??(p.length>0?$g(p):b=>({...b})),x=[...s];h=(b,S,_,P)=>{let R=g(b),v=S,M=P-S;for(;v>0;){let O=v<r?v:r;M+=O,i(R,O/1e3,M),v-=O}for(let O=0;O<x.length;O++)_[O]=R[x[O]]}}return this.trackSimulated(e,{fields:s,forwardMs:u,elapsedMs:l,smoothMs:n.smoothMs,snap:n.snap,advance:h})}trackSimulated(e,n){let r=zt(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=n.fields,o=s.length,i=s.map(h=>Sa(e,h)),a=0;for(let h of i)h>a&&(a=h);let c=new Int8Array(a+1).fill(-1);for(let h=0;h<o;h++)i[h]>=0&&(c[i[h]]=h);let u=new Float64Array(o);for(let h=0;h<o;h++)u[h]=e[s[h]]??0;let l=this.presentFn(),d=n.elapsedMs??l??(()=>performance.now()),f={instance:e,fieldIds:i,posOf:c,forwardMs:n.forwardMs,elapsedMs:d,advance:n.advance,smoothMs:n.smoothMs??50,snap:n.snap??0,smoothed:u,out:new Float64Array(o),valueOut:new Float64Array(o),offset:new Float64Array(o),outPrev:new Float64Array(o),frameVel:new Float64Array(o),lastBaseT:NaN,lastApplyTime:-1/0};return this.simByRef.set(r,f),()=>this.untrackSimulated(r)}untrackSimulated(e){this.simByRef.delete(e)}attach(e,n){let r=this.makeGroup("(attach)",n);return this.attachWithPlan(e,this.planFor(r,e))}makeGroup(e,n){return{label:e,config:n,basePlan:this.buildGroupPlan(n,e),planByCtor:new Map}}planFor(e,n){let r=n.constructor,s=e.planByCtor.get(r);return s===void 0&&(s=this.resolveCtorPlan(e,n),e.planByCtor.set(r,s)),s}resolveCtorPlan(e,n){let r=tr(n),s=n.constructor?.name||"?",o=e.config;if(!jb(o)){if(r===void 0)return e.basePlan;let c=Object.keys(o).filter(l=>o[l]!==void 0);if(c.every(l=>typeof r[l]=="number"))return e.basePlan;let u={};for(let l of c)typeof r[l]=="number"&&(u[l]=o[l]);return this.buildGroupPlan(u,`${e.label}:${s}`)}let i=o,a=i.fields;if(r!==void 0){let c=a.filter(u=>typeof r[u]=="number");c.length!==a.length&&(a=c)}return a===i.fields?e.basePlan:this.buildGroupPlan({...i,fields:a},`${e.label}:${s}`)}buildGroupPlan(e,n){let r=[];if(jb(e)){let o=e;if(!Array.isArray(o.fields))throw new Error("Predict.attach(): `fields` must be a numeric-key array.");let i=o.mode??this.defaultMode,a=o.step??this.reckonDefaults.step,c=i==="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:i,snap:o.snap,smoothMs:o.smoothMs},n);for(let l of o.fields)r.push({field:l,profileIdx:u,angle:o.angle});return{label:n,isReckon:c,reckonFields:c?o.fields:void 0,reckonStep:c?a:void 0,reckonSmoothMs:o.smoothMs??this.reckonDefaults.smoothMs,reckonSubstep:o.substep??this.reckonDefaults.substep,reckonSnap:o.snap??this.reckonDefaults.snap,reckonSnapshot:o.snapshot,fieldProfiles:r}}let s=e;for(let o of Object.keys(s)){let i=s[o];if(i===void 0)continue;let a=typeof i=="string"?{mode:i}:i;r.push({field:o,profileIdx:this.groupProfile(a,n),angle:a.angle})}return{label:n,isReckon:!1,fieldProfiles:r}}attachToGroup(e,n,r){let s=[];n.isReckon&&s.push(this.trackStepped(e,{fields:n.reckonFields,step:n.reckonStep,smoothMs:n.reckonSmoothMs,substep:n.reckonSubstep,snap:n.reckonSnap,snapshot:n.reckonSnapshot,forwardMs:r}));for(let{field:o,profileIdx:i,angle:a}of n.fieldProfiles)s.push(this.trackWithProfile(e,o,i,!!a));return()=>{for(let o of s)o()}}attachWithPlan(e,n){let r=zt(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,n),()=>this.detachByRef(r)}detach(e){let n=zt(e);n!==void 0&&this.detachByRef(n)}detachByRef(e){let n=this.slotByRef.get(e);if(n){for(let r of[...n.keys()]){let s=n.get(r);if(s===void 0)continue;let o=this.boundBySlot.get(s);o!==void 0?(this.freeStash(o),this.boundBySlot.delete(s),this.freeSlots.push(s),n.delete(r)):this.untrackSlot(e,r)}n.size===0&&this.slotByRef.delete(e)}this.simByRef.delete(e)}attachAll(...e){let n=typeof e[0]=="string",r=n?void 0:e[0],s=n?e[0]:e[1],o=n?e[1]:e[2],i=this.makeGroup(s,o),a=new Set,c=f=>{this.attachWithPlan(f,this.planFor(i,f)),a.add(f)},u=f=>{a.delete(f),this.detach(f)},l=n?this.callbacks.onAdd(s,c):this.callbacks.onAdd(r,s,c),d=n?this.callbacks.onRemove(s,u):this.callbacks.onRemove(r,s,u);return()=>{l?.(),d?.();for(let f of a)this.detach(f);a.clear()}}tick(e=performance.now()){this.renderTime=e;let n=0,r=this.fixedStepMs;if(r!==void 0&&r>0){let i=this.lastFrameNow<0?0:e-this.lastFrameNow;this.stepAcc+=i,n=Math.floor(this.stepAcc/r),n>hi.MAX_STEPS_PER_FRAME?(this.stepAcc=0,n=hi.MAX_STEPS_PER_FRAME):this.stepAcc-=n*r}this.lastFrameNow=e;let s=this.driven,o=0;for(let i=0;i<s.length;i++){let a=s[i];a.dead||(a.tick?.(e),a.prune?.(),o!==i&&(s[o]=a),o++)}return o!==s.length&&(s.length=o),n}defineEvent(e){let{confirmOn:n,...r}=e,s=new oi(r,this.clock??null);if(n!==void 0){if(n.mine!==void 0&&typeof this.sessionSource.sessionId!="string")throw new Error(`Predict.defineEvent: confirmOn.mine ("${n.mine}") requires a Predict built from a Room (it compares against room.sessionId); confirm manually instead.`);s._addTeardown(Vb(this.callbacks,s,n,()=>this.sessionSource.sessionId))}return this.driven.push(s),s}spawns(e,n={}){let r=new Hs(n,this.clock??null),s=n.fields,o=n.step,i=s!==void 0&&o!==void 0?this.makeGroup(String(e),{mode:"reckon",fields:s,step:o,smoothMs:n.smoothMs??0,substep:n.substep}):void 0,a=i!==void 0?new Map:void 0,c=this.clock;return r.attach((u,l)=>{let d=this.callbacks.onAdd(e,(h,p)=>{if(u(h,p),i===void 0||a.has(h))return;let g=r.entryFor(h)?.leadMs??0,x=c?()=>{let b=c.lastServerTime(),S=b>0?Math.max(0,c.serverNow()-b):0;return Math.max(0,S+g)}:()=>Math.max(0,g);a.set(h,this.attachToGroup(h,this.planFor(i,h),x))}),f=this.callbacks.onRemove(e,(h,p)=>{a?.get(h)?.(),a?.delete(h),l(h,p)});return()=>{if(d?.(),f?.(),a!==void 0){for(let h of a.values())h();a.clear()}}}),i!==void 0&&r.bindReader((u,l)=>this.value(u,l)),this.driven.push(r),r}canonicalDelay(){return this.profileBuf[ir*Ht+qs]}bindInputRenderDelay(e){e instanceof jo&&e.bindRenderDelay(()=>this.canonicalDelay())}reconciler(e,n){let r=new $s(e,{...n,clock:n.clock??this.clock});return this.adoptFixedStep(r.stepMs),this.bindInputRenderDelay(n.input),this.installBoundOverlay(r),this.driven.push(r),r}sim(e){let n=new js({...e,clock:e.clock??this.clock});return this.adoptFixedStep(n.stepMs),this.bindInputRenderDelay(e.input),this.installBoundOverlay(n),this.driven.push(n),n}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,n){let r=zt(e),s=r===void 0?void 0:this.slotByRef.get(r)?.get(n);if(s===void 0)return e[n];let o=this.slotBuf[s*vt+Nn]|0;return this.profileComputers[o](s)}valueAt(e,n,r){let s=zt(e),o=s===void 0?void 0:this.slotByRef.get(s)?.get(n);if(o===void 0)return e[n];let i=o*vt,a=this.slotBuf[i+Nn]|0;if(this.profileComputers[a]!==this.computeReckon)return this.profileComputers[a](o);let c=this.simByRef.get(this.slotBuf[i+qa]);if(c!==void 0){let u=this.slotBuf[i+Ga]|0,l=u<c.posOf.length?c.posOf[u]:-1;if(l>=0){let d=this.clock?.lastServerTime?.()??NaN,f=Number.isNaN(d)?0:Math.max(0,r-d);return c.advance(c.instance,f,c.valueOut,r),c.valueOut[l]}}return this.slotBuf[i+rn]}read(e,n,r){let s=r??{},o=zt(e),i=o===void 0?void 0:this.slotByRef.get(o);for(let a=0;a<n.length;a++){let c=n[a],u=i?.get(c);s[c]=u===void 0?e[c]:this.profileComputers[this.slotBuf[u*vt+Nn]|0](u)}return s}readAt(e,n,r,s){let o=s??{},i=zt(e),a=i===void 0?void 0:this.slotByRef.get(i),c,u=!1;for(let l=0;l<n.length;l++){let d=n[l],f=a?.get(d);if(f===void 0){o[d]=e[d];continue}let h=f*vt,p=this.slotBuf[h+Nn]|0;if(this.profileComputers[p]!==this.computeReckon){o[d]=this.profileComputers[p](f);continue}if(!u&&(u=!0,c=this.simByRef.get(this.slotBuf[h+qa]),c!==void 0)){let g=this.clock?.lastServerTime?.()??NaN,x=Number.isNaN(g)?0:Math.max(0,r-g);c.advance(c.instance,x,c.valueOut,r)}if(c!==void 0){let g=this.slotBuf[h+Ga]|0,x=g<c.posOf.length?c.posOf[g]:-1;if(x>=0){o[d]=c.valueOut[x];continue}}o[d]=this.slotBuf[h+rn]}return o}computeLerpRaw(e){let n=this.slotBuf,r=e*vt,s=this.profileBuf,o=(n[r+Nn]|0)*Ht,i=this.renderTime,a=n[r+ai]|0;if(a===0)return n[r+rn];let c=n[r+ii]|0,u=r+Wa,l=(c-a+ct)%ct,d=(l+a-1)%ct,f=u+d*2;if(a===1)return n[f+1];let h=s[o+qs],p=this.clock&&this.clock.lastServerTime()>0?this.clock.serverNow()-h-this.clock.smoothedRtt()/2:i-h,g=u+l*2;if(p<=n[g])return n[g+1];if(p>=n[f])return n[f+1];let x=a-2,b=(l+x)%ct;for(;x>0&&!(n[u+b*2]<=p);)x--,b=b===0?ct-1:b-1;let S=u+b*2,_=b+1>=ct?0:b+1,P=u+_*2,R=n[S],M=n[P]-R;if(M<=0)return n[P+1];let O=(p-R)/M,z=n[S+1],X=n[P+1];return z+(X-z)*O}applySimulation(e,n){let r=this.renderTime;if(e.lastApplyTime!==r){let s=e.out,o=e.smoothed,i=e.offset,a=o.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 d=0;d<a;d++)i[d]=0,o[d]=s[d];else if(Number.isNaN(c)){let d=Math.max(0,Math.min(r-e.lastApplyTime,100)),f=1-Math.exp(-d/e.smoothMs);for(let h=0;h<a;h++)o[h]+=(s[h]-o[h])*f}else{let d=Math.max(0,Math.min(r-e.lastApplyTime,100));if(c!==e.lastBaseT&&!Number.isNaN(e.lastBaseT)){let h=e.snap,p=e.frameVel;for(let g=0;g<a;g++){let x=o[g]+p[g]*d-s[g];i[g]=h>0&&Math.abs(x)>h?0:x}}else if(d>0){let h=e.outPrev,p=e.frameVel;for(let g=0;g<a;g++)p[g]=(s[g]-h[g])/d}let f=Math.exp(-d/e.smoothMs);for(let h=0;h<a;h++)i[h]*=f,o[h]=s[h]+i[h]}let l=e.outPrev;for(let d=0;d<a;d++)l[d]=s[d];e.lastBaseT=c,e.lastApplyTime=r}return e.smoothed[n]}};m(hi,"MAX_STEPS_PER_FRAME",5);Ws=hi});var p0={};Fd(p0,{DEFAULT_GRACE_TICKS:()=>xp,Predict:()=>Ws,PredictedEventChannel:()=>oi,PredictedSpawns:()=>Hs,Reconciler:()=>$s,SimReconciler:()=>js,classifyDrift:()=>ri});var Mp=at(()=>{"use strict";_p();gl();hl();bl();Sp();yl()});var Xi="genex-native";var Yc="genex_native";var Kc="genex_protocol",Xc="genex_attempt",Jc="genex_nonce",Ud="genex_caps";var ko="genex_";var Vd="genex_r";var Hd="entryRef",$d="genex_hash",jd="genex_referrer",qd="genex_ref";var Zc="__genexNative";var KE=/^[0-9a-f]{32}$/,XE=/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;function hr(t){return typeof t=="string"&&KE.test(t)}function Gd(t){return typeof t=="string"&&XE.test(t)}var Po="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",JE=(()=>{let t=new Array(128).fill(-1);for(let e=0;e<Po.length;e++)t[Po.charCodeAt(e)]=e;return t})();function cm(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(r>=55296&&r<=56319){let s=n+1<t.length?t.charCodeAt(n+1):0;s>=56320&&s<=57343?(r=65536+(r-55296<<10)+(s-56320),n++):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 ZE(t){let e="";for(let n=0;n<t.length;){let r=t[n],s,o;if(r<128)s=r,o=1;else if((r&224)===192)s=r&31,o=2;else if((r&240)===224)s=r&15,o=3;else if((r&248)===240)s=r&7,o=4;else return null;if(n+o>t.length)return null;for(let i=1;i<o;i++){let a=t[n+i];if((a&192)!==128)return null;s=s<<6|a&63}if(o===2&&s<128||o===3&&(s<2048||s>=55296&&s<=57343)||o===4&&(s<65536||s>1114111))return null;if(s>65535){let i=s-65536;e+=String.fromCharCode(55296+(i>>10),56320+(i&1023))}else e+=String.fromCharCode(s);n+=o}return e}function Wd(t){return cm(t).length}function Yd(t){let e=cm(JSON.stringify(t)),n="";for(let r=0;r<e.length;r+=3){let s=e[r],o=e[r+1],i=e[r+2];if(n+=Po[s>>2],n+=Po[(s&3)<<4|(o??0)>>4],o===void 0||(n+=Po[(o&15)<<2|(i??0)>>6],i===void 0))break;n+=Po[i&63]}return n}function Kd(t){if(t.length%4===1)return;let e=[],n=0,r=0;for(let o=0;o<t.length;o++){let i=t.charCodeAt(o),a=i<128?JE[i]:-1;if(a<0)return;n=n<<6|a,r+=6,r>=8&&(r-=8,e.push(n>>r&255))}if(r>0&&(n&(1<<r)-1)!==0)return;let s=ZE(e);if(s!==null)try{return JSON.parse(s)}catch{return}}var um=2048,lm=32;var e_=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;function t_(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Qc(t,e){if(Object.keys(t).length!==e.length)return!1;for(let r of e)if(!Object.prototype.hasOwnProperty.call(t,r))return!1;return!0}var eu=["channel","v","type","slug","attemptId","nonce"];function n_(t){return t.channel===Xi&&t.v===1&&Gd(t.slug)&&hr(t.attemptId)&&hr(t.nonce)}function Xd(t){if(!(!t_(t)||!n_(t)))switch(t.type){case"ticket":return!Qc(t,[...eu,"ticket","expiresAt"])||typeof t.ticket!="string"||t.ticket.length===0||t.ticket.length>um||typeof t.expiresAt!="string"||t.expiresAt.length>lm||!e_.test(t.expiresAt)?void 0:t;case"guest":case"cancel":return Qc(t,eu)?t:void 0;case"foreground":return!Qc(t,[...eu,"active"])||typeof t.active!="boolean"?void 0:t;case"network":return!Qc(t,[...eu,"online"])||typeof t.online!="boolean"?void 0:t;default:return}}function s_(t,e){if(typeof t!="string"||t.length===0)return{ok:!1,reason:"undecodable"};if(Wd(t)>4096)return{ok:!1,reason:"too-large"};let n=Kd(t);if(n===void 0)return{ok:!1,reason:"undecodable"};let r=e(n);return r===void 0?{ok:!1,reason:"invalid"}:{ok:!0,message:r}}function Zd(t){return s_(t,Xd)}function Qd(t){let e=Yd(t);if(!(e.length>4096))return e}function tu(t,e){let n=t.charAt(0)==="?"?t.slice(1):t;if(n.length===0)return null;for(let r of n.split("&")){let s=r.indexOf("=");if(s!==-1&&r.slice(0,s)===e)return r.slice(s+1)}return null}function nu(t){return tu(t,Yc)==="1"}function tf(t){if(!nu(t))return null;let e=tu(t,Xc),n=tu(t,Jc),r=Number(tu(t,Kc));return!hr(e)||!hr(n)||r!==1?null:{attemptId:e,nonce:n,protocol:r}}function mm(t){return t.indexOf("%")===-1?t:t.replace(/%([0-9A-Fa-f]{2})/g,(e,n)=>{let r=parseInt(n,16);return r<128?String.fromCharCode(r):e})}function ym(t){let e=t.indexOf("="),n=e===-1?t:t.slice(0,e);return mm(n.indexOf("+")===-1?n:n.split("+").join(" "))}function ru(t){return gm(t,[Vd])}var i_=[Yc,Kc,Xc,Jc,Ud];function nf(t){return gm(t,i_)}function gm(t,e){let n=t.charAt(0)==="?"?t.slice(1):t;if(n.length===0)return"";let r=n.split("&"),s=r.filter(i=>!e.includes(ym(i)));if(s.length===r.length)return`?${n}`;let o=s.join("&");return o.length===0?"":`?${o}`}var a_=/^[!$-&(-;=?-~]+$/;function su(t,e){if(typeof t!="string")return"";let n=t.charAt(0)==="?"?t.slice(1):t,r=n.indexOf("#");if(r!==-1&&(n=n.slice(0,r)),n.length===0||!a_.test(n))return"";let o=n.split("&").filter(i=>{if(i.length===0)return!1;let a=ym(i);return!a.startsWith(ko)&&!e.includes(a)}).join("&");return o.length>1024?"":o}var c_=/^#[!#-;=?-_a-~]+$/;function ou(t){return typeof t!="string"||t.length<2||t.length>4096||!c_.test(t)||mm(t).includes(ko)?"":t}var u_=/^[a-z0-9._-]+$/,l_=/^\[[0-9a-f:.]+\]$/;function d_(t){return u_.test(t)&&/[a-z0-9]/.test(t)||l_.test(t)}function ef(t){let e=t.slice(0,8).toLowerCase(),n=e==="https://"?"https":e.slice(0,7)==="http://"?"http":null;if(n===null)return null;let r=n.length+3,s=t.length;for(let u=r;u<t.length;u++){let l=t.charAt(u);if(l==="/"||l==="?"||l==="#"||l==="\\"){s=u;break}}if(s-r>255)return null;let o=t.slice(r,s).toLowerCase();if(o.length===0||o.indexOf("@")!==-1)return null;let i=o,a="",c=o.lastIndexOf(":");if(c!==-1&&o.charAt(o.length-1)!=="]"&&(i=o.slice(0,c),a=o.slice(c+1)),!d_(i))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===(n==="https"?443:80)?"":`:${u}`}return`${n}://${i}${a}`}function vo(t,e){if(typeof t!="string"||t.length===0)return null;let n=ef(t);return n===null||n.length>255||typeof e=="string"&&ef(e)===n?null:n}var bm=["open","save","fullscreen"];var wm=50*1024*1024,f_=16;function xm(t){return typeof t=="string"&&bm.includes(t)}function rf(t){if(!Array.isArray(t))return[];let e=[],n=Math.min(t.length,f_);for(let r=0;r<n;r++){let s=t[r];xm(s)&&!e.includes(s)&&e.push(s)}return e}var R_=null;function Em(t){R_=t}var P_=null;function _m(t){P_=t}var A_=null;function Rm(t){A_=t}var ea=1,uf="genex:embed:retry",Fm="genex:guest:popover-dismissed",zm="genex:embed:local-auth",Um="genex:embed:entry-referrer",v_="none",km="genex:player",T_="0.35.0",De=null,Fe="pending",Zt=null,Vr=!1,zr=null,To=!1,Ur,Mo,Vm=0,Lt,Hm,lf,$m,jm=!1,Hr=null,qm=[],Oo=!1,As=!1,Zi=!1,Jt=0,Io=1e4,M_=2e3,C_=10*6e4,O_=6e4,Pm=500,I_=3e4,D_=3e4,Ge,Rn,Co,Am=!1,vm,iu=null,Tm=new Set;var Mm=!1,B_=new Map,Gm=[],ta=[],Qi=null,au=null,Ps,sf,of=!1,cu=new Map;function Ze(){return globalThis.window}function df(){return globalThis.document}function na(t,e,n){let r;if(n!==void 0)try{let s=globalThis.AbortSignal;s&&typeof s.timeout=="function"&&(r=s.timeout(n))}catch{}return globalThis.fetch(t,r?{...e,signal:r}:e)}function N_(){try{return Ze()?.sessionStorage?.getItem(uf)==="1"}catch{return!1}}function L_(){try{Ze()?.sessionStorage?.setItem(uf,"1")}catch{}}function ff(){try{Ze()?.sessionStorage?.removeItem(uf)}catch{}}function F_(){try{return Ze()?.sessionStorage?.getItem(zm)==="1"}catch{return!1}}function z_(){try{Ze()?.sessionStorage?.setItem(zm,"1")}catch{}}function U_(){try{let t=Ze()?.sessionStorage?.getItem(Um);return t==null?void 0:vo(t)}catch{return}}function V_(t){try{Ze()?.sessionStorage?.setItem(Um,t??v_)}catch{}}function H_(){try{return Ze()?.sessionStorage?.getItem(Fm)==="1"}catch{return!1}}function $_(){try{Ze()?.sessionStorage?.setItem(Fm,"1")}catch{}}function j_(){try{let t=Ze()?.localStorage;if(!t)return"no-storage";let e=t.getItem(km);return e||(e=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,t.setItem(km,e)),e}catch{return"no-storage"}}function lu(t){let e=Ze();if(!e||Oo)return;if(Oo=!0,Co!==void 0&&(clearTimeout(Co),Co=void 0),De={slug:t.slug,apiUrl:t.apiUrl.replace(/\/$/,""),dashboardOrigins:[...t.dashboardOrigins]},Fe="pending",Qm(e),_m({apiUrl:De.apiUrl,dashboardOrigins:De.dashboardOrigins,getToken:()=>Lt,getParentOrigin:()=>Hr,isEmbedded:Ft,isNative:fn,isLocalTest:()=>Vr}),Rm({apiUrl:De.apiUrl,dashboardOrigins:De.dashboardOrigins,getToken:()=>Lt,getParentOrigin:()=>Hr,isEmbedded:Ft,isNative:fn,isLocalTest:()=>Vr}),bf(e)){gR(e);return}pu("connecting");let n=ey(e);if(n){oR(e,n);return}Ft()?rR(e):cR(e)}function Ft(){let t=Ze();if(!t)return!1;try{return t.self!==t.top}catch{return!0}}function q_(){let t=Ze();return t?Ft()?"page":fn()||hf(t)?"app":Oo?Vr?"local":"standalone":bf(t,!1)?"local":"standalone":"standalone"}function du(){return jm?{embedToken:fR}:Lt?{embedToken:Lt}:void 0}function Wm(){return Hm??[]}function Ym(){return cy(lf)??[]}function Km(){return mR($m)}function pf(){return(Fe==="authenticated"||Fe==="guest")&&Zt?Promise.resolve({user:Zt,guest:Fe==="guest"}):Fe==="blocked"?Promise.reject(new Error("genex embed auth: blocked")):(G_("waitForPlayer"),new Promise((t,e)=>{ta.push({resolve:t,reject:e})}))}function G_(t){if(!Oo){if(!Am){Am=!0;try{console.error(`[genex] ${t}() 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{}}Co===void 0&&(Co=setTimeout(()=>{Co=void 0,Oo||mr("no-identity")},Io))}}var W_=32*1024;async function Xm(){if(!De)throw new Error("genex embed: call initEmbed() first");if(Fe==="pending"&&await pf(),Fe==="blocked")throw new Error("genex embed auth: blocked")}function Jm(t,e={}){let n={Authorization:`Bearer ${Lt}`};return e.body!==void 0&&(n["Content-Type"]="application/json"),e.ifVersion!==void 0&&(n["If-Match"]=String(e.ifVersion)),na(`${De.apiUrl}/api/projects/${encodeURIComponent(De.slug)}${t}`,{method:e.method??"GET",headers:n,body:e.body,keepalive:e.body!==void 0&&e.body.length<=W_?!0:void 0})}async function Y_(t){return t.status!==403?!1:(await t.json().catch(()=>null))?.error==="staging_no_save"}async function K_(t){return t.status===409?{saved:!1,conflict:!0,version:(await t.json().catch(()=>({}))).version}:t.ok?{saved:!0,version:(await t.json()).version}:await Y_(t)?{saved:!1,staging:!0}:(Qt("error",{error:new Error(`genex state save failed (${t.status})`)}),{saved:!1})}async function X_(t,e){return await Xm(),Fe==="guest"?(sf=t,of=!0,{saved:!1,guest:!0,queued:!0}):K_(await Jm("/state/me",{method:"PUT",body:JSON.stringify(t),ifVersion:e?.ifVersion}))}async function J_(t,e){let n=e?.board??"main",r=e?.mode??"max";if(await Xm(),Fe==="guest"){let i=cu.get(n);return(!i||(r==="min"?t<i.score:t>i.score))&&cu.set(n,{score:t,mode:r}),{submitted:!1,guest:!0,queued:!0}}let s=await Jm("/scores",{method:"POST",body:JSON.stringify({score:t,board:n,mode:r})});if(!s.ok)return Qt("error",{error:new Error(`genex score submit failed (${s.status})`)}),{submitted:!1};let o=await s.json();return{submitted:!0,best:o.best,improved:o.improved}}async function Z_(){try{if(of){let e=sf;sf=void 0,of=!1,await X_(e)}let t=[...cu.entries()];cu.clear();for(let[e,{score:n,mode:r}]of t)await J_(n,{board:e,mode:r})}catch(t){Qt("error",{error:t})}}function Qt(t,e){let n=B_.get(t);if(n)for(let r of[...n])try{r(e)}catch{}}var Q_=["embed"];function Zm(t,e){let n={ticket:null,guest:!1,entryHash:"",entryReferrer:null};if(!t||t.length<2)return n;try{let r=new URLSearchParams(t.slice(1));return{ticket:r.get("genex_ticket"),guest:r.get("genex_guest")==="1",entryHash:ou(r.get($d)),entryReferrer:vo(r.get(jd),e)}}catch{return n}}function eR(t,e){try{return new URLSearchParams(t).get(e)}catch{return null}}function Qm(t){if(iu)return iu;let e="",n="",r=null;try{e=t.location.search??"",n=uu??t.location.hash??"",r=t.location.origin??null}catch{}let s=Ft(),o=Zm(n,r),i=!s&&(!!o.ticket||o.guest),a=su(e,Q_);return iu={search:a?`?${a}`:"",hash:i?o.entryHash:n.includes(ko)?"":n,referrer:tR(e,s,i,o.entryReferrer,r)},iu}function tR(t,e,n,r,s){let o=U_();if(o!==void 0)return o;let i;return e?i=vo(eR(t,qd),s):n?i=r:i=vo(df()?.referrer,s),V_(i),i}function nR(){if(!(Mm||Tm.size===0)){Mm=!0;for(let t of[...Tm])try{t()}catch{}}}function rR(t){vm=e=>{sR(e)},t.addEventListener("message",vm),t.parent.postMessage({type:"genex:embed:ready",v:ea},"*"),Ge=setTimeout(()=>{Do()},Io)}function Cm(){return(Fe==="pending"||Fe==="guest")&&!As}async function sR(t){if(!De)return;let e=t.data;if(!e||e.v!==ea)return;let n=e.type==="genex:embed:ticket",r=e.type==="genex:embed:guest";if(!(!n&&!r)&&!(n&&(!Cm()||typeof e.ticket!="string"||!e.ticket))&&!(r&&(Fe!=="pending"||As||Zi))){if(!De.dashboardOrigins.includes(t.origin)){let s=await af();if(n&&!Cm()||r&&(Fe!=="pending"||As||Zi)||!s.includes(t.origin))return}if(Ge!==void 0&&clearTimeout(Ge),Hr=t.origin,qm=rf(e.caps),r){await Do();return}await gf(e.ticket)}}function hf(t){let e=t.ReactNativeWebView;return!e||typeof e!="object"?null:typeof e.postMessage=="function"?e:null}function ey(t){if(Ft())return null;let e;try{e=t.location.search??""}catch{return null}return!nu(e)||!hf(t)?null:tf(e)}function fn(){return zr!==null}function vs(t){let e=Ze();if(!e||!De||!zr)return;let n=hf(e);if(!n)return;let r=Qd({channel:Xi,v:1,slug:De.slug,attemptId:zr.attemptId,nonce:zr.nonce,...t});if(r)try{n.postMessage(r)}catch{}}function ty(t){fn()&&vs({type:"error",code:t})}function oR(t,e){zr=e,Vm=Date.now(),t[Zc]=r=>{iR(r)},vs({type:"ready",sdkVersion:T_,capabilities:["native-ticket","native-guest","heartbeat"]}),Ge=setTimeout(()=>{Do()},Io)}async function iR(t){if(!De||!zr)return;let e=Zd(t);if(!e.ok)return;let n=e.message;if(!(n.slug!==De.slug||n.attemptId!==zr.attemptId||n.nonce!==zr.nonce))switch(n.type){case"ticket":Ge!==void 0&&clearTimeout(Ge),await gf(n.ticket);return;case"guest":Ge!==void 0&&clearTimeout(Ge),await Do();return;case"cancel":ny(),nR();return;case"foreground":case"network":return}}function ny(){Ge!==void 0&&clearTimeout(Ge),Ge=void 0,Rn!==void 0&&clearTimeout(Rn),Rn=void 0,Ur!==void 0&&clearTimeout(Ur),Ur=void 0,Mo!==void 0&&clearInterval(Mo),Mo=void 0}function ry(){!fn()||Mo!==void 0||(Mo=setInterval(()=>{vs({type:"heartbeat",uptimeMs:Math.max(0,Date.now()-Vm)})},D_),Mo.unref?.())}function aR(){!fn()||To||(To=!0,vs({type:"reauth-required"}),Ur=setTimeout(()=>{Ur=void 0,To&&(To=!1,Qt("error",{error:new Error("embed session expired")}),mr("session-expired"))},I_))}function mf(){To=!1,Ur!==void 0&&clearTimeout(Ur),Ur=void 0}function yf(t,e){let n=Ze();if(!(!n||!Ft()))try{n.parent.postMessage(t,e)}catch{}}async function cR(t){let e=sy(t);if(e.ticket){Om(),await gf(e.ticket);return}if(e.guest){Om(),await Do();return}pu("redirecting"),await fu(t,{guestOk:!0})}function Om(){Ge!==void 0&&clearTimeout(Ge),Ge=setTimeout(()=>{Ge=void 0,Fe==="pending"&&mr("no-identity")},Io+M_)}var uu=null;function uR(t){return t.location.pathname+ru(t.location.search)}function sy(t){let e=uu??t.location.hash;uu=null;let{ticket:n,guest:r,entryHash:s}=Zm(e);if(n||r)try{t.history.replaceState(t.history.state??null,"",uR(t)+s)}catch{}return{ticket:n,guest:r}}async function fu(t,e){if(!De||Vr||fn())return;let n=e?.guestOk?De.dashboardOrigins[0]??(await af())[0]:(await af())[0]??De.dashboardOrigins[0];if(!n){mr();return}let r=t.location.origin+t.location.pathname,s=nf(ru(t.location.search));s.length-1<=1024&&r.length+s.length<=2048&&s.indexOf("#")===-1&&(r+=s);let o=e?.guestOk?"&guest=ok":"",i=`${n}/play/authorize?returnTo=${encodeURIComponent(r)}&slug=${encodeURIComponent(De.slug)}${o}`,a=Qm(t).referrer;a&&(i+=`&${Hd}=${encodeURIComponent(a)}`),i+=ou(t.location.hash),t.location.replace(i)}async function af(){if(!De)return[];try{let t=await na(`${De.apiUrl}/api/embed/dashboard-origins`);if(!t.ok)return De.dashboardOrigins;let e=await t.json();if(Array.isArray(e.origins)&&e.origins.every(n=>typeof n=="string"))return e.origins}catch{}return De.dashboardOrigins}async function gf(t){if(!De||Vr||As||Fe!=="pending"&&Fe!=="guest"&&!(To&&Fe==="authenticated"))return;let n=Fe==="guest",r=++Jt;As=!0;try{let s=await na(`${De.apiUrl}/api/embed/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ticket:t})},Io);if(r!==Jt)return;if(!s.ok){Qt("error",{error:new Error(`ticket redemption failed (${s.status})`)}),n||await Im();return}let o=await s.json();if(r!==Jt)return;Lt=o.embedToken,Zt=o.user,ay(o.colyseus),Fe="authenticated",Ge!==void 0&&clearTimeout(Ge),Ge=void 0,ff(),hu(),xf(),wf(),Ft()&&Hr&&yf({type:"genex:embed:authenticated",v:ea},Hr),fn()&&(mf(),vs({type:"authenticated",guest:!1}),ry()),n&&await Z_();let i={user:Zt};for(let a of Gm.splice(0))a.resolve(i);for(let a of ta.splice(0))a.resolve({user:Zt,guest:!1});Qt("authenticated",i)}catch(s){if(r!==Jt)return;Qt("error",{error:s}),n||await Im()}finally{As=!1}}async function Do(){if(!De||Vr||Zi||As||Fe!=="pending"&&Fe!=="guest")return;let t=++Jt;Zi=!0;try{let e=await na(`${De.apiUrl}/api/embed/guest-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:De.slug,playerId:j_()})},Io);if(t!==Jt)return;if(!e.ok){Qt("error",{error:new Error(`guest session failed (${e.status})`)}),ty("guest-failed"),mr(e.status===404?"not-available":"no-identity");return}let n=await e.json();if(t!==Jt)return;Lt=n.embedToken,Zt=n.user,ay(n.colyseus),lR()}catch(e){if(t!==Jt)return;Qt("error",{error:e}),mr()}finally{Zi=!1}}function lR(){let t=Fe!=="guest";if(Fe="guest",Ge!==void 0&&clearTimeout(Ge),hu(),wf(),Ft()?yf({type:"genex:embed:authenticated",v:ea,guest:!0},Hr??"*"):fn()?(vs({type:"authenticated",guest:!0}),ry()):t&&!H_()&&RR(),Zt){let e={user:Zt};for(let n of ta.splice(0))n.resolve({user:Zt,guest:!0});Qt("guest",e)}}function oy(t){try{let e=new URL(t.location.origin);return e.protocol==="http:"&&iy.has(e.hostname)}catch{return!1}}var iy=new Set(["localhost","127.0.0.1","[::1]"]),dR="genex_authority_url",fR="local:test",pR=64;function hR(t){if(!t||t.length>pR)return null;let e;try{e=new URL(t)}catch{return null}let n=!e.username&&!e.password&&e.pathname==="/"&&!e.search&&!e.hash;return e.protocol!=="ws:"||!iy.has(e.hostname)||!n?null:`ws://${e.host}`}function ay(t){Hm=t?.urls,lf=t?.authorityUrls,$m=t?.authorityRegions}function cy(t){if(Array.isArray(t))return t.filter(e=>typeof e=="string"&&e.length>0)}function mR(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(n===null||typeof n!="object")continue;let{region:r,urls:s}=n,o=cy(s)??[];typeof r=="string"&&r.length>0&&o.length>0&&e.push({region:r,urls:o})}return e}function bf(t,e=!0){if(Ft()||ey(t)||!oy(t))return!1;let n=null;try{n=new URLSearchParams(t.location.search)}catch{}return n?.get("genex_local_test")==="1"?!0:n?.get("genex_auth")==="1"?(e&&z_(),!1):F_()?!1:!yR(t)}function yR(t){let e=uu??t.location.hash;return!!e&&e.includes("genex_")}function gR(t){Vr=!0,sy(t),bR(t);let e={id:"local:test",name:"Local Tester"};Zt=e,Fe="guest",hu();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 n of ta.splice(0))n.resolve({user:e,guest:!0});Qt("guest",{user:e})}function bR(t){if(!oy(t))return;let e=null;try{e=new URLSearchParams(t.location.search).get(dR)}catch{return}let n=hR(e);n&&(lf=[n],jm=!0)}async function Im(){let t=Ze();if(Ge!==void 0&&clearTimeout(Ge),Ge=void 0,fn()){mf(),ty("ticket-rejected"),mr();return}if(t&&!Ft()&&!N_()){L_(),pu("redirecting"),await fu(t,{guestOk:!0});return}mr()}function wf(){Rn!==void 0&&clearTimeout(Rn),Rn=setTimeout(()=>{uy()},C_)}async function uy(){if(!De||Fe!=="authenticated"&&Fe!=="guest"||!Lt)return;let t=Jt,e=Lt,n;try{let r=await na(`${De.apiUrl}/api/embed/session/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`},keepalive:!0});if(n=r.status,t!==Jt||Lt!==e)return;if(r.ok){let s=await r.json();if(t!==Jt||Lt!==e)return;Lt=s.embedToken,wf();return}}catch{n=void 0}if(!(t!==Jt||Lt!==e)){if(n===401){if(Fe==="guest"){Do();return}if(fn()){aR();return}Qt("error",{error:new Error("embed session expired")}),mr("session-expired");return}Rn!==void 0&&clearTimeout(Rn),Rn=setTimeout(()=>{uy()},O_)}}function mr(t="no-identity"){if(Fe==="blocked")return;Jt++,Fe="blocked",Zt=null,Lt=void 0,Ge!==void 0&&clearTimeout(Ge),Rn!==void 0&&clearTimeout(Rn),xf(),fn()?(ny(),mf(),hu(),vs({type:"blocked",reason:t})):pu(Ft()?"blocked-embedded":"blocked-standalone"),Ft()&&yf({type:"genex:embed:blocked",v:ea},Hr??"*");let e=new Error("genex embed auth: blocked");for(let n of Gm.splice(0))n.reject(e);for(let n of ta.splice(0))n.reject(e);Qt("blocked")}var wR={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}},xR="https://cdn.genex.technology/fonts/GeistMono-variable.woff2",ly="'Geist Mono',ui-monospace,SFMono-Regular,Menlo,monospace",Dm=!1,Bm="!<>-_/[]{}=+*^?#$%&@",dy=50,Nm=10,Lm=[{name:"churn",ticks:5},{name:"settle",ticks:10},{name:"hold",ticks:12},{name:"dissolve",ticks:8}];function cf(t){let e="";for(let n=0;n<t;n++)e+=Bm[Math.floor(Math.random()*Bm.length)];return e}function fy(){try{let t=Ze();return!t||typeof t.matchMedia!="function"?!0:t.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!0}}function SR(t,e){if(fy())return t.textContent=e,()=>{};let n=0;t.textContent=cf(e.length);let r=setInterval(()=>{if(n++,n>=Nm){t.textContent=e,clearInterval(r);return}let s=Math.floor(n/Nm*e.length);t.textContent=e.slice(0,s)+cf(e.length-s)},dy);return()=>clearInterval(r)}function ER(t,e){if(fy())return t.textContent=e,()=>{};let n=0,r=0,s=()=>{let i=Lm[n],a;i.name==="churn"?a=0:i.name==="settle"?a=Math.floor(r/i.ticks*e.length):i.name==="hold"?a=e.length:a=e.length-Math.floor(r/i.ticks*e.length),t.textContent=e.slice(0,a)+cf(e.length-a),r++,r>=i.ticks&&(r=0,n=(n+1)%Lm.length)};s();let o=setInterval(s,dy);return()=>clearInterval(o)}function py(t){if(!Dm){Dm=!0;try{let e=Ze()?.FontFace,n=t.fonts;if(!e||!n?.add)return;new e("Geist Mono",`url(${xR}) format('woff2')`,{weight:"100 900",display:"swap"}).load().then(s=>n.add(s)).catch(()=>{})}catch{}}}function pu(t){let e=df();if(e?.createElement)try{Qi||(Qi=_R(e)),Qi.setContent(t)}catch{}}function hu(t=!1){try{let e=Qi;if(Qi=null,!e)return;e.stopText();let n=e.root;if(t||!n.style){n.remove?.();return}n.style.pointerEvents="none",n.style.transition="opacity 180ms ease",n.style.opacity="0",setTimeout(()=>{try{n.remove?.()}catch{}},220)}catch{}}function _R(t){py(t);let e=t.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:${ly};text-align:center;pointer-events:auto;user-select:none`;let n=t.createElement("div");n.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(n);let r=t.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=Ze();c&&(r.disabled=!0,ff(),fu(c))}),e.appendChild(r);let s=()=>{t.body&&!e.isConnected&&t.body.appendChild(e)};t.body?s():t.addEventListener?.("DOMContentLoaded",s);let o,i,a=()=>{o!==void 0&&(clearTimeout(o),o=void 0),i&&(i(),i=void 0)};return{root:e,stopText:a,setContent(c){let u=wR[c];a(),n.textContent=u.title,n.style.letterSpacing=u.wordmark?"0.22em":"",n.style.marginRight=u.wordmark?"-0.22em":"";let l=()=>{n.style.opacity="1",i=u.wordmark?ER(n,u.title):SR(n,u.title)};u.instant||Pm<=0?l():(n.style.opacity="0",o=setTimeout(()=>{o=void 0,l()},Pm)),r.style.display=u.button?"inline-block":"none",u.button&&(r.textContent=u.button),s()}}}function RR(){let t=df();if(!(!t?.createElement||au))try{au=kR(t)}catch{}}function xf(){Ps!==void 0&&(clearTimeout(Ps),Ps=void 0);try{au?.root?.remove?.()}catch{}au=null}function kR(t){py(t);let e=!1;try{let c=Ze(),u=c?.navigator;if(c&&u){let l=c.matchMedia?.("(pointer: coarse)").matches??!1,d=(u.maxTouchPoints??0)>1,f=u.userAgentData?u.userAgentData.mobile:/Mobi|Android/i.test(u.userAgent??"");e=d&&l||f}}catch{}let n=t.createElement("div");n.setAttribute("data-genex-guest-popover",""),n.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=t.createElement("div");r.style.cssText=`display:flex;align-items:center;border-radius:12px;background:rgba(0,0,0,0.85);color:#fff;font-family:${ly};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"),n.appendChild(r);let s=t.createElement("span");s.textContent=!e&&Zt?.name?`Playing as ${Zt.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 o=t.createElement("button");o.textContent="Sign in",o.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"),o.addEventListener("mouseenter",()=>{o.style.background="#3f51a8"}),o.addEventListener("mouseleave",()=>{o.style.background="#4b60bf"}),o.addEventListener("click",()=>{let c=Ze();c&&(o.disabled=!0,ff(),fu(c))}),r.appendChild(o);let i=t.createElement("button");if(i.textContent="\xD7",i.setAttribute("aria-label","Dismiss"),i.style.cssText="font-size:16px;line-height:1;padding:6px 8px;border:none;cursor:pointer;background:transparent;color:rgba(255,255,255,0.6)",i.addEventListener("click",()=>{$_(),xf()}),r.appendChild(i),e){let c=t.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>',n.appendChild(c);let u=l=>{r.style.display=l?"none":"flex",c.style.display=l?"flex":"none"};Ps=setTimeout(()=>u(!0),5e3),r.addEventListener("pointerdown",()=>{Ps!==void 0&&clearTimeout(Ps),Ps=void 0}),c.addEventListener("click",()=>u(!1))}let a=()=>{t.body&&!n.isConnected&&t.body.appendChild(n)};return t.body?a():t.addEventListener?.("DOMContentLoaded",a),{root:n}}Em({getShell:q_,isLocalTest:()=>{let t=Ze();return!t||Ft()?!1:Oo?Vr:bf(t,!1)},getConfig:()=>De,getParentOrigin:()=>Hr,getShellCaps:()=>qm});var Bp={};Fd(Bp,{chatSend:()=>QA,claim:()=>ev,claimAsHost:()=>tv,connect:()=>HA,destroy:()=>rv,dispose:()=>$A,drainEventsJson:()=>pv,leave:()=>T0,listen:()=>XA,objectsJson:()=>dv,open:()=>VA,playersJson:()=>lv,release:()=>nv,reportEliminated:()=>sv,reportFinish:()=>iv,reportScore:()=>ov,send:()=>KA,sendInput:()=>JA,serverNow:()=>av,sessionJson:()=>uv,setIdentity:()=>LA,setMe:()=>jA,setObject:()=>WA,setRoomOpen:()=>ZA,setShared:()=>GA,sharedJson:()=>fv,snapMe:()=>qA,snapObject:()=>YA,timeUntil:()=>cv,version:()=>NA});var ra={ready(t){let e=globalThis.__GENEX__;return t&&e&&typeof e.apiUrl=="string"&&Array.isArray(e.dashboardOrigins)&&lu({slug:t,apiUrl:e.apiUrl,dashboardOrigins:e.dashboardOrigins.filter(n=>typeof n=="string")}),pf()},auth:()=>du(),urls:()=>Wm()},PR=4096;function pe(t,e){t.q.length>=PR&&(t.overflowed?t.q.splice(1,1):(t.overflowed=!0,t.q.splice(0,2,{type:"warning",message:"genex bridge: event queue full; drain it every frame (oldest events dropped)"}))),t.q.push(e)}var Bo=t=>({type:"warning",message:`genex bridge: ${t}`});function AR(t){try{return JSON.stringify(t)}catch(e){let n=typeof t.kind=="string"?t.kind:t.type;return JSON.stringify(Bo(`event ${JSON.stringify(n)} dropped: JSON cannot carry it (${Gn(e)})`))}}function mu(t){return t.overflowed=!1,`[${t.q.splice(0).map(AR).join(",")}]`}var kn=t=>!!t&&typeof t=="object"&&!Array.isArray(t),No=t=>{let e=kn(t)||t instanceof Error?t.code:void 0;return typeof e=="number"&&Number.isFinite(e)?e:0},Gn=t=>t instanceof Error?t.message:typeof t=="string"?t:"join failed";function sa(t,e){if(typeof t!="string")throw new TypeError(`genex bridge: ${e} must be a JSON string`);return JSON.parse(t)}function Wn(t,e){let n=sa(t,e);if(!kn(n))throw new TypeError(`genex bridge: ${e} must be a JSON object`);return n}ArrayBuffer.isView||(ArrayBuffer.isView=t=>t!==null&&typeof t=="object"&&t.buffer instanceof ArrayBuffer);typeof globalThis>"u"&&typeof window<"u"&&(window.globalThis=window);typeof FormData>"u"&&(globalThis.FormData=class{});yr();var Yn=class extends Error{constructor(n,r,s){super(r);m(this,"code");m(this,"headers");m(this,"status");m(this,"response");m(this,"data");this.name="ServerError",this.code=n,s&&(this.headers=s.headers,this.status=s.status,this.response=s.response,this.data=s.data)}};var oa=class t extends Error{constructor(n,r){super(n);m(this,"code");this.code=r,this.name="MatchMakeError",Object.setPrototypeOf(this,t.prototype)}};yr();wt();wt();wt();wt();wt();wt();wt();wt();var Ug=256,qf=5,Ls=class Ls{constructor(e,n={}){m(this,"instance");m(this,"mode");m(this,"historySize");m(this,"_desc");m(this,"_numFields");m(this,"_slots");m(this,"_slotLens");m(this,"_slotHead",0);m(this,"_slotCount",0);m(this,"_outBuffer");m(this,"_seq",0);m(this,"_encoder");this.instance=e,this.mode=n.mode??"reliable",this.historySize=this.mode==="unreliable"?Math.max(1,n.historySize??3):1,this._desc=Lf(e);let r=this._desc.metadata?.[bt];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(Ug);this._outBuffer=new Uint8Array((Ug+qf)*this.historySize)}this._encoder=new ha(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[I],n=this.instance[kt];for(let r=0;r<=this._numFields;r++)n[r]===void 0||n[r]===null||e.markDirty(r)}copyInto(e){let n=this.instance[kt],r=e[kt];for(let s=0;s<=this._numFields;s++)r[s]=n[s]}_produceDelta(){let e=this._encoder.encode();return this._encoder.discardChanges(),e}_pushAndEmitRing(e){this._seq++;let n=this._slots[this._slotHead];return e.length>n.byteLength&&(n=this._slots[this._slotHead]=Ls._grow(n,e.length,"unreliable ring slot")),n.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,n=qf;for(let i=0;i<this._slotCount;i++)n+=this._slotLens[i]+qf;let r=this._outBuffer;n>r.byteLength&&(r=this._outBuffer=Ls._grow(r,n,"unreliable output packet"));let s={offset:0};be.number(r,e,s);let o=(this._slotHead-this._slotCount+this.historySize)%this.historySize;for(let i=0;i<this._slotCount;i++){let a=(o+i)%this.historySize,c=this._slotLens[a];be.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,n,r){let s=Math.max(n,e.byteLength*2);return Ls._warned||(Ls._warned=!0,console.warn(`@colyseus/schema/input: InputEncoder buffer overflow in ${r}. Growing to ${s} bytes.`)),new Uint8Array(s)}};m(Ls,"_warned",!1);var $u=Ls;yr();Wf();Yu();var Fs,Bn,Go,Ra,ka,Pa,Aa,va,Ta,Wo,Ma,Ku,jg,Yo=class{constructor(e){ze(this,Ku);ze(this,Fs);ze(this,Bn);ze(this,Go);ze(this,Ra);ze(this,ka,!1);ze(this,Pa);ze(this,Aa,!1);ze(this,va,!1);ze(this,Ta);ze(this,Wo);ze(this,Ma);Ue(this,Fs,e)}get patchRate(){return ae(this,Wo)}applyReflection(e,n,r){let s=Dn.decode(e.subarray(0,r),n);Dn.makeEncodable(s.state.constructor),Ue(this,Pa,s.state.constructor),ae(this,Fs).clock===qo&&(ae(this,Fs).clock=new Wu)}applyOptions(e,n){let r=e[n.offset++];Ue(this,Aa,(r&Ts.RENDER_TIME)!==0),Ue(this,va,(r&Ts.RECKON_TIME)!==0),r&Ts.FIXED_TIMESTEP&&Ue(this,Ta,Re.number(e,n)),r&Ts.PATCH_RATE&&Ue(this,Wo,Re.number(e,n)),r&Ts.SUB_STEPS&&Ue(this,Ma,Re.number(e,n))}ackInput(e){return ae(this,Bn)?ae(this,Bn).ackInput(e):-1}reset(){ae(this,Bn)?.reset()}handle(e){if(ae(this,Bn))return e!==void 0&&ks(this,Ku,jg).call(this,e),ae(this,Bn);let n=e?.type??ae(this,Pa);if(!n)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 n,s=new $u(r,e);return Ue(this,Bn,new jo(ae(this,Fs),r,s,{stampRender:ae(this,Aa),stampReckon:ae(this,va),renderDelay:e?.renderDelay,allowRewind:e?.allowRewind,tickRate:ae(this,Ta),patchRate:ae(this,Wo),subSteps:ae(this,Ma)})),Ue(this,Go,e),Ue(this,Ra,s),ae(this,Bn)}};Fs=new WeakMap,Bn=new WeakMap,Go=new WeakMap,Ra=new WeakMap,ka=new WeakMap,Pa=new WeakMap,Aa=new WeakMap,va=new WeakMap,Ta=new WeakMap,Wo=new WeakMap,Ma=new WeakMap,Ku=new WeakSet,jg=function(e){if(ae(this,ka))return;let n=ae(this,Bn),r=[];e.type!==void 0&&e.type!==n.data?.constructor&&r.push("type"),e.mode!==void 0&&e.mode!==n.mode&&r.push("mode"),e.historySize!==void 0&&n.mode==="unreliable"&&e.historySize!==ae(this,Ra).historySize&&r.push("historySize"),e.renderDelay!==void 0&&e.renderDelay!==ae(this,Go)?.renderDelay&&r.push("renderDelay"),e.allowRewind!==void 0!=(ae(this,Go)?.allowRewind!==void 0)&&r.push("allowRewind"),r.length!==0&&(Ue(this,ka,!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 Kf;try{Kf=new TextDecoder}catch{}var J,hn,C=0;var tb=[],Xf=tb,Jf=0,Be={},ve,Xr,pn=0,nr=0,ht,_r,Vt=[],Ae,qg={useRecords:!1,mapsAsObjects:!0},Ca=class{},Qf=new Ca;Qf.name="MessagePack 0xC1";var Jr=!1,Gg=2;var Zr=class t{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,n){if(J)return ib(()=>(Ju(),this?this.unpack(e,n):t.prototype.unpack.call(qg,e,n)));!e.buffer&&e.constructor===ArrayBuffer&&(e=typeof Buffer<"u"?Buffer.from(e):new Uint8Array(e)),typeof n=="object"?(hn=n.end||e.length,C=n.start||0):(C=0,hn=n>-1?n:e.length),Jf=0,nr=0,Xr=null,Xf=tb,ht=null,J=e;try{Ae=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(r){throw J=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 t){if(Be=this,this.structures)return ve=this.structures,Xu(n);(!ve||ve.length>0)&&(ve=[])}else Be=qg,(!ve||ve.length>0)&&(ve=[]);return Xu(n)}unpackMultiple(e,n){let r,s=0;try{Jr=!0;let o=e.length,i=this?this.unpack(e,o):Qu.unpack(e,o);if(n){if(n(i,s,C)===!1)return;for(;C<o;)if(s=C,n(Xu(),s,C)===!1)return}else{for(r=[i];C<o;)s=C,r.push(Xu());return r}}catch(o){throw o.lastPosition=s,o.values=r,o}finally{Jr=!1,Ju()}}_mergeStructures(e,n){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 o=e[r];o&&(o.isShared=!0,r>=32&&(o.highByte=r-32>>5))}e.sharedLength=e.length;for(let r in n||[])if(r>=0){let s=e[r],o=n[r];o&&(s&&((e.restoreStructures||(e.restoreStructures=[]))[r]=s),e[r]=o)}return this.structures=e}decode(e,n){return this.unpack(e,n)}};function Xu(t){try{if(!Be.trusted&&!Jr){let n=ve.sharedLength||0;n<ve.length&&(ve.length=n)}let e;if(Be._readStruct&&J[C]<64&&J[C]>=32?(e=Be._readStruct(J,C,hn),J=null,!(t&&t.lazy)&&e&&(e=e.toJSON()),C=hn):e=et(),ht&&(C=ht.postBundlePosition,ht=null),Jr&&(ve.restoreStructures=null),C==hn)ve&&ve.restoreStructures&&Wg(),ve=null,J=null,_r&&(_r=null);else{if(C>hn)throw new Error("Unexpected end of MessagePack data");if(!Jr){let n;try{n=JSON.stringify(e,(r,s)=>typeof s=="bigint"?`${s}n`:s).slice(0,100)}catch(r){n="(JSON view not available "+r+")"}throw new Error("Data read, but end of buffer not reached "+n)}}return e}catch(e){throw ve&&ve.restoreStructures&&Wg(),Ju(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")||C>hn)&&(e.incomplete=!0),e}}function Wg(){for(let t in ve.restoreStructures)ve[t]=ve.restoreStructures[t];ve.restoreStructures=null}function et(){let t=J[C++];if(t<160)if(t<128){if(t<64)return t;{let e=ve[t&63]||Be.getStructures&&nb()[t&63];return e?(e.read||(e.read=ep(e,t&63)),e.read()):t}}else if(t<144)if(t-=128,Be.mapsAsObjects){let e={};for(let n=0;n<t;n++){let r=sb();r==="__proto__"&&(r="__proto_"),e[r]=et()}return e}else{let e=new Map;for(let n=0;n<t;n++)e.set(et(),et());return e}else{t-=144;let e=new Array(t);for(let n=0;n<t;n++)e[n]=et();return Be.freezeData?Object.freeze(e):e}else if(t<192){let e=t-160;if(nr>=C)return Xr.slice(C-pn,(C+=e)-pn);if(nr==0&&hn<140){let n=e<16?tp(e):rb(e);if(n!=null)return n}return Zf(e)}else{let e;switch(t){case 192:return null;case 193:return ht?(e=et(),e>0?ht[1].slice(ht.position1,ht.position1+=e):ht[0].slice(ht.position0,ht.position0-=e)):Qf;case 194:return!1;case 195:return!0;case 196:if(e=J[C++],e===void 0)throw new Error("Unexpected end of buffer");return Yf(e);case 197:return e=Ae.getUint16(C),C+=2,Yf(e);case 198:return e=Ae.getUint32(C),C+=4,Yf(e);case 199:return zs(J[C++]);case 200:return e=Ae.getUint16(C),C+=2,zs(e);case 201:return e=Ae.getUint32(C),C+=4,zs(e);case 202:if(e=Ae.getFloat32(C),Be.useFloat32>2){let n=Zu[(J[C]&127)<<1|J[C+1]>>7];return C+=4,(n*e+(e>0?.5:-.5)>>0)/n}return C+=4,e;case 203:return e=Ae.getFloat64(C),C+=8,e;case 204:return J[C++];case 205:return e=Ae.getUint16(C),C+=2,e;case 206:return e=Ae.getUint32(C),C+=4,e;case 207:return Be.int64AsType==="number"?(e=Ae.getUint32(C)*4294967296,e+=Ae.getUint32(C+4)):Be.int64AsType==="string"?e=Ae.getBigUint64(C).toString():Be.int64AsType==="auto"?(e=Ae.getBigUint64(C),e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=Ae.getBigUint64(C),C+=8,e;case 208:return Ae.getInt8(C++);case 209:return e=Ae.getInt16(C),C+=2,e;case 210:return e=Ae.getInt32(C),C+=4,e;case 211:return Be.int64AsType==="number"?(e=Ae.getInt32(C)*4294967296,e+=Ae.getUint32(C+4)):Be.int64AsType==="string"?e=Ae.getBigInt64(C).toString():Be.int64AsType==="auto"?(e=Ae.getBigInt64(C),e>=BigInt(-2)<<BigInt(52)&&e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=Ae.getBigInt64(C),C+=8,e;case 212:if(e=J[C++],e==114)return Qg(J[C++]&63);{let n=Vt[e];if(n)return n.read?(C++,n.read(et())):n.noBuffer?(C++,n()):n(J.subarray(C,++C));throw new Error("Unknown extension "+e)}case 213:return e=J[C],e==114?(C++,Qg(J[C++]&63,J[C++])):zs(2);case 214:return zs(4);case 215:return zs(8);case 216:return zs(16);case 217:return e=J[C++],nr>=C?Xr.slice(C-pn,(C+=e)-pn):gP(e);case 218:return e=Ae.getUint16(C),C+=2,nr>=C?Xr.slice(C-pn,(C+=e)-pn):bP(e);case 219:return e=Ae.getUint32(C),C+=4,nr>=C?Xr.slice(C-pn,(C+=e)-pn):wP(e);case 220:return e=Ae.getUint16(C),C+=2,Kg(e);case 221:return e=Ae.getUint32(C),C+=4,Kg(e);case 222:return e=Ae.getUint16(C),C+=2,Xg(e);case 223:return e=Ae.getUint32(C),C+=4,Xg(e);default:if(t>=224)return t-256;if(t===void 0){let n=new Error("Unexpected end of MessagePack data");throw n.incomplete=!0,n}throw new Error("Unknown MessagePack token "+t)}}}var yP=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function ep(t,e){function n(){if(n.count++>Gg){let s;try{s=t.read=new Function("r","return function(){return "+(Be.freezeData?"Object.freeze":"")+"({"+t.map(o=>o==="__proto__"?"__proto_:r()":yP.test(o)?o+":r()":"["+JSON.stringify(o)+"]:r()").join(",")+"})}")(et)}catch{return Gg=1/0,n()}return t.read0=s,t.highByte===0&&(t.read=Yg(e,t.read)),s()}let r={};for(let s=0,o=t.length;s<o;s++){let i=t[s];i==="__proto__"&&(i="__proto_"),r[i]=et()}return Be.freezeData?Object.freeze(r):r}return n.count=0,t.read0=n,t.highByte===0?Yg(e,n):n}var Yg=(t,e)=>function(){let n=J[C++];if(n===0)return e();let r=t<32?-(t+(n<<5)):t+(n<<5),s=ve[r]||nb()[r];if(!s)throw new Error("Record id is not defined for "+r);return s.read||(s.read=ep(s,t)),s.read()};function nb(){let t=ib(()=>(J=null,Be.getStructures()));return ve=Be._mergeStructures(t,ve)}var Zf=Oa,gP=Oa,bP=Oa,wP=Oa;function Oa(t){let e;if(t<16&&(e=tp(t)))return e;if(t>64&&Kf)return Kf.decode(J.subarray(C,C+=t));let n=C+t,r=[];for(e="";C<n;){let s=J[C++];if((s&128)===0)r.push(s);else if((s&224)===192){let o=J[C++]&63,i=(s&31)<<6|o;i<128?r.push(65533):r.push(i)}else if((s&240)===224){let o=J[C++]&63,i=J[C++]&63,a=(s&31)<<12|o<<6|i;a<2048||a>=55296&&a<=57343?r.push(65533):r.push(a)}else if((s&248)===240){let o=J[C++]&63,i=J[C++]&63,a=J[C++]&63,c=(s&7)<<18|o<<12|i<<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+=pt.apply(String,r),r.length=0)}return r.length>0&&(e+=pt.apply(String,r)),e}function Kg(t){let e=new Array(t);for(let n=0;n<t;n++)e[n]=et();return Be.freezeData?Object.freeze(e):e}function Xg(t){if(Be.mapsAsObjects){let e={};for(let n=0;n<t;n++){let r=sb();r==="__proto__"&&(r="__proto_"),e[r]=et()}return e}else{let e=new Map;for(let n=0;n<t;n++)e.set(et(),et());return e}}var pt=String.fromCharCode;function rb(t){let e=C,n=new Array(t);for(let r=0;r<t;r++){let s=J[C++];if((s&128)>0){C=e;return}n[r]=s}return pt.apply(String,n)}function tp(t){if(t<4)if(t<2){if(t===0)return"";{let e=J[C++];if((e&128)>1){C-=1;return}return pt(e)}}else{let e=J[C++],n=J[C++];if((e&128)>0||(n&128)>0){C-=2;return}if(t<3)return pt(e,n);let r=J[C++];if((r&128)>0){C-=3;return}return pt(e,n,r)}else{let e=J[C++],n=J[C++],r=J[C++],s=J[C++];if((e&128)>0||(n&128)>0||(r&128)>0||(s&128)>0){C-=4;return}if(t<6){if(t===4)return pt(e,n,r,s);{let o=J[C++];if((o&128)>0){C-=5;return}return pt(e,n,r,s,o)}}else if(t<8){let o=J[C++],i=J[C++];if((o&128)>0||(i&128)>0){C-=6;return}if(t<7)return pt(e,n,r,s,o,i);let a=J[C++];if((a&128)>0){C-=7;return}return pt(e,n,r,s,o,i,a)}else{let o=J[C++],i=J[C++],a=J[C++],c=J[C++];if((o&128)>0||(i&128)>0||(a&128)>0||(c&128)>0){C-=8;return}if(t<10){if(t===8)return pt(e,n,r,s,o,i,a,c);{let u=J[C++];if((u&128)>0){C-=9;return}return pt(e,n,r,s,o,i,a,c,u)}}else if(t<12){let u=J[C++],l=J[C++];if((u&128)>0||(l&128)>0){C-=10;return}if(t<11)return pt(e,n,r,s,o,i,a,c,u,l);let d=J[C++];if((d&128)>0){C-=11;return}return pt(e,n,r,s,o,i,a,c,u,l,d)}else{let u=J[C++],l=J[C++],d=J[C++],f=J[C++];if((u&128)>0||(l&128)>0||(d&128)>0||(f&128)>0){C-=12;return}if(t<14){if(t===12)return pt(e,n,r,s,o,i,a,c,u,l,d,f);{let h=J[C++];if((h&128)>0){C-=13;return}return pt(e,n,r,s,o,i,a,c,u,l,d,f,h)}}else{let h=J[C++],p=J[C++];if((h&128)>0||(p&128)>0){C-=14;return}if(t<15)return pt(e,n,r,s,o,i,a,c,u,l,d,f,h,p);let g=J[C++];if((g&128)>0){C-=15;return}return pt(e,n,r,s,o,i,a,c,u,l,d,f,h,p,g)}}}}}function Jg(){let t=J[C++],e;if(t<192)e=t-160;else switch(t){case 217:e=J[C++];break;case 218:e=Ae.getUint16(C),C+=2;break;case 219:e=Ae.getUint32(C),C+=4;break;default:throw new Error("Expected string")}return Oa(e)}function Yf(t){return Be.copyBuffers?Uint8Array.prototype.slice.call(J,C,C+=t):J.subarray(C,C+=t)}function zs(t){let e=J[C++];if(Vt[e]){let n;return Vt[e](J.subarray(C,n=C+=t),r=>{C=r;try{return et()}finally{C=n}})}else throw new Error("Unknown extension type "+e)}var Zg=new Array(4096);function sb(){let t=J[C++];if(t>=160&&t<192){if(t=t-160,nr>=C)return Xr.slice(C-pn,(C+=t)-pn);if(!(nr==0&&hn<180))return Zf(t)}else return C--,ob(et());let e=(t<<5^(t>1?Ae.getUint16(C):t>0?J[C]:0))&4095,n=Zg[e],r=C,s=C+t-3,o,i=0;if(n&&n.bytes==t){for(;r<s;){if(o=Ae.getUint32(r),o!=n[i++]){r=1879048192;break}r+=4}for(s+=3;r<s;)if(o=J[r++],o!=n[i++]){r=1879048192;break}if(r===s)return C=r,n.string;s-=3,r=C}for(n=[],Zg[e]=n,n.bytes=t;r<s;)o=Ae.getUint32(r),n.push(o),r+=4;for(s+=3;r<s;)o=J[r++],n.push(o);let a=t<16?tp(t):rb(t);return a!=null?n.string=a:n.string=Zf(t)}function ob(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return t.toString();if(t==null)return t+"";if(Be.allowArraysInMapKeys&&Array.isArray(t)&&t.flat().every(e=>["string","number","boolean","bigint"].includes(typeof e)))return t.flat().toString();throw new Error(`Invalid property type for record: ${typeof t}`)}var Qg=(t,e)=>{let n=et().map(ob),r=t;e!==void 0&&(t=t<32?-((e<<5)+t):(e<<5)+t,n.highByte=e);let s=ve[t];return s&&(s.isShared||Jr)&&((ve.restoreStructures||(ve.restoreStructures=[]))[t]=s),ve[t]=n,n.read=ep(n,r),(n.read0||n.read)()};Vt[0]=()=>{};Vt[0].noBuffer=!0;Vt[66]=t=>{let e=t.byteLength%8||8,n=BigInt(t[0]&128?t[0]-256:t[0]);for(let r=1;r<e;r++)n<<=BigInt(8),n+=BigInt(t[r]);if(t.byteLength!==e){let r=new DataView(t.buffer,t.byteOffset,t.byteLength),s=(o,i)=>{let a=i-o;if(a<=40){let d=r.getBigUint64(o);for(let f=o+8;f<i;f+=8)d<<=BigInt(64),d|=r.getBigUint64(f);return d}let c=o+(a>>4<<3),u=s(o,c),l=s(c,i);return u<<BigInt((i-c)*8)|l};n=n<<BigInt((r.byteLength-e)*8)|s(e,r.byteLength)}return n};var eb={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError=="function"?AggregateError:null};Vt[101]=()=>{let t=et();if(!eb[t[0]]){let e=Error(t[1],{cause:t[2]});return e.name=t[0],e}return eb[t[0]](t[1],{cause:t[2]})};Vt[105]=t=>{if(Be.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=Ae.getUint32(C-4);_r||(_r=new Map);let n=J[C],r;n>=144&&n<160||n==220||n==221?r=[]:n>=128&&n<144||n==222||n==223?r=new Map:(n>=199&&n<=201||n>=212&&n<=216)&&J[C+1]===115?r=new Set:r={};let s={target:r};_r.set(e,s);let o=et();if(s.used)Object.assign(r,o);else return s.target=o;if(r instanceof Map)for(let[i,a]of o.entries())r.set(i,a);if(r instanceof Set)for(let i of Array.from(o))r.add(i);return r};Vt[112]=t=>{if(Be.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=Ae.getUint32(C-4),n=_r.get(e);return n.used=!0,n.target};Vt[115]=()=>new Set(et());var np=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(t=>t+"Array"),xP=typeof globalThis=="object"?globalThis:window;Vt[116]=t=>{let e=t[0],n=Uint8Array.prototype.slice.call(t,1).buffer,r=np[e];if(!r){if(e===16)return n;if(e===17)return new DataView(n);throw new Error("Could not find typed array for code "+e)}return new xP[r](n)};Vt[120]=()=>{let t=et();return new RegExp(t[0],t[1])};var SP=[];Vt[98]=t=>{let e=(t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3],n=C;return C+=e-t.length,ht=SP,ht=[Jg(),Jg()],ht.position0=0,ht.position1=0,ht.postBundlePosition=C,C=n,et()};Vt[255]=t=>t.length==4?new Date((t[0]*16777216+(t[1]<<16)+(t[2]<<8)+t[3])*1e3):t.length==8?new Date(((t[0]<<22)+(t[1]<<14)+(t[2]<<6)+(t[3]>>2))/1e6+((t[3]&3)*4294967296+t[4]*16777216+(t[5]<<16)+(t[6]<<8)+t[7])*1e3):t.length==12?new Date(((t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3])/1e6+((t[4]&128?-281474976710656:0)+t[6]*1099511627776+t[7]*4294967296+t[8]*16777216+(t[9]<<16)+(t[10]<<8)+t[11])*1e3):new Date("invalid");function ib(t){Be&&Be._onSaveState&&Be._onSaveState();let e=hn,n=C,r=Jf,s=pn,o=nr,i=Xr,a=Xf,c=_r,u=ht,l=new Uint8Array(J.slice(0,hn)),d=ve,f=ve.slice(0,ve.length),h=Be,p=Jr,g=t();return hn=e,C=n,Jf=r,pn=s,nr=o,Xr=i,Xf=a,_r=c,ht=u,J=l,Jr=p,ve=d,ve.splice(0,ve.length,...f),Be=h,Ae=new DataView(J.buffer,J.byteOffset,J.byteLength),g}function Ju(){J=null,_r=null,ve=null}var Zu=new Array(147);for(let t=0;t<256;t++)Zu[t]=+("1e"+Math.floor(45.15-t*.30103));var Qu=new Zr({useRecords:!1}),el=Qu.unpack,EP=Qu.unpackMultiple,_P=Qu.unpack,tl={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},RP=new Float32Array(1),bB=new Uint8Array(RP.buffer,0,4);Zr.SUPPORTS_STRUCT_HOOKS=!0;var rl;try{rl=new TextEncoder}catch{}var op,ip,Xo=typeof Buffer<"u",nl=Xo?function(t){return Buffer.allocUnsafeSlow(t)}:Uint8Array,lb=Xo?Buffer:Uint8Array,ab=Xo?4294967296:2144337920,L,Ia,Ve,D=0,At,Xe=null,kP=21760,PP=/[\u0080-\uFFFF]/,Ko=Symbol("record-id"),Qr=class extends Zr{constructor(e){super(e),this.offset=0;let n,r,s,o,i,a=lb.prototype.utf8Write?function(A,W){return L.utf8Write(A,W,L.byteLength-W)}:rl&&rl.encodeInto?function(A,W){return rl.encodeInto(A,L.subarray(W)).written}:!1,c=this;e||(e={});let u=e&&e.sequential,l=e.structures||e.saveStructures,d=e.maxSharedStructures;if(d==null&&(d=l?32:0),d>8160)throw new Error("Maximum maxSharedStructure is 8160");e.structuredClone&&e.moreTypes==null&&(this.moreTypes=!0);let f=e.maxOwnStructures;f==null&&(f=l?32:64),!this.structures&&e.useRecords!=!1&&(this.structures=[]);let h=d>32||f+d>64,p=d+64,g=d+f+64;if(g>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let x=[],b=0,S=0;this.pack=this.encode=function(A,W){if(L||(L=new nl(8192),Ve=L.dataView||(L.dataView=new DataView(L.buffer,0,8192)),D=0),At=L.length-10,At-D<2048?(L=new nl(L.length),Ve=L.dataView||(L.dataView=new DataView(L.buffer,0,L.length)),At=L.length-10,D=0):D=D+7&2147483640,r=D,W&Jo&&(D+=W&255),i=c.structuredClone?new Map:null,c.bundleStrings&&typeof A!="string"?(Xe=[],Xe.size=1/0):Xe=null,o=c.structures,o){o.uninitialized&&(o=c._mergeStructures(c.getStructures()));let $=o.sharedLength||0;if($>d)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+o.sharedLength);if(!o.transitions){o.transitions=Object.create(null);for(let j=0;j<$;j++){let se=o[j];if(!se)continue;let oe,ne=o.transitions;for(let ye=0,ue=se.length;ye<ue;ye++){let yt=se[ye];oe=ne[yt],oe||(oe=ne[yt]=Object.create(null)),ne=oe}ne[Ko]=j+64}this.lastNamedStructuresLength=$}u||(o.nextId=$+64)}s&&(s=!1);let G;try{c._writeStruct&&A&&typeof A=="object"?A.constructor===Object?X(A):A.constructor!==Map&&!Array.isArray(A)&&!ip.some(j=>A instanceof j)?X(A.toJSON?A.toJSON():A):R(A):R(A);let $=Xe;if(Xe&&ub(r,R,0),i&&i.idsToInsert){let j=i.idsToInsert.sort((ye,ue)=>ye.offset>ue.offset?1:-1),se=j.length,oe=-1;for(;$&&se>0;){let ye=j[--se].offset+r;ye<$.stringsPosition+r&&oe===-1&&(oe=0),ye>$.position+r?oe>=0&&(oe+=6):(oe>=0&&(Ve.setUint32($.position+r,Ve.getUint32($.position+r)+oe),oe=-1),$=$.previous,se++)}oe>=0&&$&&Ve.setUint32($.position+r,Ve.getUint32($.position+r)+oe),D+=j.length*6,D>At&&N(D),c.offset=D;let ne=AP(L.subarray(r,D),j);return i=null,ne}return c.offset=D,W&fb?(L.start=r,L.end=D,L):L.subarray(r,D)}catch($){throw G=$,$}finally{if(o&&(_(),s&&c.saveStructures)){let $=o.sharedLength||0,j=L.subarray(r,D),se=(c._prepareStructures||vP)(o,c);if(!G)return c.saveStructures(se,se.isCompatible)===!1?(o.uninitialized=!0,c.pack(A,W)):(c.lastNamedStructuresLength=$,L.length>1073741824&&(L=null),j)}L.length>1073741824&&(L=null),W&pb&&(D=r)}};let _=()=>{S<10&&S++;let A=o.sharedLength||0;if(o.length>A&&!u&&(o.length=A),b>1e4)o.transitions=null,S=0,b=0,x.length>0&&(x=[]);else if(x.length>0&&!u){for(let W=0,G=x.length;W<G;W++)x[W][Ko]=0;x=[]}},P=A=>{var W=A.length;W<16?L[D++]=144|W:W<65536?(L[D++]=220,L[D++]=W>>8,L[D++]=W&255):(L[D++]=221,Ve.setUint32(D,W),D+=4);for(let G=0;G<W;G++)R(A[G])},R=A=>{D>At&&(L=N(D));var W=typeof A,G;if(W==="string"){let $=A.length;if(Xe&&$>=4&&$<4096){if((Xe.size+=$)>kP){let ne,ye=(Xe[0]?Xe[0].length*3+Xe[1].length:0)+10;D+ye>At&&(L=N(D+ye));let ue;Xe.position?(ue=Xe,L[D]=200,D+=3,L[D++]=98,ne=D-r,D+=4,ub(r,R,0),Ve.setUint16(ne+r-3,D-r-ne)):(L[D++]=214,L[D++]=98,ne=D-r,D+=4),Xe=["",""],Xe.previous=ue,Xe.size=0,Xe.position=ne}let oe=PP.test(A);Xe[oe?0:1]+=A,L[D++]=193,R(oe?-$:$);return}let j;$<32?j=1:$<256?j=2:$<65536?j=3:j=5;let se=$*3;if(D+se>At&&(L=N(D+se)),$<64||!a){let oe,ne,ye,ue=D+j;for(oe=0;oe<$;oe++)ne=A.charCodeAt(oe),ne<128?L[ue++]=ne:ne<2048?(L[ue++]=ne>>6|192,L[ue++]=ne&63|128):(ne&64512)===55296&&((ye=A.charCodeAt(oe+1))&64512)===56320?(ne=65536+((ne&1023)<<10)+(ye&1023),oe++,L[ue++]=ne>>18|240,L[ue++]=ne>>12&63|128,L[ue++]=ne>>6&63|128,L[ue++]=ne&63|128):(L[ue++]=ne>>12|224,L[ue++]=ne>>6&63|128,L[ue++]=ne&63|128);G=ue-D-j}else G=a(A,D+j);G<32?L[D++]=160|G:G<256?(j<2&&L.copyWithin(D+2,D+1,D+1+G),L[D++]=217,L[D++]=G):G<65536?(j<3&&L.copyWithin(D+3,D+2,D+2+G),L[D++]=218,L[D++]=G>>8,L[D++]=G&255):(j<5&&L.copyWithin(D+5,D+3,D+3+G),L[D++]=219,Ve.setUint32(D,G),D+=4),D+=G}else if(W==="number")if(A>>>0===A)A<32||A<128&&this.useRecords===!1||A<64&&!this._writeStruct?L[D++]=A:A<256?(L[D++]=204,L[D++]=A):A<65536?(L[D++]=205,L[D++]=A>>8,L[D++]=A&255):(L[D++]=206,Ve.setUint32(D,A),D+=4);else if(A>>0===A)A>=-32?L[D++]=256+A:A>=-128?(L[D++]=208,L[D++]=A+256):A>=-32768?(L[D++]=209,Ve.setInt16(D,A),D+=2):(L[D++]=210,Ve.setInt32(D,A),D+=4);else{let $;if(($=this.useFloat32)>0&&A<4294967296&&A>=-2147483648){L[D++]=202,Ve.setFloat32(D,A);let j;if($<4||(j=A*Zu[(L[D]&127)<<1|L[D+1]>>7])>>0===j){D+=4;return}else D--}L[D++]=203,Ve.setFloat64(D,A),D+=8}else if(W==="object"||W==="function")if(!A)L[D++]=192;else{if(i){let j=i.get(A);if(j){if(!j.id){let se=i.idsToInsert||(i.idsToInsert=[]);j.id=se.push(j)}L[D++]=214,L[D++]=112,Ve.setUint32(D,j.id),D+=4;return}else i.set(A,{offset:D-r})}let $=A.constructor;if($===Object)z(A);else if($===Array)P(A);else if($===Map)if(this.mapAsEmptyObject)L[D++]=128;else{G=A.size,G<16?L[D++]=128|G:G<65536?(L[D++]=222,L[D++]=G>>8,L[D++]=G&255):(L[D++]=223,Ve.setUint32(D,G),D+=4);for(let[j,se]of A)R(j),R(se)}else{for(let j=0,se=op.length;j<se;j++){let oe=ip[j];if(A instanceof oe){let ne=op[j];if(ne.write){ne.type&&(L[D++]=212,L[D++]=ne.type,L[D++]=0);let Hn=ne.write.call(this,A);Hn===A?Array.isArray(A)?P(A):z(A):R(Hn);return}let ye=L,ue=Ve,yt=D;L=null;let Gt;try{Gt=ne.pack.call(this,A,Hn=>(L=ye,ye=null,D+=Hn,D>At&&N(D),{target:L,targetView:Ve,position:D-Hn}),R)}finally{ye&&(L=ye,Ve=ue,D=yt,At=L.length-10)}Gt&&(Gt.length+D>At&&N(Gt.length+D),D=cb(Gt,L,D,ne.type));return}}if(Array.isArray(A))P(A);else{if(A.toJSON){let j=A.toJSON();if(j!==A)return R(j)}if(W==="function")return R(this.writeFunction&&this.writeFunction(A));z(A)}}}else if(W==="boolean")L[D++]=A?195:194;else if(W==="bigint"){if(A<9223372036854776e3&&A>=-9223372036854776e3)L[D++]=211,Ve.setBigInt64(D,A);else if(A<18446744073709552e3&&A>0)L[D++]=207,Ve.setBigUint64(D,A);else if(this.largeBigIntToFloat)L[D++]=203,Ve.setFloat64(D,Number(A));else{if(this.largeBigIntToString)return R(A.toString());if(this.useBigIntExtension||this.moreTypes){let $=A<0?BigInt(-1):BigInt(0),j;if(A>>BigInt(65536)===$){let se=BigInt(18446744073709552e3)-BigInt(1),oe=[];for(;oe.push(A&se),A>>BigInt(63)!==$;)A>>=BigInt(64);j=new Uint8Array(new BigUint64Array(oe).buffer),j.reverse()}else{let se=A<0,oe=(se?~A:A).toString(16);if(oe.length%2?oe="0"+oe:parseInt(oe.charAt(0),16)>=8&&(oe="00"+oe),Xo)j=Buffer.from(oe,"hex");else{j=new Uint8Array(oe.length/2);for(let ne=0;ne<j.length;ne++)j[ne]=parseInt(oe.slice(ne*2,ne*2+2),16)}if(se)for(let ne=0;ne<j.length;ne++)j[ne]=~j[ne]}j.length+D>At&&N(j.length+D),D=cb(j,L,D,66);return}else throw new RangeError(A+" 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")}D+=8}else if(W==="undefined")this.encodeUndefinedAsNil?L[D++]=192:(L[D++]=212,L[D++]=0,L[D++]=0);else throw new Error("Unknown type: "+W)},v=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?A=>{let W;if(this.skipValues){W=[];for(let j in A)(typeof A.hasOwnProperty!="function"||A.hasOwnProperty(j))&&!this.skipValues.includes(A[j])&&W.push(j)}else W=Object.keys(A);let G=W.length;G<16?L[D++]=128|G:G<65536?(L[D++]=222,L[D++]=G>>8,L[D++]=G&255):(L[D++]=223,Ve.setUint32(D,G),D+=4);let $;if(this.coercibleKeyAsNumber)for(let j=0;j<G;j++){$=W[j];let se=Number($);R(isNaN(se)?$:se),R(A[$])}else for(let j=0;j<G;j++)R($=W[j]),R(A[$])}:A=>{L[D++]=222;let W=D-r;D+=2;let G=0;for(let $ in A)(typeof A.hasOwnProperty!="function"||A.hasOwnProperty($))&&(R($),R(A[$]),G++);if(G>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');L[W+++r]=G>>8,L[W+r]=G&255},M=this.useRecords===!1?v:e.progressiveRecords&&!h?A=>{let W,G=o.transitions||(o.transitions=Object.create(null)),$=D++-r,j;for(let se in A)if(typeof A.hasOwnProperty!="function"||A.hasOwnProperty(se)){if(W=G[se],W)G=W;else{let oe=Object.keys(A),ne=G;G=o.transitions;let ye=0;for(let ue=0,yt=oe.length;ue<yt;ue++){let Gt=oe[ue];W=G[Gt],W||(W=G[Gt]=Object.create(null),ye++),G=W}$+r+1==D?(D--,Y(G,oe,ye)):he(G,oe,$,ye),j=!0,G=ne[se]}R(A[se])}if(!j){let se=G[Ko];se?L[$+r]=se:he(G,Object.keys(A),$,0)}}:A=>{let W,G=o.transitions||(o.transitions=Object.create(null)),$=0;for(let se in A)(typeof A.hasOwnProperty!="function"||A.hasOwnProperty(se))&&(W=G[se],W||(W=G[se]=Object.create(null),$++),G=W);let j=G[Ko];j?j>=96&&h?(L[D++]=((j-=96)&31)+96,L[D++]=j>>5):L[D++]=j:Y(G,G.__keys__||Object.keys(A),$);for(let se in A)(typeof A.hasOwnProperty!="function"||A.hasOwnProperty(se))&&R(A[se])},O=typeof this.useRecords=="function"&&this.useRecords,z=O?A=>{O(A)?M(A):v(A)}:M,X=A=>{let W=c._writeStruct(A,L,r,D,o,N,(G,$,j)=>{if(j)return s=!0;D=$;let se=L;return R(G),_(),se!==L?{position:D,targetView:Ve,target:L}:D});if(W===0)return z(A);D=W},N=A=>{let W;if(A>16777216){if(A-r>ab)throw new Error("Packed buffer would be larger than maximum buffer size");W=Math.min(ab,Math.round(Math.max((A-r)*(A>67108864?1.25:2),4194304)/4096)*4096)}else W=(Math.max(A-r<<2,L.length-1)>>12)+1<<12;let G=new nl(W);return Ve=G.dataView||(G.dataView=new DataView(G.buffer,0,W)),A=Math.min(A,L.length),L.copy?L.copy(G,0,r,A):G.set(L.slice(r,A)),D-=r,r=0,At=G.length-10,L=G},Y=(A,W,G)=>{let $=o.nextId;$||($=64),$<p&&this.shouldShareStructure&&!this.shouldShareStructure(W)?($=o.nextOwnId,$<g||($=p),o.nextOwnId=$+1):($>=g&&($=p),o.nextId=$+1);let j=W.highByte=$>=96&&h?$-96>>5:-1;A[Ko]=$,A.__keys__=W,o[$-64]=W,$<p?(W.isShared=!0,o.sharedLength=$-63,s=!0,j>=0?(L[D++]=($&31)+96,L[D++]=j):L[D++]=$):(j>=0?(L[D++]=213,L[D++]=114,L[D++]=($&31)+96,L[D++]=j):(L[D++]=212,L[D++]=114,L[D++]=$),G&&(b+=S*G),x.length>=f&&(x.shift()[Ko]=0),x.push(A),R(W))},he=(A,W,G,$)=>{let j=L,se=D,oe=At,ne=r;L=Ia,D=0,r=0,L||(Ia=L=new nl(8192)),At=L.length-10,Y(A,W,$),Ia=L;let ye=D;if(L=j,D=se,At=oe,r=ne,ye>1){let ue=D+ye-1;ue>At&&N(ue);let yt=G+r;L.copyWithin(yt+ye,yt+1,D),L.set(Ia.slice(0,ye),yt),D=ue}else L[G+r]=Ia[0]}}useBuffer(e){L=e,L.dataView||(L.dataView=new DataView(L.buffer,L.byteOffset,L.byteLength)),Ve=L.dataView,D=0}set position(e){D=e}get position(){return D}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}};ip=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,Ca];op=[{pack(t,e,n){let r=t.getTime()/1e3;if((this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:s,targetView:o,position:i}=e(6);s[i++]=214,s[i++]=255,o.setUint32(i,r)}else if(r>0&&r<4294967296){let{target:s,targetView:o,position:i}=e(10);s[i++]=215,s[i++]=255,o.setUint32(i,t.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),o.setUint32(i+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return e(0),n(this.onInvalidDate());let{target:s,targetView:o,position:i}=e(3);s[i++]=212,s[i++]=255,s[i++]=255}else{let{target:s,targetView:o,position:i}=e(15);s[i++]=199,s[i++]=12,s[i++]=255,o.setUint32(i,t.getMilliseconds()*1e6),o.setBigInt64(i+4,BigInt(Math.floor(r)))}}},{pack(t,e,n){if(this.setAsEmptyObject)return e(0),n({});let r=Array.from(t),{target:s,position:o}=e(this.moreTypes?3:0);this.moreTypes&&(s[o++]=212,s[o++]=115,s[o++]=0),n(r)}},{pack(t,e,n){let{target:r,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(r[s++]=212,r[s++]=101,r[s++]=0),n([t.name,t.message,t.cause])}},{pack(t,e,n){let{target:r,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(r[s++]=212,r[s++]=120,r[s++]=0),n([t.source,t.flags])}},{pack(t,e){this.moreTypes?rp(t,16,e):sp(Xo?Buffer.from(t):new Uint8Array(t),e)}},{pack(t,e){let n=t.constructor;n!==lb&&this.moreTypes?rp(t,np.indexOf(n.name),e):sp(t,e)}},{pack(t,e){this.moreTypes?rp(t,17,e):sp(Xo?Buffer.from(t):new Uint8Array(t),e)}},{pack(t,e){let{target:n,position:r}=e(1);n[r]=193}}];function rp(t,e,n,r){let s=t.byteLength;if(s+1<256){var{target:o,position:i}=n(4+s);o[i++]=199,o[i++]=s+1}else if(s+1<65536){var{target:o,position:i}=n(5+s);o[i++]=200,o[i++]=s+1>>8,o[i++]=s+1&255}else{var{target:o,position:i,targetView:a}=n(7+s);o[i++]=201,a.setUint32(i,s+1),i+=4}o[i++]=116,o[i++]=e,t.buffer||(t=new Uint8Array(t)),o.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i)}function sp(t,e){let n=t.byteLength;var r,s;if(n<256){var{target:r,position:s}=e(n+2);r[s++]=196,r[s++]=n}else if(n<65536){var{target:r,position:s}=e(n+3);r[s++]=197,r[s++]=n>>8,r[s++]=n&255}else{var{target:r,position:s,targetView:o}=e(n+5);r[s++]=198,o.setUint32(s,n),s+=4}r.set(t,s)}function cb(t,e,n,r){let s=t.length;switch(s){case 1:e[n++]=212;break;case 2:e[n++]=213;break;case 4:e[n++]=214;break;case 8:e[n++]=215;break;case 16:e[n++]=216;break;default:s<256?(e[n++]=199,e[n++]=s):s<65536?(e[n++]=200,e[n++]=s>>8,e[n++]=s&255):(e[n++]=201,e[n++]=s>>24,e[n++]=s>>16&255,e[n++]=s>>8&255,e[n++]=s&255)}return e[n++]=r,e.set(t,n),n+=s,n}function AP(t,e){let n,r=e.length*6,s=t.length-r;for(;n=e.pop();){let o=n.offset,i=n.id;t.copyWithin(o+r,o,s),r-=6;let a=o+r;t[a++]=214,t[a++]=105,t[a++]=i>>24,t[a++]=i>>16&255,t[a++]=i>>8&255,t[a++]=i&255,s=o}return t}function ub(t,e,n){if(Xe.length>0){Ve.setUint32(Xe.position+t,D+n-Xe.position-t),Xe.stringsPosition=D-t;let r=Xe;Xe=null,e(r[0]),e(r[1])}}function vP(t,e){return t.isCompatible=n=>{let r=!n||(e.lastNamedStructuresLength||0)===n.length;return r||e._mergeStructures(n),r},t}Qr.SUPPORTS_STRUCT_HOOKS=!0;var db=new Qr({useRecords:!1}),TP=db.pack,MP=db.pack;var{NEVER:CP,ALWAYS:OP,DECIMAL_ROUND:IP,DECIMAL_FIT:DP}=tl,fb=512,pb=1024,Jo=2048;wt();yr();var BP=9,sl=class{constructor(){m(this,"pending",new Uint8Array(0))}push(e){if(!e||e.byteLength===0)return[];let n=this.pending.byteLength===0?e:NP(this.pending,e),r=[],s=0;for(;s<n.byteLength;){let o={offset:s},i;try{i=Re.number(n,o)}catch(c){if(n.byteLength-s<=BP)break;throw c}let a=o.offset+i;if(a>n.byteLength)break;r.push(n.subarray(o.offset,a)),s=a}return this.pending=s<n.byteLength?n.slice(s):new Uint8Array(0),r}};function NP(t,e){let n=new Uint8Array(t.byteLength+e.byteLength);return n.set(t,0),n.set(e,t.byteLength),n}var Da=class{constructor(e){m(this,"wt");m(this,"url");m(this,"isOpen",!1);m(this,"events");m(this,"reader");m(this,"writer");m(this,"unreliableReader");m(this,"unreliableWriter");m(this,"lengthPrefixBuffer",new Uint8Array(9));m(this,"reliableReassembler",new sl);m(this,"unreliableReassembler",new sl);this.events=e}connect(e,n={}){this.url=e;let r=n.fingerprint&&{serverCertificateHashes:[{algorithm:"sha-256",value:new Uint8Array(n.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 o=this.wt.datagrams;this.unreliableWriter=(o.createWritable?o.createWritable():o.writable).getWriter(),this.wt.incomingBidirectionalStreams.getReader().read().then(a=>{this.reader=a.value.readable.getReader(),this.writer=a.value.writable.getWriter(),this.sendSeatReservation(n.roomId,n.sessionId,n.reconnectionToken,n.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 n=e instanceof Uint8Array?e:new Uint8Array(e),r=be.number(this.lengthPrefixBuffer,n.length,{offset:0}),s=new Uint8Array(r+n.length);return s.set(this.lengthPrefixBuffer.subarray(0,r),0),s.set(n,r),s}close(e,n){this.isOpen=!1;try{let r=this.wt?.close({closeCode:e,reason:n});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,n,r){for(;this.isOpen;){let s;try{s=await e.read()}catch(o){await this.onChannelFailure(r,o);return}if(s.done||!s.value)return;for(let o of n.push(s.value))this.events.onmessage({data:o})}}async onChannelFailure(e,n){await new Promise(r=>setTimeout(r,0)),this.isOpen&&(console.error(`H3Transport: stopped reading the ${e} channel while the session was open`,n),this.close(ft.ABNORMAL_CLOSURE,`h3 ${e} channel failed`))}sendSeatReservation(e,n,r,s){let o={offset:0},i=[];be.string(i,e,o),be.string(i,n,o),r&&be.string(i,r,o),s&&be.boolean(i,1,o),this.writer.write(new Uint8Array(i).buffer)}_close(){this.isOpen=!1}};var gb=YE(mb(),1);yr();var ap=globalThis.WebSocket||gb.default,yb=!1,ol=class{constructor(e){m(this,"ws");m(this,"protocols");m(this,"events");this.events=e}send(e){this.ws.send(e)}sendUnreliable(e){yb||(yb=!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,n){try{this.ws=new ap(e,{headers:n,protocols:this.protocols})}catch{this.ws=new ap(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,n){e===ft.MAY_TRY_RECONNECT&&this.events.onclose&&(this.ws.onclose=null,this.events.onclose({code:e,reason:n})),this.ws.close(e,n)}get isOpen(){return this.ws.readyState===ap.OPEN}};yr();var Ba=[],cp=typeof addEventListener=="function"&&typeof removeEventListener=="function";cp&&addEventListener("offline",()=>{console.warn(`@colyseus/sdk: \u{1F6D1} Network offline. Closing ${Ba.length} connection(s)`),Ba.forEach(t=>t())},!1);var Na,Zo=class{constructor(e){m(this,"transport");m(this,"events",{});m(this,"url");m(this,"options");ze(this,Na,cp?()=>this.close(ft.MAY_TRY_RECONNECT):null);e==="h3"?this.transport=new Da(this.events):this.transport=new ol(this.events)}connect(e,n){if(cp){let r=this.events.onopen;this.events.onopen=o=>{Ba.push(ae(this,Na)),r?.(o)};let s=this.events.onclose;this.events.onclose=o=>{Ba.splice(Ba.indexOf(ae(this,Na)),1),s?.(o)}}this.url=e,this.options=n,this.transport.connect(e,n)}send(e){this.transport.send(e)}sendUnreliable(e){this.transport.sendUnreliable(e)}reconnect(e){if(this.transport instanceof Da){this.transport.connect(this.url,{...this.options,...e});return}let n=new URL(this.url);for(let r in e)n.searchParams.set(r,e[r]);this.transport.connect(n.toString(),this.options)}close(e,n){this.transport.close(e,n)}get isOpen(){return this.transport.isOpen}};Na=new WeakMap;var bb={};function up(t,e){bb[t]=e}function lp(t){let e=bb[t];if(!e)throw new Error("missing serializer: "+t);return e}var il=()=>({emit(t,...e){let n=this.events[t]||[];for(let r=0,s=n.length;r<s;r++)n[r](...e)},events:{},on(t,e){return this.events[t]?.push(e)||(this.events[t]=[e]),()=>{this.events[t]=this.events[t]?.filter(n=>e!==n)}}});var wb=new WeakMap,dp=class{constructor(){m(this,"handlers",[])}register(e,n=!1){return this.handlers.push(e),this}invoke(...e){let n=this.handlers;for(let r=0,s=n.length;r<s;r++)n[r].apply(this,e)}invokeAsync(...e){return Promise.all(this.handlers.map(n=>n.apply(this,e)))}remove(e){let n=this.handlers.indexOf(e);n===-1&&(n=this.handlers.findIndex(r=>wb.get(r)===e)),n!==-1&&(this.handlers=this.handlers.filter((r,s)=>s!==n))}clear(){this.handlers=[]}};function Us(){let t=new dp;function e(n){return t.register(n,this===null)}return e.once=n=>{let r=function(...s){t.remove(r),n.apply(this,s)};wb.set(r,n),t.register(r)},e.remove=n=>t.remove(n),e.invoke=(...n)=>t.invoke(...n),e.invokeAsync=(...n)=>t.invokeAsync(...n),e.clear=()=>t.clear(),e}wt();function La(t){try{return Ou(t.serializer.decoder)}catch{return}}var Qo=class{constructor(){m(this,"state");m(this,"decoder")}setState(e,n){this.decoder.root.refs.size>1&&typeof this.decoder.decodeResync=="function"?this.decoder.decodeResync(e,n):this.decoder.decode(e,n)}getState(){return this.state}patch(e,n){return this.decoder.decode(e,n)}teardown(){this.decoder.root.clearRefs()}handshake(e,n){this.state?(Dn.decode(e,n),this.decoder=new In(this.state)):(this.decoder=Dn.decode(e,n),this.state=this.decoder.state)}};Yu();function xb(){return{enabled:!0,retryCount:0,maxRetries:15,delay:100,minDelay:100,maxDelay:5e3,minUptime:5e3,backoff:LP,maxEnqueuedMessages:10,enqueuedMessages:[],isReconnecting:!1}}var LP=(t,e)=>Math.floor(Math.pow(2,t)*e);function al(t,e){t.reconnection.enqueuedMessages.push({data:e}),t.reconnection.enqueuedMessages.length>t.reconnection.maxEnqueuedMessages&&t.reconnection.enqueuedMessages.shift()}function Sb(t,e){if(!e){let r=new Error("request rejected");return r.name="rejected",r.reason=t,r}let n=new Error(t?.message??"request failed");return t?.name&&(n.name=t.name),t?.code!==void 0&&(n.code=t.code),n}wa();var za,ei,ti,rr,sr,ni,or,Eb,_b,Rb,kb,cl=class cl{constructor(e,n){ze(this,or);m(this,"roomId");m(this,"sessionId");m(this,"reconnectionToken");m(this,"name");m(this,"connection");m(this,"onStateChange",Us());m(this,"onError",Us());m(this,"onLeave",Us());m(this,"onReconnect",Us());m(this,"onDrop",Us());m(this,"onJoin",Us());m(this,"serializerId");m(this,"serializer");m(this,"reconnection",xb());m(this,"joinedAtTime",0);m(this,"clock",qo);m(this,"onMessageHandlers",il());m(this,"packr");m(this,"sharedBuffer");ze(this,za,0);ze(this,ei);ze(this,ti,0);ze(this,rr,new Map);ze(this,sr);ze(this,ni,0);if(this.name=e,this.packr=new Qr,this.sharedBuffer=new Uint8Array(8192),n){let r=new(lp("schema"));this.serializer=r;let s=new n;r.state=s,r.decoder=new In(s)}this.onLeave(()=>{this.removeAllListeners(),this.destroy()})}connect(e,n,r){this.connection=new Zo(n.protocol),this.connection.events.onmessage=this.onMessageCallback.bind(this),this.connection.events.onclose=o=>{if(ks(this,or,Rb).call(this,"connection closed before a response was received."),this.joinedAtTime===0){console.warn?.(`Room connection was closed unexpectedly (${o.code}): ${o.reason}`),this.onError.invoke(o.code,o.reason);return}o.code===ft.NO_STATUS_RECEIVED||o.code===ft.ABNORMAL_CLOSURE||o.code===ft.GOING_AWAY||o.code===ft.MAY_TRY_RECONNECT?(this.onDrop.invoke(o.code,o.reason),this.handleReconnection(o.code,o.reason)):this.onLeave.invoke(o.code,o.reason)},this.connection.events.onerror=o=>{this.onError.invoke(o.code,o.reason)};let s=this.serializer?.getState()!==void 0;if(n.protocol==="h3"){let o=new URL(e);this.connection.connect(o.origin,{...n,skipHandshake:s})}else this.connection.connect(`${e}${s?"&skipHandshake=1":""}`,r)}leave(e=!0){return new Promise(n=>{this.onLeave(r=>n(r)),this.connection?e?(this.sharedBuffer[0]=We.LEAVE_ROOM,this.connection.send(this.sharedBuffer.subarray(0,1))):this.connection.close():this.onLeave.invoke(ft.CONSENTED)})}onMessage(e,n){return this.onMessageHandlers.on(this.getMessageHandlerKey(e),n)}ping(e){this.connection?.isOpen&&(Ue(this,za,Pt()),Ue(this,ei,e),this.sharedBuffer[0]=We.PING,this.connection.send(this.sharedBuffer.subarray(0,1)))}send(e,n,r){if(r!==void 0){this.request(e,n).then(a=>r(a,void 0),a=>r(void 0,a));return}let s={offset:1};this.sharedBuffer[0]=We.ROOM_DATA,typeof e=="string"?be.string(this.sharedBuffer,e,s):be.number(this.sharedBuffer,e,s);let o=s.offset,i;n!==void 0?(i=this.packr.pack(n,Jo|o),i.set(this.sharedBuffer.subarray(0,o),0)):i=this.sharedBuffer.subarray(0,o),this.connection.isOpen?this.connection.send(i):al(this,new Uint8Array(i))}request(e,n,r){if(!this.connection.isOpen)return Promise.reject(new Error(`cannot send request "${e}": connection is not open.`));let s=r?.timeout??cl.defaultRequestTimeout;return new Promise((o,i)=>{let a,c=this.sendRequest(e,n,{mode:r?.mode},(u,l,d)=>{clearTimeout(a),u?o(l):i(Sb(l,d))},u=>{clearTimeout(a),i(new Error(u))});a=setTimeout(()=>{this.cancelRequest(c),i(new Error(`request "${e}" timed out after ${s}ms.`))},s)})}sendRequest(e,n,r,s,o){let i=ks(this,or,Eb).call(this),a=ks(this,or,_b).call(this,i,e,n);if(r.mode==="unreliable"){if(!this.connection.isOpen)return-1;this.connection.sendUnreliable(a)}else this.connection.isOpen?this.connection.send(a):al(this,new Uint8Array(a));return ae(this,rr).set(i,{onReply:s,onClose:o}),i}cancelRequest(e){ae(this,rr).delete(e)}sendUnreliable(e,n){if(!this.connection.isOpen)return;let r={offset:1};this.sharedBuffer[0]=We.ROOM_DATA,typeof e=="string"?be.string(this.sharedBuffer,e,r):be.number(this.sharedBuffer,e,r);let s=r.offset,o;n!==void 0?(o=this.packr.pack(n,Jo|s),o.set(this.sharedBuffer.subarray(0,s),0)):o=this.sharedBuffer.subarray(0,s),this.connection.sendUnreliable(o)}sendBytes(e,n){let r={offset:1};this.sharedBuffer[0]=We.ROOM_DATA_BYTES,typeof e=="string"?be.string(this.sharedBuffer,e,r):be.number(this.sharedBuffer,e,r);let s=r.offset;if(s+n.byteLength>this.sharedBuffer.byteLength){let o=new Uint8Array(s+n.byteLength);o.set(this.sharedBuffer.subarray(0,s)),this.sharedBuffer=o}this.sharedBuffer.set(n,s),this.connection.isOpen?this.connection.send(this.sharedBuffer.subarray(0,s+n.byteLength)):al(this,this.sharedBuffer.subarray(0,s+n.byteLength))}input(e){return(ae(this,sr)??Ue(this,sr,new Yo(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 Qo&&(this.serializer.decoder.root.callbacks={})}onMessageCallback(e){ks(this,or,kb).call(this,new Uint8Array(e.data))}dispatchMessage(e,n){let r=this.getMessageHandlerKey(e);this.onMessageHandlers.events[r]?this.onMessageHandlers.emit(r,n):this.onMessageHandlers.events["*"]?this.onMessageHandlers.emit("*",e,n):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,n){if(!this.reconnection.enabled){this.onLeave.invoke(e,n);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(ft.ABNORMAL_CLOSURE,"Room uptime too short for reconnection.");return}this.reconnection.isReconnecting||(this.reconnection.retryCount=0,this.reconnection.isReconnecting=!0,ae(this,sr)?.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(ft.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)}};za=new WeakMap,ei=new WeakMap,ti=new WeakMap,rr=new WeakMap,sr=new WeakMap,ni=new WeakMap,or=new WeakSet,Eb=function(){let e=ae(this,ti);return Ue(this,ti,ae(this,ti)+1>>>0),e},_b=function(e,n,r){let s={offset:1};this.sharedBuffer[0]=We.ROOM_REQUEST,be.number(this.sharedBuffer,e,s),typeof n=="string"?be.string(this.sharedBuffer,n,s):be.number(this.sharedBuffer,n,s);let o=s.offset;if(r!==void 0){let i=this.packr.pack(r,Jo|o);return i.set(this.sharedBuffer.subarray(0,o),0),i}return this.sharedBuffer.subarray(0,o)},Rb=function(e){if(ae(this,rr).size!==0){for(let n of ae(this,rr).values())n.onClose?.(e);ae(this,rr).clear()}},kb=function(e){var o;let n={offset:1},r=e[0],s=r&Sf;if(r&Lo.TIMED){let i=Re.uint32(e,n),a=Re.uint32(e,n),c=ae(this,sr)?ae(this,sr).ackInput(a):-1;this.clock.sample(i,c)}if(s===We.JOIN_ROOM){let i=Re.utf8Read(e,n,e[n.offset++]);if(this.serializerId=Re.utf8Read(e,n,e[n.offset++]),!this.serializer){let u=lp(this.serializerId);this.serializer=new u}let a=Re.number(e,n);if(a>0&&this.serializer.handshake){let u=n.offset+a;this.serializer.handshake(e.subarray(0,u),n),n.offset=u}for(;n.offset<e.byteLength;){let u=e[n.offset++],l=Re.number(e,n),d=n.offset+l;u===gu.INPUT_REFLECTION?(ae(this,sr)??Ue(this,sr,new Yo(this))).applyReflection(e,n,d):u===gu.INPUT_OPTIONS&&(ae(this,sr)??Ue(this,sr,new Yo(this))).applyOptions(e,n),n.offset=d}let c=ae(this,sr)?.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}:${i}`,this.sharedBuffer[0]=We.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===We.ERROR){let i=Re.number(e,n),a=Re.string(e,n);this.onError.invoke(i,a)}else if(s===We.LEAVE_ROOM)this.leave();else if(s===We.ROOM_STATE)Ue(this,ni,0),this.serializer.setState(e,n),this.onStateChange.invoke(this.serializer.getState());else if(s===We.ROOM_STATE_PATCH){if(r&Lo.UNRELIABLE){let i=Re.uint16(e,n);if(i-ae(this,ni)<<16>>16<=0)return;Ue(this,ni,i)}this.serializer.patch(e,n),this.onStateChange.invoke(this.serializer.getState())}else if(s===We.ROOM_DATA){let i=Re.stringCheck(e,n)?Re.string(e,n):Re.number(e,n),a=e.byteLength>n.offset?el(e,{start:n.offset}):void 0;this.dispatchMessage(i,a)}else if(s===We.ROOM_DATA_BYTES){let i=Re.stringCheck(e,n)?Re.string(e,n):Re.number(e,n);this.dispatchMessage(i,e.subarray(n.offset))}else if(s===We.ROOM_RESPONSE){let i=Re.number(e,n),a=e[n.offset++],c=e.byteLength>n.offset?el(e,{start:n.offset}):void 0,u=ae(this,rr).get(i);u!==void 0&&(ae(this,rr).delete(i),u.onReply(a===yu.OK,c,a===yu.ERROR))}else s===We.PING&&((o=ae(this,ei))==null||o.call(this,Math.round(Pt()-ae(this,za))),Ue(this,ei,void 0))},m(cl,"defaultRequestTimeout",1e4);var Fa=cl;function Pb(t,e){return new Promise((n,r)=>{let s=new XMLHttpRequest,o=e?.method||"GET";s.open(o,t.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 i=new Headers,a=s.getAllResponseHeaders().trim();if(a)for(let u of a.split(/[\r\n]+/)){let l=u.indexOf(": ");l>0&&i.append(u.substring(0,l),u.substring(l+2))}let c=s.response??s.responseText;n(new fp(c,{status:s.status,statusText:s.statusText,headers:i}))},s.onerror=()=>r(new TypeError("Network request failed")),s.ontimeout=()=>r(new TypeError("Network request timed out")),s.send(e?.body??null)})}var fp=class{constructor(e,n){m(this,"status");m(this,"statusText");m(this,"headers");m(this,"ok");m(this,"body");this.body=e,this.status=n.status,this.statusText=n.statusText,this.headers=n.headers,this.ok=n.status>=200&&n.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 FP(t){if(t===void 0)return!1;let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(t)?!0:t.buffer?!1:t.constructor&&t.constructor.name==="Object"||typeof t.toJSON=="function"}function zP(t,e){let{params:n,query:r}=e||{},[s,o]=t.split("?"),i=s;if(n)if(Array.isArray(n)){let u=i.split("/").filter(l=>l.startsWith(":"));for(let[l,d]of u.entries()){let f=n[l];i=i.replace(d,f)}}else for(let[u,l]of Object.entries(n))i=i.replace(`:${u}`,String(l));let a=new URLSearchParams(o);if(r)for(let[u,l]of Object.entries(r))l!=null&&a.set(u,String(l));let c=a.toString();return c=c.length>0?`?${c}`.replace(/\+/g,"%20"):"",`${i}${c}`}var ul=class{constructor(e,n,r){m(this,"authToken");m(this,"options");m(this,"sdk");m(this,"_fetchFn");m(this,"del",this.delete);this.sdk=e,this.options=n,this._fetchFn=r}get fetchFn(){return this._fetchFn||(this._fetchFn=typeof globalThis.fetch<"u"?globalThis.fetch.bind(globalThis):Pb),this._fetchFn}async request(e,n,r){return this.executeRequest(e,n,r)}get(e,n){return this.request("GET",e,n)}post(e,n){return this.request("POST",e,n)}delete(e,n){return this.request("DELETE",e,n)}patch(e,n){return this.request("PATCH",e,n)}put(e,n){return this.request("PUT",e,n)}async executeRequest(e,n,r){let s=this.options.body?{...this.options.body,...r?.body||{}}:r?.body,o=this.options.query?{...this.options.query,...r?.query||{}}:r?.query,i=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}`),FP(s)&&typeof s=="object"&&s!==null){a.has("content-type")||a.set("content-type","application/json");for(let[h,p]of Object.entries(s))p instanceof Date&&(s[h]=p.toISOString());s=JSON.stringify(s)}let c={credentials:r?.credentials||"include",...this.options,...r,query:o,params:i,headers:a,body:s,method:e},u=zP(this.sdk.getHttpEndpoint(n.toString()),c),l;try{l=await this.fetchFn(u,c)}catch(h){if(h.name==="AbortError")throw h;let p=new Yn(h.cause?.code||h.code,h.message);throw p.response=l,p.cause=h.cause,p}let d=l.headers.get("content-type"),f;if(d?.includes("json")?f=await l.json():d?.includes("text")?f=await l.text():f=await l.blob(),!l.ok)throw new Yn(l.status,f.message??f.error??l.statusText,{headers:l.headers,status:l.status,response:l,data:f});return{raw:l,data:f,headers:l.headers,status:l.status,statusText:l.statusText}}};var Vs;function hp(){if(!Vs)try{Vs=typeof cc<"u"&&cc.sys&&cc.sys.localStorage?cc.sys.localStorage:window.localStorage}catch{}return!Vs&&typeof globalThis.indexedDB<"u"&&(Vs=new pp),Vs||(Vs={cache:{},setItem:function(t,e){this.cache[t]=e},getItem:function(t){return this.cache[t]},removeItem:function(t){delete this.cache[t]}}),Vs}function Ab(t,e){hp().setItem(t,e)}function vb(t){hp().removeItem(t)}function Tb(t,e){let n=hp().getItem(t);typeof Promise>"u"||!(n instanceof Promise)?e(n):n.then(r=>e(r))}var pp=class{constructor(){m(this,"dbPromise",new Promise(e=>{let n=indexedDB.open("_colyseus_storage",1);n.onupgradeneeded=()=>n.result.createObjectStore("store"),n.onsuccess=()=>e(n.result)}))}async tx(e,n){let s=(await this.dbPromise).transaction("store",e).objectStore("store");return n(s)}setItem(e,n){return this.tx("readwrite",r=>r.put(n,e)).then()}async getItem(e){let n=await this.tx("readonly",r=>r.get(e));return new Promise(r=>{n.onsuccess=()=>r(n.result)})}removeItem(e){return this.tx("readwrite",n=>n.delete(e)).then()}};var Va,Rr,Ha,Ua=class{constructor(e){m(this,"settings",{path:"/auth",key:"colyseus-auth-token"});ze(this,Va,!1);ze(this,Rr,null);ze(this,Ha,il());m(this,"http");this.http=e,Tb(this.settings.key,n=>this.token=n)}set token(e){this.http.authToken=e}get token(){return this.http.authToken}onChange(e){let n=ae(this,Ha).on("change",e);return ae(this,Va)||this.getUserData().then(r=>{this.emitChange({...r,token:this.token})}).catch(r=>{this.emitChange({user:null,token:void 0})}),Ue(this,Va,!0),n}async getUserData(){if(this.token)return(await this.http.get(`${this.settings.path}/userdata`)).data;throw new Error("missing auth.token")}async registerWithEmailAndPassword(e,n,r){let s=(await this.http.post(`${this.settings.path}/register`,{body:{email:e,password:n,options:r}})).data;return this.emitChange(s),s}async signInWithEmailAndPassword(e,n){let r=(await this.http.post(`${this.settings.path}/login`,{body:{email:e,password:n}})).data;return this.emitChange(r),r}async signInAnonymously(e){let n=(await this.http.post(`${this.settings.path}/anonymous`,{body:{options:e}})).data;return this.emitChange(n),n}async sendPasswordResetEmail(e){return(await this.http.post(`${this.settings.path}/forgot-password`,{body:{email:e}})).data}async signInWithProvider(e,n={}){return new Promise((r,s)=>{let o=n.width||480,i=n.height||768,a=this.token?`?token=${this.token}`:"",c=`Login with ${e[0].toUpperCase()+e.substring(1)}`,u=this.http.sdk.getHttpEndpoint(`${n.prefix||`${this.settings.path}/provider`}/${e}${a}`),l=screen.width/2-o/2,d=screen.height/2-i/2;Ue(this,Rr,window.open(u,c,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width="+o+", height="+i+", top="+d+", left="+l));let f=p=>{if(!(p.data.user===void 0&&p.data.token===void 0))if(clearInterval(h),ae(this,Rr)?.close(),Ue(this,Rr,null),window.removeEventListener("message",f),p.data.error!==void 0){let g=new Error(String(p.data.error));g.code=p.data.error,p.data.reason!==void 0&&(g.reason=p.data.reason),p.data.until!==void 0&&(g.until=p.data.until),s(g)}else r(p.data),this.emitChange(p.data)},h=setInterval(()=>{(!ae(this,Rr)||ae(this,Rr).closed)&&(Ue(this,Rr,null),s("cancelled"),window.removeEventListener("message",f))},200);window.addEventListener("message",f)})}async signOut(){this.emitChange({user:null,token:null})}emitChange(e){e.token!==void 0&&(this.token=e.token,e.token===null?vb(this.settings.key):Ab(this.settings.key,e.token)),ae(this,Ha).emit("change",e)}};Va=new WeakMap,Rr=new WeakMap,Ha=new WeakMap;function Mb(t){let e=window?.location?.hostname||"localhost",n=t.hostname.split("."),r=!t.hostname.includes("trycloudflare.com")&&!t.hostname.includes("discordsays.com")&&n.length>2?`/${n[0]}`:"";return t.pathname.startsWith("/.proxy")?`${t.protocol}//${e}${r}${t.pathname}${t.search}`:`${t.protocol}//${e}/.proxy/colyseus${r}${t.pathname}${t.search}`}xa();var Cb=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",dl=class dl{constructor(e=Cb,n){m(this,"http");m(this,"auth");m(this,"settings");m(this,"urlBuilder");if(typeof e=="string"){let r=e.startsWith("/")?new URL(e,Cb):new URL(e),s=r.protocol==="https:"||r.protocol==="wss:",o=Number(r.port||(s?443:80));this.settings={hostname:r.hostname,pathname:r.pathname,port:o,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)),n?.protocol&&(this.settings.protocol=n.protocol),this.http=new ul(this,{headers:n?.headers||{}},n?.fetchFn),this.auth=new Ua(this.http),this.urlBuilder=n?.urlBuilder,!this.urlBuilder&&typeof window<"u"&&window?.location?.hostname?.includes("discordsays.com")&&(this.urlBuilder=Mb,console.log("Colyseus SDK: Discord Embedded SDK detected. Using custom URL builder."))}static async selectByLatency(e,n,r={}){let s=e.map(i=>new dl(i,n)),o=(await Promise.allSettled(s.map((i,a)=>i.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(i=>i.status==="fulfilled").map(i=>i.value);if(o.length===0)throw new Error("All endpoints failed to respond");return s[o.sort((i,a)=>i[1]-a[1])[0][0]]}async joinOrCreate(e,n={},r){return await this.createMatchMakeRequest("joinOrCreate",e,n,r)}async create(e,n={},r){return await this.createMatchMakeRequest("create",e,n,r)}async join(e,n={},r){return await this.createMatchMakeRequest("join",e,n,r)}async joinById(e,n={},r){return await this.createMatchMakeRequest("joinById",e,n,r)}async reconnect(e,n){if(typeof e=="string"&&typeof n=="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},n)}async consumeSeatReservation(e,n){let r=this.createRoom(e.name,n);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((o,i)=>{let a=(c,u)=>i(new Yn(c,u));r.onError.once(a),r.onJoin.once(()=>{r.onError.remove(a),ju("room",r),o(r)})})}getLatency(e={}){let n=e.protocol??"ws",r=e.pingCount??1,s=e.timeout??1500;return new Promise((o,i)=>{let a=new Zo(n),c=[],u=0,l=!1,d,f=p=>{if(!l){l=!0,clearTimeout(d);try{a.close()}catch{}p()}},h=p=>f(()=>i(new Yn(ft.ABNORMAL_CLOSURE,`Failed to get latency: ${p}`)));d=setTimeout(()=>h(`timed out after ${s}ms`),s),a.events.onopen=()=>{u=Date.now(),a.send(new Uint8Array([We.PING]))},a.events.onmessage=p=>{if(c.push(Date.now()-u),c.length<r)u=Date.now(),a.send(new Uint8Array([We.PING]));else{let g=c.reduce((x,b)=>x+b,0)/c.length;f(()=>o(g))}},a.events.onclose=p=>h(`connection closed${p?.code?` (${p.code})`:""}${p?.reason?`: ${p.reason}`:""}`),a.events.onerror=p=>h(p.message);try{a.connect(this.getHttpEndpoint())}catch(p){h(p?.message??"failed to connect")}})}async createMatchMakeRequest(e,n,r={},s){try{if(!n)throw new Error("Must provide a room name");let i=(await this.http.post(`/matchmake/${e}/${n}`,{headers:{Accept:"application/json","Content-Type":"application/json"},body:r})).data;return e==="reconnect"&&(i.reconnectionToken=r.reconnectionToken),await this.consumeSeatReservation(i,s)}catch(o){throw o instanceof Yn?new oa(o.message,o.code):o}}createRoom(e,n){return new Fa(e,n)}buildEndpoint(e,n={}){let r=this.settings.protocol||"ws",s=this.settings.searchParams||"";this.http.authToken&&(n._authToken=this.http.authToken);for(let a in n)n.hasOwnProperty(a)&&(s+=(s?"&":"")+`${a}=${n[a]}`);r==="h3"&&(r="http");let o=this.settings.secure?`${r}s://`:`${r}://`;e.publicAddress?o+=`${e.publicAddress}`:o+=`${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}`;let i=`${o}/${e.processId}/${e.roomId}?${s}`;return this.urlBuilder?this.urlBuilder(new URL(i)):i}getHttpEndpoint(e=""){let n=e.startsWith("/")?e:`/${e}`,r=`${this.settings.secure?"https":"http"}://${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}${n}`;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}`:""}};m(dl,"VERSION","0.18");var ll=dl,es=ll;yr();var fl=class{setState(e){}getState(){return null}patch(e){}teardown(){}handshake(e){}};wt();_p();gl();bl();yl();up("schema",Qo);up("none",fl);var KL=Object.freeze({min:3,max:3}),XL=Object.freeze({min:4,max:4});var mi={PLAY:"play",QUEUE:"queue",MATCH:"match",AUTHORITY:"authority"};var Gb={CAPS:"caps"},yn={PHYSICS:"physics@1",PHYSICS_PREDICT:"physics@2",INPUT_REPEAT:"repeat@1",LIFTS:"lifts@1",INPUT_TICK:"tick@1",FAST:"fast@1",MAX_CAPS:16,MAX_CAP_CHARS:32};var YP=["clients","preset","winCondition","config","matchmade"],JL=[...YP,"moduleSha","tickHz","maxPlayers","lagComp","seed","units","leaseId","region"],Ka={BAD_OPTION:400,AUTH_REQUIRED:401,FORBIDDEN:403,PROTOCOL_UNSUPPORTED:426,NOT_ENTITLED:402,ROOM_QUOTA:429,MODULE_UNAVAILABLE:424,AUTHORITY_CAPACITY:503};var le={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"},xe={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"},KP=["__","match:","server:","rate:"],XP=["state","shared","claim","release","destroy","obj","queue","seat"];function ns(t){return XP.includes(t)||KP.some(e=>t.startsWith(e))}var Rl="__",ar="__t";var ZL={[le.STATE]:"state",[le.STATE_SNAP]:"state",[le.SHARED]:"bulk",[le.CLAIM]:"control",[le.RELEASE]:"control",[le.DESTROY]:"control",[le.OBJECT]:"bulk",[le.OBJECT_SNAP]:"bulk",[le.INPUT]:"input",[le.ROOM_OPEN]:"control",[le.CHAT]:"chat",[le.CHAT_HISTORY_REQUEST]:"control",[le.VOICE_ICE_REQUEST]:"voice",[le.VOICE_JOIN]:"voice",[le.VOICE_LEAVE]:"voice",[le.VOICE_SIGNAL]:"voice",[le.MATCH_ELIMINATED]:"bulk",[le.MATCH_SCORE]:"bulk",[le.MATCH_FINISH]:"bulk",[le.POSE]:"pose",[le.POSE_SNAP]:"pose"},Xa={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},$t={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},QL={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},rs={TICK_HZ:30,RENDER_DELAY_MS:100,MAX_REWIND_MS:500,INPUT_BUFFER:32,PATCH_INTERVAL_MS:50,INPUT_REPEAT_MAX_MS:100,INPUT_REPEAT_RUN_MS:33},gn={enabled:!0,minUptime:0,delay:125,minDelay:100,maxDelay:4e3,maxRetries:9,maxEnqueuedMessages:0,firstStateTimeoutMs:2e3},Wb=["x","y","z","yaw","vx","vy","vz","anim"],qe={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},Pr={HEARTBEAT_HZ:10,MIN_HEARTBEAT_HZ:5,MAX_HEARTBEAT_HZ:20,HEARTBEAT_DITHER:.15,RELAY_BUFFER:4,WARMUP_ACKS:30};var Ys={SAMPLES:3,TIMEOUT_MS:4e3,GRACE_MS:1e3};async function Yb(t,e={}){let n=t[0];if(n===void 0)throw new Error("genex multiplayer: `urls` must contain at least one relay URL");if(t.length===1)return n;let r=e.probe??Rp,s=Math.max(1,e.samples??Ys.SAMPLES),o=e.timeoutMs??Ys.TIMEOUT_MS,i=e.graceMs??Ys.GRACE_MS,a=t.map(()=>{});await new Promise(u=>{let l=t.length*s,d,f=setTimeout(h,o);function h(){clearTimeout(f),clearTimeout(d),u()}let p=()=>{--l===0&&h()};t.forEach((g,x)=>{for(let b=0;b<s;b++){let S;try{S=r(g,o)}catch(_){S=Promise.reject(_)}S.then(_=>{Number.isFinite(_)&&_>=0&&(a[x]=Math.min(a[x]??1/0,_),d??(d=setTimeout(h,i))),p()},p)}})});let c=-1;return a.forEach((u,l)=>{u!==void 0&&(c<0||u<a[c])&&(c=l)}),c<0?(console.warn(`genex multiplayer: no relay answered the latency probe \u2014 connecting to ${n}`),n):t[c]}var Rp=(t,e)=>new es(t).getLatency({pingCount:1,timeout:e});var JP=t=>typeof t=="function"?t():t;async function Ja(t){return t.url?new es(t.url):new es(await Yb(t.urls))}function Za(t,e,n){return{gameId:t,name:e,embedToken:JP(n)?.embedToken,protocol:3}}var Qa=t=>!!t&&typeof t=="object"&&t.code===Ka.PROTOCOL_UNSUPPORTED,kp=()=>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.`),Kb=t=>{throw Qa(t)&&kp(),t};function Xb(t,e){let n=null,r=null;return{request(){return n||(n=new Promise(s=>{let o,i=a=>{r&&(r=null,n=null,o&&clearTimeout(o),s(a))};r=i,o=setTimeout(()=>i(null),e),t()}),n)},deliver(s){r?.(s)},get pending(){return n!==null}}}var Jb=["x","y","z","yaw","vx","vy","vz"],Zb=[["x","vx"],["y","vy"],["z","vz"]],Pp=Math.PI*2,ZP=t=>Wb.includes(t);function Ap(t){if(!Number.isFinite(t))return 0;let e=t%Pp;return e<=-Math.PI?e+=Pp:e>Math.PI&&(e-=Pp),e}var Qb=t=>typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=$t.MAX_POSE_ABS;function e0(t){let e={},n={},r=[];for(let s of Object.keys(t)){let o=t[s];if(!ZP(s)){n[s]=o;continue}o!==void 0&&(s==="anim"?typeof o=="string"&&o.length<=$t.MAX_ANIM_CHARS?e.anim=o:r.push(s):Qb(o)?e[s]=o:r.push(s))}return{pose:e,data:n,invalid:r}}function t0(t){for(let e in t)if(t[e]!==void 0)return!0;return!1}function n0(t,e,n){let r={...t},s={t:e},o=n?e-n.t:0,i=n!==void 0&&o>qe.MIN_GAP_MS&&o<qe.MAX_GAP_MS;for(let[a,c]of Zb){let u=t[a];if(u===void 0||(s[a]=u,t[c]!==void 0))continue;let l=n?.[a],d=i&&l!==void 0?(u-l)/o*1e3:0;r[c]=Qb(d)?d:0}return{pose:r,memory:s}}function vl(t){let e=n=>typeof n=="number"&&Number.isFinite(n)?n:0;return{x:e(t.x),y:e(t.y),z:e(t.z),yaw:e(t.yaw),vx:e(t.vx),vy:e(t.vy),vz:e(t.vz),anim:typeof t.anim=="string"?t.anim:""}}var yi=(t,e)=>{let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:0};function r0(t,e){let n=t.length;if(n===0)return;let r=0;for(;r<n&&t[r].t<=e;)r++;if(r===0)return t[0].state;if(r>=n){let u=t[n-1],l={...u.state},d=Math.min(Math.max(0,e-u.t),qe.MAX_EXTRAP_MS)/1e3;for(let[f,h]of Zb)l[f]=yi(u.state,f)+yi(u.state,h)*d;if(n>=2){let f=t[n-2],h=u.t-f.t;if(h>0){let p=Math.min(Math.max(0,e-u.t),qe.ROT_EXTRAP_MS)/h,g=yi(u.state,"yaw");l.yaw=g+Ap(g-yi(f.state,"yaw"))*p}}return l}let s=t[r-1],o=t[r],i=o.t-s.t,a=i>0?(e-s.t)/i:1,c={...s.state};for(let u of Jb){let l=yi(s.state,u),d=yi(o.state,u);c[u]=u==="yaw"?l+Ap(d-l)*a:l+(d-l)*a}return c}function s0(t,e,n,r){let s={...e};for(let o of Jb){let i=t[o],a=e[o];typeof i!="number"||typeof a!="number"||!Number.isFinite(i)||!Number.isFinite(a)||(s[o]=o==="yaw"?i+Ap(a-i)*r:i+(a-i)*n)}return s}var Al=class Al{constructor(){m(this,"pending",[]);m(this,"current")}push(e,n){for(this.pending.push({t:e,state:n});this.pending.length>Al.MAX_PENDING;)this.current=this.pending.shift()?.state}at(e){for(;this.pending.length>0;){let n=this.pending[0];if(this.current!==void 0&&e!==void 0&&n.t!==void 0&&n.t>e)break;this.current=n.state,this.pending.shift()}return this.current}flush(){this.at(void 0)}};m(Al,"MAX_PENDING",64);var Pl=Al;function o0(t){try{let e=t.input();return e&&typeof e.send=="function"?e:null}catch{return null}}function i0(t,e,n=Pr.HEARTBEAT_HZ,r=Math.random){let o=1e3/Math.min(Pr.MAX_HEARTBEAT_HZ,Math.max(Pr.MIN_HEARTBEAT_HZ,n)),i=1e3/Pr.MAX_HEARTBEAT_HZ,a=1e3/Pr.MIN_HEARTBEAT_HZ,c=!1,u=!1,l,d=()=>{if(u)return;if(e()){try{t.send()}catch{}!c&&t.lastProcessed>=Pr.WARMUP_ACKS&&(c=!0)}let f=o*(1+(r()*2-1)*Pr.HEARTBEAT_DITHER);l=setTimeout(d,Math.min(a,Math.max(i,f)))};return d(),{get synced(){return!c&&t.lastProcessed>=Pr.WARMUP_ACKS&&(c=!0),c},stop(){u=!0,l&&clearTimeout(l)}}}function a0(t,e){return e.synced&&e.clockOrigin>0&&e.serverNow!==void 0&&Number.isFinite(e.serverNow)?t-e.clockOrigin-e.serverNow:t-e.wallNow}function Ks(t){let e=t.reconnection;return e.enabled=gn.enabled,e.minUptime=gn.minUptime,e.delay=gn.delay,e.minDelay=gn.minDelay,e.maxDelay=gn.maxDelay,e.maxRetries=gn.maxRetries,e.maxEnqueuedMessages=gn.maxEnqueuedMessages,e.enqueuedMessages.length=0,t}function c0(t){return t.reconnection.enabled=!1,t}function Tl(t,e){return new Promise(n=>{let r=()=>{clearTimeout(s),n(!0)},s=setTimeout(()=>{t.onStateChange.remove(r),n(!1)},e);t.onStateChange.once(r)})}function u0(t,e,n){return t!==e&&n!=null}var QP="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.",vp=class extends Error{constructor(e){super(QP,{cause:e}),this.name="VoiceNotDelegatedError"}},l0=[{urls:"stun:stun.l.google.com:19302"}],eA=120,d0=.02,tA=.6,Ml=class{constructor(e){m(this,"transport");m(this,"peers",new Map);m(this,"listeners",new Set);m(this,"roster",[]);m(this,"local",null);m(this,"audio",null);m(this,"localAnalyser",null);m(this,"levelTimer",null);m(this,"iceServers",l0);m(this,"spatial",!1);m(this,"threshold",d0);m(this,"micOn",!0);m(this,"selfSpeaking",!1);m(this,"running",!1);m(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={},n=!1){if(!this.running){this.peeringHeld=n,this.iceServers=e.iceServers?.length?e.iceServers:l0,this.spatial=e.spatial===!0,this.threshold=e.speakingThreshold??d0,this.micOn=e.startMuted!==!0;try{this.local=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1})}catch(r){throw rA(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(),eA)}}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 n of this.peers.values())try{n.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 n=this.transport.selfId(),r=new Set(e.filter(s=>s!==n));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 n of this.local?.getAudioTracks()??[])n.enabled=e;!e&&this.selfSpeaking&&(this.selfSpeaking=!1,this.emit())}mute(e){this.setMuted(e,!0)}unmute(e){this.setMuted(e,!1)}setVolume(e,n){let r=this.peers.get(e);r&&(r.volume=Math.max(0,Math.min(1,n)),r.el&&(r.el.volume=r.volume),this.emit())}async handleSignal(e,n){if(!this.running)return;let r=n;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 o=await s.pc.createAnswer();await s.pc.setLocalDescription(o),this.transport.sendSignal(e,{t:"answer",sdp:o})}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(o){console.warn(`[multiplayer] voice signaling failed with ${e}`,o)}}setMuted(e,n){let r=this.peers.get(e);!r||r.muted===n||(r.muted=n,r.el&&(r.el.muted=n||this.spatial),n&&r.speaking&&(r.speaking=!1),this.emit())}createPeer(e){let n=new RTCPeerConnection({iceServers:this.iceServers}),r={id:e,pc:n,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&&n.addTrack(s,this.local);return n.onicecandidate=s=>{s.candidate&&this.transport.sendSignal(e,{t:"ice",c:s.candidate.toJSON()})},n.ontrack=s=>{let o=s.streams[0]??new MediaStream([s.track]);r.stream=o,r.el=this.attachSink(o,r),r.analyser=this.makeAnalyser(o),this.emit()},n.onconnectionstatechange=()=>{let s=n.connectionState,o=s==="connected"?"connected":s==="failed"||s==="closed"?"failed":"connecting";if(o!==r.connection){if(r.connection=o,o==="failed"){let i=this.iceServers.some(a=>sA(a));console.warn(`[multiplayer] voice connection to ${e} failed`+(i?"":" \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 n=await e.pc.createOffer();await e.pc.setLocalDescription(n),this.transport.sendSignal(e.id,{t:"offer",sdp:n})}catch(n){console.warn(`[multiplayer] voice offer to ${e.id} failed`,n)}}async flushIce(e){let n=e.pendingIce.splice(0);for(let r of n)try{await e.pc.addIceCandidate(r)}catch{}}destroyPeer(e){let n=this.peers.get(e);if(n){this.peers.delete(e),n.pc.onicecandidate=null,n.pc.ontrack=null,n.pc.onconnectionstatechange=null;try{n.pc.close()}catch{}n.el&&(n.el.srcObject=null,n.el.remove())}}attachSink(e,n){let r=document.createElement("audio");return r.autoplay=!0,r.srcObject=e,r.muted=this.spatial||n.muted,r.volume=n.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 n=this.audio.createMediaStreamSource(e),r=this.audio.createAnalyser();return r.fftSize=512,n.connect(r),r}catch{return null}}pollLevels(){let e=!1,n=this.micOn?f0(this.localAnalyser):0,r=this.crossed(n,this.selfSpeaking);r!==this.selfSpeaking&&(this.selfSpeaking=r,e=!0);for(let s of this.peers.values()){let o=s.muted?!1:this.crossed(f0(s.analyser),s.speaking);o!==s.speaking&&(s.speaking=o,e=!0)}e&&this.emit()}crossed(e,n){return e>=(n?this.threshold*tA:this.threshold)}emit(){for(let e of[...this.listeners])try{e()}catch(n){console.error("[multiplayer] a voice listener threw",n)}}};function nA(){try{return window.self!==window.top}catch{return!0}}function rA(t){if(t?.name!=="NotAllowedError")return t;try{if(!nA()||document.featurePolicy?.allowsFeature?.("microphone")!==!1)return t}catch{return t}return new vp(t)}function sA(t){return(Array.isArray(t.urls)?t.urls:[t.urls]).some(n=>typeof n=="string"&&n.startsWith("turn"))}function f0(t){if(!t)return 0;let e=new Uint8Array(t.fftSize);t.getByteTimeDomainData(e);let n=0;for(let r=0;r<e.length;r++){let s=((e[r]??128)-128)/128;n+=s*s}return Math.sqrt(n/e.length)}var Tp=Symbol("genex.roomRef"),Ar=t=>t[Tp]();var oA=qe.RATIO,iA=qe.MIN_MS,aA=qe.MAX_MS,Cl=qe.DEFAULT_MS,cA=qe.JITTER_SAFETY,uA=qe.POISON_GUARD_MS,lA=qe.EASE,dA=qe.MAX_EXTRAP_MS,fA=qe.ROT_EXTRAP_MS,h0=qe.CLOCK_WINDOW,pA=qe.CLOCK_WINDOW_MS,hA=qe.CLOCK_WINDOW_MAX,mA=qe.INTERVAL_WINDOW,yA=qe.MIN_GAP_MS,gA=qe.MAX_GAP_MS,bA=qe.HISTORY_MS,wA=qe.SMOOTH_TAU_POS_MS,xA=qe.SMOOTH_TAU_ROT_MS,m0=qe.MAX_HOST_TICK_DT_MS,SA=qe.REBASE_AFTER_GAP_MS,cr="obj:",EA=3e3,_A=5e3,RA=6e4,kA=2e3;function b0(t){if(t==="predict")return{mode:"lerp"};if(t&&typeof t=="object"&&t.engine==="predict")return{mode:t.mode==="damped"?"damped":"lerp",delay:t.delay,smoothMs:t.smoothMs}}var Dl=async t=>b0(t)?Promise.resolve().then(()=>(Mp(),p0)):void 0;function y0(t){if(!t)return{state:{}};try{let e=JSON.parse(t);if(!e||typeof e!="object")return{state:{}};let n=e,r=n[ar];if(typeof r=="number"&&Number.isFinite(r)){let s={...n};return delete s[ar],{state:s,sendTime:r}}return{state:n}}catch{return{state:{}}}}function Ol(t){if(t!=null)try{return JSON.parse(t)}catch{return}}var PA=(t,e)=>typeof e=="number"?Number.isFinite(e)?e:0:typeof e=="bigint"?Number(e):e;function gi(t){return JSON.parse(JSON.stringify(t,PA))}var Xs=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function w0(t,e,n){let[r,s,o,i]=e,[a,c,u,l]=t,d=a*r+c*s+u*o+l*i;if(d<0&&(r=-r,s=-s,o=-o,i=-i,d=-d),d>.9995){let x=a+(r-a)*n,b=c+(s-c)*n,S=u+(o-u)*n,_=l+(i-l)*n,P=Math.hypot(x,b,S,_)||1;return[x/P,b/P,S/P,_/P]}let f=Math.acos(d),h=Math.sin(f),p=Math.sin(f-f*n)/h,g=Math.sin(f*n)/h;return[a*p+r*g,c*p+s*g,u*p+o*g,l*p+i*g]}function Il(t){return Array.isArray(t)&&t.length===4&&t.every(e=>typeof e=="number"&&Number.isFinite(e))}function g0(t,e,n,r){let s={},o=n<1;for(let i in e){let a=t[i],c=e[i];typeof a=="number"&&typeof c=="number"&&Number.isFinite(a)&&Number.isFinite(c)?s[i]=a+(c-a)*n:Il(a)&&Il(c)?s[i]=w0(a,c,r):s[i]=o&&i in t?a:c}return s}function AA(t,e,n,r){let s={};for(let o in e){let i=e[o],a=t[o];typeof a=="number"&&typeof i=="number"&&Number.isFinite(a)&&Number.isFinite(i)?s[o]=a+(i-a)*n:Il(a)&&Il(i)?s[o]=w0(a,i,r):s[o]=i}return s}function vA(t,e){let n=t.length;if(n===0)return;if(n===1)return t[0].state;let r=0;for(;r<n&&t[r].t<=e;)r++;if(r===0)return t[0].state;if(r>=n){let c=t[n-2],u=t[n-1],l=u.t-c.t;if(l<=0)return u.state;let d=(Math.min(e,u.t+dA)-c.t)/l,f=(Math.min(e,u.t+fA)-c.t)/l;return g0(c.state,u.state,d,f)}let s=t[r-1],o=t[r],i=o.t-s.t,a=i>0?(e-s.t)/i:1;return g0(s.state,o.state,a,a)}function TA(t){if(t.length===0)return 66;let e=[...t].sort((n,r)=>n-r);return e[e.length>>1]}function MA(t,e){if(t.length===0)return 0;let n=[...t].sort((s,o)=>s-o),r=Math.min(n.length-1,Math.max(0,Math.round(e*(n.length-1))));return n[r]}async function x0(t){let e=await Ja(t),n=await Dl(t.smoothing),r=Ks(await e.joinOrCreate(mi.PLAY,{...Za(t.room,t.name,t.auth),...t.options,protocol:3}).catch(Kb));return Cp(r,{pose:t.pose,smoothing:t.smoothing,predict:n})}var CA=t=>typeof t=="string"&&t.length>0&&t.length<=$t.MAX_EVENT_TYPE_CHARS&&!ns(t),OA=new Set(["join","leave","change","shared","object","host","reconnecting","reconnected","disconnect","room:open","voice","voice:rejected"]),IA=new Set([xe.OBJECT_RESULT,xe.INPUT,xe.ROOM_OPEN,xe.CHAT,xe.CHAT_HISTORY,xe.VOICE_ICE,xe.VOICE_SIGNAL,xe.VOICE_REJECTED,xe.RATE_DROP,...Object.values(le)]),DA=[500,1e3,2e3,4e3,8e3];function Cp(t,e={}){let n=new Map,r=new Map,s=new Map,o=new Map,i=new Map,a=new Map,c=new Set,u=new Map,l=new Map,d=new Map,f=new Map,h,p=new Map,g=new Map,x=new Map,b=new Map,S=new Map,_=new Map,P=new Map,R=new Map,v=new Set,M=new Map,O,z=0,X=new Map,N=w=>{for(let T of X.values())if(T.id===w)return!0;return!1},Y=typeof globalThis<"u"&&globalThis.__GENEX_MP_TEST_SKEW__||0,he=Y?()=>Xs()+Y:Xs,A=(w,T)=>{if(p.get(T)===t.sessionId)return!1;let F=`${w}:${T}`;return v.has(F)||(v.add(F),console.warn(`[multiplayer] objects.${w}('${T}') ignored because this session does not own the object \u2014 await objects.claimConfirmed('${T}') and check accepted before publishing`)),!0},W=(w,T,F,Z)=>{let _e=he(),de=F,Pe=_e-F,re=o.get(Z);re||o.set(Z,re={samples:[],mins:[],n:0});let Oe=++re.n;for(re.samples.push({at:_e,n:Oe});re.mins.length>0&&re.mins[re.mins.length-1].v>=Pe;)re.mins.pop();for(re.mins.push({v:Pe,n:Oe});re.samples.length>hA||re.samples.length>h0&&re.samples[0].at<_e-pA;)re.samples.shift();let Me=re.samples[0].n;for(;re.mins[0].n<Me;)re.mins.shift();s.set(Z,re.mins[0].v);let Je=i.get(w);Je||i.set(w,Je=[]),Je.push(Pe),Je.length>h0&&Je.shift(),a.set(w,Z);let Yt=r.get(w);if(r.set(w,de),Yt!=null){let Rt=de-Yt;if(Rt>yA&&Rt<gA){let Fr=d.get(w);Fr||d.set(w,Fr=[]),Fr.push(Rt),Fr.length>mA&&Fr.shift();let zc=Je.length>=8?Math.max(0,MA(Je,.9)-re.mins[0].v):0,pr=Math.min(aA,Math.max(iA,oA*TA(Fr),cA*zc)),Uc=f.get(w)??Cl;f.set(w,Uc+(pr-Uc)*lA)}}let $e=n.get(w);$e||n.set(w,$e=[]);let _s=M.get(w);if(_s&&$e.length===0){let Rt=f.get(w)??Cl;$e.push({t:de-Math.max(1,Rt),state:_s})}M.delete(w),$e.push({t:de,state:T});let Ct=de-bA;for(;$e.length>2&&$e[0].t<Ct;)$e.shift();for(;$e.length>1&&$e[0].t>$e[$e.length-1].t+uA;)$e.shift()},G=(w,T)=>{let F=a.get(w),Z=F===void 0?void 0:s.get(F);if(Z!==void 0)return T-Z-(f.get(w)??Cl)},$=(w,T)=>{let F=n.get(w),Z=G(w,T)??T-Cl,_e=c.has(w),de=F&&(_e?r0(F,Z):vA(F,Z));if(!de)return u.get(w);let Pe=u.get(w),re;if(Pe){let Oe=Math.min(m0,Math.max(0,T-(l.get(w)??T))),Me=1-Math.exp(-Oe/wA),Je=1-Math.exp(-Oe/xA);re=_e?s0(Pe,de,Me,Je):AA(Pe,de,Me,Je)}else re=de;return u.set(w,re),l.set(w,T),re},j=w=>{n.delete(w),r.delete(w),a.delete(w),u.delete(w),l.delete(w),d.delete(w),f.delete(w),i.delete(w),M.delete(w)},se=w=>{n.delete(w),r.delete(w),a.delete(w),d.delete(w),f.delete(w),i.delete(w)},oe=w=>{s.delete(w),o.delete(w)},ne=new Map,ye=new Set,ue=(w,...T)=>ne.get(w)?.forEach(F=>{try{F(...T)}catch(Z){console.error(`[multiplayer] a '${w}' listener threw:`,Z)}}),yt=new Map,Gt=(w,T)=>{yt.get(T)!==w&&(yt.set(T,w),ue("shared",T,Ol(w)))},Hn=w=>{let T=w||void 0;T!==O&&(O=T,ue("host",O))},Li="",hs=()=>{let w=t.state?.voice?[...t.state.voice.keys()].sort():[],T=w.join(`
14
- `);T!==Li&&(Li=T,Le.setRoster(w),ue("voice",Le.participants))},ms=(w,T)=>{let F=cr+w,Z=t.sessionId,_e=b.has(w),de=T.owner||void 0,Pe=Number.isFinite(T.seq)?T.seq:0,re=Number.isFinite(T.epoch)?T.epoch:0,Oe=Number.isFinite(T.t)?T.t:0,Me=typeof T.d=="string"?T.d:"",Yt=de!==g.get(w)||_e&&Pe!==b.get(w),$e=x.has(w)&&re!==x.get(w),_s=Oe!==S.get(w);if(b.set(w,Pe),x.set(w,re),S.set(w,Oe),Me!==_.get(w)){_.set(w,Me);let Rt=Me?Ol(Me):void 0;Rt&&typeof Rt=="object"&&!Array.isArray(Rt)&&P.set(w,Rt)}de?g.set(w,de):g.delete(w),(Yt||p.get(w)!==de&&!N(w))&&(de?p.set(w,de):p.delete(w)),$e&&j(F),Yt&&de!==Z&&(R.delete(w),$e||se(F));let Ct=P.get(w);if(Ct&&de!==Z){let Rt=Oe!==0&&_s&&de!==void 0;$e?(u.set(F,Ct),l.set(F,he()),Rt&&W(F,Ct,Oe,de)):(Yt&&M.set(F,u.get(F)??Ct),Rt&&W(F,Ct,Oe,de))}(!_e||Yt)&&ue("object",w)},Fi=w=>{let T=b.has(w)||p.has(w)||P.has(w)||R.has(w);j(cr+w),P.delete(w),p.delete(w),g.delete(w),x.delete(w),b.delete(w),S.delete(w),_.delete(w),R.delete(w),T&&ue("object",w)},zi=new Map,ys=new Map,Ui=new Map,Nr=(w,T)=>{if(!T)return{};let F=zi.get(w);if(F&&F.raw===T)return F.state;let{state:Z}=y0(T);return zi.set(w,{raw:T,state:Z}),Z},Wt=new Map,gs=new Map,Et=e.predict?b0(e.smoothing):void 0,cn,$n=new Map,Rd=(w,T)=>{if(!Et||!e.predict)return;cn??(cn=e.predict.Predict.get(t));let F={mode:Et.mode,delay:Et.delay,smoothMs:Et.smoothMs};cn.attach(T,{x:F,y:F,z:F,vx:F,vy:F,vz:F}),cn.attach(T,{yaw:{...F,angle:!0}}),$n.set(w,T)},Vi=w=>{let T=$n.get(w);T&&cn&&cn.detach(T),$n.delete(w)},Oc=w=>{let T=cn;return{x:T.value(w,"x"),y:T.value(w,"y"),z:T.value(w,"z"),yaw:T.value(w,"yaw"),vx:T.value(w,"vx"),vy:T.value(w,"vy"),vz:T.value(w,"vz"),anim:w.anim??""}},un=!1,tt=!1,xn=!0,bs=!1,ho=0,mo=0,Hi=0,yo=new Set,go=()=>yo.forEach(w=>w()),ws=(w,T)=>{if(X.delete(w.requestId),w.timeout&&clearTimeout(w.timeout),w.abort?.(),w.operation==="claim"&&w.optimistic&&!T.accepted){let F=T.owner??g.get(w.id);F?p.set(w.id,F):p.delete(w.id),F!==t.sessionId&&R.delete(w.id)}w.operation==="claim"&&T.accepted&&(p.set(w.id,t.sessionId),se(cr+w.id)),w.operation==="release"&&T.accepted&&(R.delete(w.id),p.get(w.id)===t.sessionId&&p.delete(w.id),se(cr+w.id)),w.operation==="remove"&&T.accepted&&(R.delete(w.id),P.delete(w.id),p.delete(w.id),j(cr+w.id)),w.resolve(T)},fr=(w,T)=>{let F=t.state?.objects?.get(w.id);return{requestId:w.requestId,operation:w.operation,id:w.id,accepted:!1,owner:F?.owner||void 0,sequence:F&&Number.isFinite(F.seq)?F.seq:0,reason:T}},$i=w=>{for(let T of[...X.values()])ws(T,fr(T,w))},Ic=(w,T=!1)=>{if(!T&&!xn)return;let F=w.operation==="claim"?le.CLAIM:w.operation==="release"?le.RELEASE:le.DESTROY;nt(F,w.payload)},jn=(w,T,F={})=>{let Z=String(T),_e=`${t.sessionId.slice(0,12)}:${Date.now().toString(36)}:${(++z).toString(36)}`,de=Math.max(250,Math.min(F.timeoutMs??_A,RA));return new Promise(Pe=>{let re={operation:w,id:Z,requestId:_e,payload:{id:Z,requestId:_e,...F.authority==="host"?{authority:"host"}:{}},optimistic:w==="claim"&&F.optimistic===!0,resolve:Pe,timeout:null,abort:void 0};if(un||tt){Pe(fr(re,un?"aborted":"disconnected"));return}if(re.optimistic&&p.set(Z,t.sessionId),re.timeout=setTimeout(()=>ws(re,fr(re,"timeout")),de),F.signal){let Oe=()=>ws(re,fr(re,"aborted"));F.signal.addEventListener("abort",Oe,{once:!0}),re.abort=()=>F.signal?.removeEventListener("abort",Oe)}if(X.set(_e,re),F.signal?.aborted){ws(re,fr(re,"aborted"));return}Ic(re)})},xs=0,nt=(w,T,F=!1)=>{if(t.connection?.isOpen)try{return t.send(w,T),!0}catch{}return F&&xs++,!1},bo,Dc=0,Bc,Nc=new Set,Lc=(w,T)=>{let{pose:F,data:Z,invalid:_e}=e0(w);for(let Me of _e)Nc.has(Me)||(Nc.add(Me),console.warn(`[multiplayer] me.set: '${Me}' is a typed pose key (pose: true) and its value is not a `+(Me==="anim"?`string of \u2264${$t.MAX_ANIM_CHARS} chars`:"finite number")+" \u2014 it is not sent."));if(!t0(F))return!1;let de=he(),Pe=n0(F,de,T?void 0:Bc);Bc=Pe.memory;let re=JSON.stringify(Z),Oe=T||re!==bo||de-Dc>=kA;return Oe&&nt(le.STATE,JSON.stringify({...Z,[ar]:de}))?(bo=re,Dc=de):Oe&&(bo=void 0),nt(T?le.POSE_SNAP:le.POSE,{...Pe.pose,t:de})||(bo=void 0),!0},Le=new Ml({selfId:()=>t.sessionId,nameOf:w=>t.state?.players?.get(w)?.name??"",sendSignal:(w,T)=>nt(le.VOICE_SIGNAL,{to:w,data:T},!0)});Le.onChange(()=>ue("voice",Le.participants));let Lr=null,ji=Xb(()=>nt(le.VOICE_ICE_REQUEST,{},!0),EA),ln=()=>{Lr&&clearTimeout(Lr),Lr=null},Fc=w=>{ln(),!(typeof w!="number"||!Number.isFinite(w)||w<=0)&&(Lr=setTimeout(()=>{Le.active&&ji.request().then(T=>{!Le.active||!T?.iceServers?.length||(Le.setIceServers(T.iceServers),Fc(T.ttl))})},Math.max(6e4,Math.floor(w*800))))},Sn=[],wo=new Set,xo=new Set,lt=new Set,kd=w=>!!w&&typeof w=="object"&&typeof w.id=="number"&&typeof w.from=="string"&&typeof w.name=="string"&&typeof w.text=="string",Ss=w=>{if(!kd(w)||wo.has(w.id)||lt.has(w.from))return;wo.add(w.id);let T=Sn[Sn.length-1];if(!T||w.id>T.id)Sn.push(w);else{let F=Sn.length;for(;F>0&&(Sn[F-1]?.id??0)>w.id;)F--;Sn.splice(F,0,w)}for(let F of[...xo])try{F(w)}catch(Z){console.error("[multiplayer] a chat listener threw",Z)}},_t=La(t);if(!_t)throw new Error("genex multiplayer: the relay room has no schema state");let So=(w,T,F)=>{let Z=w===t.sessionId,{state:_e,sendTime:de}=y0(T.data),Pe=Number.isFinite(T.epoch)?T.epoch:0,re=ys.has(w)&&Pe!==ys.get(w);ys.set(w,Pe);let Oe=F||T.data!==Ui.get(w);Ui.set(w,T.data);let Me=Number.isFinite(T.poseT)?T.poseT:0,Je=Me!==(gs.get(w)??0);gs.set(w,Me);let Yt=T.posed===!0;if(!Z&&Yt&&!c.has(w)&&(j(w),c.add(w),Wt.set(w,new Pl)),!Z&&re&&(j(w),$n.has(w)&&Vi(w)),ue(F?"join":"change",w,Yt?{..._e,...vl(T)}:_e),!Z){if(Yt){let $e=Wt.get(w);(Oe||re)&&($e.push(de,_e),(re||Et)&&$e.flush()),Et?$n.has(w)||Rd(w,T):Me!==0&&(Je||re)&&W(w,vl(T),Me,w);return}(Oe||re)&&u0(w,t.sessionId,de)&&W(w,_e,de,w)}};_t(t.state).players.onAdd((w,T)=>{So(T,w,!0),_t(w).onChange(()=>So(T,w,!1))});let qi=w=>{ue("leave",w),j(w),oe(w),Vi(w),zi.delete(w),ys.delete(w),Ui.delete(w),gs.delete(w),c.delete(w),Wt.delete(w)};_t(t.state).players.onRemove((w,T)=>qi(T)),_t(t.state).shared.onAdd(Gt),_t(t.state).shared.onChange(Gt),_t(t.state).objects.onAdd((w,T)=>{ms(T,w),_t(w).onChange(()=>ms(T,w))}),_t(t.state).objects.onRemove((w,T)=>Fi(T)),_t(t.state).listen("host",w=>Hn(w)),_t(t.state).voice.onAdd(hs),_t(t.state).voice.onRemove(hs);let Pd=()=>{let w=t.state;if(w){for(let T of new Set([...p.keys(),...P.keys(),...b.keys()]))w.objects?.has(T)||Fi(T);for(let T of[...ys.keys()])w.players?.has(T)||qi(T);Hn(w.host),hs()}};t.onMessage(xe.VOICE_SIGNAL,w=>{w&&typeof w.from=="string"&&Le.handleSignal(w.from,w.data)}),t.onMessage(xe.VOICE_REJECTED,w=>{ln(),Le.stop(),ue("voice:rejected",w??{reason:"full"})}),t.onMessage(xe.VOICE_ICE,w=>{ji.deliver(w??null)}),t.onMessage(xe.CHAT,w=>Ss(w)),t.onMessage(xe.CHAT_HISTORY,w=>{if(Array.isArray(w?.messages))for(let T of w.messages)Ss(T)}),t.onMessage(xe.OBJECT_RESULT,w=>{if(!w||typeof w.requestId!="string")return;let T=X.get(w.requestId);!T||w.operation!==T.operation||w.id!==T.id||ws(T,w)}),t.onMessage(xe.INPUT,w=>{w&&typeof w.from=="string"&&ue(xe.INPUT,w.from,w.d)}),t.onMessage(xe.ROOM_OPEN,w=>{typeof w?.open=="boolean"&&ue("room:open",{open:w.open})}),t.onMessage(xe.RATE_DROP,w=>{console.warn(`[multiplayer] the relay dropped ${w?.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).`)}),t.onMessage(xe.SERVER_RESTART,()=>{}),nt(le.CHAT_HISTORY_REQUEST,{});let Gi=o0(t),En=Gi?i0(Gi,()=>!tt&&!un):void 0,Eo=()=>En?t.clock.serverNow():void 0,Ad=w=>a0(w,{synced:En?.synced===!0,clockOrigin:Number.isFinite(t.state?.clockOrigin)?t.state?.clockOrigin:0,serverNow:Eo(),wallNow:Date.now()}),_o=()=>{En?.stop(),cn?.dispose(),cn=void 0,$n.clear()};t.onDrop(w=>{if(un||tt)return;Hi++,bs||(bs=!0,ho=0,mo=Xs()),xn=!1,go();let{isReconnecting:T,retryCount:F,maxRetries:Z}=t.reconnection;T&&F>=Z||ue("reconnecting",{attempt:++ho,code:w})}),t.onReconnect(()=>{if(tt)return;if(un){t.leave().catch(()=>{});return}let w=Hi;if((mo?Xs()-mo:0)>SA){for(let F of[...n.keys()])j(F);for(let F of[...o.keys()])oe(F)}(async()=>{if(await Tl(t,gn.firstStateTimeoutMs),!(w!==Hi||tt||un)){Pd();for(let F of[...X.values()])Ic(F,!0);nt(le.CHAT_HISTORY_REQUEST,{}),bs=!1,mo=0,xn=!0,go(),ue("reconnected"),xs>0&&(console.warn(`[multiplayer] ${xs} fire-and-forget event(s)/input(s) were dropped while reconnecting \u2014 they are not buffered; player/object state re-synced automatically.`),xs=0)}})()}),t.onLeave(w=>{tt||(tt=!0,xn=!1,bs=!1,_o(),go(),!un&&($i("disconnected"),ue("disconnect",w??1006)))}),t.onError(()=>{});let Wi=((w,T)=>{let F=ne.get(w);return F||ne.set(w,F=new Set),F.add(T),!OA.has(w)&&!IA.has(w)&&!ye.has(w)&&(ye.add(w),t.onMessage(w,Z=>ue(w,Z))),()=>{F?.delete(T)}}),Es={id:t.sessionId,get players(){let w=new Map,T=he();return cn&&$n.size>0&&cn.tick(Xs()),t.state?.players?.forEach((F,Z)=>{let _e=Nr(Z,F.data),de=_e,Pe=_e,re=Wt.get(Z);if(Z!==t.sessionId&&re){let Oe=vl(F);if(Pe={..._e,...Oe},$n.has(Z))de={...re.at(void 0)??_e,...Oc(F)};else{let Me=$(Z,T)??Oe;de={...re.at(G(Z,T))??_e,...Me}}}else Z===t.sessionId?h&&(de=h,Pe=h):de=$(Z,T)??_e;w.set(Z,{id:Z,name:F.name??"",avatarUrl:F.avatarUrl??"",connected:F.connected!==!1,uid:F.uid??"",team:Number.isFinite(F.team)?F.team:-1,state:de,stateRaw:Pe})}),w},get activePlayers(){return new Map([...Es.players].filter(([,w])=>w.connected))},me:{set(w){ar in w&&console.warn(`[multiplayer] '${ar}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let T=gi(w);h=T,!(e.pose&&Lc(T,!1))&&nt(le.STATE,JSON.stringify({...T,[ar]:he()}))},snap(w){ar in w&&console.warn(`[multiplayer] '${ar}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let T=gi(w);h=T,!(e.pose&&Lc(T,!0))&&nt(le.STATE_SNAP,JSON.stringify({...T,[ar]:he()}))}},shared:{get(w){return Ol(t.state?.shared?.get(w))},set(w,T){w.startsWith(Rl)||nt(le.SHARED,{key:w,value:JSON.stringify(gi(T))})},keys(){return t.state?.shared?Array.from(t.state.shared.keys()):[]}},objects:{claim(w){jn("claim",w,{optimistic:!0})},claimConfirmed(w,T){return jn("claim",w,T)},release(w){let T=String(w);R.delete(T),p.get(T)===t.sessionId&&p.delete(T),se(cr+T),jn("release",T)},releaseConfirmed(w,T){return jn("release",w,T)},remove(w){let T=String(w);p.get(T)===t.sessionId&&(R.delete(T),P.delete(T),p.delete(T),j(cr+T)),jn("remove",T)},removeConfirmed(w,T){return jn("remove",w,T)},set(w,T){let F=String(w);if(A("set",F))return;let Z=gi(T);p.get(F)===t.sessionId&&R.set(F,Z),nt(le.OBJECT,{id:F,d:Z,t:he()})},snap(w,T){let F=String(w);if(A("snap",F))return;let Z=gi(T);p.get(F)===t.sessionId&&R.set(F,Z),nt(le.OBJECT_SNAP,{id:F,d:Z,t:he()})},get(w){let T=String(w),F=p.get(T),Z=R.get(T);if(F===void 0&&!P.has(T)&&!Z)return;let _e=F!==void 0&&F===t.sessionId,de,Pe;return _e&&Z?(de=Z,Pe=Z,u.set(cr+T,Z),l.set(cr+T,he())):(Pe=P.get(T)??{},de=$(cr+T,he())??Pe),{id:T,epoch:x.get(T)??0,owner:F,isMine:_e,state:de,stateRaw:Pe}},ids(){return[...new Set([...p.keys(),...P.keys(),...R.keys()])]}},get isHost(){return xn&&!un&&!tt&&O!==void 0&&O===t.sessionId},get host(){return O},inputs:{send(w){nt(le.INPUT,gi(w),!0)},on(w){let T=ne.get(xe.INPUT);T||ne.set(xe.INPUT,T=new Set);let F=(Z,_e)=>w(Z,_e);return T.add(F),()=>{T?.delete(F)}}},onHostTick(w,T){let F=null,Z=0,_e=Number.isFinite(w)&&w>0?Math.min(w,100):20,de=Math.max(10,Math.round(1e3/_e)),Pe=()=>{let Oe=xn&&!un&&!tt&&O!==void 0&&O===t.sessionId;Oe&&!F?(Z=Xs(),F=setInterval(()=>{let Me=Xs();T(Math.min(Me-Z,m0)),Z=Me},de)):!Oe&&F&&(clearInterval(F),F=null)},re=Wi("host",Pe);return yo.add(Pe),Pe(),()=>{re(),yo.delete(Pe),F&&clearInterval(F),F=null}},on:Wi,send(w,T){if(!CA(w)){console.warn(`[multiplayer] send('${w}') collides with a relay-internal channel \u2014 use a different event name`);return}nt(w,T,!0)},chat:{send(w){typeof w=="string"&&w.trim()&&nt(le.CHAT,{text:w},!0)},on(w){return xo.add(w),()=>xo.delete(w)},get history(){return[...Sn]},mute(w){typeof w=="string"&&w&&lt.add(w)},unmute(w){lt.delete(w)},get muted(){return[...lt]}},voice:{async join(w){if(await Le.start(w,!0),!w?.iceServers?.length){let T=await ji.request();Le.active&&T?.iceServers?.length&&(Le.setIceServers(T.iceServers),Fc(T.ttl))}Le.active&&(nt(le.VOICE_JOIN,{},!0),Le.releasePeering())},leave(){ln(),nt(le.VOICE_LEAVE,{},!0),Le.stop()},get active(){return Le.active},get participants(){return Le.participants},setMicEnabled(w){Le.setMicEnabled(w===!0)},get micEnabled(){return Le.micEnabled},get speaking(){return Le.speaking},mute(w){Le.mute(w)},unmute(w){Le.unmute(w)},setVolume(w,T){Le.setVolume(w,T)},get muted(){return Le.participants.filter(w=>w.muted).map(w=>w.id)}},setRoomOpen(w){nt(le.ROOM_OPEN,{open:w===!0})},leave(){un=!0,_o(),Le.stop(),ln(),xn=!1,go(),$i("aborted"),t.reconnection.enabled=!1,t.leave().catch(()=>{})},serverNow:Eo,get rtt(){if(!En)return;let w=t.clock.smoothedRtt();return w>0?w:void 0},get clockSynced(){return En?.synced===!0},timeUntil:Ad};return Object.defineProperty(Es,Tp,{value:()=>t,enumerable:!1}),Object.defineProperty(Es,Symbol.for("genex.multiplayer.internals"),{enumerable:!1,value:{senderOf:w=>a.get(w),offsetOf:w=>{let T=a.get(w);return T===void 0?void 0:s.get(T)},offsetSamples:w=>o.get(w)?.samples.length??0,bufferLength:w=>n.get(w)?.length??0}}),Es}var BA=[1e3,2e3,4e3],Op=t=>Za(t.room,t.name,t.auth);function S0(t,e,n=r=>r-Date.now()){let r=t?.state?.match,s=r?Ol(r):null,o=s&&typeof s=="object"?s:null;if(!o)return{status:t?"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:t?"Waiting for players\u2026":"Finding a match\u2026",startsAt:null,endsBy:null,startsInMs:null,endsInMs:null};let i=t?.sessionId,a=o.championId??null,c=o.challengerId??null,u=o.teams??{},l=Array.isArray(o.players)?o.players:[],d=o.connectedPlayers??l,f=i!=null&&l.includes(i),h=f?o.phase:"spectating",p=l.filter(v=>v!==i),g=i?Object.keys(u).find(v=>u[v]?.includes(i))??null:null,{winCondition:x,...b}=o.cfg??{},S=v=>typeof v=="number"&&Number.isFinite(v)&&v>0?v:null,_=S(o.startsAt),P=S(o.endsBy),R=v=>v===null?null:Math.max(0,n(v));return{status:h,role:f?"player":"spectator",queue:{position:0,size:0},players:l,connectedPlayers:d,opponents:p,teams:u,myTeam:g,scores:o.scores??{},config:b,winCondition:x?.type??"lastStanding",championId:a,challengerId:c,roundId:o.roundId??0,winnerId:o.winnerId??null,message:o.message??"",startsAt:_,endsBy:P,startsInMs:R(_),endsInMs:R(P)}}function bi(t,e,n){if(t?.connection?.isOpen)try{t.send(e,n)}catch{}}async function E0(t){let e=await Ja(t),n=await Dl(t.smoothing),r=new Map,s=(v,...M)=>r.get(v)?.forEach(O=>O(...M)),o=((v,M)=>{let O=r.get(v);return O||r.set(v,O=new Set),O.add(M),()=>{O?.delete(M)}}),i=null,a=null,c=null,u={position:0,size:0},l=!1,d=!1,f=0,h=!1,p=!1,g=async()=>{if(l||d)return;d=!0;let v=++f;try{i=null,a=null;for(let M=0;;M++){c&&(c.leave(),c=null),u={position:0,size:0};let O;try{O=c0(await e.joinOrCreate(mi.QUEUE,Op(t)))}catch(z){if(l)return;let X=Qa(z);X&&kp();let N=X?void 0:BA[M];if(N==null){if(M===0&&await new Promise(Y=>setTimeout(Y,0)),l)return;s("error",z);return}if(await new Promise(Y=>setTimeout(Y,N)),l)return;continue}if(l||v!==f){O.leave();return}c=O,O.onMessage(xe.QUEUE,z=>{u={position:z.position,size:z.size},s("queue",z)}),O.onMessage(xe.SEAT,z=>{l||v!==f||c!==O||h||(h=!0,c=null,O.leave(),x(z.reservation,z.role,v))}),O.onLeave(()=>{l||c!==O||(c=null,(async()=>{for(let z of DA)if(await new Promise(X=>setTimeout(X,z)),l||c||i||(await g(),c||i))return})())}),s("searching");return}}finally{d=!1}},x=async(v,M,O)=>{try{let z=Ks(await e.consumeSeatReservation(v));if(l||O!==f){z.leave();return}a=z;let X=Cp(z,{pose:t.pose,smoothing:t.smoothing,predict:n});i=X,X.on(xe.MATCH_START,N=>s("matchStart",N)),X.on(xe.MATCH_ENDED,N=>s("matchEnded",N)),X.on(xe.MATCH_REQUEUE,()=>{i===X&&b()}),X.on("disconnect",N=>{if(!(l||i!==X)){if(N===Xa.SUPERSEDED||N===Xa.REVOKED){f++,h=!1,a=null,i=null,s("disconnect",N);return}b()}}),c&&(c.leave(),c=null),s("matched"),M==="spectator"&&s("spectate")}catch{!l&&O===f&&(h=!1,g())}finally{O===f&&(h=!1)}},b=async()=>{if(!(l||p)){p=!0;try{f++,h=!1,i?.leave(),a=null,i=null,await g()}finally{p=!1}}};g();let S=()=>i?Ar(i):null,_=null,P=null,R=()=>{i!==_&&(_=i,P=null);let v=S(),M=!!v?.state?.match;if(!M&&i&&P)return P;let O=S0(v,u,i?i.timeUntil:void 0);return M&&(P=O),O};return{get session(){return i},get matchmaking(){return R()},on:o,eliminated(){bi(S(),le.MATCH_ELIMINATED,{})},score(v=1){bi(S(),le.MATCH_SCORE,{delta:v})},finish(){bi(S(),le.MATCH_FINISH,{})},retry(){l||d||c||a||g()},cancel(){l=!0,f++,h=!1,i?.leave(),!i&&a&&a.leave(),c&&c.leave(),a=null,c=null,i=null}}}function _0(t,e){let n=new Map,r=(c,...u)=>n.get(c)?.forEach(l=>l(...u)),s=((c,u)=>{let l=n.get(c);return l||n.set(c,l=new Set),l.add(u),()=>{l?.delete(u)}}),o=!0,i=Cp(t,e);i.on(xe.MATCH_START,c=>r("matchStart",c)),i.on(xe.MATCH_ENDED,c=>r("matchEnded",c)),i.on(xe.MATCH_REQUEUE,()=>{o=!1}),i.on("disconnect",()=>{o=!1});let a=()=>o?Ar(i):null;return{get session(){return o?i:null},get matchmaking(){return S0(a(),{position:0,size:0},i.timeUntil)},on:s,eliminated(){bi(a(),le.MATCH_ELIMINATED,{})},score(c=1){bi(a(),le.MATCH_SCORE,{delta:c})},finish(){bi(a(),le.MATCH_FINISH,{})},retry(){},cancel(){i.leave(),o=!1}}}async function R0(t){let e=await Ja(t),n=await Dl(t.smoothing),r=Ks(await e.create(mi.MATCH,Op(t))),s=_0(r,{pose:t.pose,smoothing:t.smoothing,predict:n});return Object.defineProperty(s,"code",{value:r.roomId,enumerable:!0}),s}async function k0(t,e){let n=await Ja(e),r=await Dl(e.smoothing),s=Ks(await n.joinById(t,Op(e)));return _0(s,{pose:e.pose,smoothing:e.smoothing,predict:r})}var NA=2,Bl=ra;function LA(t){Bl=t??ra}function FA(t){let e=JSON.parse(t);if(!kn(e))throw new TypeError("genex bridge: options must be a JSON object");let n=typeof e.gameId=="string"?e.gameId:"";if(!n)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(kn(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 o=typeof e.controlTimeoutMs=="number"&&Number.isFinite(e.controlTimeoutMs)?e.controlTimeoutMs:void 0,i=e.smoothing==="genex"||e.smoothing==="predict"||kn(e.smoothing)?e.smoothing:void 0;return{gameId:n,name:typeof e.name=="string"&&e.name?e.name:void 0,urls:r,room:s,pose:e.pose===!0,smoothing:i,controlTimeoutMs:o,options:kn(e.options)?e.options:void 0}}var Ip=new Map,zA=1,Dp=t=>t.closed?null:t.mm?t.mm.session:t.session;function ec(t){t.closed=!0,t.connected=!1;for(let e of t.unwire.splice(0))e();t.wired=null,t.session=null,t.mm=null}function A0(t,e){if(t.wired===e)return;for(let i of t.unwire.splice(0))i();t.wired=e,t.connected=!0,t.lastConnected.clear(),t.lastMatch="";let n=Ar(e);t.sessionId=e.id,t.roomId=n.roomId;let r=t.unwire,s=i=>n.state?.players?.get(i)?.connected!==!1,o=i=>{let a=s(i),c=t.lastConnected.get(i);t.lastConnected.set(i,a),c!==void 0&&c!==a&&pe(t,{type:"playerConnection",id:i,connected:a})};pe(t,{type:"joined",sessionId:e.id}),n.state?.players?.forEach((i,a)=>{t.lastConnected.set(a,s(a)),pe(t,{type:"playerJoined",id:a})});for(let i of e.objects.ids())pe(t,{type:"objectChanged",id:i,owner:e.objects.get(i)?.owner??null});e.host!==void 0&&pe(t,{type:"hostChanged",host:e.host}),r.push(e.on("join",i=>{t.lastConnected.set(i,s(i)),pe(t,{type:"playerJoined",id:i})}),e.on("change",i=>{o(i),t.changed.has(i)||(t.changed.add(i),pe(t,{type:"playerChanged",id:i}))}),e.on("leave",i=>{t.lastConnected.delete(i),pe(t,{type:"playerLeft",id:i})}),e.on("host",i=>pe(t,{type:"hostChanged",host:i??null})),e.on("shared",(i,a)=>pe(t,{type:"sharedChanged",key:i,value:a??null})),e.on("object",i=>{let a=e.objects.get(i);pe(t,a?{type:"objectChanged",id:i,owner:a.owner??null}:{type:"objectRemoved",id:i})}),e.on("room:open",({open:i})=>pe(t,{type:"roomOpen",open:i})),e.on("reconnecting",({attempt:i,code:a})=>{t.connected=!1,pe(t,{type:"reconnecting",code:a,attempt:i})}),e.on("reconnected",()=>{t.connected=!0,pe(t,{type:"reconnected"})}),e.on("disconnect",i=>{t.connected=!1,t.opts.room!=="queue"&&(ec(t),pe(t,{type:"disconnected",code:i,reason:""}))}),e.on(xe.SERVER_RESTART,()=>pe(t,{type:"serverRestart"})),e.on(xe.MATCH_START,i=>pe(t,{type:"matchStart",roundId:kn(i)&&typeof i.roundId=="number"?i.roundId:0})),e.on(xe.MATCH_ENDED,i=>pe(t,{type:"matchEnded",data:i??null})),e.on(xe.MATCH_REQUEUE,i=>pe(t,{type:"matchRequeue",reason:kn(i)&&typeof i.reason=="string"?i.reason:null})),e.inputs.on((i,a)=>pe(t,{type:"input",from:i,data:a??null})),e.chat.on(i=>pe(t,{type:"chat",id:i.id,from:i.from,name:i.name,text:i.text,at:i.at})),n.onMessage(xe.RATE_DROP,i=>pe(t,{type:"rateDrop",dropped:kn(i)&&typeof i.dropped=="number"?i.dropped:0})),n.onMessage("*",(i,a)=>{typeof i=="string"&&!ns(i)&&pe(t,{type:"message",kind:i,data:a??null})}))}function Nl(t){let e=Dp(t);e&&e!==t.wired&&A0(t,e)}async function UA(t){let e=t.opts;if(await Bl.ready(e.gameId),t.closed)return;let n=e.urls.length?e.urls:Bl.urls();if(!n.length)throw Object.assign(new Error("genex bridge: no relay URL (pass urls, or run on a Genex page)"),{code:0});let r=()=>Bl.auth(),s={urls:n,room:e.gameId,name:e.name,auth:r,pose:e.pose,smoothing:e.smoothing};if(e.room==="play"){let a=await x0({...s,options:e.options});if(t.closed)return void a.leave();t.session=a,A0(t,a);return}let o=s,i=e.room==="queue"?await E0(o):e.room==="private"?await R0(o):await k0(e.room.joinById,o);if(t.closed)return void i.cancel();t.mm=i,i.on("queue",a=>{kn(a)&&pe(t,{type:"queue",position:Number(a.position)||0,size:Number(a.size)||0})}),i.on("matched",()=>{pe(t,{type:"seated"}),Nl(t)}),i.on("searching",()=>{if(t.wired){for(let a of t.unwire.splice(0))a();t.wired=null,t.connected=!1}}),i.on("error",a=>{let c=t.mm;ec(t),c?.cancel(),pe(t,{type:"joinFailed",code:No(a),message:Gn(a)})}),i.on("disconnect",a=>{ec(t),pe(t,{type:"disconnected",code:typeof a=="number"?a:0,reason:""})}),Nl(t)}function v0(t){let e=FA(t),n=zA++,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};Ip.set(n,r);let s=UA(r).catch(o=>{throw ec(r),pe(r,{type:"joinFailed",code:No(o),message:Gn(o)}),o});return{handle:n,done:s}}function VA(t){let{handle:e,done:n}=v0(t);return n.catch(()=>{}),e}async function HA(t){let{handle:e,done:n}=v0(t);try{await n}catch(r){let s=new Error(Gn(r));throw s.code=No(r),s}return e}var ss=t=>Ip.get(t),Tt=t=>{let e=ss(t);return e?(Nl(e),Dp(e)):null};function T0(t){let e=ss(t);if(!e||e.closed)return;let{mm:n,session:r}=e;ec(e),n?n.cancel():r?.leave(),pe(e,{type:"disconnected",code:4e3,reason:"left"})}function $A(t){T0(t),typeof t=="number"&&Ip.delete(t)}function jA(t,e){let n=Wn(e,"state"),r=Tt(t);return r?(r.me.set(n),!0):!1}function qA(t,e){let n=Wn(e,"state"),r=Tt(t);return r?(r.me.snap(n),!0):!1}function GA(t,e,n){let r=sa(n,"value");if(typeof e!="string"||!e||e.startsWith(Rl))return!1;let s=Tt(t);return s?(s.shared.set(e,r),!0):!1}function WA(t,e,n){let r=Wn(n,"object state"),s=Tt(t);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.set(e,r),!0)}function YA(t,e,n){let r=Wn(n,"object state"),s=Tt(t);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.snap(e,r),!0)}function KA(t,e,n){let r=sa(n,"event data");if(typeof e!="string"||!e||e.length>$t.MAX_EVENT_TYPE_CHARS||ns(e))return!1;let s=Tt(t);return s?(s.send(e,r),!0):!1}function XA(t,e){}function JA(t,e){let n=sa(e,"input"),r=Tt(t);return r?(r.inputs.send(n),!0):!1}function ZA(t,e){let n=Tt(t);return n?(n.setRoomOpen(e===!0),!0):!1}function QA(t,e){let n=Tt(t);return!n||typeof e!="string"?!1:(n.chat.send(e),!0)}function Ll(t,e,n,r,s=!1){if(typeof n!="string"||!n)throw new TypeError("genex bridge: object id must be a non-empty string");let o=ss(t),i=Tt(t),a=l=>{if(!o)return;let d={type:"controlResult",requestId:String(r),operation:e,id:n,accepted:l.accepted,owner:l.owner??null,sequence:l.sequence,reason:l.reason};typeof l.retryAfterMs=="number"&&(d.retryAfterMs=l.retryAfterMs),pe(o,d)};if(!i){a({accepted:!1,sequence:0,reason:"disconnected"});return}let c={timeoutMs:o?.opts.controlTimeoutMs,...s?{authority:"host"}:{}};(e==="claim"?i.objects.claimConfirmed(n,c):e==="release"?i.objects.releaseConfirmed(n,c):i.objects.removeConfirmed(n,c)).then(a,()=>a({accepted:!1,sequence:0,reason:"disconnected"}))}function ev(t,e,n){Ll(t,"claim",e,n)}function tv(t,e,n){Ll(t,"claim",e,n,!0)}function nv(t,e,n){Ll(t,"release",e,n)}function rv(t,e,n){Ll(t,"remove",e,n)}function sv(t){let e=ss(t);return!e?.mm||e.closed?!1:(e.mm.eliminated(),!0)}function ov(t,e=1){let n=ss(t);return!n?.mm||n.closed||typeof e!="number"||!Number.isFinite(e)?!1:(n.mm.score(e),!0)}function iv(t){let e=ss(t);return!e?.mm||e.closed?!1:(e.mm.finish(),!0)}function av(t){return Tt(t)?.serverNow()??null}function cv(t,e){let n=Tt(t);return n?n.timeUntil(e):e-Date.now()}var P0=t=>typeof t=="number"&&Number.isFinite(t)?t:null;function uv(t){let e=ss(t),n=Tt(t),r=n?Ar(n):null,s=r?.state?.match,o=null;if(s)try{o=JSON.parse(s)}catch{o=null}return JSON.stringify({sessionId:n?.id??e?.sessionId??"",roomId:r?.roomId??e?.roomId??"",hostId:n?.host??null,isHost:n?.isHost??!1,connected:!!n&&!!e?.connected,closed:!e||e.closed,serverNow:P0(n?.serverNow()),rtt:P0(n?.rtt),clockSynced:n?.clockSynced??!1,clockOrigin:r?.state?.clockOrigin??0,matchState:o})}function lv(t){let e=Tt(t);if(!e)return"[]";let n=Ar(e).state?.players,r=[];for(let[s,o]of e.players){let i=n?.get(s);r.push({id:s,name:o.name,uid:o.uid,team:o.team,connected:o.connected,avatarUrl:o.avatarUrl,state:o.state??{},stateRaw:o.stateRaw??{},epoch:i?.epoch??0,isMe:s===e.id,posed:i?.posed===!0})}return JSON.stringify(r)}function dv(t){let e=Tt(t);if(!e)return"[]";let n=Ar(e).state?.objects,r=[];for(let s of e.objects.ids()){let o=e.objects.get(s);o&&r.push({id:s,owner:o.owner??null,isMine:o.isMine,seq:n?.get(s)?.seq??0,epoch:o.epoch,state:o.state??null,stateRaw:o.stateRaw??null})}return JSON.stringify(r)}function fv(t){let e=Tt(t),n={};if(e)for(let r of e.shared.keys())n[r]=e.shared.get(r)??null;return JSON.stringify(n)}function pv(t){let e=ss(t);if(!e)return"[]";try{Nl(e);let n=Dp(e);if(n){let r=Ar(n).state?.match??"";if(r!==e.lastMatch){e.lastMatch=r;let s=null;try{s=r?JSON.parse(r):null}catch{s=null}pe(e,{type:"matchState",state:s})}}e.changed.clear()}catch(n){pe(e,Bo(Gn(n)))}return mu(e)}var Yh={};Fd(Yh,{BODY_F32_STRIDE:()=>jh,BodyF32Flag:()=>qh,authorityJson:()=>xI,bodiesF32:()=>bI,bodyKeysJson:()=>wI,closeAuthority:()=>kE,disposeAuthority:()=>_I,drainAuthorityEventsJson:()=>EI,frame:()=>yI,openAuthority:()=>dI,predictProjectile:()=>pI,setAuthorityIdentity:()=>QO,setAuthorityPhysicsCore:()=>eI,setInput:()=>fI,setWorld:()=>hI,version:()=>ZO});var M0=2*Math.PI,C0=Math.fround(Math.PI),Te=t=>t===0?0:t;function Ln(t){if(typeof t!="number"||!Number.isFinite(t))return 0;let e=t<-1?-1:t>1?1:t;return Te(Math.fround(e))}function os(t){if(typeof t!="number"||!Number.isFinite(t)||Math.abs(t)>1e9)return null;let e=Math.fround(t-M0*Math.floor((t+Math.PI)/M0));return e===C0?-C0:Te(e)}function Js(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<16777216?t:0}function Fl(t,e){return typeof t!="number"||!Number.isFinite(t)||t<=0?0:t>e?e:t}var sn=(t,e,n)=>t<e?e:t>n?n:t,O0=5734161139222659/2**53,I0=1686629713/2**30,D0=2242054355/2**65,B0=5376105825661043/2**121,N0=-6004799503160649/2**55,L0=0x8888888887c53/2**58,F0=-7320136532976085/2**65,z0=6506786730409597/2**71,U0=-7571127717829867/2**78,V0=0x5764e96b3f55f/2**83,H0=0x5555555555553/2**55,$0=-6405119470031223/2**62,j0=457508533350745/2**64,q0=-5205429506036397/2**74,G0=0x47ba7af6d2c71/2**79,W0=-0x63eba6fa20e35/2**87,FF=Object.freeze({invpio2:O0,pio2_1:I0,pio2_2:D0,pio2_2t:B0,S1:N0,S2:L0,S3:F0,S4:z0,S5:U0,S6:V0,C1:H0,C2:$0,C3:j0,C4:q0,C5:G0,C6:W0});function Dt(t){if(!Number.isFinite(t)||Math.abs(t)>1e9)return[0,1];let e=Math.floor(t*O0+.5),n=e-4*Math.floor(e/4),r=t-e*I0-e*D0-e*B0,s=r*r,o=r+s*r*(N0+s*(L0+s*(F0+s*(z0+s*(U0+s*V0))))),i=.5*s,a=1-i,c=a+(1-a-i+s*(s*(H0+s*($0+s*(j0+s*(q0+s*(G0+s*W0)))))));return n===0?[Te(o),Te(c)]:n===1?[Te(c),Te(-o)]:n===2?[Te(-o),Te(-c)]:[Te(-c),Te(o)]}var Y0=t=>Dt(t)[0],K0=t=>Dt(t)[1];var lr={TOPDOWN:"topdown",FIRSTPERSON:"firstperson",VEHICLE:"vehicle"},Up=.25,hv=Object.freeze({speed:6,arena:20}),mv={speed:{min:0,max:1e3,positive:!1},arena:{min:0,max:1e6,positive:!0}};var Vp=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.getPrototypeOf(t)===Object.prototype;function tw(t,e){if(e===void 0)return!0;let n=oc(t)?.ranges;return n===void 0||!Vp(e)?!1:Object.keys(e).every(r=>{if(!Object.hasOwn(n,r))return!1;let s=n[r],o=e[r];return typeof o!="number"||!Number.isFinite(o)||o<s.min||o>s.max||s.integer===!0&&!Number.isInteger(o)?!1:!s.positive||o>0&&Math.fround(o)>0})}function wi(t,e){let n=oc(t);if(n===void 0)return{};let r={...n.defaults};if(!Vp(e))return r;for(let s of Object.keys(n.ranges))tw(t,{[s]:e[s]})&&(r[s]=e[s]);return r}var Np=t=>Number.isFinite(t)?t:0;function yv(t,e,n,r){let s=Ln(e.moveX),o=Ln(e.moveY),i=Fl(n,Up),a=Math.sqrt(s*s+o*o),c=a>1?1/a:1,u=Np(t.x)+s*c*r.speed*i,l=Np(t.y)+o*c*r.speed*i;return{x:Te(Math.fround(sn(u,-r.arena,r.arena))),y:Te(Math.fround(sn(l,-r.arena,r.arena))),yaw:os(e.yaw)??Te(Math.fround(Np(t.yaw)))}}var nw=2615243109,gv=Object.freeze({maxSpeed:250,walkSpeed:.52,crouchSpeed:.34,accelerate:5.5,airAccelerate:12,airMaxWishSpeed:30,friction:5.2,stopSpeed:80,gravity:800,jumpImpulse:301.993,maxVelocity:3500,radius:16,standHeight:72,crouchHeight:54,duckTime:.4,stepHeight:18,standable:.7,groundTrace:2.5,groundSnap:1,skin:.03,pitchLimit:1.5533430576324463,jumpBit:1,duckBit:2,walkBit:4,substeps:2,world:nw}),Se=(t,e)=>({min:t,max:e,positive:!1}),Qs=t=>({min:0,max:t,positive:!0}),ur=(t,e)=>({min:t,max:e,positive:!1,integer:!0}),bv={maxSpeed:Se(0,1e4),walkSpeed:Se(0,1),crouchSpeed:Se(0,1),accelerate:Se(0,1e3),airAccelerate:Se(0,1e3),airMaxWishSpeed:Se(0,1e4),friction:Se(0,1e3),stopSpeed:Se(0,1e4),gravity:Se(0,1e5),jumpImpulse:Se(0,1e5),maxVelocity:Se(0,1e5),radius:Qs(1e4),standHeight:Qs(1e4),crouchHeight:Qs(1e4),duckTime:Qs(100),stepHeight:Se(0,1e4),standable:Se(0,1),groundTrace:Se(0,1e4),groundSnap:Se(0,1e4),skin:Se(0,100),pitchLimit:Se(0,1.5707963705062866),jumpBit:ur(0,16777215),duckBit:ur(0,16777215),walkBit:ur(0,16777215),substeps:ur(1,8),world:ur(0,2**32-1)};var Bt={ON_GROUND:1,DUCKING:2,JUMP_HELD:4},wv=Bt.ON_GROUND|Bt.DUCKING|Bt.JUMP_HELD,X0={MAX_BOXES:4096,MAX_RAMPS:512,MAX_ABS:1e9},on=class extends RangeError{constructor(n,r){super(`firstperson world: ${n} ${r}`);m(this,"path");this.name="WorldError",this.path=n}},tc=new WeakMap,xv=(t,e)=>{if(typeof t!="number"||!Number.isFinite(t))throw new on(e,"is not a finite number");if(Math.fround(t)!==t)throw new on(e,"is not a float32");if(Math.abs(t)>1e9)throw new on(e,`is past \xB1${1e9}`);return Te(t)};function J0(t,e,n){if(!Array.isArray(t)||t.length!==e)throw new on(n,`is not an array of ${e} numbers`);let r=[];for(let s=0;s<e;s++)r.push(xv(t[s],`${n}[${s}]`));if(!(r[0]<r[3]&&r[1]<r[4]&&r[2]<r[5]))throw new on(n,"needs min < max on every axis");return r}function Z0(t,e,n){if(t===void 0)return[];if(!Array.isArray(t))throw new on(e,"is not an array");if(t.length>n)throw new on(e,`holds more than ${n}`);return t}function Sv(t,e){let n=new DataView(new ArrayBuffer(8+4*(6*t.length+9*e.length)));n.setUint32(0,t.length,!0),n.setUint32(4,e.length,!0);let r=8;for(let o of[...t,...e])for(let i of o)n.setFloat32(r,i,!0),r+=4;let s=2166136261;for(let o=0;o<n.byteLength;o++)s=Math.imul(s^n.getUint8(o),16777619)>>>0;return s}function eo(t,e={}){let n=tc.has(t)?t:void 0;if(n!==void 0&&(e.broadphase===void 0||e.broadphase===n.broadphase))return n;if(t!==void 0&&!Vp(t))throw new on("$","is not an object");let r=t??{},s=Z0(r.boxes,"boxes",X0.MAX_BOXES).map((a,c)=>Object.freeze(J0(a,6,`boxes[${c}]`))),o=Z0(r.ramps,"ramps",X0.MAX_RAMPS).map((a,c)=>{let u=`ramps[${c}]`,l=J0(a,9,u);if(l[6]!==0&&l[6]!==1)throw new on(`${u}[6]`,"is not an axis (0 or 1)");let[d,f,h,p]=[l[2],l[5],l[7],l[8]];if(!(d<=h&&d<=p))throw new on(u,"needs minZ \u2264 lo and minZ \u2264 hi");if(f!==Math.max(h,p))throw new on(u,"needs maxZ = max(lo, hi)");return Object.freeze(l)}),i=Object.freeze({boxes:Object.freeze(s),ramps:Object.freeze(o),hash:Sv(s,o),broadphase:e.broadphase!==!1});return tc.set(i,Ev(i)),i}var rc=eo(void 0),Tr={Box:0,OBox:1,Disc:2},Fp=96,Hp=new Int32Array(Fp);function sc(t){let e=t.length;if(e>Fp)throw new RangeError(`posed solids: at most ${Fp} a tick`);let n=()=>new Float64Array(e),r={count:e,kind:new Uint8Array(e),minX:n(),minY:n(),minZ:n(),maxX:n(),maxY:n(),maxZ:n(),cx:n(),cy:n(),hx:n(),hy:n(),sin:n(),cos:n(),radius:n()};return t.forEach((s,o)=>{if(s.kind==="box"){r.kind[o]=Tr.Box,[r.minX[o],r.minY[o],r.minZ[o]]=s.min,[r.maxX[o],r.maxY[o],r.maxZ[o]]=s.max;return}if(r.cx[o]=s.c[0],r.cy[o]=s.c[1],r.minZ[o]=s.c[2]-(s.kind==="disc"?s.half:s.half[2]),r.maxZ[o]=s.c[2]+(s.kind==="disc"?s.half:s.half[2]),s.kind==="disc"){r.kind[o]=Tr.Disc,r.radius[o]=s.radius,r.minX[o]=s.c[0]-s.radius,r.maxX[o]=s.c[0]+s.radius,r.minY[o]=s.c[1]-s.radius,r.maxY[o]=s.c[1]+s.radius;return}r.kind[o]=Tr.OBox,r.hx[o]=s.half[0],r.hy[o]=s.half[1],r.sin[o]=s.sin,r.cos[o]=s.cos;let i=Math.abs(s.cos),a=Math.abs(s.sin),c=s.half[0]*i+s.half[1]*a,u=s.half[0]*a+s.half[1]*i;r.minX[o]=s.c[0]-c,r.maxX[o]=s.c[0]+c,r.minY[o]=s.c[1]-u,r.maxY[o]=s.c[1]+u}),r}var rw=sc([]);function $p(t){let e=tc.get(t);if(e!==void 0)return e;let n=eo(t,{broadphase:t.broadphase!==!1}),r=tc.get(n);return tc.set(t,r),r}var nc=8;function Ev(t){let e=[...t.boxes,...t.ramps],n=e.length,r=()=>new Float64Array(n),s={boxCount:t.boxes.length,count:n,minX:r(),minY:r(),minZ:r(),maxX:r(),maxY:r(),maxZ:r(),axis:new Uint8Array(n),lo:r(),hi:r(),m0:r(),span:r(),slope:r(),topZ:r()};return e.forEach((o,i)=>{if(s.minX[i]=o[0],s.minY[i]=o[1],s.minZ[i]=o[2],s.maxX[i]=o[3],s.maxY[i]=o[4],s.maxZ[i]=o[5],i<s.boxCount)return;let a=o[6],c=a===0?o[0]:o[1],l=(a===0?o[3]:o[4])-c,d=(o[8]-o[7])/l;s.axis[i]=a,s.lo[i]=o[7],s.hi[i]=o[8],s.m0[i]=c,s.span[i]=l,s.slope[i]=d,s.topZ[i]=1/Math.sqrt(1+d*d)}),{...s,tree:t.broadphase&&n>0?_v(s):null}}function Lp(t){let e=t&1023;return e=(e|e<<16)&50331903,e=(e|e<<8)&50393103,e=(e|e<<4)&51130563,e=(e|e<<2)&153391689,e}function _v(t){let e=t.count,n=1/0,r=1/0,s=1/0,o=-1/0,i=-1/0,a=-1/0;for(let b=0;b<e;b++)n=Math.min(n,t.minX[b]),r=Math.min(r,t.minY[b]),s=Math.min(s,t.minZ[b]),o=Math.max(o,t.maxX[b]),i=Math.max(i,t.maxY[b]),a=Math.max(a,t.maxZ[b]);let c=(b,S,_)=>_>S?Math.min(1023,Math.floor((b-S)/(_-S)*1024)):0,u=new Float64Array(e);for(let b=0;b<e;b++){let S=c((t.minX[b]+t.maxX[b])/2,n,o),_=c((t.minY[b]+t.maxY[b])/2,r,i),P=c((t.minZ[b]+t.maxZ[b])/2,s,a);u[b]=(Lp(S)|Lp(_)<<1|Lp(P)<<2)*8192+b}u.sort();let l=[e];for(;l[l.length-1]>1;)l.push(Math.ceil(l[l.length-1]/nc));let d=l.reduce((b,S)=>b+S,0),f=new Float64Array(d*6),h=new Int32Array(d),p=new Int32Array(l.length);for(let b=0;b<e;b++){let S=u[b]%8192,_=b*6;f[_]=t.minX[S],f[_+1]=t.minY[S],f[_+2]=t.minZ[S],f[_+3]=t.maxX[S],f[_+4]=t.maxY[S],f[_+5]=t.maxZ[S],h[b]=S}p[0]=e;let g=0,x=e;for(let b=1;b<l.length;b++){let S=p[b-1];for(let _=g;_<S;_+=nc){let P=Math.min(_+nc,S),R=1/0,v=1/0,M=1/0,O=-1/0,z=-1/0,X=-1/0;for(let Y=_;Y<P;Y++){let he=Y*6;R=Math.min(R,f[he]),v=Math.min(v,f[he+1]),M=Math.min(M,f[he+2]),O=Math.max(O,f[he+3]),z=Math.max(z,f[he+4]),X=Math.max(X,f[he+5])}let N=x*6;f[N]=R,f[N+1]=v,f[N+2]=M,f[N+3]=O,f[N+4]=z,f[N+5]=X,h[x]=_,x++}g=S,p[b]=x}return{boxes:f,ref:h,levelEnd:p,root:d-1}}var sw=(t,e,n,r,s,o)=>.001+1e-7*(Math.abs(t)+Math.abs(e)+Math.abs(n)+Math.abs(r)+Math.abs(s)+Math.abs(o));function jp(t,e,n,r,s,o,i){Rv(t,e,n,r,s,o,i);let a=t.w.tree;if(a===null){t.nCand=-1;return}let c=sw(e,n,r,s,o,i),u=t.r+c,l=e-u,d=s+u,f=n-u,h=o+u,p=r-c,g=i+c,{boxes:x,ref:b,levelEnd:S}=a,_=S[0],P=t.cand,R=t.stack,v=0,M=0;for(R[M++]=a.root;M>0;){let O=R[--M],z=O*6;if(x[z+3]<l||x[z]>d||x[z+4]<f||x[z+1]>h||x[z+5]<p||x[z+2]>g)continue;if(O<_){P[v++]=b[O];continue}let X=b[O],N=X+nc;for(let Y=0;Y<S.length;Y++)if(X<S[Y]){N=Math.min(N,S[Y]);break}for(let Y=X;Y<N;Y++)R[M++]=Y}t.nCand=v}function Rv(t,e,n,r,s,o,i){let a=t.p,c=0;if(a.count>0){let u=sw(e,n,r,s,o,i),l=t.r+u,d=e-l,f=s+l,h=n-l,p=o+l,g=r-u,x=i+u;for(let b=0;b<a.count;b++)a.maxX[b]<d||a.minX[b]>f||a.maxY[b]<h||a.minY[b]>p||a.maxZ[b]<g||a.minZ[b]>x||(t.pc[c++]=b)}t.nPosed=c}var qp=t=>(t.nCand<0?t.w.count:t.nCand)+t.nPosed,Gp=(t,e)=>{let n=t.nCand<0?t.w.count:t.nCand;return e>=n?t.w.count+t.pc[e-n]:t.nCand<0?e:t.cand[e]},vr=(t,e)=>t.standHeight+(t.crouchHeight-t.standHeight)*e;function kv(t,e,n,r){let s=t.w,o=s.slope[e],i=s.axis[e]===0?n:r,a=o>0?i+t.r:o<0?i-t.r:i;return s.lo[e]+o*sn(a-s.m0[e],0,s.span[e])}function ow(t,e,n,r){let s=t.w;return e<s.boxCount?s.maxZ[e]:e<s.count?kv(t,e,n,r):t.p.maxZ[e-s.count]}var Pv=(t,e)=>e<t.w.count?t.w.minZ[e]:t.p.minZ[e-t.w.count];function iw(t,e,n,r){let s=t.w,o=t.r;return e>=s.count?dw(t,e-s.count,n,r):n+o>s.minX[e]&&n-o<s.maxX[e]&&r+o>s.minY[e]&&r-o<s.maxY[e]}function aw(t,e,n,r,s){let o=t.w;jp(t,e,n,r,e,n,r+s);let i=qp(t);for(let a=0;a<i;a++){let c=Gp(t,a);if(!iw(t,c,e,n)||!(r+s>Pv(t,c)))continue;let u=ow(t,c,e,n);if(r<u-1e-4)return!1}return!0}function jl(t,e,n,r,s,o){let i=t.w;jp(t,e,n,r-s,e,n,r+o);let a=qp(t),c=Number.NaN,u=Number.NaN;for(let l=0;l<a;l++){let d=Gp(t,l);if(!iw(t,d,e,n))continue;let f=ow(t,d,e,n);f<=r+o&&f>=r-s&&(d<i.boxCount||d>=i.count||i.topZ[d]>=t.standable?(c!==c||f>c)&&(c=f):(u!==u||f>u)&&(u=f))}return u>c?Number.NaN:c}function Vl(t){if(t.vz>.1){t.onGround=!1;return}let e=jl(t,t.x,t.y,t.z,t.groundTrace,t.groundSnap);e===e?(t.z=e,t.onGround=!0):t.onGround=!1}function Ul(t,e,n,r,s,o){if(Math.abs(n)<1e-9)return e>r&&e<s;let i=(r-e)/n,a=(s-e)/n,c=-1;if(i>a){let u=i;i=a,a=u,c=1}return i>=t.tMin&&(t.tMin=i,t.ax=o,t.sg=c),a<t.tMax&&(t.tMax=a),!(t.tMin>t.tMax)}var Ke=new Float64Array(4);function Av(t,e,n,r){let s=t.w,o=t.r,i=0,a=0,c=0,u;switch(n){case 0:i=1,u=s.maxX[e]+o;break;case 1:i=-1,u=-s.minX[e]+o;break;case 2:a=1,u=s.maxY[e]+o;break;case 3:a=-1,u=-s.minY[e]+o;break;case 4:c=-1,u=-s.minZ[e]+r;break;case 5:{let l=s.slope[e];s.axis[e]===0?i=-l:a=-l,c=1,u=s.lo[e]-l*s.m0[e]+o*Math.abs(l);break}default:c=1,u=s.maxZ[e]}Ke[0]=i,Ke[1]=a,Ke[2]=c,Ke[3]=u}function Hl(t,e,n,r,s,o){let i=t.w,a=t.r,c=t.skin;if(s>=i.count)return Ov(t,e,n,r,s-i.count,o);if(s<i.boxCount)return e-(i.minX[s]-a)>c&&i.maxX[s]+a-e>c&&n-(i.minY[s]-a)>c&&i.maxY[s]+a-n>c&&r-(i.minZ[s]-o)>c&&i.maxZ[s]-r>c;for(let u=0;u<7;u++){Av(t,s,u,o);let l=Ke[0],d=Ke[1],f=Ke[2];if(!(-(l*e+d*n+f*r-Ke[3])*(1/Math.sqrt(l*l+d*d+f*f))>c))return!1}return!0}function Wp(t,e,n,r,s,o,i,a,c){let u=t.w.count+t.p.count;for(let l=0;l<u;l++)if(l!==a&&Hl(t,e,n,r,l,c)&&!Hl(t,s,o,i,l,c))return!0;return!1}function cw(t,e,n,r,s,o,i,a,c,u){return Wp(t,e+s*a,n+o*a,r+i*a,e,n,r,c,u)}function vv(t,e,n,r,s,o,i,a){let c=t.r,u=t.skin,l=e-(s.minX[o]-c),d=s.maxX[o]+c-e,f=n-(s.minY[o]-c),h=s.maxY[o]+c-n,p=r-(s.minZ[o]-i),g=s.maxZ[o]-r;if(!(l>u&&d>u&&f>u&&h>u&&p>u&&g>u))return!1;let x=l,b=-1,S=0,_=0;return d<x&&([x,b,S,_]=[d,1,0,0]),f<x&&([x,b,S,_]=[f,0,-1,0]),h<x&&([x,b,S,_]=[h,0,1,0]),g<x&&!Wp(t,e,n,r+g,e,n,r,a,i)&&([x,b,S,_]=[g,0,0,1]),t.tMin=0,t.nx=b,t.ny=S,t.nz=_,t.depth=x,!0}function Yp(t,e,n,r,s,o,i,a,c,u=t.w,l=a){let d=t.r;return t.depth=0,vv(t,e,n,r,u,a,c,l)?!0:(t.tMin=0,t.tMax=1,t.ax=-1,t.sg=0,!Ul(t,e,s,u.minX[a]-d,u.maxX[a]+d,0)||!Ul(t,n,o,u.minY[a]-d,u.maxY[a]+d,1)||!Ul(t,r,i,u.minZ[a]-c,u.maxZ[a],2)||t.tMin>=1||t.ax<0?!1:(t.nx=t.ax===0?t.sg:0,t.ny=t.ax===1?t.sg:0,t.nz=t.ax===2?t.sg:0,!0))}function Tv(t,e,n,r,s,o,i,a,c){let u=t.w,l=t.r,d=u.slope[a],f=u.axis[a]===0,h=0,p=1,g=!1,x=!0,b=Number.POSITIVE_INFINITY,S=0,_=0,P=0;t.depth=0;for(let R=0;R<7;R++){let v=0,M=0,O=0,z;switch(R){case 0:v=1,z=u.maxX[a]+l;break;case 1:v=-1,z=-u.minX[a]+l;break;case 2:M=1,z=u.maxY[a]+l;break;case 3:M=-1,z=-u.minY[a]+l;break;case 4:O=-1,z=-u.minZ[a]+c;break;case 5:f?v=-d:M=-d,O=1,z=u.lo[a]-d*u.m0[a]+l*Math.abs(d);break;default:O=1,z=u.maxZ[a]}let X=v*e+M*n+O*r-z,N=v*s+M*o+O*i,Y=1/Math.sqrt(v*v+M*M+O*O),he=-X*Y;if(he>t.skin?R!==4&&he<b&&!(x&&R>=5&&cw(t,e,n,r,v*Y,M*Y,O*Y,he,a,c))&&(b=he,S=v*Y,_=M*Y,P=O*Y):x=!1,Math.abs(N)<1e-9){if(X>0)return!1;continue}let A=N<0&&X<=0&&X>-t.skin?0:-X/N;if(N<0?A>=h&&(h=A,t.nx=v*Y,t.ny=M*Y,t.nz=O*Y,g=!0):p=Math.min(p,A),h>p)return!1}return x?(t.tMin=0,t.nx=S,t.ny=_,t.nz=P,t.depth=b,!0):!g||!(h<1)||!(p>=0)?!1:(t.tMin=h,!0)}function uw(t,e,n,r){let s=t.p,o=s.cos[e],i=s.sin[e],a=s.cx[e],c=s.cy[e],u=s.hx[e],l=s.hy[e],d=t.r,f=d*(Math.abs(o)+Math.abs(i)),h=0,p=0,g=0,x;switch(n){case 0:h=o,p=i,x=o*a+i*c+u+f;break;case 1:h=-o,p=-i,x=-(o*a+i*c)+u+f;break;case 2:h=-i,p=o,x=-i*a+o*c+l+f;break;case 3:h=i,p=-o,x=i*a-o*c+l+f;break;case 4:h=1,x=a+d+u*Math.abs(o)+l*Math.abs(i);break;case 5:h=-1,x=-a+d+u*Math.abs(o)+l*Math.abs(i);break;case 6:p=1,x=c+d+u*Math.abs(i)+l*Math.abs(o);break;case 7:p=-1,x=-c+d+u*Math.abs(i)+l*Math.abs(o);break;case 8:g=-1,x=-s.minZ[e]+r;break;default:g=1,x=s.maxZ[e]}Ke[0]=h,Ke[1]=p,Ke[2]=g,Ke[3]=x}var Mv=10,lw=8,Cv=9;function dw(t,e,n,r){let s=t.p,o=t.r;if(!(n+o>s.minX[e]&&n-o<s.maxX[e]&&r+o>s.minY[e]&&r-o<s.maxY[e]))return!1;let i=s.kind[e];if(i===Tr.Box)return!0;let a=n-s.cx[e],c=r-s.cy[e];if(i===Tr.Disc){let f=Math.max(Math.abs(a)-o,0),h=Math.max(Math.abs(c)-o,0);return f*f+h*h<s.radius[e]*s.radius[e]}let u=s.cos[e],l=s.sin[e],d=o*(Math.abs(u)+Math.abs(l));return Math.abs(u*a+l*c)<s.hx[e]+d&&Math.abs(-l*a+u*c)<s.hy[e]+d}function fw(t,e,n,r){let s=t.p,o=t.r,i=n-s.cx[e],a=r-s.cy[e],c=Math.abs(i),u=Math.abs(a),l=s.radius[e];if(c<=o&&u<=o){let p=c>=u;return Ke[0]=p?i<0?-1:1:0,Ke[1]=p?0:a<0?-1:1,l+o-(p?c:u)}let d=c>o?i<0?-(c-o):c-o:0,f=u>o?a<0?-(u-o):u-o:0,h=Math.sqrt(d*d+f*f);return Ke[0]=d/h,Ke[1]=f/h,l-h}function Ov(t,e,n,r,s,o){let i=t.p,a=t.skin,c=i.kind[s];if(c===Tr.Box){let u=t.r;return e-(i.minX[s]-u)>a&&i.maxX[s]+u-e>a&&n-(i.minY[s]-u)>a&&i.maxY[s]+u-n>a&&r-(i.minZ[s]-o)>a&&i.maxZ[s]-r>a}if(!(r-(i.minZ[s]-o)>a&&i.maxZ[s]-r>a))return!1;if(c===Tr.Disc)return fw(t,s,e,n)>a;for(let u=0;u<lw;u++){uw(t,s,u,o);let l=Ke[0],d=Ke[1];if(!(-(l*e+d*n-Ke[3])*(1/Math.sqrt(l*l+d*d))>a))return!1}return!0}function Iv(t,e,n,r,s,o,i,a,c,u){let l=0,d=1,f=!1,h=!0,p=Number.POSITIVE_INFINITY,g=0,x=0,b=0;t.depth=0;for(let S=0;S<Mv;S++){uw(t,a,S,u);let _=Ke[0],P=Ke[1],R=Ke[2],v=_*e+P*n+R*r-Ke[3],M=_*s+P*o+R*i,O=1/Math.sqrt(_*_+P*P+R*R),z=-v*O;if(z>t.skin?S!==lw&&z<p&&!(h&&S===Cv&&cw(t,e,n,r,_*O,P*O,R*O,z,c,u))&&(p=z,g=_*O,x=P*O,b=R*O):h=!1,Math.abs(M)<1e-9){if(v>0)return!1;continue}let X=M<0&&v<=0&&v>-t.skin?0:-v/M;if(M<0?X>=l&&(l=X,t.nx=_*O,t.ny=P*O,t.nz=R*O,f=!0):d=Math.min(d,X),l>d)return!1}return h?(t.tMin=0,t.nx=g,t.ny=x,t.nz=b,t.depth=p,!0):!f||!(l<1)||!(d>=0)?!1:(t.tMin=l,!0)}function Dv(t,e,n,r,s,o,i,a,c,u,l,d){t.tMin=0,t.tMax=1,t.ax=-1,t.sg=0;let f=e-a,h=n-c,p=s*s+o*o,g=f*f+h*h-u*u;if(p<1e-18){if(!(g<0))return!1}else{let x=f*s+h*o,b=x*x-p*g;if(b<0)return!1;let S=Math.sqrt(b),_=(-x-S)/p,P=(-x+S)/p;if(_>=t.tMin&&(t.tMin=_,t.ax=3),P<t.tMax&&(t.tMax=P),t.tMin>t.tMax)return!1}if(!Ul(t,r,i,l,d,2)||t.tMin>=1||t.ax<0)return!1;if(t.ax===3){let x=f+s*t.tMin,b=h+o*t.tMin,S=Math.sqrt(x*x+b*b);t.nx=x/S,t.ny=b/S,t.nz=0}else t.nx=0,t.ny=0,t.nz=t.sg;return!0}var Fn={minX:new Float64Array(2),minY:new Float64Array(2),minZ:new Float64Array(2),maxX:new Float64Array(2),maxY:new Float64Array(2),maxZ:new Float64Array(2)};function Bv(t,e,n,r,s,o,i,a,c,u){let l=t.p,d=t.r,f=l.radius[a],h=l.cx[a],p=l.cy[a],g=l.minZ[a]-u,x=l.maxZ[a];t.depth=0;let b=fw(t,a,e,n),S=r-g,_=x-r;if(b>t.skin&&S>t.skin&&_>t.skin)return t.tMin=0,_<b&&!Wp(t,e,n,r+_,e,n,r,c,u)?[t.nx,t.ny,t.nz,t.depth]=[0,0,1,_]:[t.nx,t.ny,t.nz,t.depth]=[Ke[0],Ke[1],0,b],!0;let P=!1,R=0,v=0,M=0,O=0;Fn.minX[0]=h-f,Fn.maxX[0]=h+f,Fn.minY[0]=p,Fn.maxY[0]=p,Fn.minX[1]=h,Fn.maxX[1]=h,Fn.minY[1]=p-f,Fn.maxY[1]=p+f;for(let z=0;z<2;z++)Fn.minZ[z]=l.minZ[a],Fn.maxZ[z]=x,Yp(t,e,n,r,s,o,i,z,u,Fn,c)&&(!P||t.tMin<R)&&(P=!0,R=t.tMin,v=t.nx,M=t.ny,O=t.nz);for(let z=0;z<4;z++){let X=z%2===0?h-d:h+d,N=z<2?p-d:p+d;Dv(t,e,n,r,s,o,i,X,N,f,g,x)&&(!P||t.tMin<R)&&(P=!0,R=t.tMin,v=t.nx,M=t.ny,O=t.nz)}return P?(t.tMin=R,t.nx=v,t.ny=M,t.nz=O,t.depth=0,!0):!1}function Nv(t,e,n,r,s,o,i,a,c){let u=a-t.w.count,l=t.p.kind[u];return l===Tr.Box?Yp(t,e,n,r,s,o,i,u,c,t.p,a):l===Tr.OBox?Iv(t,e,n,r,s,o,i,u,a,c):Bv(t,e,n,r,s,o,i,u,a,c)}function Kp(t,e,n,r,s,o,i){let a=t.w,c=vr(t,t.duck),u=e+s,l=n+o,d=r+i;jp(t,e<u?e:u,n<l?n:l,r<d?r:d,e<u?u:e,n<l?l:n,(r<d?d:r)+c);let f=qp(t),h=!1,p=0,g=0,x=0,b=0,S=0,_=0;for(let P=0;P<f;P++){let R=Gp(t,P);(R<a.boxCount?Yp(t,e,n,r,s,o,i,R,c):R<a.count?Tv(t,e,n,r,s,o,i,R,c):Nv(t,e,n,r,s,o,i,R,c))&&(!h||t.tMin<p||t.tMin===p&&R<g)&&(h=!0,p=t.tMin,g=R,x=t.nx,b=t.ny,S=t.nz,_=t.depth)}t.hit=h,h?(t.tMin=Math.max(0,p-1e-4),t.nx=x,t.ny=b,t.nz=S,t.depth=_):(t.tMin=1,t.depth=0)}function $l(t,e,n=!1){let r=e,s=!1,o=0,i=0,a=0;for(let c=0;c<4&&r>1e-6;c++){if(t.vx*t.vx+t.vy*t.vy+t.vz*t.vz<1e-8)return;Kp(t,t.x,t.y,t.z,t.vx*r,t.vy*r,t.vz*r);let u=t.tMin;if(u>0){let g=u*r;t.x=t.x+t.vx*g,t.y=t.y+t.vy*g,t.z=t.z+t.vz*g,r=r-g}if(!t.hit)return;t.depth>0&&(t.x=t.x+t.nx*t.depth,t.y=t.y+t.ny*t.depth,t.z=t.z+t.nz*t.depth);let l=t.nx,d=t.ny,f=t.nz,h=!1;if(n&&f>0)if(f>=t.standable)h=!0;else{let g=1/Math.sqrt(l*l+d*d);l=l*g,d=d*g,f=0}t.x=t.x+l*t.skin,t.y=t.y+d*t.skin,t.z=t.z+f*t.skin;let p=t.vx*l+t.vy*d+t.vz*f;if(p<0&&(h?t.vz=t.vz-p/f:(t.vx=t.vx+l*-p,t.vy=t.vy+d*-p,t.vz=t.vz+f*-p)),s){let g=i*f-a*d,x=a*l-o*f,b=o*d-i*l,S=g*g+x*x+b*b;if(S>1e-6){let _=1/Math.sqrt(S);g=g*_,x=x*_,b=b*_;let P=t.vx*g+t.vy*x+t.vz*b;t.vx=g*P,t.vy=x*P,t.vz=b*P}}if(s=!0,o=l,i=d,a=f,t.vx*t.vx+t.vy*t.vy+t.vz*t.vz<1e-8)return}}function pw(t,e=!1){let n=t.x,r=t.y,s=t.z,o=t.vx,i=t.vy,a=t.vz;$l(t,t.h,e);let c=t.x,u=t.y,l=t.z,d=t.vx,f=t.vy,h=t.vz,p=c-n,g=u-r,x=p*p+g*g;t.x=n,t.y=r,t.z=s,t.vx=o,t.vy=i,t.vz=a;let b=t.stepHeight+t.skin;Kp(t,n,r,s,0,0,b);let S=t.tMin,_=s+b*S;if(S>0&&aw(t,n,r,_,vr(t,t.duck))){t.z=_,$l(t,t.h,e);let P=jl(t,t.x,t.y,t.z,t.stepHeight*2,.001);P===P&&(t.z=P);let R=t.x-n,v=t.y-r,M=R*R+v*v;if(P===P&&M>x+.001){t.vz=0;return}}t.x=c,t.y=u,t.z=l,t.vx=d,t.vy=f,t.vz=h}function hw(t){let e=jl(t,t.x,t.y,t.z,t.stepHeight,t.groundSnap);e===e&&(t.z=e,t.vz=0)}function Lv(t){let e=Math.sqrt(t.vx*t.vx+t.vy*t.vy);if(e<.1){t.vx=0,t.vy=0;return}let r=(e<t.stopSpeed?t.stopSpeed:e)*t.friction*t.h,s=Math.max(0,e-r)/e;t.vx=t.vx*s,t.vy=t.vy*s}function Fv(t){let e=t.wishSpeed-(t.vx*t.dirX+t.vy*t.dirY);if(e<=0)return;let n=t.accelerate*t.h*Math.max(t.wishSpeed,t.maxSpeed);n>e&&(n=e),t.vx=t.vx+n*t.dirX,t.vy=t.vy+n*t.dirY}function Q0(t){let e=Math.min(t.wishSpeed,t.airMaxWishSpeed)-(t.vx*t.dirX+t.vy*t.dirY);if(e<=0)return;let n=t.airAccelerate*t.wishSpeed*t.h;n>e&&(n=e),t.vx=t.vx+n*t.dirX,t.vy=t.vy+n*t.dirY}var bn=t=>Te(Math.fround(sn(t,-1e9,1e9)));function zv(t,e,n){let r=t.h/t.duckTime;if(e){let a=Math.min(1,t.duck+r);t.onGround||(t.z=t.z+(vr(t,t.duck)-vr(t,a))),t.duck=a,t.ducking=!0}else if(t.duck>0){let a=Math.max(0,t.duck-r),c=t.onGround?t.z:t.z-(vr(t,a)-vr(t,t.duck));aw(t,t.x,t.y,c,vr(t,a))&&(t.duck=a,t.z=c,t.duck===0&&(t.ducking=!1))}let s=t.onGround;Vl(t),t.onGround&&!s&&(t.vz=0),t.base=t.maxSpeed*t.cap;let o=t.ducking?t.base*t.crouchSpeed:n?t.base*t.walkSpeed:t.base;t.wishSpeed=t.amount*o,t.onGround?t.pressed?(t.vz=t.jumpImpulse,t.onGround=!1,t.pressed=!1,Q0(t)):(Lv(t),Fv(t),t.vz=0):Q0(t);let i=!t.onGround;i&&(t.vz=t.vz-t.gravity*t.h*.5),t.vx=sn(t.vx,-t.maxVelocity,t.maxVelocity),t.vy=sn(t.vy,-t.maxVelocity,t.maxVelocity),t.vz=sn(t.vz,-t.maxVelocity,t.maxVelocity),t.onGround?(pw(t),hw(t)):$l(t,t.h),Vl(t),i&&!t.onGround?t.vz=t.vz-t.gravity*t.h*.5:t.onGround&&(t.vz=0),t.x=bn(t.x),t.y=bn(t.y),t.z=bn(t.z),t.vx=bn(t.vx),t.vy=bn(t.vy),t.vz=bn(t.vz),t.duck=Te(Math.fround(t.duck))}var xt=(t,e,n,r)=>Te(Math.fround(sn(typeof t=="number"&&Number.isFinite(t)?t:e,n,r))),zp=t=>Te(Math.fround(typeof t=="number"&&Number.isFinite(t)?t:0)),zl={cand:new Int32Array(0),stack:new Int32Array(nc*16)};function Xp(t){return zl.cand.length<t.count&&(zl={cand:new Int32Array(t.count),stack:zl.stack}),zl}function mw(t,e,n=rc){let r=$p(n),s=Math.fround,o=a=>s(t==="vehicle"?e.height:e[a]),i=(a,c)=>{let u=Xp(r);return{w:r,p:sc(c),r:s(e.radius),standHeight:o("standHeight"),crouchHeight:o("crouchHeight"),stepHeight:s(e.stepHeight),standable:s(e.standable),groundTrace:s(e.groundTrace),groundSnap:s(e.groundSnap),skin:s(e.skin),x:a.x,y:a.y,z:a.z,vx:0,vy:0,vz:a.vz??0,duck:t==="vehicle"?0:a.duck??0,onGround:!1,h:0,tMin:0,tMax:0,ax:-1,sg:0,nx:0,ny:0,nz:0,hit:!1,depth:0,cand:u.cand,nCand:-1,pc:Hp,nPosed:0,stack:u.stack}};return{support(a,c){let u=i(a,c);if(u.vz>.1)return-1;let l=jl(u,u.x,u.y,u.z,u.groundTrace,u.groundSnap);if(l!==l)return-1;for(let d=0;d<u.p.count;d++)if(u.p.maxZ[d]===l&&dw(u,d,u.x,u.y))return d;return-1},inside(a,c,u){let l=i(a,c);return Hl(l,l.x,l.y,l.z,r.count+u,vr(l,l.duck))},pushOut(a,c){let u=i(a,c);for(let f=0;f<4&&(Kp(u,u.x,u.y,u.z,0,0,0),!!u.hit);f++)u.x=u.x+u.nx*u.depth,u.y=u.y+u.ny*u.depth,u.z=u.z+u.nz*u.depth,u.x=u.x+u.nx*u.skin,u.y=u.y+u.ny*u.skin,u.z=u.z+u.nz*u.skin;let l=vr(u,u.duck),d=!1;for(let f=0;f<r.count+u.p.count&&!d;f++)d=Hl(u,u.x,u.y,u.z,f,l);return{x:u.x,y:u.y,z:u.z,inside:d}}}}function Uv(t,e,n,r,s=rc,o=rw){let i=$p(s),a=Xp(i),c=Math.fround,u=Js(t.mstate)&wv,l={w:i,p:o,maxSpeed:c(r.maxSpeed),walkSpeed:c(r.walkSpeed),crouchSpeed:c(r.crouchSpeed),accelerate:c(r.accelerate),airAccelerate:c(r.airAccelerate),airMaxWishSpeed:c(r.airMaxWishSpeed),friction:c(r.friction),stopSpeed:c(r.stopSpeed),gravity:c(r.gravity),jumpImpulse:c(r.jumpImpulse),maxVelocity:c(r.maxVelocity),r:c(r.radius),standHeight:c(r.standHeight),crouchHeight:c(r.crouchHeight),duckTime:c(r.duckTime),stepHeight:c(r.stepHeight),standable:c(r.standable),groundTrace:c(r.groundTrace),groundSnap:c(r.groundSnap),skin:c(r.skin),x:xt(t.x,0,-1e9,1e9),y:xt(t.y,0,-1e9,1e9),z:xt(t.z,0,-1e9,1e9),vx:xt(t.vx,0,-1e9,1e9),vy:xt(t.vy,0,-1e9,1e9),vz:xt(t.vz,0,-1e9,1e9),duck:xt(t.duck,0,0,1),cap:xt(t.cap,1,0,4),onGround:(u&Bt.ON_GROUND)!==0,ducking:(u&Bt.DUCKING)!==0,jumpHeld:(u&Bt.JUMP_HELD)!==0,pressed:!1,h:0,dirX:0,dirY:0,amount:0,base:0,wishSpeed:0,tMin:0,tMax:0,ax:-1,sg:0,nx:0,ny:0,nz:0,hit:!1,depth:0,cand:a.cand,nCand:-1,pc:Hp,nPosed:0,stack:a.stack},d=Ln(e.moveX),f=Ln(e.moveY),h=Math.sqrt(d*d+f*f);h>1e-4&&(l.dirX=d/h,l.dirY=f/h,l.amount=Math.min(h,1));let p=Js(e.buttons),g=(p&r.jumpBit)!==0,x=(p&r.duckBit)!==0,b=(p&r.walkBit)!==0,S=Fl(n,Up);l.h=S/r.substeps;let _=os(e.yaw)??zp(t.yaw),P=c(r.pitchLimit),R=Te(sn(os(e.pitch)??zp(t.pitch),-P,P));if(S>0){l.pressed=g&&!l.jumpHeld,l.jumpHeld=g;for(let v=0;v<r.substeps;v++)zv(l,x,b)}return{x:l.x,y:l.y,z:l.z,vx:l.vx,vy:l.vy,vz:l.vz,yaw:_,pitch:R,duck:l.duck,mstate:(l.onGround?Bt.ON_GROUND:0)+(l.ducking?Bt.DUCKING:0)+(l.jumpHeld?Bt.JUMP_HELD:0)}}var Vv=Object.freeze({maxSpeed:1410,accel:1e3,brake:3500,coast:525,boostAccel:1e3,boostMaxSpeed:2300,boostBurn:.3333333432674408,grip:6e3,driftGrip:1500,turnRate:2.2,turnSpeed:400,spinAccel:30,airTurnRate:5.5,airSpinAccel:9,gravity:650,jumpImpulse:450,maxVelocity:6e3,radius:50,height:36,stepHeight:8,standable:.7,groundTrace:4,groundSnap:2,skin:.03,jumpBit:1,boostBit:2,driftBit:4,substeps:2,world:nw}),Hv={maxSpeed:Se(0,1e5),accel:Se(0,1e5),brake:Se(0,1e5),coast:Se(0,1e5),boostAccel:Se(0,1e5),boostMaxSpeed:Se(0,1e5),boostBurn:Se(0,1e3),grip:Se(0,1e5),driftGrip:Se(0,1e5),turnRate:Se(0,100),turnSpeed:Qs(1e5),spinAccel:Se(0,1e4),airTurnRate:Se(0,100),airSpinAccel:Se(0,1e4),gravity:Se(0,1e5),jumpImpulse:Se(0,1e5),maxVelocity:Se(0,1e5),radius:Qs(1e4),height:Qs(1e4),stepHeight:Se(0,1e4),standable:Se(0,1),groundTrace:Se(0,1e4),groundSnap:Se(0,1e4),skin:Se(0,100),jumpBit:ur(0,16777215),boostBit:ur(0,16777215),driftBit:ur(0,16777215),substeps:ur(1,8),world:ur(0,2**32-1)};var $v=Bt.ON_GROUND|Bt.JUMP_HELD,Zs=(t,e,n)=>t<e?Math.min(e,t+n):t>e?Math.max(e,t-n):t,yw=t=>os(t)??0;function jv(t){let e=t.maxSpeed*t.cap,n=t.boosting?1:t.throttle,r=n*e,s=t.f;if(n===0?s=Zs(s,0,t.coast*t.h):n>0&&s<0||n<0&&s>0?s=Zs(s,0,t.brake*t.h):Math.abs(s)<Math.abs(r)?s=Zs(s,r,t.accel*t.h):t.boosting||(s=Zs(s,r,t.coast*t.h)),t.boosting){let a=t.boostMaxSpeed*t.cap;s<a&&(s=Math.min(a,s+t.boostAccel*t.h))}let o=Zs(t.l,0,(t.drift?t.driftGrip:t.grip)*t.h),i=t.steer*t.turnRate*Math.min(1,Math.abs(s)/t.turnSpeed);s<0&&(i=-i),t.spin=Zs(t.spin,i,t.spinAccel*t.h),t.vx=s*t.c-o*t.s,t.vy=s*t.s+o*t.c,t.vz=0,t.f=s,t.l=o}function qv(t){if(t.spin=Zs(t.spin,t.steer*t.airTurnRate,t.airSpinAccel*t.h),t.boosting){let e=t.boostMaxSpeed*t.cap;if(t.f<e){let n=Math.min(t.boostAccel*t.h,e-t.f);t.vx=t.vx+n*t.c,t.vy=t.vy+n*t.s}}}function Gv(t){let e=t.onGround;Vl(t),t.onGround&&!e&&(t.vz=0),t.c=K0(t.yaw),t.s=Y0(t.yaw),t.f=t.vx*t.c+t.vy*t.s,t.l=t.vy*t.c-t.vx*t.s,t.boosting=t.boost&&t.fuel>0,t.boosting&&(t.fuel=Math.max(0,t.fuel-t.boostBurn*t.h)),t.onGround&&t.pressed&&(t.vz=t.jumpImpulse,t.onGround=!1,t.pressed=!1),t.onGround?jv(t):qv(t);let n=!t.onGround;n&&(t.vz-=t.gravity*t.h*.5),t.vx=sn(t.vx,-t.maxVelocity,t.maxVelocity),t.vy=sn(t.vy,-t.maxVelocity,t.maxVelocity),t.vz=sn(t.vz,-t.maxVelocity,t.maxVelocity),t.yaw=yw(t.yaw+t.spin*t.h),t.onGround?(pw(t,!0),hw(t)):$l(t,t.h),Vl(t),n&&!t.onGround?t.vz-=t.gravity*t.h*.5:t.onGround&&(t.vz=0),t.x=bn(t.x),t.y=bn(t.y),t.z=bn(t.z),t.vx=bn(t.vx),t.vy=bn(t.vy),t.vz=bn(t.vz),t.spin=Te(Math.fround(t.spin)),t.fuel=Te(Math.fround(t.fuel))}function Wv(t,e,n,r,s=rc,o=rw){let i=$p(s),a=Xp(i),c=Math.fround,u=Js(t.mstate)&$v,l=c(r.height),d=Te(-Ln(e.moveX)),f=Ln(e.moveY),h=Js(e.buttons),p=(h&r.jumpBit)!==0,g=Fl(n,Up),x=zp(t.yaw),b={w:i,p:o,r:c(r.radius),standHeight:l,crouchHeight:l,stepHeight:c(r.stepHeight),standable:c(r.standable),groundTrace:c(r.groundTrace),groundSnap:c(r.groundSnap),skin:c(r.skin),maxSpeed:c(r.maxSpeed),accel:c(r.accel),brake:c(r.brake),coast:c(r.coast),boostAccel:c(r.boostAccel),boostMaxSpeed:c(r.boostMaxSpeed),boostBurn:c(r.boostBurn),grip:c(r.grip),driftGrip:c(r.driftGrip),turnRate:c(r.turnRate),turnSpeed:c(r.turnSpeed),spinAccel:c(r.spinAccel),airTurnRate:c(r.airTurnRate),airSpinAccel:c(r.airSpinAccel),gravity:c(r.gravity),jumpImpulse:c(r.jumpImpulse),maxVelocity:c(r.maxVelocity),x:xt(t.x,0,-1e9,1e9),y:xt(t.y,0,-1e9,1e9),z:xt(t.z,0,-1e9,1e9),vx:xt(t.vx,0,-1e9,1e9),vy:xt(t.vy,0,-1e9,1e9),vz:xt(t.vz,0,-1e9,1e9),yaw:Math.abs(x)<=1e9?yw(x):0,spin:xt(t.spin,0,-1e3,1e3),fuel:xt(t.fuel,0,0,1),cap:xt(t.cap,1,0,4),duck:0,onGround:(u&Bt.ON_GROUND)!==0,jumpHeld:(u&Bt.JUMP_HELD)!==0,pressed:!1,boosting:!1,steer:d,throttle:f,boost:(h&r.boostBit)!==0,drift:(h&r.driftBit)!==0,h:g/r.substeps,c:1,s:0,f:0,l:0,tMin:0,tMax:0,ax:-1,sg:0,nx:0,ny:0,nz:0,hit:!1,depth:0,cand:a.cand,nCand:-1,pc:Hp,nPosed:0,stack:a.stack};if(g>0){b.pressed=p&&!b.jumpHeld,b.jumpHeld=p;for(let S=0;S<r.substeps;S++)Gv(b)}return{x:b.x,y:b.y,z:b.z,vx:b.vx,vy:b.vy,vz:b.vz,yaw:b.yaw,spin:b.spin,fuel:b.fuel,mstate:(b.onGround?Bt.ON_GROUND:0)+(b.jumpHeld?Bt.JUMP_HELD:0)}}var Yv={defaults:hv,ranges:mv,fields:["x","y","yaw"],reads:[],world:!1,step:(t,e,n,r)=>yv(t,e,n,r)},Kv={defaults:gv,ranges:bv,fields:["x","y","z","vx","vy","vz","yaw","pitch","duck","mstate"],reads:["cap"],world:!0,step:(t,e,n,r,s,o)=>Uv(t,e,n,r,s,o)},Xv={defaults:Vv,ranges:Hv,fields:["x","y","z","vx","vy","vz","yaw","spin","fuel","mstate"],reads:["cap"],world:!0,step:(t,e,n,r,s,o)=>Wv(t,e,n,r,s,o)},ew=Object.freeze({[lr.TOPDOWN]:Object.freeze(Yv),[lr.FIRSTPERSON]:Object.freeze(Kv),[lr.VEHICLE]:Object.freeze(Xv)});function oc(t){return typeof t=="string"&&Object.hasOwn(ew,t)?ew[t]:void 0}Mp();var Jv=2,gw=t=>typeof t=="string"&&t.length>0;function ww(t,e){let n=[],r=new Set;for(let s of Array.isArray(t)?t:[]){if(s===null||typeof s!="object")continue;let{region:o,urls:i}=s;if(typeof o!="string"||o.length===0||r.has(o))continue;let a=Array.isArray(i)?i.filter(gw):[];a.length!==0&&(r.add(o),n.push({region:o,urls:a}))}return n.length>0?n:(Array.isArray(e)?e.filter(gw):[]).map(s=>({region:s,urls:[s]}))}function Zv(t,e){return Array.from({length:e},(n,r)=>t[r%t.length])}var xw=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0;function bw(t,e){let n=[],r=[];return t.forEach((s,o)=>{let i=null,a=s.urls[0];s.urls.forEach((c,u)=>{let l=e[o]?.[u];!xw(l)||i!==null&&l>=i||(i=l,a=c)}),(i===null?r:n).push({index:o,ms:i,pick:{region:s.region,url:a}})}),n.sort((s,o)=>s.ms-o.ms||s.index-o.index),[...n,...r].map(s=>s.pick)}function Sw(t,e,n){let r=t.refused+1;if(r>=Jv&&t.region+1<e){let o=t.region+1;return{attempt:{region:o,waitMs:0},state:{region:o,refused:0,step:t.step}}}let s=n[t.step];return s===void 0?null:{attempt:{region:t.region,waitMs:s},state:{region:t.region,refused:r,step:t.step+1}}}async function Ew(t,e={}){if(t.length===0)return[];if(t.length===1)return bw(t,[]);let n=Math.max(1,e.samples??Ys.SAMPLES),r=t.map(i=>Zv(i.urls,n)),s=await Qv(r,e),o=t.map((i,a)=>i.urls.map(c=>{let u;return r[a]?.forEach((l,d)=>{let f=s[a]?.[d];l===c&&xw(f)&&(u=Math.min(u??Number.POSITIVE_INFINITY,f))}),u}));return bw(t,o)}async function Qv(t,e={}){let n=e.probe??Rp,r=e.timeoutMs??Ys.TIMEOUT_MS,s=e.graceMs??Ys.GRACE_MS,o=t.map(a=>a.map(()=>{})),i=t.reduce((a,c)=>a+c.length,0);return i===0||await new Promise(a=>{let c,u=!1,l=setTimeout(d,r);function d(){u=!0,clearTimeout(l),clearTimeout(c),a()}let f=()=>{--i===0&&d()};t.forEach((h,p)=>{h.forEach((g,x)=>{let b;try{b=n(g,r)}catch(S){b=Promise.reject(S)}b.then(S=>{!u&&Number.isFinite(S)&&S>=0&&(o[p][x]=S,c??(c=setTimeout(d,s))),f()},f)})})}),o}var jt={EXTRAPOLATE:"extrapolate",HOLD:"hold",INPUT_DECAY:"inputDecay"};var tT=Object.freeze({bodies:512,collidersPerBody:8,hullVertices:64,triangles:65536,joints:64,ccdBodies:16,queriesPerStep:64,eventsPerStep:64,heightfieldSamples:1048576,staticPieces:4608,memoryBytes:64*1024*1024,worldExtent:1e5,maxSpeed:1e3,maxAngularSpeed:1e3}),YF=Object.freeze(Object.keys(tT)),KF=Object.freeze(["worldExtent","maxSpeed"]),XF=Object.freeze(["worldExtent","maxSpeed","maxAngularSpeed"]);var _w=Object.freeze({[lr.FIRSTPERSON]:39.37,[lr.VEHICLE]:100}),JF=Object.freeze([10,15,20,30,60]);var dr={DEFAULT_REMOTE_PREDICT:jt.EXTRAPOLATE,DEFAULT_REMOTE_DECAY_MS:50,MAX_REMOTE_DECAY_MS:1e3,DEFAULT_LEAD_MS:250,MIN_LEAD_MS:50,MAX_LEAD_MS:1e3},ZF=Object.values(jt);var Rw=64,kw=64;var QF=Object.freeze({20:3,30:2,60:1,120:1});var nT=Object.freeze(["qx","qy","qz","qw","lvx","lvy","lvz","avx","avy","avz","sleep"]),rT=Object.freeze(["x","y","z",...nT]),ql={BITS:16,SPAN:65534,ORIENTATION:Object.freeze({min:-1,max:1}),VELOCITY:Object.freeze({min:-64,max:64})};function qt(t,e){if(Number.isNaN(t))return 0;let n=t<e.min?e.min:t>e.max?e.max:t;return Math.floor((n-e.min)/(e.max-e.min)*ql.SPAN+.5)}var Pw=250,Aw=1,vw=100,Tw=1;var Qp=[0,0,0,1];function zn(t,e){return[t[3]*e[0]+t[0]*e[3]+t[1]*e[2]-t[2]*e[1],t[3]*e[1]-t[0]*e[2]+t[1]*e[3]+t[2]*e[0],t[3]*e[2]+t[0]*e[1]-t[1]*e[0]+t[2]*e[3],t[3]*e[3]-t[0]*e[0]-t[1]*e[1]-t[2]*e[2]]}function Mr(t){let e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]+t[3]*t[3]);return e===0?Qp:[t[0]/e,t[1]/e,t[2]/e,t[3]/e]}function Mw(t,e,n,r){let s=Math.sin(r/2);return[t*s,e*s,n*s,Math.cos(r/2)]}function xi(t,e){let n=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);if(n===0)return Qp;let r=2*Math.atan2(n,t[3]);return Mw(t[0]/n,t[1]/n,t[2]/n,e*r)}function Cw(t,e){return{tick:e+1,p:[t.x,t.y,t.z],q:Mr([t.qx,t.qy,t.qz,t.qw]),lv:[t.lvx,t.lvy,t.lvz],av:[t.avx,t.avy,t.avz],sleep:t.sleep,epoch:t.epoch}}function sT(t,e,n){if(t.sleep||!(n.tickHz>0))return 0;let s=((e-n.tickOrigin)*n.tickHz/1e3-t.tick)/n.tickHz,o=-Aw/n.tickHz,i=Pw/1e3;return s<o?o:s>i?i:s}function Ow(t,e,n){let r=sT(t,e,n),s=n.lengthUnit,o=[t.p[0]+t.lv[0]*s*r,t.p[1]+t.lv[1]*s*r,t.p[2]+t.lv[2]*s*r],[i,a,c]=t.av,u=Math.sqrt(i*i+a*a+c*c);return u===0||r===0?{p:o,q:t.q}:{p:o,q:Mr(zn(Mw(i/u,a/u,c/u,u*r),t.q))}}var Jp={SPAWNED:"spawned",EPOCH:"epoch",DISTANCE:"distance"},Zp=(t,e)=>({state:t,arrivedAt:e,dp:[0,0,0],dq:Qp});function eh(t,e,n){let r=Ow(t.state,e,n),s=e-t.arrivedAt,o=Math.exp(-(s<0?0:s)/vw),{dp:i}=t;return{p:[r.p[0]+i[0]*o,r.p[1]+i[1]*o,r.p[2]+i[2]*o],q:zn(xi(t.dq,o),r.q)}}function Iw(t,e,n,r){if(t===null)return{drawing:Zp(e,n),snap:Jp.SPAWNED};if(e.epoch!==t.state.epoch)return{drawing:Zp(e,n),snap:Jp.EPOCH};let s=eh(t,n,r),o=Ow(e,n,r),i=[s.p[0]-o.p[0],s.p[1]-o.p[1],s.p[2]-o.p[2]];if(Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2])>Tw*r.lengthUnit)return{drawing:Zp(e,n),snap:Jp.DISTANCE};let a=zn(s.q,[-o.q[0],-o.q[1],-o.q[2],o.q[3]]),c=a[3]<0?[-a[0],-a[1],-a[2],-a[3]]:a;return{drawing:{state:e,arrivedAt:n,dp:i,dq:c},snap:null}}function Dw(t,e){let n=(r,s)=>r.every((o,i)=>Object.is(o,s[i]));return t.sleep===e.sleep&&t.epoch===e.epoch&&n(t.p,e.p)&&n(t.q,e.q)&&n(t.lv,e.lv)&&n(t.av,e.av)}var Bw=2**32-1,ic=1e3,Cr=t=>typeof t.t0=="number"&&t.t0>0;function th(t,e,n){let r=(e-t.t0)/n,s=Number.isFinite(r)&&r>=0?r:0;return{x:Te(Math.fround(t.x+t.vx*s)),y:Te(Math.fround(t.y+t.vy*s)),z:Te(Math.fround(t.z+t.vz*s-.5*t.g*s*s)),vx:Te(t.vx),vy:Te(t.vy),vz:Te(Math.fround(t.vz-t.g*s))}}function nh(t,e,n){return(t-e)*n/1e3}function Gl(t,e,n){return e+t*1e3/n}var an={Predicted:"predicted",Separate:"separate",Timeline:"timeline"},to={Shared:"shared",Mover:"mover"},Un={Shooter:"shooter",Platformer:"platformer",VehicleArena:"vehicle-arena",PhysicsSandbox:"physics-sandbox",Party:"party"},ot={Stand:"stand",Slide:"slide",Bounce:"bounce",Ghost:"ghost"},Vn={Box:"box",Hull:"hull"},no={Slide:"slide",Carry:"carry"};var rh=(t,e,n)=>({speed:t,step:e,share:n}),ac=t=>({policy:ot.Slide,...t}),uc=(t,e,n)=>({policy:ot.Stand,ride:t,center:e,slide:n}),Si=rh(300,150,1),Or=rh(950,480,1),oT=rh(600,null,.5),iT=.25,i2=Object.freeze({speed:300,step:150}),a2={policy:ot.Bounce,stompMin:150,bounceSpeed:450,jumpBoost:150,slide:Si},Nw={[Un.Shooter]:{character:uc(!1,iT,Si),vehicle:ac(Or),restitution:0,passes:16,vehicleOffWall:Or,stopSpin:!1,drawing:an.Separate,push:to.Mover,headFriction:no.Slide},[Un.Platformer]:{character:uc(!0,null,Si),vehicle:ac(Or),restitution:0,passes:16,vehicleOffWall:Or,stopSpin:!1,drawing:an.Separate,push:to.Mover,headFriction:no.Slide},[Un.VehicleArena]:{character:ac(Si),vehicle:ac(Or),restitution:.6,passes:32,vehicleOffWall:oT,stopSpin:!0,drawing:an.Predicted,push:to.Shared,headFriction:no.Carry},[Un.PhysicsSandbox]:{character:uc(!0,null,Si),vehicle:uc(!0,null,Or),restitution:.2,passes:16,vehicleOffWall:Or,stopSpin:!1,drawing:an.Separate,push:to.Shared,headFriction:no.Carry},[Un.Party]:{character:uc(!0,null,Si),vehicle:ac(Or),restitution:.3,passes:16,vehicleOffWall:Or,stopSpin:!1,drawing:an.Separate,push:to.Shared,headFriction:no.Slide}},c2=Object.freeze({supportCos:.7,entrySpeed:1,entryWindow:1/60,slop:.1,roofSkin:.01});var u2={[ot.Stand]:new Set(["policy","ride","center","slide"]),[ot.Slide]:new Set(["policy","speed","step","share"]),[ot.Bounce]:new Set(["policy","stompMin","bounceSpeed","jumpBoost"]),[ot.Ghost]:new Set(["policy"])};function aT(t,e,n){let[r,s,o,i,a,c]=t;return[[-1,0,0,-(r-e)],[1,0,0,i+e],[0,-1,0,-(s-e)],[0,1,0,a+e],[0,0,1,c],[0,0,-1,-(o-n)]]}function cT(t,e,n){let[r,s,o,i,a,c,u,l,d]=t,f=u===0?r:s,h=(d-l)/((u===0?i:a)-f),p=1/Math.sqrt(h*h+1),g=(l-h*f+e*Math.abs(h))*p,x=u===0?[-h*p,0,p,g]:[0,-h*p,p,g];return[[1,0,0,i+e],[-1,0,0,-r+e],[0,1,0,a+e],[0,-1,0,-s+e],x,[0,0,1,c],[0,0,-1,-o+n]]}function Lw(t,e,n,r){return{planes:t,min:[e[0]-n,e[1]-n,e[2]-r],max:[e[3]+n,e[4]+n,e[5]]}}function Uw(t,e,n,r){let s=(t?.boxes??[]).map(c=>Lw(aT(c,e,n),c,e,n)),o=(t?.ramps??[]).map(c=>Lw(cT(c,e,n),c,e,n)),i=[...s,...o],a=uT(i);return a===null?{solids:i,skin:r}:{solids:i,skin:r,grid:a}}var Fw=t=>Number.isFinite(t.min[0])&&Number.isFinite(t.min[1])&&Number.isFinite(t.max[0])&&Number.isFinite(t.max[1]);function as(t,e,n,r){let s=Math.floor((t-e)/n);return s<0?0:s>r-1?r-1:s}function uT(t){let e=t.filter(Fw);if(e.length<32)return null;let n=Number.POSITIVE_INFINITY,r=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY;for(let d of e)n=Math.min(n,d.min[0]-1),r=Math.min(r,d.min[1]-1),s=Math.max(s,d.max[0]+1),o=Math.max(o,d.max[1]+1);let i=Math.max(64,(s-n)/32,(o-r)/32),a=Math.min(32,Math.floor((s-n)/i)+1),c=Math.min(32,Math.floor((o-r)/i)+1),u=Array.from({length:a*c},()=>[]),l=[];return t.forEach((d,f)=>{if(!Fw(d)){l.push(f);return}let h=as(d.min[0]-1,n,i,a),p=as(d.max[0]+1,n,i,a),g=as(d.min[1]-1,r,i,c),x=as(d.max[1]+1,r,i,c);if((p-h+1)*(x-g+1)>64){l.push(f);return}for(let b=g;b<=x;b++)for(let S=h;S<=p;S++)u[S+b*a].push(f)}),{x0:n,y0:r,size:i,nx:a,ny:c,cells:u,wide:l}}function lT(t,e){if(e.length===0)return t;let n=[],r=0,s=0;for(;r<t.length||s<e.length;){let o=s>=e.length||r<t.length&&t[r]<=e[s],i=o?t[r]:e[s];o?r+=1:s+=1,n[n.length-1]!==i&&n.push(i)}return n}function dT(t,e,n,r,s){let o=t.grid;if(o===void 0||!(Number.isFinite(e)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(s)))return null;let i=as(e,o.x0,o.size,o.nx),a=as(n,o.x0,o.size,o.nx),c=as(r,o.y0,o.size,o.ny),u=as(s,o.y0,o.size,o.ny);if((a-i+1)*(u-c+1)>16)return null;let l=o.wide;for(let d=c;d<=u;d++)for(let f=i;f<=a;f++)l=lT(l,o.cells[f+d*o.nx]);return l}function lc(t,e,n,r,s){for(let[o,i,a,c]of t)if(!(c-(o*n+i*r+a*s)>e))return!1;return!0}function fT(t,e,n,r){for(let s=0;s<3;s++){let o=e[s],i=o+n[s]*r,a=o<i?o:i;if((o<i?i:o)<t.min[s]-1||a>t.max[s]+1)return!1}return!0}function pT(t,e,n,r,s){for(let o of t.planes){let[i,a,c,u]=o;if(u-(i*n[0]+a*n[1]+c*n[2])<=e&&i*r[0]+a*r[1]+c*r[2]<0&&!s?.(o))return{t:0,face:o}}return null}var Vw=(t,e)=>n=>n[2]>=e&&n[0]*t[0]+n[1]*t[1]+n[2]*t[2]>=e;function hT(t,e,n,r,s,o){if(lc(t.planes,e,n[0],n[1],n[2]))return null;if(lc(t.planes,-e,n[0],n[1],n[2]))return pT(t,e,n,r,o);let i=0,a=s,c=Number.NEGATIVE_INFINITY,u=null;for(let l of t.planes){let[d,f,h,p]=l,g=p+e-(d*n[0]+f*n[1]+h*n[2]),x=d*r[0]+f*r[1]+h*r[2];if(x===0){if(!(g>0))return null;continue}let b=g/x;x>0&&b<a&&(a=b),x<0&&b>c&&(c=b,u=l)}return c>i&&(i=c),u===null||!(i<a)||o?.(u)?null:{t:i,face:u}}function dc(t,e,n,r,s){let o={t:r,face:null};if(!(r>0))return{t:0,face:null};let i=f=>{if(!fT(f,e,n,o.t))return;let h=hT(f,t.skin,e,n,o.t,s);h!==null&&h.t<o.t&&(o=h)},[a,c]=[e[0],e[1]],[u,l]=[a+n[0]*r,c+n[1]*r],d=dT(t,Math.min(a,u),Math.max(a,u),Math.min(c,l),Math.max(c,l));if(d===null)for(let f of t.solids)i(f);else for(let f of d)i(t.solids[f]);return o}function Wl(t,e,n,r,s){if(t===null)return r;let o=dc(t,e,n,r,s).t;return o<0?0:o}var zw=[0,0,1],mT=[0,0,-1];function Hw(t,e,n,r,s){if(t===null)return zw;let o=dc(t,[e,n,r],mT,s);return o.face===null||!(o.face[2]>0)?zw:[o.face[0],o.face[1],o.face[2]]}function yT(t,e,n,r,s,o){let{solids:i,skin:a}=t;for(let c=0;c<i.length;c++){if(c===e)continue;let u=i[c].planes;if(lc(u,a,o[0],o[1],o[2])&&!lc(u,a,n,r,s))return!0}return!1}function gT(t,e,n,r,s,o){let i=null;for(let a=0;a<n.length-1;a++){let[c,u,l,d]=n[a],f=d-(c*r+u*s+l*o);i!==null&&!(f<i[3])||l>0&&yT(t,e,r,s,o,[r+c*f,s+u*f,o+l*f])||(i=[c,u,l,f])}return i}function bT(t,e,n,r){let{solids:s,skin:o}=t;for(let i=0;i<s.length;i++){let a=s[i].planes;if(lc(a,o,e,n,r))return gT(t,i,a,e,n,r)}return null}function $w(t,e,n){let{x:r,y:s,z:o}=e,i=0;for(let a=0;a<4;a++){let c=bT(t,r,s,o);if(c===null)break;n?.(c);let[u,l,d,f]=c;i=Math.max(i,f),r+=u*(f+t.skin),s+=l*(f+t.skin),o+=d*(f+t.skin)}return i>0&&(e.x=r,e.y=s,e.z=o),i}var so={Side:"side",Top:"top"},Xl={Free:"free",LowerYields:"lower-yields",Pinned:"pinned"},wT={Stomp:"stomp"},sh={j:0,way:null,w:null},fc=[0,0,1],Ne=(t,e)=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2],oo=(t,e)=>[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]],it=t=>[-t[0],-t[1],-t[2]];function xT(t,e,n){return n.supportUp!==void 0?n.supportUp(t.x,t.y,t.z):Hw(n.world,t.x,t.y,t.z,e.groundTrace)}function io(t,e,n){let r=e.shape,s=xT(t,e,n);if(r.kind===Vn.Hull)return{b:t,up:fc,support:s,hl:r.radius,hw:r.radius,top:r.height,s:0,c:1};let[o,i]=Dt(t.yaw);return{b:t,up:s,support:s,hl:r.length/2,hw:r.width/2,top:r.top,s:o,c:i}}var Jl=t=>Math.sqrt(t.hl*t.hl+t.hw*t.hw),Yl=(t,e,n)=>t.hl*Math.abs(t.c*e+t.s*n)+t.hw*Math.abs(t.c*n-t.s*e);function ST(t,e){let n=e.b.z-t.b.z+(e.top-t.top)/2,r=(t.top+e.top)/2;if(Math.abs(n)>=r)return null;let s=e.b.x-t.b.x,o=e.b.y-t.b.y,i=Jl(t)+Jl(e);if(Math.abs(s)>=i||Math.abs(o)>=i)return null;let a=[t.c,t.s,-t.s,t.c,e.c,e.s,-e.s,e.c],c=null,u=[];for(let d=0;d<8;d+=2){let f=a[d],h=a[d+1],p=s*f+o*h,g=Yl(t,f,h)+Yl(e,f,h)-Math.abs(p);if(g<=0)return null;let x=p<0?{depth:g,n:[-f,-h,0]}:{depth:g,n:[f,h,0]};u.push(x),(c===null||g<c.depth)&&(c=x)}let l=n<0?[0,0,-1]:fc;return{plane:fc,level:!0,side:c,axes:u,across:{depth:r-Math.abs(n),n:l},d:[s,o,0],half:d=>Yl(t,d[0],d[1])+Yl(e,d[0],d[1])}}function ih(t,e,n){let r=t*n[0]+e*n[1],s=t-r*n[0],o=e-r*n[1],i=-r*n[2],a=Math.sqrt(s*s+o*o+i*i);return a<1e-9&&(s=-n[2]*n[0],o=-n[2]*n[1],i=1-n[2]*n[2],a=Math.sqrt(s*s+o*o+i*i)),[s/a,o/a,i/a]}function ET(t,e){let n=[t.up[0]+e.up[0],t.up[1]+e.up[1],t.up[2]+e.up[2]],r=Math.sqrt(Ne(n,n));if(r<1e-9)return null;let s=[n[0]/r,n[1]/r,n[2]/r],o=t.top/2,i=e.top/2,a=[e.b.x+e.up[0]*i-t.b.x-t.up[0]*o,e.b.y+e.up[1]*i-t.b.y-t.up[1]*o,e.b.z+e.up[2]*i-t.b.z-t.up[2]*o],c=Ne(a,s),u=o+i;if(Math.abs(c)>=u)return null;let l=ih(t.c,t.s,s),d=ih(e.c,e.s,s),f=oo(s,l),h=oo(s,d),p=b=>t.hl*Math.abs(Ne(l,b))+t.hw*Math.abs(Ne(f,b))+(e.hl*Math.abs(Ne(d,b))+e.hw*Math.abs(Ne(h,b))),g=null,x=[];for(let b of[l,f,d,h]){let S=Ne(a,b),_=t.hl*Math.abs(Ne(l,b))+t.hw*Math.abs(Ne(f,b))+(e.hl*Math.abs(Ne(d,b))+e.hw*Math.abs(Ne(h,b)))-Math.abs(S);if(_<=0)return null;let P={depth:_,n:S<0?it(b):b};x.push(P),(g===null||_<g.depth)&&(g=P)}return{plane:s,level:!1,side:g,axes:x,across:{depth:u-Math.abs(c),n:c<0?it(s):s},d:a,half:p}}var _T=1e-6;function jw(t){let e=ih(t.c,t.s,t.up),n=t.top/2;return{c:[t.b.x+t.up[0]*n,t.b.y+t.up[1]*n,t.b.z+t.up[2]*n],axes:[e,oo(t.up,e),t.up],half:[t.hl,t.hw,n]}}function RT(t,e,n){let r=jw(t),s=jw(e),o=[s.c[0]-r.c[0],s.c[1]-r.c[1],s.c[2]-r.c[2]],i=(f,h)=>f.half[0]*Math.abs(Ne(f.axes[0],h))+f.half[1]*Math.abs(Ne(f.axes[1],h))+f.half[2]*Math.abs(Ne(f.axes[2],h)),a=f=>i(r,f)+i(s,f),c=[...r.axes,...s.axes];for(let f of r.axes)for(let h of s.axes){let p=oo(f,h),g=Math.sqrt(Ne(p,p));g>_T&&c.push([p[0]/g,p[1]/g,p[2]/g])}let u=[];for(let f of c){let h=Ne(o,f),p=a(f)-Math.abs(h);if(p<=0)return null;u.push({depth:p,n:h<0?it(f):f})}let l=u.reduce((f,h)=>h.depth<f.depth?h:f),d=Ne(o,n);return{plane:n,level:!1,side:l,axes:u,across:{depth:a(n)-Math.abs(d),n:d<0?it(n):n},d:o,half:a}}function ah(t,e){let n=Jl(t)+Jl(e),r=(t.top+e.top)/2,s=Math.sqrt(n*n+r*r)+r;if(Math.abs(e.b.x-t.b.x)>=s||Math.abs(e.b.y-t.b.y)>=s||Math.abs(e.b.z-t.b.z)>=s)return null;if(t.up[2]===1&&e.up[2]===1)return ST(t,e);if(t.up[0]===e.up[0]&&t.up[1]===e.up[1]&&t.up[2]===e.up[2])return ET(t,e);let o=[t.up[0]+e.up[0],t.up[1]+e.up[1],t.up[2]+e.up[2]],i=Math.sqrt(Ne(o,o));return i<1e-9?null:RT(t,e,[o[0]/i,o[1]/i,o[2]/i])}var Zl=(t,e,n)=>-((e.vx-t.vx)*n[0]+(e.vy-t.vy)*n[1]+((e.vz??0)-(t.vz??0))*n[2]);function kT(t,e,n,r){let s=t.across.depth/Math.max(Zl(e.b,n.b,t.across.n),r.entrySpeed),i=s<=r.entryWindow&&t.across.depth<=(e.top+n.top)/4||!t.level&&t.across.depth<=r.groundTrace;if(!i)return{across:!1,landed:i};let a=t.side.depth/Math.max(Zl(e.b,n.b,t.side.n),r.entrySpeed);return{across:s<a||s===a&&t.across.depth<t.side.depth,landed:i}}function qw(t){let e=[...t.tags??[]],n=t.flags??0;for(let r=0;r<24;r++)Math.floor(n/2**r)%2===1&&e.push(`flag:${r}`);return e}function _i(t,e,n){if(t.pairs.length===0)return t.top;let r=qw(e),s=qw(n),o=i=>r.includes(i.a)&&s.includes(i.b)||r.includes(i.b)&&s.includes(i.a);return t.pairs.find(o)?.top??t.top}function uh(t,e,n){let r=ah(t,e);if(r===null)return PT(t,e,n);let s=kT(r,t,e,n);if(!s.across){let l=Ne(r.d,r.plane)>=0;return{contact:{kind:so.Side,n:r.side.n,depth:r.side.depth,upperIsB:l},g:r}}let o=r.across.n,i=o===r.plane||Ne(o,r.plane)>0,a=i?t:e,c=i?o:it(o);return{contact:{kind:s.landed&&Ne(c,a.support)>=n.supportCos?so.Top:so.Side,n:o,depth:r.across.depth,upperIsB:i},g:r}}function PT(t,e,n){let r=e.b.z>=t.b.z,s=l=>({...l,b:{...l.b,z:l.b.z-n.groundTrace}}),o=r?ah(t,s(e)):ah(s(t),e);if(o===null||!(o.across.depth<o.side.depth))return null;let i=r?o.across.n:it(o.across.n);if(!(Ne(i,o.plane)>0))return null;let a=r?t:e;if(a.support[2]<n.supportCos||Ne(i,a.support)<n.supportCos)return null;let[c,u]=r?[e.b,t.b]:[t.b,e.b];return-Zl(u,c,i)>n.entrySpeed?null:{contact:{kind:so.Top,n:o.across.n,depth:o.across.depth-n.groundTrace,upperIsB:r},g:o}}function AT(t,e,n,r){return lh(t,e,n)?null:uh(io(t,n,r),io(e,n,r),n)?.contact??null}function vT(t){let e=t.shape;return e.kind===Vn.Hull?Math.sqrt(2*e.radius*e.radius+e.height*e.height):Math.sqrt(e.length*e.length/4+e.width*e.width/4+e.top*e.top)}function lh(t,e,n){let r=2*vT(n)+n.groundTrace+1,s=e.x-t.x,o=e.y-t.y,i=e.z-t.z;return s*s+o*o+i*i>r*r}var Zw=t=>e=>{let n=t.maxVelocity;return n===null?e:e<-n?-n:e>n?n:e},Ir=t=>[t.x,t.y,t.z],TT=.7,MT=.5,Gw=.5;function Ei(t,e,n,r,s,o){let i=dc(t,e,n,r,Ne(n,o)<-MT?void 0:s),a=i.t,c=i.face;if(c===null||!(a<r))return{d:n,straight:a,slide:null,cos:1,sep:a};let u=[c[0],c[1],c[2]],l=CT(u,n,o);if(l===null)return{d:n,straight:a,slide:null,cos:1,sep:a};let d=Ne(l,n),f=[e[0]+n[0]*a,e[1]+n[1]*a,e[2]+n[2]*a],h=dc(t,f,l,(r-a)/d,s).t;return{d:n,straight:a,slide:l,cos:d,sep:a+h*d}}function CT(t,e,n){if(Ne(t,n)>=TT){let a=Ne(e,t),c=[e[0]-a*t[0],e[1]-a*t[1],e[2]-a*t[2]],u=Math.hypot(c[0],c[1],c[2]);return u>=Gw?[c[0]/u,c[1]/u,c[2]/u]:null}let r=oo(t,n),s=Math.hypot(r[0],r[1],r[2]),o=s>0?Ne(r,e)/s:0;if(!(Math.abs(o)>=Gw))return null;let i=o>0?1/s:-1/s;return[r[0]*i,r[1]*i,r[2]*i]}function Ww(t,e){let n=t.d;if(t.slide===null||!(e>t.straight))return[n[0]*e,n[1]*e,n[2]*e];let r=(e-t.straight)/t.cos,s=t.slide;return[n[0]*t.straight+s[0]*r,n[1]*t.straight+s[1]*r,n[2]*t.straight+s[2]*r]}function OT(t,e,n=.5){let r=Math.min(e,1-Math.min(t,n));return[Math.min(t,1-r),r]}function IT(t,e,n,r,s,o,i,a=fc,c=fc,u=.5){if(s===null)return[u,1-u];let l=Ei(s,Ir(t),it(n),r,o,a),d=Ei(s,Ir(e),n,r,i,c);return OT(l.sep/r,d.sep/r,u)}function Qw(t,e,n,r){if(r.push!==to.Mover)return .5;let s=t.vx*n[0]+t.vy*n[1],o=e.vx*n[0]+e.vy*n[1];n[2]!==0&&(s+=(t.vz??0)*n[2],o+=(e.vz??0)*n[2]);let i=s>0?s:0,a=o<0?-o:0;return i+a>0?i/(i+a):.5}function ch(t,e,n,r,s,o){let[i,a]=IT(t.b,e.b,n,r,o.world,ro(t,s),ro(e,s),t.support,e.support,Qw(t.b,e.b,n,s));return o.fixed===void 0?[i,a]:t.b.id===o.fixed?[0,o.world===null?1:Ei(o.world,Ir(e.b),n,r,ro(e,s),e.support).sep/r]:e.b.id===o.fixed?[o.world===null?1:Ei(o.world,Ir(t.b),it(n),r,ro(t,s),t.support).sep/r,0]:[i,a]}var ro=(t,e)=>Vw(t.support,e.supportCos);function DT(t,e,n,r,s,o){let i=r.axes.filter(l=>l.n!==n.n).sort((l,d)=>l.depth-d.depth);for(let l of i){let[d,f]=ch(t,e,l.n,l.depth,s,o);if(!(d+f<1))return{n:l.n,depth:l.depth,sa:d,sb:f}}let[a,c]=ch(t,e,n.n,n.depth,s,o),u=1-a-c;return t.b.id===o.fixed?{n:n.n,depth:n.depth,sa:a,sb:c+u}:e.b.id===o.fixed?{n:n.n,depth:n.depth,sa:a+u,sb:c}:{n:n.n,depth:n.depth,sa:a+u/2,sb:c+u/2}}function Yw(t,e){t.x+=e[0],t.y+=e[1],e[2]!==0&&(t.z+=e[2])}function BT(t,e,n,r,s,o,i,a){let[c,u]=[t.b,e.b],l=a.world,d=it(n),f=l===null?{d,straight:r,slide:null,cos:1,sep:r}:Ei(l,Ir(c),d,r,ro(t,i),t.support),h=l===null?{d:n,straight:r,slide:null,cos:1,sep:r}:Ei(l,Ir(u),n,r,ro(e,i),e.support);Yw(c,Ww(f,r*s)),Yw(u,Ww(h,r*o))}function NT(t,e,n,r,s,o,i){let a=Zw(s),[c,u]=[t.b,e.b],[l,d]=ch(t,e,n.n,n.depth,s,o),f=l+d<1?DT(t,e,n,r,s,o):null,{depth:h,n:p,sa:g,sb:x}=f??{depth:n.depth,n:n.n,sa:l,sb:d},[b,S,_]=p,P=(u.vx-c.vx)*b+(u.vy-c.vy)*S;_!==0&&(P+=((u.vz??0)-(c.vz??0))*_);let R=P<0&&!i?-(1+s.restitution)*P/2:0,v=Qw(c,u,p,s),M=2*R*v,O=2*R*(1-v);return BT(t,e,p,h,g,x,s,o),c.vx=a(c.vx-M*b),c.vy=a(c.vy-M*S),s.stopSpin&&(c.spin=0),u.vx=a(u.vx+O*b),u.vy=a(u.vy+O*S),s.stopSpin&&(u.spin=0),_!==0&&(c.vz=a((c.vz??0)-M*_),u.vz=a((u.vz??0)+O*_)),{j:R,n:p,depth:h}}function ex(t,e){let n=e?t.side.n:it(t.side.n),r=e?t.d:it(t.d),s=oo(t.plane,n);return[n,it(n),s,it(s)].map(i=>({w:i,move:t.half(i)-Ne(r,i)})).map((i,a)=>({way:i,k:a})).sort((i,a)=>i.way.move-a.way.move||i.k-a.k).map(i=>i.way)}var Kw=(t,e,n)=>t.half(n)-Ne(e?t.d:it(t.d),n);function LT(t,e,n,r,s){let o=[];for(let i of n){if(i===t.b||i===e||lh(t.b,i,r)||_i(r,t.b,i).policy===ot.Ghost)continue;let a=uh(t,io(i,r,s),r);a!==null&&a.contact.kind===so.Top&&!a.contact.upperIsB&&o.push(a.g)}return o}function FT(t,e,n){if(n.length===0)return ex(t,e);let r=e?t.side.n:it(t.side.n),s=oo(t.plane,r);return[r,it(r),s,it(s)].map(i=>({w:i,move:n.reduce((a,c)=>Math.max(a,Kw(c,!1,i)),Kw(t,e,i))})).map((i,a)=>({way:i,k:a})).sort((i,a)=>i.way.move-a.way.move||i.k-a.k).map(i=>i.way)}var Xw=(t,e,n,r)=>n.move<=0||Wl(t,Ir(e.b),n.w,n.move,ro(e,r))>=n.move;function oh(t,e,n,r){t.vx=r(t.vx+n*e[0]),t.vy=r(t.vy+n*e[1]),e[2]!==0&&(t.vz=r((t.vz??0)+n*e[2]))}function Jw(t,e){if(!(e<t.speed))return 0;let n=t.speed-e;return t.step===null?n:Math.min(n,t.step)}function Kl(t,e,n,r,s,o,i,a){let[c,u]=[t.b,e.b],l=Zw(o),d=ex(n,r),f=FT(n,r,LT(t,u,a,o,i)).find(x=>Xw(i.world,t,x,o));if(f!==void 0){let x=(c.vx-u.vx)*f.w[0]+(c.vy-u.vy)*f.w[1]+((c.vz??0)-(u.vz??0))*f.w[2],b=Jw(s,x);return oh(c,f.w,b*s.share,l),s.share!==1&&oh(u,f.w,-b*(1-s.share),l),{j:b,way:Xl.Free,w:f.w}}let h=d.map(x=>({w:it(x.w),move:x.move})).find(x=>Xw(i.world,e,x,o));if(h===void 0)return{j:0,way:Xl.Pinned,w:null};let p=(u.vx-c.vx)*h.w[0]+(u.vy-c.vy)*h.w[1]+((u.vz??0)-(c.vz??0))*h.w[2],g=Jw(s,p);return oh(u,h.w,g,l),{j:g,way:Xl.LowerYields,w:h.w}}function zT(t,e,n,r,s,o,i,a){let c=r+i.roofSkin;if(!(c>0))return;let u=t.id===a.fixed?0:Wl(a.world,Ir(t),n,c);if(u>=c&&s.level){t.z=e.z+o+i.roofSkin;return}if(t.x+=n[0]*u,t.y+=n[1]*u,t.z+=n[2]*u,u>=c)return;let l=e.id===a.fixed?0:Wl(a.world,Ir(e),it(n),c-u);e.x-=n[0]*l,e.y-=n[1]*l,e.z-=n[2]*l}function UT(t,e,n){let r=t.vx*n[0]+t.vy*n[1]+(t.vz??0)*n[2],s=e.vx*n[0]+e.vy*n[1]+(e.vz??0)*n[2];if(r<s){if(n[0]===0&&n[1]===0){t.vz=e.vz??0;return}t.vx+=n[0]*(s-r),t.vy+=n[1]*(s-r),t.vz=(t.vz??0)+n[2]*(s-r)}}function VT(t,e,n){let r=t.vx*e[0]+t.vy*e[1]+(t.vz??0)*e[2];t.vx+=e[0]*(n-r),t.vy+=e[1]*(n-r),t.vz=(t.vz??0)+e[2]*(n-r)}function dh(t,e,n){let r=t.x-e.x,s=t.y-e.y,o=n.shape;if(o.kind===Vn.Hull)return Math.max(Math.abs(r),Math.abs(s))/o.radius;let[i,a]=Dt(e.yaw);return Math.max(Math.abs(r*a+s*i)/(o.length/2),Math.abs(s*a-r*i)/(o.width/2))}function HT(t,e,n){if(n)return 0;let r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s);return o>0?-(e.vx*r+e.vy*s)/o:0}var $T=100,cs={Stand:"stand",Release:"release",Slide:"slide"};function tx(t,e,n,r){if(n.center===null)return cs.Stand;let s=dh(t,e,r);return s<=n.center?cs.Stand:(e.vz??0)-(t.vz??0)>$T?cs.Slide:HT(t,e,n.ride)>=(n.slide.step??n.slide.speed)/2?cs.Release:s>1?cs.Slide:cs.Stand}var nx=(t,e,n,r)=>n.policy===ot.Stand&&tx(t,e,n,r)===cs.Stand;function jT(t,e,n,r,s,o,i,a){let[c,u]=n.upperIsB?[e,t]:[t,e],l=c.b,d=u.b,f=n.upperIsB?n.n:it(n.n),h=Zl(d,l,f),p=s.policy===ot.Stand&&tx(l,d,s,o)===cs.Slide;return zT(l,d,f,n.depth,r,u.top,o,i),UT(l,d,f),u.support[2]<o.supportCos?Kl(c,u,r,n.upperIsB,o.offWall,o,i,a):s.policy===ot.Stand?p?Kl(c,u,r,n.upperIsB,s.slide,o,i,a):sh:s.policy===ot.Slide?Kl(c,u,r,n.upperIsB,s,o,i,a):s.policy===ot.Bounce&&h>=s.stompMin?(VT(l,f,s.bounceSpeed+(l.jump?s.jumpBoost:0)),i.onContact?.(l,d,wT.Stomp),sh):s.policy===ot.Bounce?Kl(c,u,r,n.upperIsB,s.slide,o,i,a):sh}function rx(t,e,n,r,s=!1,o=[]){let i=_i(n,t,e);if(i.policy===ot.Ghost||lh(t,e,n))return null;let a=io(t,n,r),c=io(e,n,r),u=uh(a,c,n);if(u===null)return null;let{contact:l,g:d}=u;return l.kind===so.Side?{...l,...NT(a,c,l,d,n,r,s),way:null,w:null}:{...l,...jT(a,c,l,d,i,n,r,o)}}function qT(t,e,n,r,s,o,i){let a=o.cooling?o.cooling(t,e):!1,c=n===0?o.first?.(t,e,a):void 0;return c===void 0?rx(t,e,r,s,a,i):c}var GT=(t,e)=>t!==null&&(t.depth>e.slop||t.kind===so.Top&&t.depth>0);function WT(t,e,n,r,s,o){let i=!1;for(let a=0;a<t.length;a++)for(let c=a+1;c<t.length;c++){let u=t[a],l=t[c];if(e>0&&!GT(AT(u,l,n,r),n))continue;let d=qT(u,l,e,n,r,s,t);d!==null&&(i=!0,d.way===Xl.Pinned&&(o.pinned+=1),s.onPair?.(u,l,d))}return i}function YT(t,e,n,r={}){let s={passes:0,pushed:new Map,walls:new Map,pinned:0};for(let o=0;o<e.passes&&WT(t,o,e,n,r,s);o++)if(s.passes+=1,n.world!==null)for(let i of t){let a=u=>{u[2]<e.supportCos&&u[3]>(s.walls.get(i.id)??0)&&s.walls.set(i.id,u[3])},c=$w(n.world,i,a);c>(s.pushed.get(i.id)??0)&&s.pushed.set(i.id,c)}return s}var fh=(t,e)=>(n,r)=>{rx(n,r,t,e)},sx=(t,e)=>n=>{YT(n,t,e)};function ox(t){return t.top.policy===ot.Stand||t.pairs.some(e=>e.top.policy===ot.Stand)}function KT(t,e,n){let r=t.x+t.vx*n,s=t.y+t.vy*n,o=t.z+(t.vz??0)*n,i=e.shape,a=e.groundTrace;if(i.kind===Vn.Hull){let l=i.radius;return{kind:"box",min:[r-l,s-l,o+i.height-a],max:[r+l,s+l,o+i.height]}}let[c,u]=Dt(t.yaw);return{kind:"obox",c:[r,s,o+i.top-a/2],half:[i.length/2,i.width/2,a/2],sin:c,cos:u}}var ix=t=>t.shape.kind===Vn.Hull?t.shape.height:t.shape.top,ax=2;function XT(t,e,n,r){let s=_i(n,t,e);if(s.policy!==ot.Stand)return!1;let o=ix(n);return t.z<e.z+o-n.groundTrace||t.z>e.z+2*o||!(dh(t,e,n)<ax)||io(e,n,r).support[2]<n.supportCos?!1:nx(t,e,s,n)}var JT=t=>ax*(t.shape.kind===Vn.Hull?t.shape.radius:Math.hypot(t.shape.length,t.shape.width)/2);function ZT(t,e,n=0){let r=ix(e),s=JT(e);for(let o of t)for(let i of t){if(i===o)continue;let a=i.z+(i.vz??0)*n;if(o.z<a+r-e.groundTrace||o.z>a+2*r)continue;let c=(Math.abs(i.vx)+Math.abs(i.vy))*n;if(Math.abs(o.x-i.x)<s+c&&Math.abs(o.y-i.y)<s+c)return!0}return!1}function pc(t,e,n,r){return ZT(t,e)?t.map(s=>{let o=[],i=[];for(let a of t)a===s||!XT(s,a,e,n)||(o.push(KT(a,e,r)),i.push(a.id));return{solids:o,lowers:i}}):t.map(()=>({solids:[],lowers:[]}))}function ph(t,e,n){let[r,s,o]=[e[0],e[1],e[2]],[i,a,c]=[n[0],n[1],n[2]];return t.find(u=>Math.abs(i-u.x)<=r&&Math.abs(a-u.y)<=s&&c>u.z+2*o&&c<=u.z+4*o)}function cx(t,e,n,r){let s=[];for(let o of n){let[i,a]=[o.p[0],o.p[1]],c=ph(t,e,o.p);if(c===void 0)continue;let u=i-c.x,l=a-c.y,d=Math.hypot(u,l),[f,h]=d>0?[u/d,l/d]:[1,0],[p,g,x]=[o.v[0],o.v[1],o.v[2]],b=(p-c.vx)*f+(g-c.vy)*h;if(!(b<r.speed))continue;let S=Math.min(r.step,r.speed-b);s.push({key:o.key,v:[p+f*S,g+h*S,x]})}return s}var ao={Box:"box",Disc:"disc"},ux={PingPong:"pingpong",Loop:"loop"},lx={Linear:"linear",Smooth:"smooth"},dx={All:"all",None:"none"},fx=Object.freeze({platforms:Object.freeze([]),bodies:!1});var S2=2**24;var E2=2*Math.PI;var mx=2*Math.PI,Mt=Math.fround,yx=(t,e)=>(t%e+e)%e;function QT(t,e,n,r,s){if(s===lx.Linear)return[Mt(t[0]+(e[0]-t[0])*n/r),Mt(t[1]+(e[1]-t[1])*n/r),Mt(t[2]+(e[2]-t[2])*n/r)];let o=n/r,i=o*o*(3-2*o);return[Mt(t[0]+(e[0]-t[0])*i),Mt(t[1]+(e[1]-t[1])*i),Mt(t[2]+(e[2]-t[2])*i)]}function eM(t,e){let n=t.legs.length,r=t.mode===ux.Loop,s=r?n:2*n,o=e;for(let i=0;i<s;i++){let a=i,c=i,u=i+1;r?u=(i+1)%n:i>=n&&(a=2*n-1-i,c=a+1,u=a);let l=t.legs[a],d=t.points[u];if(o<l)return QT(t.points[c],d,o,l,t.ease);o-=l;let f=t.waits[u];if(o<f)return d;o-=f}return t.points[0]}function tM(t,e,n,r){return t.called?r===void 0||n<r||n-r>=e.period?0:n-r:yx(n+e.phase,e.period)}function us(t,e,n){let r=t.path===null?t.at:eM(t.path,tM(t,t.path,e,n)),s=t.spin;return s===null?{c:r,yaw:0}:{c:r,yaw:Mt(s.dir*(mx*yx(e+s.phase,s.period)/s.period))}}function px(t,e,n){return t.platforms.map(r=>us(r,e,n?.get(r.id)))}var hh=t=>t.spin===null?0:t.spin.dir*mx/t.spin.period;function ed(t,e,n,r,s){let o=us(t,n,s),i=us(t,n+1,s),a=hh(t),c,u;if(a===0)c=e.x+(i.c[0]-o.c[0]),u=e.y+(i.c[1]-o.c[1]);else{let[d,f]=Dt(a),h=e.x-o.c[0],p=e.y-o.c[1];c=i.c[0]+(f*h-d*p),u=i.c[1]+(d*h+f*p)}let l=e.z+(i.c[2]-o.c[2]);if(t.surface!==null){let[d,f]=t.surface;if(i.yaw===0)c+=d/r,u+=f/r;else{let[h,p]=Dt(i.yaw);c+=(p*d-h*f)/r,u+=(h*d+p*f)/r}}return{x:c,y:u,z:l,yaw:e.yaw+a,v:[(c-e.x)*r,(u-e.y)*r,(l-e.z)*r]}}function Ql(t,e){return t.platforms.map((n,r)=>{let{c:s,yaw:o}=e[r],i=n.shape;if(i.kind===ao.Disc)return{kind:"disc",c:s,radius:i.radius,half:i.half};let a=i.half;if(n.spin===null)return{kind:"box",min:[s[0]-a[0],s[1]-a[1],s[2]-a[2]],max:[s[0]+a[0],s[1]+a[1],s[2]+a[2]]};let[c,u]=Dt(o);return{kind:"obox",c:s,half:a,sin:c,cos:u}})}var gx=4;function td(t,e,n){return{now:Ql(t,px(t,e,n)),next:Ql(t,px(t,e+1,n))}}var bx=(t,e)=>t?.get(e.id);function hx(t,e){t.x=Mt(e.x),t.y=Mt(e.y),t.z=Mt(e.z)}function nM(t,e,n,r,s){let o=[],i=[],a=s===void 0?null:pc(e,s.policy,s.env,0);return e.forEach((c,u)=>{let l=a?.[u];if(n.length===0&&(l===void 0||l.solids.length===0)){o.push(-1),i.push(null);return}let d=l===void 0||l.solids.length===0?r.support(c,n):r.support(c,[...n,...l.solids]),f=d>=t.platforms.length&&l!==void 0?e.find(p=>p.id===l.lowers[d-t.platforms.length])??null:null,h=s!==void 0&&f!==null?_i(s.policy,c,f):null;o.push(d<t.platforms.length?d:-1),i.push(f!==null&&h?.policy==="stand"&&h.ride?f.id:null)}),{bases:o,on:i}}function rM(t,e,n,r,s,o,i){let a=e.map((l,d)=>{let f=n[d];if(f<0)return null;let h=t.platforms[f];return ed(h,l,s,o,bx(i,h))}),c=new Map(e.map((l,d)=>[l.id,d])),u=(l,d)=>{let f=a[l];if(f!=null)return[f.x-e[l].x,f.y-e[l].y,f.z-e[l].z];let h=r[l]===null||r[l]===void 0?void 0:c.get(r[l]);return h===void 0||d>=gx?[0,0,0]:u(h,d+1)};return e.map((l,d)=>{if(a[d]!==null)return a[d];if(r[d]===null)return null;let f=u(d,0);return{x:l.x+f[0],y:l.y+f[1],z:l.z+f[2],yaw:l.yaw,v:[f[0]*o,f[1]*o,f[2]*o]}})}function wx(t,e,n,r,s,o,i,a=td(t,n,s),c){let{now:u,next:l}=a,d=e.map(b=>({...b})),{bases:f,on:h}=nM(t,d,u,o,c),p=rM(t,d,f,h,n,r,s),g=[],x=[];return e.forEach((b,S)=>{let _=f[S],P=p[S]??null;P!==null&&(hx(b,P),i&&_>=0&&(b.yaw=Mt(P.yaw))),g.push(P===null?null:P.v),t.platforms.forEach((R,v)=>{if(v===_||!o.inside(b,l,v))return;let M=ed(R,b,n,r,bx(s,R)),O=o.pushOut({...b,x:M.x,y:M.y,z:M.z},l);hx(b,O),O.inside&&x.push({seat:b.id,lift:R.id})})}),{bases:f,on:h,v:g,crushed:x,from:e.map(b=>[b.x,b.y,b.z])}}function xx(t,e,n){if(e.on.every(c=>c===null))return e;let r=new Map(t.map((c,u)=>[c.id,u])),s=t.map((c,u)=>{let l=e.from[u];return[c.x-l[0],c.y-l[1]]}),o=(c,u)=>{let l=e.on[c],d=l==null?void 0:r.get(l);if(d===void 0||u>=gx)return[0,0];let f=s[d],h=o(d,u+1);return[f[0]+h[0],f[1]+h[1]]},i=t.map((c,u)=>o(u,0)),a=e.v.map((c,u)=>{let l=i[u];return c===null||e.on[u]===null?c:[c[0]+l[0]*n,c[1]+l[1]*n,c[2]]});return t.forEach((c,u)=>{let l=i[u];e.on[u]!==null&&(c.x=Mt(c.x+l[0]),c.y=Mt(c.y+l[1]))}),{...e,v:a}}function sM(t,e,n,r,s,o){let i=pc(t,o.policy,o.env,0)[e];if(i===void 0||i.solids.length===0)return!1;let a=s.support(t[e],[...r,...i.solids]);return a>=r.length&&i.lowers[a-r.length]===n}function Sx(t,e,n,r,s,o,i=td(t,r,s).next,a){if(n.v.every(u=>u===null))return;let c=e.map(u=>({...u}));e.forEach((u,l)=>{let d=n.bases[l]??-1,f=n.v[l],h=n.on[l]??null;if(f!=null){if(h!==null&&a!==void 0){if(sM(c,l,h,i,o,a))return}else if(d<0||t.platforms[d].impart!==dx.All||o.support(u,i)===d)return;u.vx=Mt(u.vx+f[0]),u.vy=Mt(u.vy+f[1]),u.vz=Mt(u.vz+f[2])}})}var hc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function oM(t){return!hc(t)||!Array.isArray(t.platforms)||typeof t.bodies!="boolean"?!1:t.platforms.every(e=>hc(e)&&typeof e.id=="string"&&hc(e.shape)&&Array.isArray(e.at)&&typeof e.called=="boolean")}function kx(t,e,n,r){if(!t)return null;let s;try{s=JSON.parse(t)}catch{return null}if(!hc(s)||s.name!==lr.FIRSTPERSON&&s.name!==lr.VEHICLE)return null;let o=oM(s.lifts)?s.lifts:null;if(o===null&&n===void 0)return null;let i=wi(s.name,s.params);return{policy:o??fx,ops:mw(s.name,i,e),vehicle:s.name===lr.VEHICLE,heads:n,tickHz:r}}function Px(t){if(!t)return;let e;try{e=JSON.parse(t)}catch{return}if(!hc(e))return;let n=new Map;for(let[r,s]of Object.entries(e))typeof s=="number"&&Number.isInteger(s)&&n.set(r,s);return n}var iM=128,Ri=class{constructor(){m(this,"kept",new Map);m(this,"startsText","")}at(e,n,r){let s=r===void 0?"":JSON.stringify([...r]);s!==this.startsText&&(this.kept.clear(),this.startsText=s);let o=this.kept.get(n);if(o!==void 0)return o;let i=td(e,n,r),a={solids:i,next:sc(i.next)};return this.kept.size>=iM&&this.kept.delete(this.kept.keys().next().value),this.kept.set(n,a),a}};function yc(t,e,n,r,s,o){let{solids:i,next:a}=o.at(t.policy,n,r),c=wx(t.policy,e,n,t.tickHz,r,t.ops,t.vehicle,i,t.heads),u=new Map;return t.heads!==void 0&&pc(e,t.heads.policy,t.heads.env,s).forEach((d,f)=>{d.solids.length>0&&u.set(e[f].id,sc([...i.next,...d.solids]))}),{tick:n,solids:i,report:c,seats:e,posed:u,next:a}}function Ax(t,e){e.report=xx(e.seats,e.report,t.tickHz)}function vx(t,e,n,r){let s=e.report.v;e.report={...e.report,v:s.map((o,i)=>i!==n||o===null?o:[o[0]+r[0]*t.tickHz,o[1]+r[1]*t.tickHz,o[2]])}}var gc=(t,e)=>t.posed.get(e)??t.next;function bc(t,e,n){Sx(t.policy,e.seats,e.report,e.tick,n,t.ops,e.solids.next,t.heads)}function aM(t,e,n){return t.platforms.map((r,s)=>mc(t,s,e,n))}function mc(t,e,n,r){let s=t.platforms[e];if(s===void 0)return{c:[0,0,0],yaw:0};let o=Math.floor(n),i=us(s,o,r?.get(s.id)),a=us(s,o+1,r?.get(s.id)),c=s.spin===null?0:s.spin.dir*2*Math.PI/s.spin.period,u=n-o;return{c:[i.c[0]+(a.c[0]-i.c[0])*u,i.c[1]+(a.c[1]-i.c[1])*u,i.c[2]+(a.c[2]-i.c[2])*u],yaw:i.yaw+c*u}}function wc(t,e,n,r){return t.policy.platforms.length===0?-1:t.ops.support({x:e.x,y:e.y,z:e.z,vz:0,duck:e.duck??0},Ql(t.policy,aM(t.policy,n,r)))}function mh(t,e,n,r,s,o){let i=mc(t,e,r,o),a=mc(t,e,s,o),c=a.yaw-i.yaw,[u,l]=[Math.sin(c),Math.cos(c)],d=n.x-i.c[0],f=n.y-i.c[1];return{x:a.c[0]+l*d-u*f,y:a.c[1]+u*d+l*f,z:n.z+a.c[2]-i.c[2],yaw:n.yaw+c}}function Tx(t,e,n,r){let s=t.platforms.findIndex(i=>i.id===e);if(s<0)return;let o=mc(t,s,n,r);return{x:o.c[0],y:o.c[1],z:o.c[2],yaw:o.yaw}}function yh(t,e,n,r){let s=t.platforms[e];if(s===void 0)return 0;let o=s.shape.kind===ao.Box?s.shape.half[2]:s.shape.half;return mc(t,e,n,r).c[2]+o}var Ex=["x","y","z"],_x=["vx","vy","vz"];function Mx(t,e,n,r,s,o,i){let a={...t,heads:void 0},c={id:"",x:s.x??0,y:s.y??0,z:s.z??0,vx:s.vx??0,vy:s.vy??0,vz:s.vz??0,yaw:s.yaw??0,duck:s.duck??0,flags:0},u=yc(a,[c],o,e,i,n);for(let l of Ex)s[l]=c[l];t.vehicle&&(s.yaw=c.yaw),r(s,gc(u,c.id));for(let l of[...Ex,..._x])c[l]=s[l]??0;bc(a,u,e);for(let l of _x)s[l]=c[l]}var xc=t=>`lift.${t}`,Rx=16;function cM(t){let e=t.surface===null?{}:{friction:0};if(t.shape.kind===ao.Box)return{key:"lift",shape:{kind:"box",half:[t.shape.half[0],t.shape.half[1],t.shape.half[2]]},...e};let{radius:n,half:r}=t.shape,s=[];for(let o=0;o<Rx;o++){let[i,a]=Dt(2*Math.PI*o/Rx);s.push([Math.fround(n*a),Math.fround(n*i),-r],[Math.fround(n*a),Math.fround(n*i),r])}return{key:"lift",shape:{kind:"hull",points:s},...e}}function nd(t,e,n){let r=us(t,e,n?.get(t.id)),[s,o]=Dt(r.yaw/2);return{p:[r.c[0],r.c[1],r.c[2]],q:[0,0,Math.fround(s),Math.fround(o)]}}function Cx(t,e,n){return{key:xc(t.id),type:"kinematic",pose:nd(t,e,n),colliders:[cM(t)]}}var uM=20;function lM(t,e,n,r){let s=n-e.c[0],o=r-e.c[1],[i,a]=e.yaw===0?[0,1]:Dt(e.yaw),c=a*s+i*o,u=a*o-i*s;return t.shape.kind===ao.Disc?c*c+u*u<=t.shape.radius*t.shape.radius:Math.abs(c)<=t.shape.half[0]&&Math.abs(u)<=t.shape.half[1]}var dM=(t,e)=>e+(t.shape.kind===ao.Disc?t.shape.half:t.shape.half[2]);function gh(t,e,n,r){let s=t.platforms.filter(i=>i.surface!==null),o=s.map(i=>us(i,e,n?.get(i.id)));return i=>{let[a,c,u]=[i[0],i[1],i[2]];return s.find((l,d)=>{let f=o[d],h=u-dM(l,f.c[2]);return h>0&&h<=r&&lM(l,f,a,c)})}}function Ox(t,e,n,r,s,o){let i=gh(t,e,n,o),a=Math.min(1,uM/r),c=[];for(let u of s){let[l,d,f]=[u.p[0],u.p[1],u.p[2]],h=i(u.p);if(h===void 0)continue;let p=ed(h,{x:l,y:d,z:f,yaw:0},e,r,n?.get(h.id)),[g,x,b]=[u.v[0],u.v[1],u.v[2]],S=p.v[0]-g,_=p.v[1]-x;S===0&&_===0||c.push({key:u.key,v:[g+S*a,x+_*a,b]})}return c}var co=15,fM=65535;var pM=Object.values(jt),Ix=(t,e,n)=>typeof t=="number"&&Number.isFinite(t)&&t>=e&&t<=n,Dr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Dx=t=>typeof t=="number"&&Number.isFinite(t)&&t>0;function Ec(t){if(t===void 0||t==="")return null;let e;try{e=JSON.parse(t)}catch{return null}if(!Dr(e)||!Dr(e.world))return null;let{keyframeTicks:n,maxLinear:r,maxAngular:s}=e;if(!(typeof n=="number"&&Number.isInteger(n)&&n>=1)||!Dx(r)||!Dx(s))return null;let i=e.presetBody,a=Dr(i)&&Array.isArray(i.half)&&i.half.length===3?{half:i.half,events:i.events===!0}:null,c=pM.includes(e.remotePredict)?e.remotePredict:dr.DEFAULT_REMOTE_PREDICT,u=e.remoteDecayMs,l=Ix(u,0,dr.MAX_REMOTE_DECAY_MS)?u:dr.DEFAULT_REMOTE_DECAY_MS,d=e.leadMs,f=Ix(d,dr.MIN_LEAD_MS,dr.MAX_LEAD_MS)?d:dr.DEFAULT_LEAD_MS;return{world:e.world,keyframeTicks:n,maxLinear:r,maxAngular:s,presetBody:a,remotePredict:c,remoteDecayMs:l,leadMs:f}}function bh(t){return Math.fround(Math.fround(t.dt)/t.substeps)}function hM(t,e){let n=Math.floor(t/e+.5);return Number.isNaN(n)||n<0?0:Math.min(n,fM)}var Sc=ql.ORIENTATION,ls=ql.VELOCITY,ki=t=>t===0?0:t;function Lx(t,e,n){e[n]=ki(t.x),e[n+1]=ki(t.y),e[n+2]=ki(t.z),e[n+3]=qt(t.qx,Sc),e[n+4]=qt(t.qy,Sc),e[n+5]=qt(t.qz,Sc),e[n+6]=qt(t.qw,Sc),e[n+7]=qt(t.lvx,ls),e[n+8]=qt(t.lvy,ls),e[n+9]=qt(t.lvz,ls),e[n+10]=qt(t.avx,ls),e[n+11]=qt(t.avy,ls),e[n+12]=qt(t.avz,ls),e[n+13]=t.sleep?1:0,e[n+14]=t.rest}function wh(t,e,n,r,s,o){s[o]=ki(t[e]),s[o+1]=ki(t[e+1]),s[o+2]=ki(t[e+2]);for(let i=3;i<7;i++)s[o+i]=qt(t[e+i],Sc);for(let i=7;i<10;i++)s[o+i]=qt(t[e+i]/n,ls);for(let i=10;i<13;i++)s[o+i]=qt(t[e+i],ls);s[o+13]=t[e+13]===1?1:0,s[o+14]=hM(t[e+14],r)}function Fx(t,e,n){let r=[...Array.from(t.p),...Array.from(t.q),...Array.from(t.v),...Array.from(t.w),t.sleeping?1:0,t.rest??0],s=[];return wh(r,0,e,n,s,0),s}function Bx(t,e){let n=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);if(!(n>e))return null;let r=e/n;return[t[0]*r,t[1]*r,t[2]*r]}function zx(t,e,n,r=Rw,s=kw){let o=Bx(t,r*n),i=Bx(e,s);return o===null&&i===null?null:{linvel:o??[t[0],t[1],t[2]],angvel:i??[e[0],e[1],e[2]]}}var V2=16*1024;function Ux(t,e){let n;try{n=JSON.parse(t)}catch{return null}if(!Dr(n)||!Array.isArray(n.colliders))return null;for(let r of n.colliders){if(!Dr(r)||!Dr(r.shape))return null;let s=r.shape.ref;if(s===void 0)continue;let o=typeof s=="string"?e(s):void 0;if(o===void 0)return null;try{r.shape=JSON.parse(o)}catch{return null}}return n}var Vx=.5,rd=t=>{if(!Array.isArray(t)||t.length!==3)return 0;let[e,n,r]=t;return Math.sqrt(e*e+n*n+r*r)},Nx=t=>Array.isArray(t)?t.reduce((e,n)=>Math.max(e,rd(n)),0):0;function mM(t){switch(t.kind){case"box":return rd(t.half);case"sphere":return typeof t.radius=="number"?t.radius:0;case"capsule":return(typeof t.halfHeight=="number"?t.halfHeight:0)+(typeof t.radius=="number"?t.radius:0);case"hull":return Nx(t.points);case"trimesh":return Nx(t.vertices);case"heightfield":return rd(t.size);default:return 0}}function _c(t){let e=Array.isArray(t.colliders)?t.colliders:[],n=0;for(let r of e){if(!Dr(r)||!Dr(r.shape))continue;let s=Dr(r.offset)?rd(r.offset.p):0;n=Math.max(n,s+mM(r.shape))}return n}function Hx(t,e,n){let r=new Map,s=u=>{let l=u;for(;r.get(l)!==l;)l=r.get(l);let d=u;for(;d!==l;){let f=r.get(d);r.set(d,l),d=f}return l},o=(u,l)=>{let d=s(u),f=s(l);d!==f&&(d<f?r.set(f,d):r.set(d,f))};for(let u of t)r.set(u.key,u.key);let i=[...t].sort((u,l)=>u.x-l.x||(u.key<l.key?-1:1)),a=i.reduce((u,l)=>Math.max(u,l.radius),0);for(let u=0;u<i.length;u++){let l=i[u];for(let d=u+1;d<i.length;d++){let f=i[d];if(f.x-l.x>l.radius+a+n)break;let h=f.x-l.x,p=f.y-l.y,g=f.z-l.z,x=l.radius+f.radius+n;h*h+p*p+g*g<=x*x&&o(l.key,f.key)}}for(let[u,l]of e)r.has(u)&&r.has(l)&&o(u,l);let c=new Map;for(let u of t)c.set(u.key,s(u.key));return c}function yM(t,e,n){if(n<=0)return t<=1?1:0;let r=1-(t-1)*(1e3/e)/n;return r<=0?0:r>=1?1:r}function od(t,e,n,r){let s=yM(e,n,r);return{...t,moveX:t.moveX*s,moveY:t.moveY*s,moveZ:t.moveZ*s}}var mt={TAU_SMALL_MS:300,TAU_LARGE_MS:100,SMALL_METRES:.25,LARGE_METRES:1,SNAP_PLAYER_METRES:2,SNAP_OTHER_METRES:6,PLAYER_KINDS:Object.freeze(["player","vehicle"]),SEAT_TAU_MS:70,SEAT_CONTACT_TAU_MS:100,SEAT_SNAP_METRES:6,SEAT_HOLD_MS:120,SEAT_MOVING_UNITS_PER_MS:.2,SEAT_CLOCK_TAU_MS:100,SEAT_CLOCK_SNAP_INPUTS:1.5};function gM(t,e){let n=Math.max(t,0)/e;return(1+n)*Math.exp(-n)}function id(t,e,n,r){let s=Math.max(n,0),o=r/2,i=Math.exp(-s/o),a=e+t/o;return[(t+a*s)*i,(e-a*s/o)*i]}function Pi(t){let{TAU_SMALL_MS:e,TAU_LARGE_MS:n,SMALL_METRES:r,LARGE_METRES:s}=mt;return t<=r?e:t>=s?n:e+(t-r)/(s-r)*(n-e)}var sd=class{constructor(){m(this,"last",null);m(this,"offset",null)}draw(e,n,r,s,o,i){let a=this.last;a===null||a.epoch!==r?this.offset=null:a.predicted!==n&&this.startFrom(a,e,s,o,i);let c=this.apply(e,s);return this.last={p:c.p,q:c.q,predicted:n,epoch:r},c}startFrom(e,n,r,s,o){let i=[e.p[0]-n.p[0],e.p[1]-n.p[1],e.p[2]-n.p[2]],a=Math.hypot(i[0],i[1],i[2])/o;if(a>s){this.offset=null;return}let c=zn(e.q,[-n.q[0],-n.q[1],-n.q[2],n.q[3]]),u=c[3]<0?[-c[0],-c[1],-c[2],-c[3]]:c;this.offset={dp:i,dq:u,since:r,tau:Pi(a)}}apply(e,n){let r=this.offset;if(r===null)return{p:[e.p[0],e.p[1],e.p[2]],q:[e.q[0],e.q[1],e.q[2],e.q[3]]};let s=gM(n-r.since,r.tau);return{p:[e.p[0]+r.dp[0]*s,e.p[1]+r.dp[1]*s,e.p[2]+r.dp[2]*s],q:zn(xi(r.dq,s),e.q)}}};function ad(t){return typeof t=="string"&&mt.PLAYER_KINDS.includes(t)?mt.SNAP_PLAYER_METRES:mt.SNAP_OTHER_METRES}function Wx(t,e,n,r){let s=(n-r.tickOrigin)*r.tickHz/1e3,o=Math.floor(s),i=t(e,o),a=t(e,o+1);if(i===null||a===null)return null;let c=s-o;return{p:[i.p[0]+(a.p[0]-i.p[0])*c,i.p[1]+(a.p[1]-i.p[1])*c,i.p[2]+(a.p[2]-i.p[2])*c],q:Mr([...i.q])}}var bM=.1,wM=30,ud={desktop:4,mobile:5};function Yx(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:e}var Rh=Object.freeze([128,64,32]),xh=60,xM=20,SM=2,$x=.5,EM=500,_M=4;function RM(t,e){for(let n=t+1;n<Rh.length;n++)if(Rh[n]<e)return n;return null}function jx(t,e){if(t.length===0)return 0;let n=[...t].sort((r,s)=>r-s);return n[Math.min(n.length-1,Math.floor(e*n.length))]}var qx=500,kM=.02,PM=200,He={ON:"on",OFF:"off",LOADING:"loading",UNAVAILABLE:"unavailable",MISMATCH:"mismatch",SELF_TEST:"self_test",DIVERGED:"diverged",CPU:"cpu"},AM=600;function Gx(t,e){return[id(t.dp[0],t.dv[0],e,t.tau),id(t.dp[1],t.dv[1],e,t.tau),id(t.dp[2],t.dv[2],e,t.tau)]}var Rc=[0,0,0,1],vM=[32767,32767,32767,65534,32767,32767,32767,32767,32767,32767,0,0],TM=[32767,32767,32767,32767,32767,32767,0,0],MM=t=>Math.floor((t+1)/2*65534+.5),Ai=[0,0,0],vi=(t,e)=>t<e?-1:t>e?1:0,CM=(t,e)=>{for(let n=0;n<co;n++)if(!Object.is(t[n],e[n]))return!1;return!0},cd=class{constructor(e,n){m(this,"status",He.LOADING);m(this,"core");m(this,"desc");m(this,"tickHz");m(this,"innerDt");m(this,"lengthUnit");m(this,"leadMax");m(this,"budgetMs");m(this,"clock");m(this,"remoteStep");m(this,"hashesKept");m(this,"world",null);m(this,"base",null);m(this,"seq",0);m(this,"simulated",new Map);m(this,"seats",new Map);m(this,"kinematic",new Map);m(this,"joints",new Map);m(this,"ring",new Map);m(this,"pure",new Set);m(this,"drawn",new Map);m(this,"kinds",new Map);m(this,"ruledClock",null);m(this,"ownPose",()=>{});m(this,"ownVelocity",()=>{});m(this,"bodyRule");m(this,"headSlide");m(this,"propStates",null);m(this,"propStale",!1);m(this,"kinematicRule");m(this,"lifts");m(this,"liftBodies",null);m(this,"seatRule");m(this,"seatPose");m(this,"contactPass");m(this,"posedBySeats",!1);m(this,"remoteBodies",new Map);m(this,"setSize",0);m(this,"costs",[]);m(this,"probedAt",Number.NEGATIVE_INFINITY);m(this,"calmProbes",0);m(this,"chosenCount",0);m(this,"fallbacks",0);m(this,"recoveries",0);m(this,"steppedAt",0);m(this,"canary",[]);m(this,"epochs",new Map);m(this,"hashes",[]);m(this,"chosenKeys",new Set);this.core=e,this.desc=n.desc,this.tickHz=n.tickHz,this.innerDt=bh(n.desc.world),this.lengthUnit=Math.fround(n.desc.world.lengthUnit);let r=n.leadMs??n.desc.leadMs;this.leadMax=Math.ceil(r*n.tickHz/1e3)+n.desc.keyframeTicks-1;let s=n.desc.remotePredict===jt.INPUT_DECAY||n.desc.remotePredict===jt.HOLD;this.remoteStep=s?n.remoteStep:void 0,this.seatPose=n.seatPose,this.contactPass=n.contactPass,this.budgetMs=n.budgetMs??ud.desktop,this.clock=n.clock??(()=>performance.now()),this.hashesKept=n.hashesKept??AM,this.bodyRule=n.bodyRule,this.headSlide=n.headSlide??(()=>null),this.kinematicRule=n.kinematicRule,this.lifts=n.lifts??(()=>null),this.seatRule=n.seatRule;let o=e.World.create(n.desc.world);if(!o.ok){this.status=He.MISMATCH;return}let i=o.world,a=n.staticWorld;if(!(a==null||a.boxes.length===0&&a.ramps.length===0)&&!i.addStaticWorld(a).ok){i.free(),this.status=He.MISMATCH;return}if(i.physicsHash()!==n.physicsHash){i.free(),this.status=He.MISMATCH;return}this.world=i}get predicting(){return this.status===He.ON||this.status===He.LOADING}get stopped(){return this.world===null}draws(e){return this.status===He.ON&&(this.drawn.has(e)||this.ruledElsewhere(e))}ruledElsewhere(e){return this.base!==null&&!this.drawn.has(e)&&this.ruled(e)}stateHash(){return this.world?.stateHash()??""}stop(e){this.status=e,this.world?.free(),this.world=null,this.drawn.clear()}adopt(e,n,r,s,o=()=>{}){let i={kind:"none",replayed:0,ms:0,pure:0,mismatched:0},a=this.world;if(a===null)return i;let c=this.status===He.CPU;if(c&&s-this.probedAt<EM||!c&&!this.predicting)return i;this.ownPose=r,this.ownVelocity=o;let u=this.choose(e),l=new Set(u.filter(b=>b.epoch!==void 0&&this.epochs.has(b.key)&&this.epochs.get(b.key)!==b.epoch).map(b=>b.key));for(let b of u)b.epoch!==void 0&&this.epochs.set(b.key,b.epoch);let d=c?{...i,kind:"replay"}:this.compare(e,u,l);if(this.world===null)return{...d,kind:"none"};if(d.kind==="match"){this.base={tick:e.tick,ack:e.ack};for(let b of this.seatsOf(e))this.seats.set(b.key,b);for(let b of u)this.kinematic.has(b.key)&&this.kinematic.set(b.key,Array.from(b.row));return this.prune(e.tick),this.status=He.ON,d}c&&this.drawn.clear();let f=this.snapshotDrawn(s),h=this.clock();if(!this.rebuild(a,e,u))return this.stop(He.MISMATCH),i;this.base={tick:e.tick,ack:e.ack},this.seq=e.ack,this.ring.clear(),this.readAll(a);let p=Math.min(n,e.ack+this.leadMax),g=0;for(let b=e.ack+1;b<=p&&(this.stepOnce(a),this.world!==null);b++,g++);let x=this.clock()-h;return this.world===null?{...d,kind:"replay",replayed:g,ms:x}:(this.steppedAt=s,this.ease(f,s,l),c?this.judgeProbe(x,s):(this.status=He.ON,this.judgeBudget(x)),{...d,kind:"replay",replayed:g,ms:x})}advance(e,n){let r=this.world;r===null||this.base===null||this.status!==He.ON||e!==this.seq+1||e-this.base.ack>this.leadMax||(this.stepOnce(r),this.steppedAt=n)}draw(e,n){if(this.status!==He.ON)return null;let r=this.drawn.get(e);if(r===void 0)return this.ruledElsewhere(e)?this.ruledDrawn(e,n):null;let s=r.sleep?0:Math.min(Math.max((n-this.steppedAt)/1e3,0),1/this.tickHz),o=this.lengthUnit,i=[r.p[0]+r.lv[0]*o*s,r.p[1]+r.lv[1]*o*s,r.p[2]+r.lv[2]*o*s],a=IM(r.q,r.av,s),c=Math.max(n-r.since,0),u=Gx(r,c);return{p:[i[0]+u[0][0],i[1]+u[1][0],i[2]+u[2][0]],q:zn(xi(r.dq,Math.exp(-c/r.tau)),a)}}choose(e){let n=Vx*this.lengthUnit,r=[],s=new Map;for(let p of e.bodies)s.set(p.key,p),r.push({key:p.key,x:p.row[0],y:p.row[1],z:p.row[2],radius:p.desc===null?0:_c(p.desc)});for(let p of e.outside)r.push(p);let o=[];for(let p of e.joints)typeof p.desc.a=="string"&&typeof p.desc.b=="string"&&o.push([p.desc.a,p.desc.b]);let i=Hx(r,o,n),a=new Map;for(let p of r){let g=i.get(p.key),x=a.get(g);x===void 0?a.set(g,[p.key]):x.push(p.key)}let c=e.seats.find(p=>p.own),u=p=>{let g=s.get(p);return c===void 0?0:Math.hypot(g.row[0]-c.x,g.row[1]-c.y,g.row[2]-c.z)},l=[...a.entries()].filter(([,p])=>p.every(g=>s.get(g)?.desc!=null)).map(([p,g])=>({island:p,keys:g,near:Math.min(...g.map(u))})).sort((p,g)=>p.near-g.near||vi(p.island,g.island)),d=Rh[this.setSize],f=[];this.pure.clear();let h=[...e.seats,...this.seats.values()];for(let{keys:p}of l){if(f.length+p.length>d)continue;for(let b of p)f.push(s.get(b));let g=h.some(b=>p.some(S=>OM(s.get(S),b,n,this.desc))),x=p.some(b=>s.get(b).desc?.type==="kinematic");if(!g&&!x)for(let b of p)this.pure.add(b)}return f.sort((p,g)=>vi(p.key,g.key)),this.chosenKeys=new Set(f.map(p=>p.key)),this.chosenCount=l.reduce((p,{keys:g})=>p+g.length,0),f}compare(e,n,r){let s={kind:"replay",replayed:0,ms:0,pure:0,mismatched:0},o=this.base,i=this.ring.get(e.tick);if(o===null||i===void 0)return s;let a=0,c=0,u=!0;for(let p of n){if(p.desc?.type==="kinematic")continue;let g=i.get(p.key),x=g!==void 0&&CM(g,p.row);this.pure.has(p.key)&&!r.has(p.key)&&g!==void 0&&(a++,x||c++),x||(u=!1)}this.noteCanary(a,c);let l=n.length===this.simulated.size&&n.every(p=>this.simulated.get(p.key)?.desc===Sh(p.desc)),d=e.ack===o.ack+(e.tick-o.tick)&&this.seq>=e.ack,f={...s,pure:a,mismatched:c};return u&&l&&d&&this.sameJoints(e)&&this.sameSeats(e,i)?{...f,kind:"match"}:f}sameJoints(e){let n=this.jointsOf(e);if(n.size!==this.joints.size)return!1;for(let[r,s]of n){let o=this.joints.get(r);if(o===void 0||o.desc!==s.desc||o.motor!==s.motor)return!1}return!0}sameSeats(e,n){let r=this.seatsOf(e);return r.length!==this.seats.size?!1:r.every(s=>{let o=n.get(`seat:${s.key}`);if(o===void 0||this.seats.get(s.key)?.epoch!==s.epoch)return!1;let i=this.presetPosition(s.x,s.y,s.z);return o[0]===i[0]&&o[1]===i[1]&&o[2]===i[2]})}noteCanary(e,n){for(let s=0;s<e;s++)this.canary.push(s<n);if(this.canary.length>qx&&this.canary.splice(0,this.canary.length-qx),this.canary.length<PM)return;this.canary.filter(Boolean).length/this.canary.length>kM&&this.stop(He.DIVERGED)}judgeBudget(e){if(this.costs.push(e),this.costs.length>xh&&this.costs.splice(0,this.costs.length-xh),this.costs.length<xM)return;let n=jx(this.costs,.5),r=jx(this.costs,.9);if(n>this.budgetMs||r>SM*this.budgetMs){this.costs=[];let i=RM(this.setSize,this.chosenCount);if(i!==null){this.setSize=i;return}this.fallBack();return}this.costs.length>=xh&&r<=$x*this.budgetMs&&this.setSize>0&&(this.setSize--,this.costs=[])}fallBack(){this.status=He.CPU,this.fallbacks++,this.drawn.clear(),this.probedAt=Number.NEGATIVE_INFINITY,this.calmProbes=0}judgeProbe(e,n){if(this.probedAt=n,this.calmProbes=e<=$x*this.budgetMs?this.calmProbes+1:0,this.calmProbes<_M){this.drawn.clear();return}this.status=He.ON,this.recoveries++,this.costs=[],this.calmProbes=0}jointsOf(e){let n=new Map;for(let r of e.joints){let s=r.desc.a,o=r.desc.b;!this.simulated.has(s)&&!this.chosenHas(s)||o!==null&&!this.simulated.has(o)&&!this.chosenHas(o)||n.set(r.key,{desc:JSON.stringify(r.desc),motor:r.motor===null?"":JSON.stringify(r.motor),parsed:r})}return n}chosenHas(e){return this.chosenKeys.has(e)}seatsOf(e){if(this.desc.presetBody===null)return[];let n=this.desc.world.limits.worldExtent;return e.seats.filter(r=>this.presetPosition(r.x,r.y,r.z).every(s=>Math.abs(s)<=n)).sort((r,s)=>vi(r.key,s.key))}presetPosition(e,n,r){let s=this.desc.presetBody?.half[2]??0;return[Math.fround(e),Math.fround(n),Math.fround(Math.fround(r)+s)]}rebuild(e,n,r){let s=this.jointsOf(n);for(let c of[...this.joints.keys()]){let u=s.get(c);u!==void 0&&u.desc===this.joints.get(c).desc||(e.removeJoint(c),this.joints.delete(c))}for(let[c,u]of[...this.simulated]){let l=r.find(d=>d.key===c);l!==void 0&&Sh(l.desc)===u.desc||(e.remove(c),this.simulated.delete(c),this.kinematic.delete(c),this.drawn.delete(c))}for(let c of r)if(!(this.simulated.has(c.key)||c.desc===null)){if(!e.spawn(c.desc).ok)return!1;this.kinds.set(c.key,c.desc.kind),this.simulated.set(c.key,{type:String(c.desc.type),desc:Sh(c.desc)})}this.kinematic.clear();for(let c of r)c.desc?.type==="kinematic"&&(this.kinematic.set(c.key,Array.from(c.row)),this.ruled(c.key)||this.drawn.delete(c.key));if(this.propStates=null,!this.rebuildSeats(e,n))return!1;let o=this.rebuildLifts(e,n.tick);if(o===null)return!1;for(let[c,u]of s){if(!this.joints.has(c)&&!e.addJoint(u.parsed.desc).ok)return!1;let l=this.joints.get(c);if(u.parsed.motor!==null&&l?.motor!==u.motor&&!e.setMotor(c,u.parsed.motor).ok)return!1;this.joints.set(c,{desc:u.desc,motor:u.motor})}let i=[],a=[];for(let c of r){i.push(c.key);for(let u=0;u<co;u++)a.push(c.row[u])}for(let c of this.seats.values())i.push(c.key),a.push(...this.presetPosition(c.x,c.y,c.z),...vM);for(let[c,u]of o)i.push(c),a.push(...u);return i.length>0&&!e.importWire(i,a).ok?!1:e.canonicalize({quantize:!0}).ok}rebuildLifts(e,n){let r=this.lifts(),s=this.liftBodies;if(s!==null&&s.policy!==r?.policy){for(let o of s.keys)e.remove(o);this.liftBodies=null}if(r===null||r.policy.platforms.length===0)return[];if(this.liftBodies===null){for(let o of r.policy.platforms)if(!e.spawn(Cx(o,n+1,r.starts)).ok)return null;this.liftBodies={policy:r.policy,keys:r.policy.platforms.map(o=>xc(o.id))}}return r.policy.platforms.map(o=>{let{p:i,q:a}=nd(o,n+1,r.starts);return[xc(o.id),[...i,...a.map(MM),...TM]]})}rebuildSeats(e,n){let r=new Map(this.seatsOf(n).map(o=>[o.key,o]));for(let[o,i]of[...this.seats])r.get(o)?.epoch!==i.epoch&&(e.remove(o),this.seats.delete(o));let s=this.desc.presetBody;for(let[o,i]of r){if(!this.seats.has(o)&&s!==null){let a={key:"hull",shape:{kind:"box",half:[...s.half]},events:s.events,...this.headSlide()===null?{}:{friction:0}};if(!e.spawn({key:o,type:"kinematic",pose:{p:this.presetPosition(i.x,i.y,i.z),q:[...Rc]},colliders:[a]}).ok)return!1}this.seats.set(o,i)}return!0}stepOnce(e){let n=this.base,r=this.seq+1,s=n.tick+(r-n.ack),o=[],i=!1;for(let l of this.seats.values())o.push(this.seatAt(l,r,s-n.tick)),i||(i=this.posedBySeats);i||this.passSeats(o);for(let l of o)e.setNextKinematicPose(l.key,{p:this.presetPosition(l.x,l.y,l.z),q:[...Rc]});for(let[l,d]of this.kinematic){let f=this.kinematicRule?.(l,s+1)??null;e.setNextKinematicPose(l,f===null?DM(d):{p:[...f.p],q:[...f.q]})}let a=this.liftBodies===null?null:this.lifts();for(let l of a?.policy.platforms??[])e.setNextKinematicPose(xc(l.id),nd(l,s+1,a?.starts));this.applyBodyRule(e,s,o);let c=e.tick,u=e.step();if(!u.ok){this.stop(He.DIVERGED);return}for(let l of u.escaped)e.remove(l),this.simulated.delete(l),this.drawn.delete(l);this.clamp(e,c),s%this.desc.keyframeTicks===0&&(e.canonicalize({quantize:!0}),this.propStale=!0,this.ring.set(s,this.rowsNow(e))),this.seq=r,this.readDrawn(e,c),this.hashes.push({tick:s,hash:e.stateHash()}),this.hashes.length>this.hashesKept&&this.hashes.splice(0,this.hashes.length-this.hashesKept)}seatAt(e,n,r){this.posedBySeats=!1;let s=e.own?this.ownPose(n):void 0;if(s!==void 0){let f=this.ownVelocity(n)??[e.vx,e.vy,e.vz];return{key:e.key,x:s[0],y:s[1],z:s[2],vx:f[0],vy:f[1],vz:f[2]}}let o=e.own?void 0:this.seatPose?.(e.key,n);if(o!==void 0)return this.posedBySeats=!0,{...o,key:e.key};let i=this.remoteStep;if(e.own||i===void 0||e.input===void 0){let f=r/this.tickHz;return{key:e.key,x:e.x+e.vx*f,y:e.y+e.vy*f,z:e.z+e.vz*f,vx:e.vx,vy:e.vy,vz:e.vz}}let a=this.remoteBodies.get(e.key),c=a!==void 0&&a.from===e&&a.j<=r,u=c?a.body:{...e.body??{},x:e.x,y:e.y,z:e.z},l=1/this.tickHz,d=this.base?.tick??0;for(let f=(c?a.j:0)+1;f<=r;f++){this.seatRule?.(u,d+f);let h=this.desc.remotePredict===jt.HOLD;i(u,h?e.input:od(e.input,f,this.tickHz,this.desc.remoteDecayMs),l,d+f)}return this.remoteBodies.set(e.key,{from:e,j:r,body:u}),{key:e.key,x:u.x,y:u.y,z:u.z,vx:u.vx??e.vx,vy:u.vy??e.vy,vz:u.vz??e.vz,...u.yaw===void 0?{}:{yaw:u.yaw}}}passSeats(e){let n=this.contactPass;if(n===void 0||e.length<2)return;let r=e.map(o=>({id:o.key,x:o.x,y:o.y,z:o.z,vx:o.vx,vy:o.vy,vz:o.vz,yaw:o.yaw??0}));r.sort((o,i)=>vi(o.id,i.id)),n(r);let s=new Map(r.map(o=>[o.id,o]));for(let o of e){let i=s.get(o.key);o.x=i.x,o.y=i.y,o.z=i.z,o.vx=i.vx,o.vy=i.vy,o.vz=i.vz}}applyBodyRule(e,n,r){let s=this.bodyRule,o=this.headSlide(),i=this.liftBodies===null?null:this.lifts(),a=i!==null&&i.policy.platforms.some(d=>d.surface!==null)?i:null;if(s===void 0&&o===null&&a===null)return;r.sort((d,f)=>vi(d.key,f.key));let c=d=>{if(this.simulated.get(d)?.type!=="dynamic")return null;let f=e.exportBodyState(d);return f===null?null:{p:[f.p[0],f.p[1],f.p[2]],v:[f.v[0],f.v[1],f.v[2]]}};for(let d of s?.({tick:n,seats:r,body:c})??[])this.simulated.get(d.key)?.type==="dynamic"&&e.setVelocity(d.key,[d.v[0],d.v[1],d.v[2]]);let u=this.desc.presetBody?.half;if(o===null&&a===null||u===void 0)return;if(this.propStates===null){this.propStates=new Map;for(let d of this.simulated.keys()){let f=c(d);f!==null&&this.propStates.set(d,{key:d,p:f.p,v:f.v})}this.propStale=!1}this.propStale&&this.freshenPicked(r,u,a===null?null:gh(a.policy,n,a.starts,2*u[2]),o!==null,c);let l=[...this.propStates.values()].filter(d=>this.simulated.get(d.key)?.type==="dynamic").sort((d,f)=>vi(d.key,f.key));if(a!==null)for(let d of Ox(a.policy,n,a.starts,this.tickHz,l,2*u[2]))e.setVelocity(d.key,d.v);if(o!==null)for(let d of cx(r,u,l,o))e.setVelocity(d.key,d.v)}freshenPicked(e,n,r,s,o){let i=this.propStates;if(this.propStale=!1,i!==null)for(let[a,c]of i){if(!(s&&ph(e,n,c.p)!==void 0||r!==null&&r(c.p)!==void 0))continue;let l=o(a);l!==null&&i.set(a,{key:a,p:l.p,v:l.v})}}clamp(e,n){let{keys:r,data:s}=e.exportChanged(n,{rest:!0});for(let o=0;o<r.length;o++){let i=r[o];if(this.simulated.get(i)?.type!=="dynamic")continue;let a=o*co,c=[s[a+7],s[a+8],s[a+9]],u=[s[a+10],s[a+11],s[a+12]],l=zx(c,u,this.lengthUnit,this.desc.maxLinear,this.desc.maxAngular);l!==null&&e.setVelocity(i,l.linvel,l.angvel),this.propStates?.set(i,{key:i,p:[s[a],s[a+1],s[a+2]],v:l===null?c:[l.linvel[0],l.linvel[1],l.linvel[2]]})}}rowsNow(e){let n=new Map,r=(s,o)=>{let i=e.exportBodyState(s,{rest:!0});i!==null&&n.set(o,Fx(i,this.lengthUnit,this.innerDt))};for(let s of this.simulated.keys())r(s,s);for(let s of this.seats.keys())r(s,`seat:${s}`);return n}ruledDrawn(e,n){let r=this.kinematicRule,s=this.ruledTick(n);if(r===void 0||s===null)return null;let o=Math.floor(s),i=r(e,o),a=r(e,o+1);if(i===null||a===null)return null;let c=s-o;return{p:[i.p[0]+(a.p[0]-i.p[0])*c,i.p[1]+(a.p[1]-i.p[1])*c,i.p[2]+(a.p[2]-i.p[2])*c],q:Mr([...i.q])}}ruledTick(e){let n=this.base;if(n===null)return null;let r=Math.min(Math.max((e-this.steppedAt)/1e3*this.tickHz,0),1),s=n.tick+(this.seq-n.ack)+1+r,o=this.ruledClock;if(o===null||e<o.at||Math.abs(s-o.tick)>wM)return this.ruledClock={at:e,tick:s},s;let i=(e-o.at)/1e3*this.tickHz,a=o.tick+i,c=bM*i,u=a+Math.min(Math.max(s-a,-c),c);return this.ruledClock={at:e,tick:u},u}ruled(e){if(this.kinematicRule===void 0)return!1;let n=this.base,r=n===null?0:n.tick+(this.seq-n.ack);return this.kinematicRule(e,r)!==null}prune(e){for(let n of this.ring.keys())n<=e&&this.ring.delete(n)}readDrawn(e,n){let{keys:r,data:s}=e.exportChanged(n,{rest:!0});for(let o=0;o<r.length;o++){let i=r[o];if(!this.simulated.has(i)||this.kinematic.has(i)&&!this.ruled(i))continue;let a=o*co,c=this.drawn.get(i);this.drawn.set(i,{p:[s[a],s[a+1],s[a+2]],q:Mr([s[a+3],s[a+4],s[a+5],s[a+6]]),lv:[s[a+7]/this.lengthUnit,s[a+8]/this.lengthUnit,s[a+9]/this.lengthUnit],av:[s[a+10],s[a+11],s[a+12]],sleep:s[a+13]===1,dp:c?.dp??Ai,dv:c?.dv??Ai,dq:c?.dq??Rc,since:c?.since??0,tau:c?.tau??Pi(0),snap:c?.snap??this.snapOf(i)})}}builtInRules(){if(!this.desc.presetBody)return!1;if(this.headSlide()!==null)return!0;let e=this.liftBodies===null?null:this.lifts();return e!==null&&e.policy.platforms.some(n=>n.surface!==null)}readAll(e){let n=this.builtInRules()?new Map:null;for(let r of this.simulated.keys()){let s=this.kinematic.has(r)&&!this.ruled(r)?null:e.exportBodyState(r,{rest:!0});if(s===null)continue;n!==null&&this.simulated.get(r)?.type==="dynamic"&&n.set(r,{key:r,p:[s.p[0],s.p[1],s.p[2]],v:[s.v[0],s.v[1],s.v[2]]});let o=this.drawn.get(r),i=this.lengthUnit;this.drawn.set(r,{p:[s.p[0],s.p[1],s.p[2]],q:Mr([s.q[0],s.q[1],s.q[2],s.q[3]]),lv:[s.v[0]/i,s.v[1]/i,s.v[2]/i],av:[s.w[0],s.w[1],s.w[2]],sleep:s.sleeping,dp:o?.dp??Ai,dv:o?.dv??Ai,dq:o?.dq??Rc,since:o?.since??0,tau:o?.tau??Pi(0),snap:o?.snap??this.snapOf(r)})}n!==null&&(this.propStates=n,this.propStale=!1)}snapshotDrawn(e){let n=new Map;for(let[r,s]of this.drawn){let o=Math.max(e-s.since,0),i=Gx(s,o);n.set(r,{p:[s.p[0]+i[0][0],s.p[1]+i[1][0],s.p[2]+i[2][0]],q:zn(xi(s.dq,Math.exp(-o/s.tau)),s.q),rate:[i[0][1],i[1][1],i[2][1]]})}return n}snapOf(e){return ad(this.kinds.get(e))*this.lengthUnit}ease(e,n,r){for(let[s,o]of this.drawn){let i=e.get(s),a={...o,dp:Ai,dv:Ai,dq:Rc,since:n,tau:Pi(0)};if(i===void 0||r.has(s)){this.drawn.set(s,a);continue}let c=[i.p[0]-o.p[0],i.p[1]-o.p[1],i.p[2]-o.p[2]],u=Math.hypot(c[0],c[1],c[2]);if(u>o.snap){this.drawn.set(s,a);continue}let l=zn(i.q,[-o.q[0],-o.q[1],-o.q[2],o.q[3]]),d=l[3]<0?[-l[0],-l[1],-l[2],-l[3]]:l;this.drawn.set(s,{...o,dp:c,dv:i.rate,dq:d,since:n,tau:Pi(u/this.lengthUnit)})}}},Sh=t=>t===null?"":JSON.stringify(t);function OM(t,e,n,r){let s=r.presetBody?.half??[0,0,0],o=Math.hypot(s[0],s[1],s[2])+(t.desc===null?0:_c(t.desc))+n;return Math.hypot(t.row[0]-e.x,t.row[1]-e.y,t.row[2]-(e.z+s[2]))<=o}function IM(t,e,n){let r=Math.hypot(e[0],e[1],e[2]);if(r===0||n===0)return t;let s=r*n/2,o=Math.sin(s)/r;return Mr(zn([e[0]*o,e[1]*o,e[2]*o,Math.cos(s)],t))}function DM(t){let e=r=>-1+r/65534*2,n=Mr([e(t[3]),e(t[4]),e(t[5]),e(t[6])]);return{p:[t[0],t[1],t[2]],q:[n[0],n[1],n[2],n[3]]}}var Eh={contract:"1.0",dt:1/60,substeps:1,gravity:[0,0,-9.81],upAxis:"z",lengthUnit:1},_h=12;function BM(){let t=(e,n,r)=>({key:e,type:"dynamic",pose:{p:n,q:[0,0,0,1]},linvel:[1,0,0],colliders:[{key:"c",shape:{kind:"box",half:[r,r,r]}}]});return[t("a",[0,0,.5],.5),t("b",[0,0,1.6],.5),{key:"c",type:"dynamic",pose:{p:[2,0,1],q:[0,0,0,1]},angvel:[0,3,0],colliders:[{key:"c",shape:{kind:"sphere",radius:.4}}]}]}function Kx(t){let n=[t.World.create(Eh),t.World.create(Eh)].flatMap(r=>r.ok?[r.world]:[]);try{if(n.length!==2)return!1;let[r,s]=n,o={boxes:[[-20,-20,-1,20,20,0]],ramps:[]};if(!r.addStaticWorld(o).ok||!s.addStaticWorld(o).ok)return!1;for(let l of BM())if(!r.spawn(l).ok||!s.spawn(l).ok)return!1;for(let l=0;l<_h;l++)r.step();s.canonicalize({});for(let l=0;l<_h;l++)s.step();if(!r.canonicalize({quantize:!0}).ok)return!1;let{keys:i,data:a}=r.exportChanged(r.tick,{rest:!0}),c=[],u=bh(Eh);for(let l=0;l<i.length;l++)wh(a,l*co,1,u,c,l*co);if(i.length!==3||!s.importWire(i,c).ok||!s.canonicalize({quantize:!0}).ok)return!1;for(let l=0;l<_h;l++)if(r.step(),s.step(),r.stateHash()!==s.stateHash())return!1;return!0}finally{for(let r of n)r.free()}}var K2=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);var uo=["x","y","z","vx","vy","vz","yaw","spin"],NM=(t,e)=>t.body.id<e.body.id?-1:t.body.id>e.body.id?1:0,ld=class{constructor(e,n){m(this,"pass",null);m(this,"rule");m(this,"others");this.rule=e,this.others=n}apply(e,n,r,s){(this.pass===null||this.pass.ack!==n||e<=this.pass.last)&&(this.pass={ack:n,last:n,others:this.others().map(u=>({body:{...u},from:0})).sort(NM)});let i=this.pass,a=e-n,c={...r};i.others=i.others.map(u=>{let l=(a-u.from)/s,d=u.body,f={...d,x:d.x+d.vx*l,y:d.y+d.vy*l,z:d.z+d.vz*l},h=JSON.stringify(f);return c.id<f.id?this.rule(c,f):this.rule(f,c),JSON.stringify(f)===h?u:{body:f,from:a}});for(let u of uo){let l=c[u];typeof l=="number"&&l!==r[u]&&(r[u]=Math.fround(l))}i.last=e}seatAt(e,n,r,s){let o=this.pass!==null&&this.pass.ack===n?this.pass.others.find(l=>l.body.id===e):void 0,i=o===void 0?this.others().find(l=>l.id===e):void 0,a=o?.from??0,c=o?.body??i;if(c===void 0)return;let u=(r-a)/s;return{...c,x:c.x+c.vx*u,y:c.y+c.vy*u,z:c.z+c.vz*u}}};function lo(t,e,n){let r={x:n.x,y:n.y,z:n.z};for(let s=0;s<LM;s++){let o={...e,vx:0,vy:0,vz:0},i={...n,...r,vx:0,vy:0,vz:0};o.id<i.id?t(o,i):t(i,o);let a={x:r.x+(i.x-r.x)-(o.x-e.x),y:r.y+(i.y-r.y)-(o.y-e.y),z:r.z+(i.z-r.z)-(o.z-e.z)};if(s>0&&a.x===r.x&&a.y===r.y&&a.z===r.z||(r=a,s===0&&dd(t,e,n,r)<=FM))break}return dd(t,e,n,r)>eS?HM(t,e,n,r):r}var LM=8,FM=.01,eS=.001,zM=30,UM=8,VM=1;function HM(t,e,n,r){let s={x:n.x,y:n.y,z:n.z},o={x:r.x-s.x,y:r.y-s.y,z:r.z-s.z},i=Math.hypot(o.x,o.y,o.z)>0?o:tS(t,e,n,s),a=Math.hypot(i.x,i.y,i.z);if(a===0)return r;let c={x:i.x/a,y:i.y/a,z:i.z/a},u=h=>({x:s.x+c.x*h,y:s.y+c.y*h,z:s.z+c.z*h}),l=h=>dd(t,e,n,u(h))>0,d=a,f=a+Math.max(VM,a);for(let h=0;h<UM&&l(f);h++)d=f,f=a+(f-a)*2;if(l(f))return r;for(let h=0;h<zM;h++){let p=(d+f)/2;l(p)?d=p:f=p}return u(f)}function tS(t,e,n,r){let s={...e,vx:0,vy:0,vz:0},o={...n,...r,vx:0,vy:0,vz:0};return s.id<o.id?t(s,o):t(o,s),{x:o.x-r.x-(s.x-e.x),y:o.y-r.y-(s.y-e.y),z:o.z-r.z-(s.z-e.z)}}function dd(t,e,n,r){let s=tS(t,e,n,r);return Math.hypot(s.x,s.y,s.z)}var $M=3*Math.PI,jM=Math.PI/2,qM=.05,GM=8,Xx=16,WM=30,YM=8,nS=(t,e,n)=>({...e,x:t.x+n.dx,y:t.y+n.dy,z:t.z+n.dz,vx:0,vy:0,vz:0});function Ah(t,e,n,r){let s=nS(e,n,r),o=lo(t,e,s);return Math.hypot(o.x-s.x,o.y-s.y,o.z-s.z)}function fd(t,e,n,r,s){let o=Math.hypot(s.dx-r.dx,s.dy-r.dy,s.dz-r.dz),i=Math.min(o,Math.hypot(r.dx,r.dy,r.dz));if(i===0)return!1;for(let a=1;a<Xx;a++){let c=a/Xx,u={dx:r.dx+(s.dx-r.dx)*c,dy:r.dy+(s.dy-r.dy)*c,dz:r.dz+(s.dz-r.dz)*c};if(Ah(t,e,n,u)>Math.min(qM*i,GM))return!0}return!1}function Ph(t,e,n,r,s,o){let i=Math.cos(r),a=Math.sin(r),c=d=>Ah(t,e,n,{dx:d*i,dy:d*a,dz:s})>0;if(!c(0)||o<=0)return 0;let u=0,l=o;for(let d=0;d<YM&&c(l);d++)u=l,l*=2;for(let d=0;d<WM;d++){let f=(u+l)/2;c(f)?u=f:l=f}return l}var Jx=4,KM=20;function XM(t,e,n){let r=n.z>=e.z?1:-1,s=a=>Ah(t,e,n,{dx:n.x-e.x,dy:n.y-e.y,dz:n.z-e.z+r*a})>0;if(!s(0)||s(Jx))return n;let o=0,i=Jx;for(let a=0;a<KM;a++){let c=(o+i)/2;s(c)?o=c:i=c}return{...n,z:n.z+r*i}}var Zx=2*Math.PI,JM=t=>t-Zx*Math.floor((t+Math.PI)/Zx);function Qx(t,e,n,r,s,o=!1){let i=XM(t,e,n),a=lo(t,e,i),c={dx:a.x-e.x,dy:a.y-e.y,dz:a.z-e.z},u=a.x!==i.x||a.y!==i.y||a.z!==i.z,l=i.x-e.x,d=i.y-e.y,f=(N,Y)=>({x:e.x+N.dx,y:e.y+N.dy,z:e.z+N.dz,side:{...N,held:Y,bx:l,by:d,at:s}}),h=N=>f(ZM(t,e,i,N),!0);if(r===void 0||!(o||fd(t,e,i,r,c)))return f(c,u);let p=Math.hypot(r.dx,r.dy),g=Math.hypot(c.dx,c.dy),x=Math.atan2(r.dy,r.dx);if(!r.held){if(r.dx*c.dx+r.dy*c.dy>=0)return f(c,u);let N=Ph(t,e,i,x,c.dz,Math.max(p,g));return h({dx:N*Math.cos(x),dy:N*Math.sin(x),dz:c.dz})}let b=JM(Math.atan2(c.dy,c.dx)-x),S=p>0?jM*Math.hypot(l-r.bx,d-r.by)/p:0,_=Math.max(S,$M*Math.max(0,s-r.at)/1e3),P=Math.min(Math.abs(b),_),R=b===0?1:P/Math.abs(b),v=x+Math.sign(b)*P,M=c.dz-r.dz,O=_*Math.max(p,g),z=Math.abs(M*R)>O?r.dz+Math.sign(M)*O:r.dz+M*R,X=Math.max(p+(g-p)*R,Ph(t,e,i,v,z,Math.max(p,g)));return h({dx:X*Math.cos(v),dy:X*Math.sin(v),dz:z})}function ZM(t,e,n,r){let s=nS(e,n,r);return dd(t,e,s,s)>eS?Ti(e,lo(t,e,s)):r}function QM(t,e,n,r,s,o,i){let a={dx:i.x-e.x,dy:i.y-e.y,dz:i.z-e.z};for(let c of r){let u=c===n?void 0:s.get(c.id);if(u===void 0)continue;let l={...c,x:e.x+u.dx,y:e.y+u.dy,z:e.z+u.dz,vx:0,vy:0,vz:0},d=f=>({dx:f.dx-u.dx,dy:f.dy-u.dy,dz:f.dz-u.dz});if(fd(t,l,n,d(o),d(a)))return!0}return!1}var kc=(t,e)=>t<e?`${t}\0${e}`:`${e}\0${t}`,eC=12,Br=(t,e)=>({...t,x:e.x,y:e.y,z:e.z,vx:0,vy:0,vz:0}),Ti=(t,e)=>({dx:e.x-t.x,dy:e.y-t.y,dz:e.z-t.z}),pd=(t,e)=>t.x===e.x&&t.y===e.y&&t.z===e.z,tC=720,nC=.1,rC=24,sC=8,oC=64;function vh(t,e,n,r,s){return!pd(lo(t,Br(e,r),Br(n,s)),s)}var rS=(t,e,n,r)=>[{x:t.x-n.nx*r/2,y:t.y-n.ny*r/2,z:t.z},{x:e.x+n.nx*r/2,y:e.y+n.ny*r/2,z:e.z}];function iC(t,e,n,r,s,o,i){let a=l=>vh(t,e,n,...rS(r,s,o,l));if(!a(i))return i;let c=i,u=i+oC;for(let l=0;l<sC&&a(u);l++)c=u,u=i+(u-i)*2;for(let l=0;l<rC;l++){let d=(c+u)/2;a(d)?c=d:u=d}return u}function kh(t,e){let n=Math.hypot(t,e);return n>0?{nx:t/n,ny:e/n}:null}function aC(t,e,n,r,s,o){let i=lo(t,Br(e,r),Br(n,s)),a=(o===void 0?null:kh(o.dx,o.dy))??kh(s.x-r.x,s.y-r.y),c=kh(i.x-s.x,i.y-s.y),u=c!==null&&a!==null&&c.nx*a.nx+c.ny*a.ny<0?-1:1;return{...c===null?a??{nx:1,ny:0}:{nx:u*c.nx,ny:u*c.ny},push:0}}function cC(t,e,n,r){let s=r.get(e.id),o=r.get(n.id),i=lo(t,Br(e,s),Br(n,o));if(pd(i,o))return!1;let a={x:(i.x-o.x)/2,y:(i.y-o.y)/2,z:(i.z-o.z)/2};return r.set(e.id,{x:s.x-a.x,y:s.y-a.y,z:s.z-a.z}),r.set(n.id,{x:o.x+a.x,y:o.y+a.y,z:o.z+a.z}),!0}function sS(t,e,n,r){return r.nx*(n.x-e.x)+r.ny*(n.y-e.y)<0&&!vh(t,e,n,e,n)}var oS=(t,e,n,r,s)=>s.nx*(r.x-n.x-(e.x-t.x))+s.ny*(r.y-n.y-(e.y-t.y));function uC(t,e,n,r,s,o,i){let a=kc(e.id,n.id),c=r.get(e.id),u=r.get(n.id),l=s.get(a),d=0;if(l===void 0){let g=o?.pair;if(g===void 0?!vh(t,e,n,e,n):sS(t,e,n,g))return cC(t,e,n,r);l=g??aC(t,e,n,c,u,o),s.set(a,l);let x=g===void 0?0:g.push-tC*Math.min(i,nC);d=Math.max(0,x-oS(e,n,c,u,l))}let f=iC(t,e,n,c,u,l,d);if(f<=0)return!1;let[h,p]=rS(c,u,l,f);return r.set(e.id,h),r.set(n.id,p),!0}function lC(t,e,n,r,s,o){if(s===void 0)return;let i=r.get(e.id),a=r.get(n.id),c=Ti(i,a);if(s.dx*c.dx+s.dy*c.dy>=0)return;let u=Br(e,i),l=Br(n,a);if(!fd(t,u,l,s,c))return;let d=Math.atan2(s.dy,s.dx),f=Ph(t,u,l,d,s.dz,Math.hypot(s.dx,s.dy)),h={dx:f*Math.cos(d),dy:f*Math.sin(d),dz:s.dz};return o(n.id)>=o(e.id)?(r.set(n.id,{x:i.x+h.dx,y:i.y+h.dy,z:i.z+h.dz}),n.id):(r.set(e.id,{x:a.x-h.dx,y:a.y-h.dy,z:a.z-h.dz}),e.id)}function dC(t,e,n,r,s){let o=Br(n,r),i=lo(t,e,o);return pd(i,r)?r:fd(t,e,o,Ti(e,s),Ti(e,i))?s:i}function fC(t){return t.flatMap((e,n)=>t.slice(n+1).map(r=>[e,r]))}function iS(t,e,n,r,s){let o=[...n].sort((h,p)=>h.id<p.id?-1:h.id>p.id?1:0),i=new Map;for(let h of o){let p=r.get(h.id),g=Qx(t,e,h,p,s),b=p?.held===!0&&!g.side.held&&QM(t,e,h,o,r,p,g)?Qx(t,e,h,p,s,!0):g;i.set(h.id,{x:b.x,y:b.y,z:b.z})}let a=new Map(i),c=h=>{let p=r.get(h),g=a.get(h);return p===void 0?Number.POSITIVE_INFINITY:Math.hypot(g.x-e.x-p.dx,g.y-e.y-p.dy,g.z-e.z-p.dz)},u=fC(o),l=(h,p)=>r.get(kc(h.id,p.id));for(let[h,p]of u){let g=l(h,p);(g?.pair===void 0||sS(t,h,p,g.pair))&&lC(t,h,p,i,g,c)}let d=new Map;for(let h=0;;h++){for(let g of o)i.set(g.id,dC(t,e,g,i.get(g.id),a.get(g.id)));if(h===eC)break;let p=!1;for(let[g,x]of u){let b=l(g,x);p=uC(t,g,x,i,d,b,b===void 0?0:Math.max(0,s-b.at)/1e3)||p}if(!p)break}let f=new Map;for(let h of o){let p=i.get(h.id);f.set(h.id,{...Ti(e,p),held:!pd(p,h),bx:h.x-e.x,by:h.y-e.y,at:s})}for(let[h,p]of u){let g=i.get(h.id),x=kc(h.id,p.id),b=d.get(x),S=b===void 0?0:oS(h,p,g,i.get(p.id),b),_=b!==void 0&&S>0?{pair:{nx:b.nx,ny:b.ny,push:S}}:{};f.set(x,{...Ti(g,i.get(p.id)),held:!1,bx:p.x-h.x,by:p.y-h.y,at:s,..._})}return{drawn:i,sides:f}}var Mi=(t,e,n)=>t+(n-e);var Ci=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function pC(t){if(!Ci(t)||typeof t.preset!="string"||!Object.hasOwn(Nw,t.preset))return!1;let e=t.shape,n=t.hull;return!Ci(e)||e.kind!==Vn.Box&&e.kind!==Vn.Hull||!Ci(n)?!1:Ci(t.top)&&Ci(t.offWall)&&Array.isArray(t.pairs)&&typeof t.passes=="number"}function aS(t,e){if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}let r=Ci(n)?n.contacts:void 0;if(!pC(r))return null;let s={world:Uw(e,r.hull.radius,r.hull.height,r.hull.skin)},o=new Map,i=a=>{let c=o.get(a);if(c!==void 0)return c;let u=fh(r,{...s,fixed:a});return o.set(a,u),u};return{policy:r,rule:fh(r,s),pass:sx(r,s),env:s,drawRule:i}}function cS(t){return Number.isSafeInteger(t)?(t%65536+65536)%65536:0}var mS=500;function hC(t,e,n,r){let s=t.poses.get(n)?.get(e);if(s===void 0)return;let o=t.poses.get(n-1)?.get(e),i=t.poses.get(n-2)?.get(e);if(o===void 0){let h=r/t.tickHz;return{...s,x:s.x+s.vx*h,y:s.y+s.vy*h,z:s.z+s.vz*h}}let a=Math.floor(r),c=h=>h*(h+1)/2,u=(h,p,g)=>{let x=h+p*a+g*c(a),b=h+p*(a+1)+g*c(a+1);return x+(b-x)*(r-a)},l=(h,p,g)=>g===void 0?0:h-2*p+g,d=ds(s.yaw-o.yaw),f=i===void 0?0:d-ds(o.yaw-i.yaw);return{...s,x:u(s.x,s.x-o.x,l(s.x,o.x,i?.x)),y:u(s.y,s.y-o.y,l(s.y,o.y,i?.y)),z:u(s.z,s.z-o.z,l(s.z,o.z,i?.z)),yaw:ds(u(s.yaw,d,f))}}function mC(t,e){let n=t.ack+t.ticks,r=Math.min(Math.max(e,t.ack+1),n),s=Math.floor(r),o=t.own.get(s);if(o===void 0)return;let i=t.own.get(s+1),a=r-s;return i===void 0||a===0?o:{...o,x:o.x+(i.x-o.x)*a,y:o.y+(i.y-o.y)*a,z:o.z+(i.z-o.z)*a,yaw:o.yaw+ds(i.yaw-o.yaw)*a}}var uS=8,yC=3,Th=.5,Mh=(t,e)=>t.id<e.id?-1:t.id>e.id?1:0,Ee=(t,e=0)=>typeof t=="number"&&Number.isFinite(t)?t:e,lS=2*Math.PI,ds=t=>t-lS*Math.floor((t+Math.PI)/lS),dS=t=>({x:Ee(t.x),y:Ee(t.y),z:Ee(t.z),yaw:Ee(t.yaw),vx:Ee(t.vx),vy:Ee(t.vy),vz:Ee(t.vz)}),fS=(t,e)=>({id:t,x:Ee(e.x),y:Ee(e.y),z:Ee(e.z),vx:Ee(e.vx),vy:Ee(e.vy),vz:Ee(e.vz),yaw:Ee(e.yaw),spin:Ee(e.spin),...typeof e.flags=="number"?{flags:e.flags}:{}}),pS=(t,e)=>({id:t,x:Ee(e.x),y:Ee(e.y),z:Ee(e.z),vx:Ee(e.vx),vy:Ee(e.vy),vz:Ee(e.vz),yaw:Ee(e.yaw),duck:Ee(e.duck),flags:Ee(e.flags)}),hS=(t,e)=>uo.every(n=>t[n]===e[n]),md=class{constructor(e){m(this,"options");m(this,"serial",0);m(this,"current",null);m(this,"recent",[]);m(this,"applied",new Map);m(this,"missed",new Set);this.options=e}apply(e,n,r,s,o,i=null){let a=this.current,c=a===null||a.ack!==n||a.stateTick!==r||e<=a.last,u=a,l=c?this.start(n,r,o):a,d=e-n;for(let p=l.ticks+1;p<d;p++)this.tick(l,p,u?.ownIn.get(n+p),!1,u?.ownOn.get(n+p)??null),this.noteMissed(l,n+p);let f=d>l.ticks,h=f?this.tick(l,d,s,!0,i):null;f&&this.applied.set(e,l.touching.get(e)??new Set),l.last=e;for(let p of this.recent)this.extend(p,l,e);return h}takeMissed(){let e=[...this.missed].sort();return this.missed.clear(),e}noteMissed(e,n){let r=this.applied.get(n),s=e.touching.get(n);if(!(r===void 0||s===void 0))for(let o of s)r.has(o)||this.missed.add(o)}extend(e,n,r){let s=r-e.ack;for(let o=e.ticks+1;o<=s;o++)this.tick(e,o,n.ownIn.get(e.ack+o),!1,n.ownOn.get(e.ack+o)??null);e.last=Math.max(e.last,r)}poseAt(e,n,r=this.current){if(r===null)return;let s=Math.max(n,r.ack),o=r.ack+r.ticks,i=Math.min(Math.floor(s),o),a=r.poses.get(i)?.get(e);if(a===void 0)return;let c=i<o?r.poses.get(i+1)?.get(e):void 0,u=s-i;if(c===void 0){if(r===this.current){let l=Math.min(u,1)/r.tickHz;return{...a,x:a.x+a.vx*l,y:a.y+a.vy*l,z:a.z+a.vz*l}}return hC(r,e,i,u)??a}return{x:a.x+(c.x-a.x)*u,y:a.y+(c.y-a.y)*u,z:a.z+(c.z-a.z)*u,yaw:a.yaw+ds(c.yaw-a.yaw)*u,vx:a.vx+(c.vx-a.vx)*u,vy:a.vy+(c.vy-a.vy)*u,vz:a.vz+(c.vz-a.vz)*u}}motionAt(e,n,r=this.current){let s=this.poseAt(e,n,r),o=this.poseAt(e,n-Th,r),i=this.poseAt(e,n+Th,r);if(s===void 0||o===void 0||i===void 0||r===null)return;let a=r.tickHz/1e3/(2*Th);return{pose:s,rate:{vx:(i.x-o.x)*a,vy:(i.y-o.y)*a,vz:(i.z-o.z)*a,vyaw:ds(i.yaw-o.yaw)*a}}}changeAt(e,n,r){if(this.current===null||this.current===r)return;let s=Math.min(n,r.ack+r.ticks),o=this.motionAt(e,s,r),i=this.motionAt(e,s);return o===void 0||i===void 0?void 0:{before:o,after:i}}touchAheadMs(e,n){let r=this.current;if(r===null)return;let s=Math.floor(Math.max(n,r.ack));if(r.touching.get(s)?.has(e)===!0||r.touching.get(s+1)?.has(e)===!0)return 0;let o=r.seats.find(l=>l.id===e),i=this.poseAt(e,n,r),a=mC(r,n);if(o===void 0||i===void 0||a===void 0)return;let c={...fS(e,o.body),x:i.x,y:i.y,z:i.z,yaw:i.yaw,vx:i.vx,vy:i.vy,vz:i.vz},u={x:(i.vx-a.vx)/1e3,y:(i.vy-a.vy)/1e3,z:(i.vz-a.vz)/1e3};for(let l=0;l<=uS;l++){let d=l/uS*mt.SEAT_CLOCK_TAU_MS;if(this.touches(a,{...c,x:c.x+u.x*d,y:c.y+u.y*d,z:c.z+u.z*d}))return d}}touchingAt(e,n){let r=this.current;return r===null?!1:r.touching.get(Math.round(Math.max(n,r.ack)))?.has(e)===!0}stateRate(e){let n=this.current,r=n?.poses.get(n.ack)?.get(e);if(r!==void 0)return{vx:r.vx/1e3,vy:r.vy/1e3,vz:r.vz/1e3,vyaw:0}}start(e,n,r){let s=this.options.others().map(a=>({id:a.id,epoch:a.epoch,body:{...a.body},input:a.input})).sort(Mh),o=new Map([[e,new Map(s.map(a=>[a.id,dS(a.body)]))]]);this.serial+=1,this.current!==null&&(this.recent=[this.current,...this.recent].slice(0,yC));for(let a of this.applied.keys())a<=e&&this.applied.delete(a);let i={id:this.serial,ack:e,stateTick:n,tickHz:r,last:e,ticks:0,seats:s,poses:o,touching:new Map,own:new Map,ownIn:new Map,ownOn:new Map};return this.current=i,i}tick(e,n,r,s,o){let i=Math.ceil(this.options.maxAheadMs()*e.tickHz/1e3),a=n<=i?this.carry(e,n):null;if(n<=i)for(let p of e.seats)this.move(e,p,n,a===null?void 0:gc(a.t,p.id));let c=r===void 0?void 0:{...r};r!==void 0&&(e.ownIn.set(e.ack+n,{...r}),e.ownOn.set(e.ack+n,o));let u=a===null?null:this.ride(e,a,c,o),l=e.seats.map(p=>fS(p.id,p.body)),d=new Set;if(c!==void 0)for(let p of l)this.touches(c,p)&&d.add(p.id);let f=c===void 0?l:[...l,c].sort(Mh);if(this.contactPass(f),e.seats.forEach((p,g)=>{let x=l[g];for(let b of uo)typeof x[b]=="number"&&(p.body[b]=x[b])}),a!==null&&this.impart(e,a,c),r!==void 0&&c!==void 0&&s)for(let p of uo){let g=c[p];typeof g=="number"&&g!==r[p]&&(r[p]=Math.fround(g))}let h=e.ack+n;return e.poses.set(h,new Map(e.seats.map(p=>[p.id,dS(p.body)]))),e.touching.set(h,d),c!==void 0&&e.own.set(h,s&&r!==void 0?{...r}:c),e.ticks=n,u}ride(e,n,r,s){let o=n.t,i=new Map(e.seats.map(h=>[h.id,h.body])),a=h=>r!==void 0&&h===r.id?r:i.get(h);for(let h of o.seats){let p=a(h.id);p!==void 0&&(h.x=Ee(p.x),h.y=Ee(p.y))}Ax(n.l.lifts,o);for(let h of o.seats){let p=i.get(h.id);p!==void 0&&(p.x=h.x,p.y=h.y)}if(r===void 0||s===null)return null;let c=o.seats.find(h=>h.id===r.id),u=o.seats.findIndex(h=>h.id===s);if(c===void 0&&u<0)return null;let l=c===void 0?o.report.from[u]:[r.x,r.y],d=c??o.seats[u],f=[d.x-l[0],d.y-l[1]];return r.x=Math.fround(r.x+f[0]),r.y=Math.fround(r.y+f[1]),f}carry(e,n){let r=this.options.lifts?.()??null;if(r===null)return null;let s=e.own.get(e.ack+n-1),o=e.seats.map(c=>pS(c.id,c.body));s!==void 0&&o.push(pS(s.id,s)),o.sort(Mh);let i=yc(r.lifts,o,e.stateTick+n,r.starts,1/e.tickHz,r.cache),a=new Map(i.seats.map(c=>[c.id,c]));for(let c of e.seats){let u=a.get(c.id);c.body.x=u.x,c.body.y=u.y,c.body.z=u.z,r.lifts.vehicle&&(c.body.yaw=u.yaw)}return{l:r,t:i}}impart(e,n,r){let s=new Map(e.seats.map(i=>[i.id,i.body]));r!==void 0&&s.set(r.id,r);for(let i of n.t.seats){let a=s.get(i.id);a!==void 0&&(i.x=Ee(a.x),i.y=Ee(a.y),i.z=Ee(a.z),i.vx=Ee(a.vx),i.vy=Ee(a.vy),i.vz=Ee(a.vz))}bc(n.l.lifts,n.t,n.l.starts);let o=new Map(n.t.seats.map(i=>[i.id,i]));for(let i of e.seats){let a=o.get(i.id);i.body.vx=a.vx,i.body.vy=a.vy,i.body.vz=a.vz}}move(e,n,r,s){let o=1/e.tickHz,{predict:i,decayMs:a}=this.options.remote(),c=i===jt.EXTRAPOLATE?void 0:this.options.step();if(c===void 0||n.input===void 0){let l=n.body;l.x=Ee(l.x)+Ee(l.vx)*o,l.y=Ee(l.y)+Ee(l.vy)*o,l.z=Ee(l.z)+Ee(l.vz)*o;return}this.options.seatRule?.(n.body,e.stateTick+r);let u=i===jt.INPUT_DECAY?od(n.input,r,e.tickHz,a):n.input;c(n.body,u,o,s)}contactPass(e){if(this.options.pass!==void 0){this.options.pass(e);return}for(let n=0;n<e.length;n++)for(let r=n+1;r<e.length;r++)this.options.rule(e[n],e[r])}touches(e,n){let r={...e},s={...n};return r.id<s.id?this.options.rule(r,s):this.options.rule(s,r),!hS(r,e)||!hS(s,n)}};function yS(t,e,n,r){if(t===void 0||!Number.isFinite(t.seq))return{seq:e,at:n};let s=Math.max(0,n-t.at),o=t.seq+s*r/1e3,i=e-o;if(Math.abs(i)>mt.SEAT_CLOCK_SNAP_INPUTS)return{seq:e,at:n};let a=o+i*(1-Math.exp(-s/mt.SEAT_CLOCK_TAU_MS));return{seq:Math.max(t.seq,a),at:n}}function gS(t,e,n){if(t===void 0||!Number.isFinite(t))return e?1:0;let r=Math.max(0,n)/mt.SEAT_CLOCK_TAU_MS;return e?Math.min(1,t+r):Math.max(0,t-r)}var gC=.01;function bS(t,e){let n=Math.exp(-e/mt.SEAT_TAU_MS),r=Math.max(Math.abs(t.dx),Math.abs(t.dy),Math.abs(t.dz))*n<gC;return{dx:t.dx*n,dy:t.dy*n,dz:t.dz*n,done:r}}var bC=t=>t?mt.SEAT_CONTACT_TAU_MS:mt.SEAT_TAU_MS;function hd(t,e,n,r){let s=1/r,o=Math.exp(-s*n),i=e+s*t;return[(t+i*n)*o,(e-s*i*n)*o]}function wS(t,e,n,r,s,o,i,a,c){let u={ax:s.pose.x,ay:s.pose.y,az:s.pose.z},l={pass:e,epoch:n,dx:0,dy:0,dz:0,dyaw:0,vx:0,vy:0,vz:0,vyaw:0,...u,hx:0,hy:0,hz:0,stillMs:0,stopFound:!1};if(t===void 0||t.epoch!==n)return l;let d=bC(i),f=Math.max(0,o),[h,p]=hd(t.dx,t.vx,f,d),[g,x]=hd(t.dy,t.vy,f,d),[b,S]=hd(t.dz,t.vz,f,d),[_,P]=hd(t.dyaw,t.vyaw,f,d),R=t.pass!==e&&r!==void 0,v=R?r.before:s,M=R?r.after:s,O={x:v.pose.x-M.pose.x,y:v.pose.y-M.pose.y,z:v.pose.z-M.pose.z,yaw:ds(v.pose.yaw-M.pose.yaw)},z={vx:v.rate.vx-M.rate.vx,vy:v.rate.vy-M.rate.vy,vz:v.rate.vz-M.rate.vz,vyaw:v.rate.vyaw-M.rate.vyaw},X={pose:{...s.pose,x:s.pose.x+O.x,y:s.pose.y+O.y,z:s.pose.z+O.z},rate:{vx:s.rate.vx+z.vx,vy:s.rate.vy+z.vy,vz:s.rate.vz+z.vz,vyaw:s.rate.vyaw+z.vyaw}},N=R?wC(t,z)||t.stopFound&&t.stillMs>0:t.stopFound,Y=xC(t,{...t,pass:e,dx:h,dy:g,dz:b,dyaw:_,vx:p,vy:x,vz:S,vyaw:P,stopFound:N},X,s.rate,c),he={dx:Y.dx+O.x,dy:Y.dy+O.y,dz:Y.dz+O.z,dyaw:ds(Y.dyaw+O.yaw)};if(Math.hypot(he.dx,he.dy,he.dz)>a)return l;let A={vx:Y.vx+z.vx,vy:Y.vy+z.vy,vz:Y.vz+z.vz,vyaw:Y.vyaw+z.vyaw};return SC({...Y,...he,...A,...u},s.rate,f)}function wC(t,e){return e.vx*t.hx+e.vy*t.hy+e.vz*t.hz>mt.SEAT_MOVING_UNITS_PER_MS}function xC(t,e,n,r,s){let o={x:t.hx,y:t.hy,z:t.hz},i=_=>_.x*o.x+_.y*o.y+_.z*o.z,a=i({x:n.rate.vx,y:n.rate.vy,z:n.rate.vz}),c=n.pose,l=i({x:c.x-t.ax,y:c.y-t.ay,z:c.z-t.az})+i({x:e.dx-t.dx,y:e.dy-t.dy,z:e.dz-t.dz}),d=i({x:r.vx,y:r.vy,z:r.vz})<0,f=s!==void 0&&i({x:s.vx,y:s.vy,z:s.vz})>mt.SEAT_MOVING_UNITS_PER_MS,h=i({x:t.dx,y:t.dy,z:t.dz})>0,p=e.stopFound&&f&&h;if(t.stillMs>=mt.SEAT_HOLD_MS||d&&!p)return e;let x=a+i({x:e.vx,y:e.vy,z:e.vz});if(l>=0&&x>=0)return e;let b=Math.max(0,-l),S=-x;return{...e,dx:e.dx+b*o.x,dy:e.dy+b*o.y,dz:e.dz+b*o.z,vx:e.vx+S*o.x,vy:e.vy+S*o.y,vz:e.vz+S*o.z}}function SC(t,e,n){let r=e.vx+t.vx,s=e.vy+t.vy,o=e.vz+t.vz,i=Math.hypot(r,s,o);return i>mt.SEAT_MOVING_UNITS_PER_MS?{...t,hx:r/i,hy:s/i,hz:o/i,stillMs:0}:{...t,stillMs:t.stillMs+n}}function EC(t){if(!(t===void 0||typeof t.inMoveX!="number"))return{moveX:St(t.inMoveX),moveY:St(t.inMoveY),moveZ:St(t.inMoveZ),yaw:St(t.inYaw),pitch:St(t.inPitch),buttons:St(t.inButtons)}}var xS=1e3/60,_C=xS,RC=0,St=t=>typeof t=="number"&&Number.isFinite(t)?t:RC;function SS(t){let e={status:t.enabled?He.LOADING:He.OFF,matched:0,replayed:0,peakResimMs:0,lastResimMs:0,slowResims:0,fallbacks:0,recoveries:0},n=null,r=null,s=0,o=0,i=new Map,a,c=t.state,u=new Map,l=S=>{e.status=S,n?.stop(S),n=null},d=()=>{if(r!==null||t.loadCore===void 0){t.loadCore===void 0&&(e.status=He.UNAVAILABLE);return}r=t.loadCore().then(S=>{if(e.status!==He.LOADING)return;if(!Kx(S))return l(He.SELF_TEST);let _=Ec(c.physDesc);if(_===null)return l(He.MISMATCH);let P=t.staticWorld();n=new cd(S,{desc:_,staticWorld:{boxes:P.boxes.map(R=>[...R]),ramps:P.ramps.map(R=>[...R])},physicsHash:c.physics??"",tickHz:t.tickHz(),budgetMs:t.budgetMs,remoteStep:t.remoteStep?.(),bodyRule:t.bodyRule,...t.headSlide===void 0?{}:{headSlide:t.headSlide},kinematicRule:t.kinematicRule,...t.lifts===void 0?{}:{lifts:t.lifts},seatRule:t.seatRule,seatPose:t.seatPose,contactPass:t.contactPass,...t.clock===void 0?{}:{clock:t.clock}}),n.predicting||l(n.status)}).catch(()=>l(He.UNAVAILABLE))},f=()=>{let S=c.entities??new Map,_=N=>c.shapes?.get(N)?.data,P=[],R=[],v=N=>c.bodies?.has(N)===!0;for(let[N,Y]of c.bodies??[]){let he=Y.desc===void 0||Y.desc===""?null:Ux(Y.desc,_),A=S.get(N);if(A===void 0||t.motionKnown?.(N)===!1){let $=u.get(N)??(A===void 0?[0,0,0]:[A.x,A.y,A.z]);R.push({key:N,x:$[0],y:$[1],z:$[2],radius:he===null?0:_c(he)});continue}u.set(N,[A.x,A.y,A.z]);let W=new Array(15),G={x:A.x,y:A.y,z:A.z,qx:St(A.qx),qy:St(A.qy),qz:St(A.qz),qw:St(A.qw),lvx:St(A.lvx),lvy:St(A.lvy),lvz:St(A.lvz),avx:St(A.avx),avy:St(A.avy),avz:St(A.avz),sleep:A.sleep===!0,rest:St(A.rest)};Lx(G,W,0),P.push({key:N,desc:he,row:W,epoch:A.epoch})}for(let N of u.keys())c.bodies?.has(N)!==!0&&u.delete(N);let M=[];for(let[N,Y]of c.joints??[])try{M.push({key:N,desc:JSON.parse(Y.desc),motor:Y.motor===""?null:JSON.parse(Y.motor)})}catch{}let O=[],z=new Set,X=t.ownId();for(let[N,Y]of S){if(Y.owner===""||z.has(Y.owner)||Cr(Y)||v(N)||c.players?.has(Y.owner)!==!0)continue;z.add(Y.owner);let he={...Y};O.push({key:N,x:Y.x,y:Y.y,z:Y.z,vx:Y.vx,vy:Y.vy,vz:Y.vz,epoch:Y.epoch,own:N===X,input:EC(c.players?.get(Y.owner)),body:he})}return{tick:c.keyframe??0,ack:t.acked(),bodies:P,outside:R,joints:M,seats:O}},h=null,p=0,g=t.clock??(()=>performance.now()),x=()=>{let S=h;h=null,p=0,S!==null&&b(S)},b=S=>{if(n===null)return;for(let[P,R]of t.ownPath?.()??[])i.set(P,R);let _=n.adopt(S.keyframe,S.sent,P=>i.get(P)?.p,S.now,P=>i.get(P)?.v);_.kind==="match"&&e.matched++,_.kind==="replay"&&e.replayed++,_.kind==="replay"&&(e.lastResimMs=_.ms,_.ms>xS&&e.slowResims++),e.peakResimMs=Math.max(e.peakResimMs,_.ms),e.fallbacks=n.fallbacks,e.recoveries=n.recoveries,n.stopped?l(n.status):e.status=n.status,o=S.sent};return{status:e,onState(S){if(e.status===He.OFF)return;let _=c.keyframe??0;if(_===0||(c.physDesc??"")==="")return;if(n===null){d();return}if(_===s||c.tick!==_)return;s=_;let P={keyframe:f(),sent:t.sent(),now:S};if(p>=_C){h=P;return}let R=g();b(P),p+=g()-R},settle:x,afterSend(S,_){x();let P=t.sent(),R=a??S,v=P-o;for(let M=1;M<=v;M++){let O=M/v;if(S!==void 0&&R!==void 0){let z=[R.p[0]+(S.p[0]-R.p[0])*O,R.p[1]+(S.p[1]-R.p[1])*O,R.p[2]+(S.p[2]-R.p[2])*O];i.set(o+M,{p:z,v:S.v})}n?.advance(o+M,_)}o=P,a=S;for(let M of i.keys())M<P-256&&i.delete(M)},draw(S,_){return x(),n===null||!n.draws(S)?null:n.draw(S,_)},dispose(){n?.stop(He.OFF),n=null}}}wt();var yd={min:-1,max:1,bits:16,mode:"clamp"},Oi={min:-64,max:64,bits:16,mode:"clamp"},ES=It({moveX:q.float32().default(0),moveY:q.float32().default(0),moveZ:q.float32().default(0),yaw:q.float32().default(0),pitch:q.float32().default(0),buttons:q.number().default(0),tick:q.number().default(0)},"AuthorityInput"),kC=1,_S=t=>({kind:q.string().default(""),owner:q.string().default(""),x:t(q.float32().default(0)),y:t(q.float32().default(0)),z:t(q.float32().default(0)),vx:t(q.float32().default(0)),vy:t(q.float32().default(0)),vz:t(q.float32().default(0)),yaw:t(q.float32().default(0)),hp:q.number().default(0),flags:q.number().default(0),epoch:t(q.number().default(0)),data:q.string().default(""),t0:q.number().default(0),g:q.float32().default(0),src:q.string().default(""),pitch:t(q.float32().default(0)),duck:t(q.float32().default(0)),mstate:t(q.number().default(0)),cap:q.float32().default(1),spin:t(q.float32().default(0)),fuel:t(q.float32().default(0)),qx:t(q.quantized(yd).optional()),qy:t(q.quantized(yd).optional()),qz:t(q.quantized(yd).optional()),qw:t(q.quantized(yd).optional()),lvx:t(q.quantized(Oi).optional()),lvy:t(q.quantized(Oi).optional()),lvz:t(q.quantized(Oi).optional()),avx:t(q.quantized(Oi).optional()),avy:t(q.quantized(Oi).optional()),avz:t(q.quantized(Oi).optional()),sleep:t(q.boolean().optional()),rest:t(q.number().optional())}),PC=It(_S(t=>t),"AuthorityEntity"),AC=It(_S(t=>t.view(kC)),"AuthorityEntity"),vC=It({type:q.string().default(""),kind:q.string().default(""),colliders:q.string().default(""),desc:q.string().optional()},"AuthorityBody"),TC=It({data:q.string().default("")},"AuthorityShape"),MC=It({desc:q.string().default(""),motor:q.string().default("")},"AuthorityJoint"),CC=It({name:q.string().default(""),uid:q.string().default(""),team:q.string().default(""),connected:q.boolean().default(!0),avatarUrl:q.string().default(""),seqBase:q.number().default(0),inMoveX:q.float32().optional(),inMoveY:q.float32().optional(),inMoveZ:q.float32().optional(),inYaw:q.float32().optional(),inPitch:q.float32().optional(),inButtons:q.number().optional(),inRep:q.number().optional(),inStarve:q.number().optional(),inBuf:q.number().optional()},"AuthorityPlayer"),RS={players:q.map(CC),entities:q.map(PC),tick:q.number().default(0),clockOrigin:q.float64().default(0),preset:q.string().default(""),moduleSha:q.string().default(""),tickOrigin:q.float64().default(0),physics:q.string().optional(),lengthUnit:q.float32().optional(),bodies:q.map(vC).optional(),physDesc:q.string().optional(),keyframe:q.number().optional(),shapes:q.map(TC).optional(),joints:q.map(MC).optional(),lifts:q.string().optional()},yz=It(RS,"AuthorityRoomState"),gz=It({...RS,entities:q.map(AC).view()},"AuthorityRoomState");var OC=(t,e)=>t+Math.atan2(Math.sin(e-t),Math.cos(e-t)),IC=(t,e,n)=>({x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n,z:t.z+(e.z-t.z)*n,yaw:t.yaw+(e.yaw-t.yaw)*n,pitch:t.pitch+(e.pitch-t.pitch)*n,duck:t.duck+(e.duck-t.duck)*n}),gd=class{constructor(){m(this,"rings",new WeakMap)}push(e,n,r,s,o=0){let i=this.rings.get(e);i===void 0&&(i=[],this.rings.set(e,i));let a=i.at(-1);if(a!==void 0&&n<=a.t)return;let c=a!==void 0&&a.life===o,u=c?OC(a.pose.yaw,r.yaw):r.yaw;c&&n-a.t>s*1.5&&i.push({t:n-s,life:o,pose:a.pose}),i.push({t:n,life:o,pose:{...r,yaw:u}}),i.length>80&&i.splice(0,i.length-80)}at(e,n){let r=this.rings.get(e);if(r===void 0||r.length===0)return;let s=r[0],o=r.at(-1);if(n<=s.t)return s.pose;if(n>=o.t)return o.pose;let i=r.length-2;for(;i>0&&r[i].t>n;)i--;let a=r[i],c=r[i+1];return a.life!==c.life?a.pose:IC(a.pose,c.pose,(n-a.t)/(c.t-a.t))}forget(e){this.rings.delete(e)}};var ut={On:"on",Off:"off"},Ez={[Un.Shooter]:{repeat:ut.On},[Un.Platformer]:{repeat:ut.On},[Un.VehicleArena]:{repeat:ut.Off},[Un.PhysicsSandbox]:{repeat:ut.On},[Un.Party]:{repeat:ut.On}},_z={repeat:ut.On};var kS=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);function PS(t){let e;try{e=JSON.parse(t)}catch{return ut.On}let n=kS(e)?e.inputs:void 0;return kS(n)&&n.repeat===ut.Off?ut.Off:ut.On}var jz={MAX_ENTITIES:256,MAX_ROOM_ENTITIES:1024,MAX_OUTPUT_BYTES:32*1024,MAX_EVENTS_PER_TICK:64,MAX_ENTITY_DATA_BYTES:256,MAX_ENTITY_ID_CHARS:64,MAX_KIND_CHARS:64,MAX_SESSION_ID_CHARS:64,MAX_ABS:1e9,MASK_LIMIT:16777216,MAX_EPOCH:2**32-1,MAX_PROJECTILE_TICK:Bw,MAX_PROJECTILE_G:ic,MAX_LAUNCH_UPDATES:224,MAX_LAUNCH_BYTES:28*1024,MAX_EVENT_TYPE_CHARS:$t.MAX_EVENT_TYPE_CHARS,MAX_EVENT_BYTES:$t.MAX_EVENT_BYTES,MAX_JSON_DEPTH:$t.MAX_JSON_DEPTH,MAX_JSON_NODES:$t.MAX_JSON_NODES,MAX_PLAYERS:$t.ROOM_MAX_CLIENTS,MAX_PHYS_COMMANDS:256,MAX_PHYS_BYTES:32*1024,MAX_PHYSICS_OUTPUT_BYTES:64*1024,MAX_WORLD_TEXT_CHARS:155660};function Ii(t){return{moveX:Ln(t.moveX),moveY:Ln(t.moveY),moveZ:Ln(t.moveZ),yaw:os(t.yaw)??0,pitch:os(t.pitch)??0,buttons:Js(t.buttons)}}var qz=2**31-1;var Zz=rs.INPUT_REPEAT_MAX_MS,Qz=rs.INPUT_REPEAT_RUN_MS;function vS(t,e,n,r=ut.On){return r===ut.Off?t:Math.max(t,Math.min(t+MS(e),n))}function TS(t,e,n=ut.On){return n===ut.Off?t:t+MS(e)}var DC=(t,e,n)=>e<=n?e:Math.min(t,n),MS=t=>typeof t=="number"&&Number.isInteger(t)&&t>0?t:0;function CS(){return{shown:0,heldFrom:null}}function OS(t,e,n,r,s){let o=DC(t.shown,e,n);return o<=t.shown?(o<t.shown&&(t.heldFrom=null),t.shown=o,o):o===n||n-(o+1)<r||s?(t.heldFrom=null,t.shown=o,o):(t.heldFrom??(t.heldFrom=n),n-t.heldFrom<r?t.shown:(t.shown=o,o))}var BC=.03,NC=1,AS=.5;function IS(){return{seenRuns:null,owedMs:0,accMs:0,aheadMs:0}}function DS(t,e,n,r,s=ut.On){if(s===ut.Off||typeof e!="number"||!Number.isFinite(e))return;let o=t.seenRuns!==null&&e>t.seenRuns;if(t.seenRuns=e,!o||!(r>0))return;(typeof n=="number"&&Number.isFinite(n)?n:0)<=NC&&(t.owedMs=Math.max(t.owedMs,r))}function BS(t,e,n,r,s){let o=r>0?n.accMs/r:0;return{raw:t+e+AS*o,at:s+AS*n.aheadMs}}function NS(t,e,n){if(!(n>0)||!(e>0)||t.owedMs<=0)return 0;let r=Math.min(t.owedMs,e*BC);t.owedMs-=r,t.accMs+=r,t.aheadMs+=r;let s=Math.floor(t.accMs/n+.5);return t.accMs-=s*n,s}wt();var US=1,VS=1200,Ih=8,LC=170,FC=3,HS=32,Dh=8;var zC=5e3,UC=32,VC=32,HC=4,$C=1024,$S=1e3,jS=2e3,bd={Bind:"__fast",Off:"__fast:off"},qS={Uplink:1,Snapshot:2},ke={Oversized:"oversized",Truncated:"truncated",Trailing:"trailing",Version:"version",Kind:"kind",Session:"session",Key:"key",Count:"count",Fresh:"fresh",Actions:"actions",Flags:"flags",Order:"order",Field:"field",Ahead:"ahead",Fragment:"fragment",Mismatch:"mismatch",Duplicate:"duplicate",Keyframe:"keyframe",Body:"body",Base:"base",Stale:"stale"};var GS=29,LS=29,wd=24,Bh=1,Nh=2,Lh=4,nU=Bh|Nh|Lh,FS=255,WS=10,jC=4+wd,Pc=4294967295,YS=65536,Ch=1;var Fh=t=>({ok:!0,value:t}),wn=t=>({ok:!1,fault:t}),KS=(t,e)=>Math.ceil(t*(Number.isFinite(e)&&e>0?e:0)/1e3),fo=(t,e)=>typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=e;function Ac(t){return Math.min(HS,Math.max(FC,KS(LC,t)))}function XS(t){return GS+Dh*(WS+wd)+Ac(t)*jC}var vc=t=>KS(zC,t);function qC(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function GC(t){return/^(?:[0-9a-fA-F]{2})*$/.test(t)?Uint8Array.from(t.match(/../g)??[],e=>Number.parseInt(e,16)):new Uint8Array(0)}var WC=t=>typeof t=="string"&&t.length===2*Ih&&/^[0-9a-f]+$/.test(t),YC=(t,e)=>(e.buttons&~(t?.buttons??0))!==0,KC=t=>[t.moveX,t.moveY,t.moveZ,t.yaw,t.pitch].every(e=>typeof e=="number"&&Number.isFinite(Math.fround(e)))&&fo(t.buttons,Pc),XC=t=>fo(t.seq,Pc)&&t.seq>=1&&fo(t.tick,YS-1)&&fo(t.render,Pc)&&KC(t.input),JC=t=>t.reduce((e,n)=>Math.max(e,n.render),0),ZC=(t,e)=>e.render===0||t-e.render>=FS?FS:t-e.render;function QC(t){let{window:e,actions:n}=t;if(!fo(t.sid,Pc)||!WC(t.key)||!fo(t.ackSnap,Pc)||e.length<1||e.length>HS||n.length>Dh||!fo(t.fresh,e.length)||t.fresh<1||![...n,...e].every(XC))return!1;let r=e.every((o,i)=>i===0||o.seq===e[i-1].seq+1),s=n.every((o,i)=>o.seq<(i+1<n.length?n[i+1].seq:e[0].seq));return r&&s}function Oh(t,e,n){return t.setFloat32(e,n.moveX,!0),t.setFloat32(e+4,n.moveY,!0),t.setFloat32(e+8,n.moveZ,!0),t.setFloat32(e+12,n.yaw,!0),t.setFloat32(e+16,n.pitch,!0),t.setUint32(e+20,n.buttons,!0),e+wd}var zS=t=>{let e=new Uint8Array(wd);return Oh(new DataView(e.buffer),0,t),qC(e)};function eO(t,e){if(t===null)return 0;let n=zS(t.input)===zS(e.input)?Bh:0;return e.tick===t.tick?n|=Nh:e.tick===(t.tick+1)%YS&&(n|=Lh),n}function JS(t){if(!QC(t))return wn(ke.Field);let e=new Uint8Array(VS),n=new DataView(e.buffer);e[0]=US,e[1]=qS.Uplink,n.setUint32(2,t.sid,!0),e.set(GC(t.key),6),n.setUint32(14,t.ackSnap,!0),n.setUint32(18,t.window[t.window.length-1].seq,!0),e[22]=t.window.length,e[23]=t.fresh,e[24]=t.actions.length;let r=JC(t.window);n.setUint32(25,r,!0);let s=GS;for(let o of t.actions)n.setUint32(s,o.seq,!0),n.setUint16(s+4,o.tick,!0),n.setUint32(s+6,o.render,!0),s=Oh(n,s+WS,o.input);return t.window.forEach((o,i)=>{let a=eO(i===0?null:t.window[i-1],o);e[s]=a,s+=1,(a&(Nh|Lh))===0&&(n.setUint16(s,o.tick,!0),s+=2),e[s]=ZC(r,o),s+=1,(a&Bh)===0&&(s=Oh(n,s,o.input))}),Fh(e.slice(0,s))}function tO(t,e,n){return t.length>VS?ke.Oversized:t.length<2?ke.Truncated:t[0]!==US?ke.Version:t[1]!==e?ke.Kind:t.length<n?ke.Truncated:null}function ZS(t,e){let n=t.slice(-Ac(e.tickHz)),r=n.length>0?n[0].seq:Number.POSITIVE_INFINITY,s=t.filter((o,i)=>o.seq>e.inputAck&&o.seq<r&&YC(i>0?t[i-1].input:null,o.input)).slice(0,Dh);return{sid:e.sid,key:e.key,ackSnap:e.ackSnap,fresh:Math.min(e.fresh,n.length),actions:s,window:n}}var nO=t=>[...t].sort((e,n)=>e.key-n.key);function rO(t,e){let n=tO(t,qS.Snapshot,LS);if(n!==null)return wn(n);let r=new DataView(t.buffer,t.byteOffset,t.byteLength);if(r.getUint32(2,!0)!==e)return wn(ke.Session);let s=r.getUint32(6,!0),o=r.getUint32(10,!0),i=t[22],a=t[23],c=t[24];if(c<1||c>VC||a>=c)return wn(ke.Fragment);if(!((i&~Ch)===0&&i===Ch==(o===0))||s<1||o>=s)return wn(ke.Keyframe);let l=t.slice(LS);return Fh({snap:s,base:o,tick:r.getUint32(14,!0),inputAck:r.getUint32(18,!0),sent:r.getUint32(25,!0),keyframe:i===Ch,frag:a,frags:c,chunk:l})}function sO(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.length<2)return wn(ke.Body);let n=e.getUint16(0,!0),r=2,s=[];for(let a=0;a<n;a+=1){if(r+2>t.length)return wn(ke.Body);let c=e.getUint16(r,!0);if(a>0&&c<=s[a-1])return wn(ke.Body);s.push(c),r+=2}if(r+2>t.length)return wn(ke.Body);let o=e.getUint16(r,!0);r+=2;let i=[];for(let a=0;a<o;a+=1){if(r+4>t.length)return wn(ke.Body);let c=e.getUint16(r,!0),u=e.getUint16(r+2,!0);if(u>$C||r+4+u>t.length||a>0&&c<=i[a-1].key)return wn(ke.Body);i.push({key:c,bytes:t.slice(r+4,r+4+u)}),r+=4+u}return r===t.length?Fh({removed:s,records:i}):wn(ke.Body)}function oO(t,e){let n=new Set(e.removed),r=new Map(t.filter(s=>!n.has(s.key)).map(s=>[s.key,s]));for(let s of e.records)r.set(s.key,s);return nO([...r.values()])}var QS=()=>({partials:[],history:[],newest:0}),iO=(t,e)=>t.base===e.base&&t.tick===e.tick&&t.inputAck===e.inputAck&&t.sent===e.sent&&t.keyframe===e.keyframe&&t.frags===e.frags;function eE(t,e,n){let r=rO(e,n);if(!r.ok)return{rx:t,applied:null,fault:r.fault};let s=r.value;if(s.snap<=t.newest)return{rx:t,applied:null,fault:ke.Stale};let o=t.partials.find(u=>u.snap===s.snap);if(o!==void 0&&!iO(o,s))return{rx:t,applied:null,fault:ke.Mismatch};if(o?.chunks[s.frag])return{rx:t,applied:null,fault:ke.Duplicate};let i=o??{snap:s.snap,base:s.base,tick:s.tick,inputAck:s.inputAck,sent:s.sent,keyframe:s.keyframe,frags:s.frags,chunks:Array(s.frags).fill(null)},a={...i,chunks:i.chunks.map((u,l)=>l===s.frag?s.chunk:u)},c=t.partials.filter(u=>u.snap!==s.snap);if(a.chunks.some(u=>u===null)){let u=[...c,a].sort((l,d)=>l.snap-d.snap).slice(-HC);return{rx:{...t,partials:u},applied:null}}return aO({...t,partials:c},t,a)}function aO(t,e,n){let r=t.partials.length===e.partials.length?e:t,s=sO(cO(n.chunks));if(!s.ok)return{rx:r,applied:null,fault:ke.Body};let o=n.keyframe?null:e.history.find(u=>u.snap===n.base);if(o===void 0)return{rx:r,applied:null,fault:ke.Base};if(n.keyframe&&s.value.removed.length>0)return{rx:r,applied:null,fault:ke.Body};let i=oO(o?.records??[],s.value),a=[...e.history,{snap:n.snap,tick:n.tick,inputAck:n.inputAck,sent:n.sent,records:i}].slice(-UC);return{rx:{partials:t.partials.filter(u=>u.snap>n.snap),history:a,newest:n.snap},applied:n.snap}}function cO(t){let e=new Uint8Array(t.reduce((r,s)=>r+s.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}var Nt={Entity:1,Seat:2},we={F32:"f32",U32:"u32",U16:"u16",Orientation:"q-orientation",Velocity:"q-velocity",Flag:"flag"},uO=[["x",we.F32],["y",we.F32],["z",we.F32],["vx",we.F32],["vy",we.F32],["vz",we.F32],["yaw",we.F32],["pitch",we.F32],["duck",we.F32],["spin",we.F32],["fuel",we.F32],["epoch",we.U32],["mstate",we.U32],["qx",we.Orientation],["qy",we.Orientation],["qz",we.Orientation],["qw",we.Orientation],["lvx",we.Velocity],["lvy",we.Velocity],["lvz",we.Velocity],["avx",we.Velocity],["avy",we.Velocity],["avz",we.Velocity],["sleep",we.Flag],["rest",we.U16]],lO=[["inMoveX",we.F32],["inMoveY",we.F32],["inMoveZ",we.F32],["inYaw",we.F32],["inPitch",we.F32],["inButtons",we.U32],["inRep",we.U32],["inStarve",we.U32],["inBuf",we.U32],["inAck",we.U32]],dO=64,Tc=2,tE=4;var zh=65534,fO=zh/2,pO={[we.Orientation]:1,[we.Velocity]:64},xd=()=>({x:0,y:0,z:0,vx:0,vy:0,vz:0,yaw:0,pitch:0,duck:0,spin:0,fuel:0,epoch:0,mstate:0,qx:0,qy:0,qz:0,qw:0,lvx:0,lvy:0,lvz:0,avx:0,avy:0,avz:0,sleep:!1,rest:0}),Sd=()=>({inMoveX:0,inMoveY:0,inMoveZ:0,inYaw:0,inPitch:0,inButtons:0,inRep:0,inStarve:0,inBuf:0,inAck:0});var hO=(t,e)=>-t+e/zh*(2*t),mO=t=>t===Nt.Entity?uO:t===Nt.Seat?lO:null;var rE={f32:4,u32:4,u16:2,"q-orientation":2,"q-velocity":2,flag:0};function yO(t,e,n){if(e+rE[n]>t.byteLength)return{ok:!1,fault:ke.Truncated};switch(n){case we.Flag:return{ok:!0,value:!0};case we.F32:{let r=t.getFloat32(e,!0);return Number.isFinite(r)&&r!==0?{ok:!0,value:r}:{ok:!1,fault:ke.Field}}case we.U32:{let r=t.getUint32(e,!0);return r!==0?{ok:!0,value:r}:{ok:!1,fault:ke.Field}}case we.U16:{let r=t.getUint16(e,!0);return r!==0?{ok:!0,value:r}:{ok:!1,fault:ke.Field}}default:{let r=t.getUint16(e,!0);return r!==fO&&r<=zh?{ok:!0,value:hO(pO[n],r)}:{ok:!1,fault:ke.Field}}}}var gO=new TextDecoder("utf-8",{fatal:!0});function bO(t){let e=t[1];if(Tc+e>t.length)return{ok:!1,fault:ke.Truncated};if(e===0)return{ok:!1,fault:ke.Field};try{let n=gO.decode(t.subarray(Tc,Tc+e));return n.length<=dO?{ok:!0,value:n}:{ok:!1,fault:ke.Field}}catch{return{ok:!1,fault:ke.Field}}}function sE(t){if(t.length<Tc)return{ok:!1,fault:ke.Truncated};let e=mO(t[0]);if(e===null)return{ok:!1,fault:ke.Kind};let n=bO(t);if(!n.ok)return n;let r=new DataView(t.buffer,t.byteOffset,t.byteLength),s=Tc+t[1];if(s+tE>t.length)return{ok:!1,fault:ke.Truncated};let o=r.getUint32(s,!0);if(s+=tE,e.length<32&&o>>>e.length)return{ok:!1,fault:ke.Flags};if(t[0]===Nt.Entity){let a=nE(r,s,o,xd(),e);return a.ok?{ok:!0,value:{kind:Nt.Entity,id:n.value,motion:a.value}}:a}let i=nE(r,s,o,Sd(),e);return i.ok?{ok:!0,value:{kind:Nt.Seat,id:n.value,motion:i.value}}:i}function nE(t,e,n,r,s){let o={},i=e;for(let[a,[c,u]]of s.entries()){if((n&1<<a)===0)continue;let l=yO(t,i,u);if(!l.ok)return l;o[c]=l.value,i+=rE[u]}return i!==t.byteLength?{ok:!1,fault:ke.Trailing}:{ok:!0,value:Object.assign(r,o)}}var wO=4294967295,fs={Unreachable:"unreachable",Handshake:"handshake",Stall:"stall",Server:"server"},xO=(t,e)=>typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=e;function iE(t){if(typeof t!="object"||t===null)return!1;let{sid:e,key:n,url:r}=t,s=typeof n=="string"&&n.length===2*Ih&&/^[0-9a-f]+$/.test(n);return xO(e,wO)&&s&&typeof r=="string"&&r.length>0}function SO(t,e,n){if(t.length===0)return[];let r=t[t.length-1].seq,s=Math.min(e,r-Ac(n)+1),o=Math.max(s,r-vc(n)+1);return t.filter(i=>i.seq>=o)}var oE=(t,e)=>`${t}:${e}`;function aE(t){let e=QS(),n=[],r=new Map,s=0,o=!1,i=null,a=null,c=new Map,u=new Map,l=()=>e.history.at(-1)?.inputAck??0,d=g=>{let x=new Map,b=new Map,S=[];for(let _ of g){let P=c.get(_.key),R=P!==void 0&&(P.bytes===_.bytes||RO(P.bytes,_.bytes)),v=R?P.record:_O(_.bytes);x.set(_.key,{bytes:_.bytes,record:v}),v!==null&&(b.set(oE(v.kind,v.id),v),R||S.push(v))}return c=x,u=b,S};function f(g){if(o)return{applied:null};let x=eE(e,g,t.bind.sid);if(e=x.rx,x.fault!==void 0||x.applied===null)return{applied:null,fault:x.fault};let b=e.history.at(-1);if(b===void 0)return{applied:null};a=t.now(),n=SO(n,b.inputAck,t.tickHz);let S={snap:b.snap,tick:b.tick,inputAck:b.inputAck,sent:b.sent,changed:d(b.records)};return t.onSnapshot?.(S),{applied:S}}let h=t.open(t.bind.url,g=>{f(g)},t.bind);if(h===null)return null;let p=XS(t.tickHz);return{bind:t.bind,get rx(){return e},get lastQueued(){return n.at(-1)?.seq??0},get closed(){return o},queue(g){o||(n.push({seq:g.seq,tick:g.tick,render:g.render,input:{...g.input}}),s+=1)},flush(){if(o||s===0)return;let g=t.now();for(let S of n.slice(-s))r.set(S.seq,g);EO(r,(n.at(-1)?.seq??0)-vc(t.tickHz)+1);let x=Ac(t.tickHz),b=n.length-s;for(s=0;b<n.length;){let S=Math.min(b+x,n.length),_=ZS(n.slice(0,S),{sid:t.bind.sid,key:t.bind.key,ackSnap:e.newest,inputAck:l(),fresh:S-b,tickHz:t.tickHz});b=S;let P=JS(_);P.ok&&(i??(i=g),h.send(P.value))}},inputAt:g=>n.find(x=>x.seq===g),sentAt:g=>r.get(g),motionOf:(g,x)=>u.get(oE(g,x)),due(){if(o)return null;if(h.failed?.()===!0)return fs.Unreachable;let g=h.maxDatagramBytes?.();if(g!==void 0&&g<p)return fs.Unreachable;let x=t.now();return a!==null?x-a>jS?fs.Stall:null:i!==null&&x-i>$S?fs.Handshake:null},receive:f,close(){o||(o=!0,h.close())}}}function EO(t,e){for(let n of t.keys()){if(n>=e)return;t.delete(n)}}function _O(t){let e=sE(t);return e.ok?e.value:null}var RO=(t,e)=>t.length===e.length&&t.every((n,r)=>n===e[r]);var kO=19,PO=31,AO=Object.keys(xd()),vO=Object.keys(Sd()).filter(t=>t!=="inAck"),TO=t=>t===Nt.Entity?AO:vO,MO=["tick","keyframe"];function CO(t){if(typeof t!="object"||t===null)return null;let e=t,n=e._encoder;return typeof e._lastStamp!="number"||typeof n?.reset!="function"?null:t}function OO(t){let e=t;if(typeof e?._sampleStamp!="function")return()=>0;let n=e;return()=>{let r=n._sampleStamp().stamp;return typeof r=="number"&&Number.isInteger(r)&&r>=0&&r<=4294967295?r:0}}function lE(t){let{room:e,handle:n}=t,r={live:!1,snapshots:0,fallback:null},s=null,o=null,i=0,a=[],c=null,u=t.open===void 0?null:BO(e,()=>s?.client??null),l=CO(n),d=OO(n),f=()=>{if(s!==null)return Math.min(n.sentCount,i);if(o===null)return n.lastProcessed;let b=n.lastProcessed-o.wsBefore;return b>0?Math.max(o.ack,o.at+b):o.ack},h=()=>e.state.players?.get(e.sessionId)?.seqBase??0,p=b=>{if(o!==null)return;let S=s,_=s?.seqBase??h();o={at:n.sentCount,wsBefore:s?.wsBefore??n.sentCount,ack:f(),reason:b},s?.client.close(),s=null,a=[],r.live=!1,r.fallback=b,S!==null&&l!==null&&(l._encoder.reset(),l._lastStamp=S.stampAtBind);let P={last:_+n.sentCount};e.send(bd.Off,P),u?.release()},g=b=>{let S=s;if(S===null)return;r.snapshots+=1;let _=S.client.motionOf(Nt.Seat,e.sessionId),P=_?.kind===Nt.Seat?_.motion.inAck:0,R=Math.max(0,Math.min(n.sentCount,P-S.seqBase)),v=-1;if(R>i){let M=S.client.sentAt(S.seqBase+R);M!==void 0&&(v=t.now()-M),i=R}e.clock.sample(b.sent,v),u?.write(b)},x=b=>{if(t.open===void 0||s!==null||o!==null)return;if(!t.stateCurrent()){c=b;return}if(c=null,!iE(b))return p(fs.Unreachable);let S=aE({bind:b,tickHz:t.tickHz(),open:t.open,now:t.now,onSnapshot:g});if(S===null)return p(fs.Unreachable);s={client:S,seqBase:h(),wsBefore:n.sentCount,stampAtBind:l?._lastStamp??0},i=0,r.live=!0;for(let _ of a)S.queue({..._,seq:s.seqBase+_.seq});a=[],S.flush()};return t.open!==void 0&&(e.onMessage(bd.Bind,b=>x(b)),e.onMessage(bd.Off,()=>p(fs.Server)),e.onStateChange(()=>{c!==null&&t.stateCurrent()&&x(c)}),l!==null&&IO(e,()=>s!==null)),{status:r,ack:f,sent(b,S,_){if(t.open===void 0||o!==null)return;let P=d();if(s!==null){s.client.queue({seq:s.seqBase+b,tick:S,render:P,input:_});return}a.push({seq:b,tick:S,render:P,input:{..._}});let R=vc(t.tickHz());a.length>R&&(a=a.slice(-R))},flush(){s?.client.flush()},poll(){let b=s?.client.due()??null;b!==null&&p(b)},motionKnown(b){return s===null||s.client.motionOf(Nt.Entity,b)!==void 0},inputAt(b){if(s===null)return;let S=s.client.inputAt(s.seqBase+b);return S===void 0?void 0:{...S.input,tick:S.tick}},dropped(){s?.client.close(),s=null,u?.forget(),o=null,i=0,a=[],c=null,r.live=!1,r.fallback=null},dispose(){s?.client.close(),s=null,r.live=!1,u?.dispose()}}}function IO(t,e){let n=t.connection;if(n===void 0)return;let r=n.send.bind(n);n.send=s=>{e()&&s.length>0&&(s[0]&PO)===kO||r(s)}}var DO={...xd(),...Sd()};function BO(t,e){let n=t.serializer.decoder,r=t.state,s=new WeakMap,o=new Map,i=!1,a=n.triggerChanges,c=Object.getOwnPropertyDescriptor(n,"decode"),u=n.decode,l=S=>{let _=s.get(S),P=e();return _===void 0||P===null?void 0:P.motionOf(_.kind,_.id)},d=()=>{t.state.entities?.forEach((S,_)=>s.set(S,{kind:Nt.Entity,id:_})),t.state.players?.forEach((S,_)=>s.set(S,{kind:Nt.Seat,id:_}))},f=S=>{if(S===r)return!0;let _=s.get(S);return _===void 0?!1:(_.kind===Nt.Entity?t.state.entities?.get(_.id):t.state.players?.get(_.id))===S},h=(S,_,P,R)=>{let v=o.get(S);v===void 0&&(v=new Map,o.set(S,v));let M=v.get(_);M===void 0?v.set(_,{fast:P,ws:S[_]??DO[_]}):M.fast=P,uE(S,_,P,R)},p=()=>{d();for(let[S,_]of o){if(!f(S)){o.delete(S);continue}for(let[P,R]of _)R.ws!==R.fast&&(S[P]=R.ws)}i=!0},g=()=>{if(i){i=!1;for(let[S,_]of o)for(let[P,R]of _)R.ws!==R.fast&&(S[P]=R.fast)}},x=S=>{let _=S.field;if(_===void 0)return!1;let P=o.get(S.ref)?.get(_);return P===void 0?!1:(P.ws=S.value,!0)},b=S=>{if(e()===null)return a?.(S);d();for(let P of S){let R=P.value;if(P.field!==void 0||typeof R!="object"||R===null)continue;let v=l(R);v!==void 0&&cE(R,v,(M,O,z)=>h(M,O,z,null))}let _=S.filter(P=>!x(P));g(),a?.(_)};return Object.defineProperty(n,"triggerChanges",{configurable:!0,get:()=>b,set:S=>{a=S}}),Object.defineProperty(n,"decode",{configurable:!0,writable:!0,value:(...S)=>{e()!==null&&o.size>0&&p();try{return u.apply(n,S)}finally{g()}}}),{write(S){d();let _=[];for(let R of S.changed){let v=R.kind===Nt.Entity?t.state.entities?.get(R.id):t.state.players?.get(R.id);v!==void 0&&cE(v,R,(M,O,z)=>h(M,O,z,_))}let P=t.state.keyframe===void 0?["tick"]:MO;for(let R of P)h(r,R,S.tick,_);_.length>0&&a?.(_),t.onStateChange.invoke(t.state)},release(){d();let S=[],_=t.state.physics!==void 0;for(let[P,R]of o)if(!(!f(P)||_&&s.get(P)?.kind===Nt.Entity))for(let[v,M]of R)uE(P,v,M.ws,S);o.clear(),S.length!==0&&(a?.(S),t.onStateChange.invoke(t.state))},forget(){o.clear()},dispose(){o.clear(),Object.defineProperty(n,"triggerChanges",{configurable:!0,writable:!0,value:a}),c===void 0?Reflect.deleteProperty(n,"decode"):Object.defineProperty(n,"decode",c)}}}function cE(t,e,n){let r=e.motion;for(let s of TO(e.kind)){let o=r[s];(o===0||o===!1)&&t[s]===void 0||n(t,s,o)}}function uE(t,e,n,r){let s=t[e];s!==n&&(t[e]=n,r?.push({ref:t,refId:t[Q],op:B.REPLACE,field:e,value:n,previousValue:s}))}var NO=.05,dE=100,Ed=["x","y","z","yaw"],LO=.001;function fE(t,e,n,r){if(t===void 0)return[0,0,0,0];let s=t.err.map(o=>o*r);return t.k===e?s:t.shift.map((o,i)=>o+s[i]-n[i])}var Uh=[.5,1,5,20],FO=[1e3,2e3,4e3],pE=8,zO=250,hE=600,UO=["x","y","z","vx","vy","vz","yaw"],VO=new Set(["mstate","cap","spin","fuel"]),HO=new Set(["yaw"]),_d={Reconnecting:"reconnecting",Reconnected:"reconnected",Disconnect:"disconnect"},$O=new Set(Object.values(_d)),mE={protocol:`[multiplayer] the authority server refused protocol ${4} (code 426) \u2014 this game was built with a @genex-ai/multiplayer that the server no longer serves. Update the package and republish.`,notEntitled:"[multiplayer] server-authoritative rooms are not available for this game (code 402): its owner is not entitled to them. This is final; the session does not retry."},wE=t=>t&&typeof t=="object"?t.code:void 0;function jO(t){throw Qa(t)?console.error(mE.protocol):wE(t)===Ka.NOT_ENTITLED&&console.error(mE.notEntitled),t}var xE=t=>t.physicsCore!==void 0&&t.predictPhysics!==!1;function qO(){let t=typeof navigator>"u"?"":String(navigator.userAgent??"");return/Mobi|Android|iPhone|iPad/i.test(t)?ud.mobile:ud.desktop}async function GO(t){if(t.url)return[t.url];let e=ww(t.regions,t.urls);if(e.length===0)throw new Error("genex multiplayer: `urls` must contain at least one authority server URL");return(await Ew(e,t.probe===void 0?{}:{probe:t.probe})).map(r=>r.url)}async function WO(t){let e=await GO(t),n=t.capacityRetryMs??FO,r={region:0,refused:0,step:0};for(;;){let s=e[r.region];try{return{room:await YO(new es(s),t),url:s}}catch(o){let i=wE(o)===Ka.AUTHORITY_CAPACITY?Sw(r,e.length,n):null;i===null&&jO(o);let a=i.attempt.waitMs;a>0&&await new Promise(c=>setTimeout(c,a)),r=i.state}}}function YO(t,e){let n=e.fast===void 0?[]:[yn.FAST];return t.joinOrCreate(mi.AUTHORITY,{...Za(e.room,e.name,e.auth),[Gb.CAPS]:xE(e)?[yn.PHYSICS,yn.PHYSICS_PREDICT,yn.INPUT_REPEAT,yn.LIFTS,yn.INPUT_TICK,...n]:[yn.PHYSICS,yn.INPUT_REPEAT,yn.LIFTS,yn.INPUT_TICK,...n],protocol:4})}function Di(t){if(!t)return null;let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n=e.name,r=oc(n);if(r===void 0)return null;let s=wi(n,e.params);return{name:n,definition:r,params:s}}function Vh(t,e){let{definition:n,params:r}=t,s=[...n.fields,...n.reads],o=n.fields;return{fields:s,step:(i,a,c,u)=>{let l=n.step(i,a,c,r,e,u);for(let d of o)i[d]=l[d]}}}var Hh=t=>t!==null&&t.definition.world?t.params.world??null:null,ce=(t,e)=>typeof t=="number"&&Number.isFinite(t)?t:e;function KO(t){if(typeof t.inMoveX=="number")return{moveX:ce(t.inMoveX,0),moveY:ce(t.inMoveY,0),moveZ:ce(t.inMoveZ,0),yaw:ce(t.inYaw,0),pitch:ce(t.inPitch,0),buttons:ce(t.inButtons,0)}}var $h={body:!1,qx:0,qy:0,qz:0,qw:1,sleep:!1},yE=new Map,gE=2*Math.PI,ps=t=>t-gE*Math.floor((t+Math.PI)/gE),qU=[an.Predicted,an.Separate,an.Timeline],XO=an.Predicted,Bi=t=>{let e=t;return typeof e.local=="object"&&typeof e.error=="object"&&typeof e.prev=="object"&&typeof e.renderAlpha=="function"?e:null};async function SE(t){let e=await WO(t);return JO(Ks(e.room),t,e.url)}function JO(t,e,n){let r=t.state,s=()=>r.entities??yE,o=()=>r.players??yE,i=e.renderDelayMs??rs.RENDER_DELAY_MS,a=t.input({type:ES,mode:"reliable",renderDelay:i}),c=lE({room:t,handle:a,open:e.fast,now:e.fastClock??(()=>performance.now()),tickHz:()=>F(),stateCurrent:()=>!$e}),u=null,l=ut.On,d=()=>{let y=r.preset??"";return y!==u&&(u=y,l=PS(y)),l},f=()=>vS(c.ack(),o().get(t.sessionId)?.inRep,a.sentCount,d()),h=y=>a.at(y)??c.inputAt(y),p=CS(),g=()=>{let y=TS(c.ack(),o().get(t.sessionId)?.inRep,d()),E=a.sentCount,k=y<E&&c.inputAt(y+1)!==void 0;return OS(p,y,E,a.replayBufferSize,k)},x=new Map,b=new Proxy(a,{get(y,E){if(E==="lastProcessed")return g();if(E==="pendingCount")return a.sentCount-c.ack();if(E==="at")return h;let k=Reflect.get(y,E,y);if(typeof k!="function")return k;let V=x.get(E);return V===void 0&&(V=k.bind(y),x.set(E,V)),V}}),S=Ws.get(t,{mode:"lerp",delay:i}),_={mode:"lerp",fields:["x","y","z"]},P={mode:"lerp",fields:["yaw"],angle:!0};S.attachAll("entities",_),S.attachAll("entities",P),S.attachAll("entities",{mode:"lerp",fields:["pitch"]}),S.attachAll("entities",{mode:"lerp",fields:["duck"]});let R={moveX:0,moveY:0,moveZ:0,yaw:0,pitch:0,buttons:0},v={inputsSent:0,inputsDropped:0,reconciles:0,visibleCorrections:0,correctionBuckets:Uh.map(()=>0).concat(0),peakCorrection:0,lastCorrection:0,reseeds:0,bodyStates:0,bodySnaps:0,peakBodyCorrection:0,projectilesPredicted:0,projectilesConfirmed:0,projectilesRejected:0,lastProjectileLeadMs:0},M=new Map,O=(y,E)=>{for(let k of M.get(y)??[])k(E)},z=!0,X=!1,N=null,Y=!0,he=()=>{N?.predicted?.reconciler.dispose(),N=null},A=e.world===void 0?rc:eo(e.world),W="no_entity",G="",$=typeof e.physics=="string"?e.physics:"",j="",se=()=>{if(e.predict===!1)return{prediction:null,reason:"off"};if(e.predict)return{prediction:e.predict,reason:""};let y=Di(r.preset);if(y===null)return{prediction:null,reason:"no_preset"};let E=Hh(y);if(E!==null&&E!==A.hash){let k=`${E}/${A.hash}`;return G!==k&&(G=k,console.warn(`[multiplayer] the room's ${y.name} world (hash ${E}) is not this client's (hash ${A.hash}): your own entity is drawn from the server without prediction. Pass the room module's world to session.setWorld().`)),{prediction:null,reason:"world_mismatch"}}return{prediction:Vh(y,A),reason:""}},oe=()=>{let y=[];for(let[E,k]of s())E===N?.id||k.owner===""||Cr(k)||r.bodies?.has(E)===!0||!o().has(k.owner)||y.push({id:E,x:k.x,y:k.y,z:k.z,vx:k.vx,vy:k.vy,vz:k.vz,yaw:k.yaw,spin:ce(k.spin,0)});return y},ne=null,ye=()=>{if(e.contacts!==void 0)return null;let y=r.preset??"";return(ne===null||ne.text!==y||ne.hash!==A.hash)&&(ne={text:y,hash:A.hash,contacts:aS(y,A)}),ne.contacts},ue=()=>e.contacts!==void 0||ye()!==null,yt=e.contacts??((y,E)=>ye()?.rule(y,E)),Gt=e.contactPass??(e.contacts===void 0?y=>ye()?.pass(y):void 0),Hn=new ld(yt,()=>zi(oe())),Li=()=>e.seatDrawing??ye()?.policy.drawing??XO,hs=e.seatDrawing===void 0||e.seatDrawing===an.Predicted?Ui(yt):null,ms=()=>ue()?hs:null,Fi=()=>Li()===an.Predicted?ms():null;function zi(y){return ye()===null?y:y.map(E=>({...E,flags:ce(s().get(E.id)?.flags,0)}))}let ys=(y,E,k=null)=>{if(N===null||!ue())return null;let V={...E,id:N.id,...ye()===null?{}:{flags:ce(N.entity.flags,0)}},H=ms(),U=null;H!==null?U=H.apply(y,f(),r.tick??0,V,F(),k):Hn.apply(y,f(),V,F());for(let te of uo)typeof V[te]=="number"&&(E[te]=V[te]);return U};function Ui(y){let E=null,k=()=>{let H=r.preset??"";if(E!==null&&E.text===H&&E.hash===A.hash)return E;let U=Di(H),te=Hh(U),K=U!==null&&(te===null||te===A.hash)?Vh(U,A):null;return E={text:H,hash:A.hash,fields:U===null?[]:[...U.definition.fields,...U.definition.reads],step:K===null?void 0:(me,ie,fe,dt)=>K.step(me,Ii({...ie}),fe,dt)},E},V=()=>{let{fields:H}=k(),U=[];for(let[te,ee]of s()){if(te===N?.id||ee.owner===""||Cr(ee)||r.bodies?.has(te)===!0)continue;let K=o().get(ee.owner);if(K===void 0)continue;let me=ee,ie={x:ee.x,y:ee.y,z:ee.z,vx:ee.vx,vy:ee.vy,vz:ee.vz,yaw:ee.yaw,spin:ce(ee.spin,0)};for(let fe of H)ie[fe]=ce(me[fe],fe==="cap"?1:0);ye()!==null&&(ie.flags=ce(ee.flags,0)),U.push({id:te,epoch:ee.epoch,body:ie,input:KO(K)})}return U};return new md({rule:y,pass:Gt,others:V,step:()=>k().step,seatRule:e.seatRule,lifts:()=>{let H=Wt();return H===null?null:{lifts:H,starts:Et(),cache:$n}},remote:()=>{let H=Wi();return{predict:H?.remotePredict??jt.HOLD,decayMs:H?.remoteDecayMs??dr.DEFAULT_REMOTE_DECAY_MS}},maxAheadMs:()=>(Wi()?.leadMs??dr.DEFAULT_LEAD_MS)+mS})}let Nr=null,Wt=()=>{let y=r.preset??"",E=ye();if(Nr===null||Nr.text!==y||Nr.hash!==A.hash||Nr.heads!==E){let k=E!==null&&ox(E.policy)?{policy:E.policy,env:E.env}:void 0;Nr={text:y,hash:A.hash,heads:E,lifts:kx(y,A,k,F())}}return Nr.lifts},gs={text:void 0,starts:void 0},Et=()=>{let y=r.lifts;return gs.text!==y&&(gs={text:y,starts:Px(y)}),gs.starts},cn=new Ri,$n=new Ri,Rd=y=>{let E=ms();return oe().map(k=>{let V=E?.poseAt(k.id,y-1),H=ce(s().get(k.id)?.flags,0),U=ce(s().get(k.id)?.duck,0);return V===void 0?{...k,duck:U,flags:H}:{id:k.id,x:V.x,y:V.y,z:V.z,vx:V.vx,vy:V.vy,vz:V.vz,yaw:V.yaw,duck:U,flags:H}})},Vi=["x","y","z"],Oc=["vx","vy","vz"],un=(y,E,k,V,H)=>{if(N===null)return null;let U=V,te={id:N.id,x:U.x??0,y:U.y??0,z:U.z??0,vx:U.vx??0,vy:U.vy??0,vz:U.vz??0,yaw:U.yaw??0,duck:U.duck??0,flags:ce(N.entity.flags,0)},K=[...y.heads===void 0?[]:Rd(E),te].sort((ie,fe)=>ie.id<fe.id?-1:ie.id>fe.id?1:0),me=yc(y,K,k,Et(),H,cn);for(let ie of Vi)U[ie]=te[ie];return y.vehicle&&(U.yaw=te.yaw),{t:me,mine:te}},tt=Number.NaN,xn=null,bs=null,ho=(y,E,k,V,H,U)=>{let te=Mi(r.tick??0,f(),E),ee=Wt(),K=ee===null?null:un(ee,E,U??te,k,H);e.seatRule?.(k,te,E),y(k,Ii(V),H,K===null?void 0:gc(K.t,K.mine.id));let me=K===null?-1:K.t.seats.indexOf(K.mine),ie=K===null?null:K.t.report.on[me]??null,fe=ys(E,k,ie);if(ee===null||K===null)return;fe!==null&&vx(ee,K.t,me,fe);let dt=k;xn=ie;for(let Xt of[...Vi,...Oc])K.mine[Xt]=dt[Xt]??0;bc(ee,K.t,Et());for(let Xt of Oc)dt[Xt]=K.mine[Xt]},mo=new Ri,Hi=(y,E,k,V,H)=>{let U=Wt();U===null||U.policy.platforms.length===0?y(E,k,V):Mx(U,Et(),mo,(te,ee)=>y(te,k,V,ee),E,H,V)},yo=y=>{let{prediction:E,reason:k}=se();if(W=k,!E)return null;let V=E.fields??UO;return{reconciler:S.reconciler(y,{input:b,fields:V,step:(U,te,ee)=>{(U.isReplay||Number.isNaN(tt))&&(tt=Mi(r.tick??0,f(),U.tick)-U.tick),xn=null,ho(E.step,U.tick,te,ee,U.dt,U.tick+tt),bs=xn}}),fields:V,step:E.step}},go=()=>{let y=N?.predicted;if(!N||!y)return null;let E=N.entity,k={};for(let U of y.fields)k[U]=ce(E[U],0);let V=a.stepSeconds??y.reconciler.stepMs/1e3,H=new Map;for(let U=f()+1;U<=a.sentCount;U++){let te=h(U);te!==void 0&&(ho(y.step,U,k,te,V),H.set(U,{p:[k.x??0,k.y??0,k.z??0],v:[k.vx??0,k.vy??0,k.vz??0]}))}return H},ws=y=>{y.predicted&&(v.reseeds++,fr(y))},fr=y=>{y.predicted?.reconciler.dispose();let E=yo(y.entity);if(y.predicted=E,!E)return;let k=E.reconciler.state,V=a.stepSeconds??E.reconciler.stepMs/1e3;tt=Mi(r.tick??0,f(),0);for(let H=f()+1;H<=a.sentCount;H++){let U=h(H);U!==void 0&&ho(E.step,H,k,U,V)}y.reseeded=!0},$i=(y,E)=>E.owner===t.sessionId&&!Cr(E)&&r.bodies?.has(y)!==!0,Ic=y=>s().get(y.id)===y.entity&&$i(y.id,y.entity),jn=()=>{if(N&&Ic(N)){N.entity.epoch!==N.epoch&&(N.epoch=N.entity.epoch,ws(N));return}if(!(!N&&!Y)){he(),Y=!1,W="no_entity";for(let[y,E]of s())if($i(y,E)){N={id:y,entity:E,epoch:E.epoch,predicted:yo(E),reseeded:!1};return}}},xs=y=>{let E=y.reconciler.state;return y.fields.map(k=>E[k]??0)},nt=(y,E,k)=>{if(y.reconciler.reconcileSeq===k)return;let V=xs(y),H=0;if(y.fields.forEach((U,te)=>{if(VO.has(U))return;let ee=(V[te]??0)-(E[te]??0);H=Math.max(H,Math.abs(HO.has(U)?ps(ee):ee))}),v.reconciles++,v.lastCorrection=H,v.peakCorrection=Math.max(v.peakCorrection,H),H>NO){v.visibleCorrections++;let U=Uh.findIndex(te=>H<te);v.correctionBuckets[U<0?Uh.length:U]+=1}},bo=y=>{if(!y.fields.includes("yaw"))return null;let E=Bi(y.reconciler),k=E?.local.yaw;return E&&typeof k=="number"?{local:k,error:E.error.yaw??0}:null},Dc=(y,E,k)=>{if(k===null||y.reconciler.reconcileSeq===E)return;let V=Bi(y.reconciler),H=V?.local.yaw,U=V?.error.yaw;if(!V||typeof H!="number"||typeof U!="number")return;let te=k.local+k.error-H;(te<-Math.PI||te>=Math.PI)&&(V.error.yaw=ps(te)*(U/te))},Bc=y=>{let E=Bi(y.reconciler);if(E===null||Number.isNaN(tt))return null;let k=V=>Object.fromEntries(Ed.map(H=>[H,ce(V[H],0)]));return{offset:tt,local:k(E.local),error:k(E.error),prev:k(E.prev)}},Nc=(y,E,k,V)=>{if(V===null||y.reconciler.reconcileSeq===E||V.offset===tt)return k;let H=Wt(),U=Bi(y.reconciler);if(H===null||H.policy.platforms.length===0||U===null)return k;let te=Et(),ee=a.sentCount+V.offset+1,K=a.sentCount+tt+1,me=je=>({x:je.x??0,y:je.y??0,z:je.z??0,yaw:je.yaw??0,duck:ce(U.local.duck,0)}),ie=wc(H,me(V.local),ee,te);if(ie<0||wc(H,me(U.local),K,te)!==ie)return k;let fe=(je,dn,qn)=>{let _n=mh(H.policy,ie,me(je),dn,qn,te);return{..._n,yaw:H.vehicle?_n.yaw:je.yaw??0}},dt=Object.fromEntries(Ed.map(je=>[je,(V.local[je]??0)+(V.error[je]??0)])),Xt=fe(dt,ee,K),gt=fe(V.prev,ee-1,K-1),Ro=fe(V.local,ee,K);for(let je of Ed){if(typeof U.local[je]!="number")continue;let dn=ce(U.local[je],0),qn=(dt[je]??0)-dn,_n=qn===0?0:(U.error[je]??0)/qn;U.error[je]=(Xt[je]-dn)*_n,U.prev[je]!==void 0&&(U.prev[je]=gt[je])}return y.fields.map((je,dn)=>Ed.includes(je)?Ro[je]:k[dn]??0)},Lc=y=>{let E=N?.entity===y?N.predicted:null;if(!E||!E.fields.includes("yaw"))return;let k=Bi(E.reconciler),V=k?.local.yaw;if(!k||typeof V!="number")return;let H=V+(k.error.yaw??0),U=k.prev.yaw??H;return U+ps(H-U)*k.renderAlpha()},Le=IS(),Lr=Number.NaN,ji=y=>{let E=a.stepMs??0,k=o().get(t.sessionId);DS(Le,k?.inStarve,k?.inBuf,E,d());let V=Number.isNaN(Lr)?0:y-Lr;return Lr=y,NS(Le,V,E)},ln,Fc=y=>{let E=a.stepMs;if(!E)return 0;if(ln===void 0)return ln=y,0;let k=Math.floor((y-ln)/E);return k>pE?(ln=y,pE):(ln+=k*E,k)},Sn=()=>Mi(r.tick??0,f(),0),wo=null,xo=y=>{if(!z)return v.inputsDropped+=y,0;let E=0,k=cS((wo??Sn())+a.sentCount+1);for(let V=0;V<y;V++){let H=Ii({...R});Object.assign(a.data,H),a.data.tick=k;let U=a.send();if(U===0){v.inputsDropped++;continue}E++,c.sent(U,k,H)}return c.flush(),v.inputsSent+=E,E},lt=t.clock,kd=()=>lt.lastServerTime()>0?lt.lastServerTime():performance.now(),Ss=()=>lt.lastServerTime()>0?lt.serverNow()-i-lt.smoothedRtt()/2:performance.now()-i,_t=new WeakMap,So=y=>({x:y.x,y:y.y,z:y.z,yaw:y.yaw,pitch:ce(y.pitch,0),duck:ce(y.duck,0)}),qi=y=>{let E=kd(),k=_t.get(y);if(k===void 0){_t.set(y,{at:E,epoch:y.epoch,pose:So(y),respawns:[]});return}k.epoch!==y.epoch&&y.owner!==t.sessionId&&k.respawns.push({from:k.at,at:E,epoch:k.epoch,pose:k.pose}),k.at=E,k.epoch=y.epoch,k.pose=So(y)},Pd=y=>{let E=_t.get(y)?.respawns;if(E===void 0||E.length===0)return;let k=Ss();for(;E.length>0&&k>=E[0].at;)E.shift();return E[0]},Gi=new gd,En=new Set,Eo={text:"",k:1},Ad=y=>(Eo.text!==y&&(Eo={text:y,k:Ec(y)?.keyframeTicks??1}),Eo.k),_o={text:"\0",desc:null},Wi=()=>{let y=r.physDesc??"";return _o.text!==y&&(_o={text:y,desc:Ec(y)}),_o.desc},Es=()=>e.remoteSamples!=="patch"&&(r.physDesc??"")!=="",w=()=>{if(En.size===0)return;let y=r.tick??0;if(Es()&&y===(r.keyframe??-1)){let k=Gl(y,Z(),F()),V=1e3/F()*Ad(r.physDesc??"");for(let H of En)Gi.push(H,k,So(H),V,H.epoch)}En.clear()},T=La(t);T(r).entities.onAdd(y=>{Y=!0,qi(y),En.add(y),T(y).onChange(()=>{qi(y),En.add(y)})}),t.onStateChange(w),T(r).entities.onRemove(()=>{Y=!0});let F=()=>a.stepMs?Math.round(1e3/a.stepMs):rs.TICK_HZ,Z=()=>r.tickOrigin??0,_e=()=>nh(lt.serverNow(),Z(),F()),de=y=>({x:y.x,y:y.y,z:y.z,vx:y.vx,vy:y.vy,vz:y.vz,g:y.g??0,t0:y.t0??0}),Pe=y=>Gl(y.t0??0,Z(),F()),re=S.spawns("entities",{owned:y=>Cr(y)&&y.src===t.sessionId,correlate:(y,E)=>s().get(y.id)!==E?!1:(Je.delete(y),v.projectilesConfirmed++,v.lastProjectileLeadMs=Pe(E)-y.at,!0),spawnTime:Pe,ttl:y=>{let E=Math.max(2*y,hE);if(!z)return E;let k=performance.now(),V=k-Me.endedAt<E+Me.ms?Me.ms:0;return E+Math.max(k-Oe,V)},onReject:y=>{Je.delete(y),v.projectilesRejected++}}),Oe=performance.now(),Me={ms:0,endedAt:0},Je=new Map,Yt=()=>{if(Je.size===0)return;let y=c.ack();for(let[E,k]of Je)E.epoch!==a.epoch||E.seq>y||s().has(E.id)||(Je.delete(E),k(),v.projectilesRejected++)},$e=!1,_s=()=>{$e=!1;for(let[y,E]of Je)y.epoch!==a.epoch&&(Je.delete(y),E(),v.projectilesRejected++)};t.onStateChange(()=>{let y=performance.now();(y-Oe>Me.ms||y-Me.endedAt>hE+Me.ms)&&(Me={ms:y-Oe,endedAt:y}),Oe=y,$e&&_s(),Yt()});let Ct=new Map,Rt=()=>{let y=ce(r.lengthUnit,0);return{tickHz:F(),tickOrigin:Z(),lengthUnit:y>0?y:1}},Fr=y=>({x:y.x,y:y.y,z:y.z,qx:ce(y.qx,0),qy:ce(y.qy,0),qz:ce(y.qz,0),qw:ce(y.qw,0),lvx:ce(y.lvx,0),lvy:ce(y.lvy,0),lvz:ce(y.lvz,0),avx:ce(y.avx,0),avy:ce(y.avy,0),avz:ce(y.avz,0),sleep:y.sleep===!0,epoch:y.epoch}),zc=()=>{let y=r.bodies;for(let[H,U]of Ct)y?.get(H)!==U.descriptor&&Ct.delete(H);if(y===void 0||y.size===0)return;let E=lt.serverNow(),k=Rt(),V=r.tick??0;for(let[H,U]of y){let te=s().get(H);if(te===void 0)continue;let ee=Ct.get(H),K=Cw(Fr(te),V);if(ee!==void 0&&Dw(ee.last,K)){ee.entity=te;continue}let{drawing:me,snap:ie}=Iw(ee?.drawing??null,K,E,k);v.bodyStates++,ie!==null?v.bodySnaps++:v.peakBodyCorrection=Math.max(v.peakBodyCorrection,Math.hypot(...me.dp)),Ct.set(H,{descriptor:U,entity:te,last:K,drawing:me,handoff:ee?.handoff??new sd})}};t.onStateChange(zc);let pr=SS({enabled:xE(e),loadCore:e.physicsCore,state:r,sessionId:t.sessionId,staticWorld:()=>A,tickHz:F,sent:()=>a.sentCount,acked:()=>f(),ownId:()=>N?.id,ownPath:go,bodyRule:e.bodyRule,headSlide:()=>{let y=ye()?.policy;return y?.headFriction===no.Slide?y.propSlide:null},kinematicRule:e.kinematicRule,lifts:()=>{let y=Wt();return y===null||y.policy.platforms.length===0?null:{policy:y.policy,starts:Et()}},seatRule:e.seatRule,budgetMs:Yx(e.physicsBudgetMs,qO()),contactPass:y=>ye()?.pass(y),motionKnown:y=>c.motionKnown(y),...typeof e.physicsClock=="function"?{clock:e.physicsClock}:{},...hs===null?{}:{seatPose:(y,E)=>{let k=ms()?.poseAt(y,E);return k===void 0?void 0:{key:y,x:k.x,y:k.y,z:k.z,vx:k.vx,vy:k.vy,vz:k.vz}}},remoteStep:()=>{let y=Di(r.preset??"");if(y===null)return;let{step:E}=Vh(y,A);return(k,V,H,U)=>Hi(E,k,Ii({...V}),H,U)}});t.onStateChange(()=>pr.onState(lt.serverNow()));let Uc=()=>{let y=N?.predicted?.reconciler.state;return y===void 0?void 0:{p:[y.x??0,y.y??0,y.z??0],v:[y.vx??0,y.vy??0,y.vz??0]}},Kh=y=>(!Ct.has(y)&&r.bodies?.has(y)===!0&&zc(),Ct.get(y)),vd=(y,E)=>{let k=Rt(),V=lt.serverNow(),H=pr.draw(y,V),U=E.entity,te=E.descriptor?.kind,ee=H===null&&e.kinematicRule!==void 0?Wx(e.kinematicRule,y,V,k):null,K=E.handoff.draw(H??ee??eh(E.drawing,V,k),H!==null,U.epoch,V,ad(te),k.lengthUnit),[me,ie,fe]=E.last.lv;return{id:y,kind:U.kind,owner:U.owner,x:K.p[0],y:K.p[1],z:K.p[2],yaw:ps(U.yaw),vx:me*k.lengthUnit,vy:ie*k.lengthUnit,vz:fe*k.lengthUnit,hp:U.hp,flags:U.flags,epoch:U.epoch,data:U.data,t0:0,g:0,src:"",pitch:0,duck:0,mstate:0,cap:1,spin:0,fuel:0,body:!0,qx:K.q[0],qy:K.q[1],qz:K.q[2],qw:K.q[3],sleep:E.last.sleep,predicted:H!==null}},Vc={epoch:-1,seq:0,n:0},Rs=y=>typeof y=="number"&&Number.isFinite(y)?Te(Math.fround(y)):0,Xh=y=>{let E=th(y.launch,_e(),F());return{id:y.id,kind:y.kind,owner:"",...E,yaw:0,hp:0,flags:0,epoch:0,data:"",t0:y.launch.t0,g:y.launch.g,src:t.sessionId,pitch:0,duck:0,mstate:0,cap:1,spin:0,fuel:0,...$h}},Jh=()=>{let y=new Map;for(let E of re.entries())E.state==="pending"&&E.local&&y.set(E.local.id,E.local);return y};t.onDrop(y=>{c.dropped(),z=!1,$e=!0,O(_d.Reconnecting,{code:y})}),t.onReconnect(()=>{if(X){t.leave(!0).catch(()=>{});return}(async()=>(await Tl(t,gn.firstStateTimeoutMs),!X&&($e&&_s(),N?.predicted&&(N.predicted.reconciler.reset(),v.reseeds++),ln=void 0,z=!0,O(_d.Reconnected))))()});let Zh=()=>{X=!0,z=!1,c.dispose(),he(),S.dispose(),pr.dispose()};t.onLeave(y=>{X||(Zh(),O(_d.Disconnect,y))}),t.onMessage("*",(y,E)=>{typeof y=="string"&&(e.onEvent?.(y,E),$O.has(y)||O(y,E))});let PE=y=>{if(!N?.reseeded||N.entity!==y||!N.predicted)return;let E=N.predicted.reconciler.state;return{x:E.x??y.x,y:E.y??y.y,z:E.z??y.z,yaw:E.yaw??y.yaw,pitch:E.pitch??ce(y.pitch,0),duck:E.duck??ce(y.duck,0),epoch:y.epoch}},AE=()=>{if(N===null||N.predicted===null)return null;let y=im(N.entity);return{id:N.id,x:y.x,y:y.y,z:y.z,vx:0,vy:0,vz:0,yaw:y.yaw}},Qh=y=>{let k=N?.reseeded===!0&&N.predicted===y?1:Bi(y.reconciler)?.renderAlpha()??1;return Math.max(0,a.sentCount-f()-1+k)},Hc=new Map,Kt=0,em=()=>ue()&&Li()!==an.Timeline,Td=y=>N?.entity!==y&&y.owner!==""&&!Cr(y)&&o().has(y.owner),vE=(y,E)=>{let k=Hc.get(y);return k!==void 0&&k.lives===E&&Kt-k.at<=zO?k:void 0},$c=new Map,Md,jc=new Map,Cd=Number.NaN,Yi={tick:Number.NaN,leadMs:Number.NaN},TE=()=>{let y=ce(r.lengthUnit,0);return y>0?y:_w[Di(r.preset??"")?.name??""]??1},ME=()=>{let y=Fi(),E=y?.current??null;if(y===null||E===null||N===null||N.predicted===null)return Yi={tick:Number.NaN,leadMs:Number.NaN},null;let k=f(),V=Qh(N.predicted),H=BS(k,V,Le,a.stepMs??0,Kt);Md=yS(Md,H.raw,H.at,F());let U=Md.seq,te=k+V,ee=Number.isNaN(Cd)?0:Kt-Cd;Cd=Kt;let K=E.stateTick+(U-E.ack);Yi={tick:K,leadMs:Gl(K+1,Z(),F())-lt.serverNow()};let me=mt.SEAT_SNAP_METRES*TE(),ie=new Map;for(let[fe,dt]of s()){if(!Td(dt))continue;let Xt=y.motionAt(fe,U);if(Xt===void 0)continue;let gt=Xt.pose,Ro=$c.get(fe),je=Ro?.pass!=null&&Ro.pass!==E?y.changeAt(fe,U,Ro.pass):void 0,dn=wS(Ro,E,dt.epoch,je,Xt,ee,y.touchingAt(fe,U),me,y.stateRate(fe));$c.set(fe,dn);let qn={x:gt.x+dn.dx,y:gt.y+dn.dy,z:gt.z+dn.dz,yaw:gt.yaw+dn.dyaw,pitch:ce(dt.pitch,0),duck:ce(dt.duck,0),epoch:dt.epoch},_n=gS(jc.get(fe),y.touchAheadMs(fe,te)!==void 0,ee);jc.set(fe,_n);let Ki=_n>0?y.motionAt(fe,te)?.pose:void 0;Ki!==void 0&&(qn.x+=(Ki.x-gt.x)*_n,qn.y+=(Ki.y-gt.y)*_n,qn.z+=(Ki.z-gt.z)*_n,qn.yaw+=ps(Ki.yaw-gt.yaw)*_n),ie.set(fe,{pose:qn,at:gt})}for(let fe of[...$c.keys()])ie.has(fe)||$c.delete(fe);for(let fe of[...jc.keys()])ie.has(fe)||jc.delete(fe);return ie},CE=y=>{if(!ue())return;let E=e.contacts===void 0?ye():null;return E===null||y===null?yt:E.drawRule(y.id)},OE=()=>{let y=new Map,E=em()?AE():null,k=CE(E);if(k===void 0||E===null||N===null||N.predicted===null)return Hc.clear(),Yi={tick:Number.NaN,leadMs:Number.NaN},y;let V=Fi()===null?null:ME(),H=[];for(let[K,me]of s()){if(!Td(me))continue;let ie=V?.get(K)?.pose??Gc(me);y.set(K,ie),H.push({id:K,x:ie.x,y:ie.y,z:ie.z,vx:0,vy:0,vz:0,yaw:ie.yaw,...ye()===null?{}:{flags:ce(me.flags,0)}})}let U=new Map;for(let[K,me]of y)U.set(K,`${N.entity.epoch}/${me.epoch}`);for(let[K,me]of y)for(let[ie,fe]of y)K<ie&&U.set(kc(K,ie),`${me.epoch}/${fe.epoch}`);let te=new Map;for(let[K,me]of U){let ie=vE(K,me);ie!==void 0&&te.set(K,ie)}let ee=iS(k,E,H,te,Kt);Hc.clear();for(let[K,me]of ee.sides)Hc.set(K,{...me,lives:U.get(K)??""});for(let[K,me]of ee.drawn){let ie=y.get(K);if(ie===void 0)continue;let fe=V?.get(K)?.at,dt=fe===void 0?void 0:Math.hypot(me.x-fe.x,me.y-fe.y,me.z-fe.z);y.set(K,{...ie,x:me.x,y:me.y,z:me.z,...dt===void 0?{}:{correction:dt}})}return IE(y,E),y},qc=new Map,IE=(y,E)=>{let k=N?.entity;for(let[V,H]of y){let U=s().get(V),te=V===bs&&k!==void 0&&U!==void 0,ee=te?[E.x-(k.x-U.x)-H.x,E.y-(k.y-U.y)-H.y,E.z-(k.z-U.z)-H.z,0]:[0,0,0,0],K=qc.get(V),me=K===void 0?0:Math.exp(-Math.max(0,Kt-K.at)/dE),ie=fE(K,te?1:0,ee,me);qc.set(V,{k:te?1:0,shift:ee,err:ie,at:Kt}),!(!te&&ie.every(fe=>Math.abs(fe)<LO))&&y.set(V,{...H,x:H.x+ee[0]+ie[0],y:H.y+ee[1]+ie[1],z:H.z+ee[2]+ie[2]})}for(let V of[...qc.keys()])y.has(V)||qc.delete(V)},Od=0;t.onStateChange(()=>{Od++});let tm,nm=()=>{let y=tm;if(y!==void 0&&y.at===Kt&&y.states===Od)return y.seats;let E=OE();return tm={at:Kt,states:Od,seats:E},E},Id=null,rm=()=>N?.predicted?(Number.isNaN(tt)?(r.tick??0)-f():tt)+f()+Qh(N.predicted)+1:sm(),sm=()=>(Ss()-Z())*F()/1e3,om=new WeakMap,DE=(y,E)=>{let k=Wt();if(k===null||k.policy.platforms.length===0||!N?.predicted)return E;let V=sm(),H=rm(),U=Et(),te=(r.tick??0)+1,ee=wc(k,{x:y.x,y:y.y,z:y.z,duck:ce(y.duck,0)},te,U),K=ee<0?E:{...E,...mh(k.policy,ee,E,V,H,U)};ee>=0&&(K.z=yh(k.policy,ee,H,U)+(y.z-yh(k.policy,ee,te,U)));let me=[K.x-E.x,K.y-E.y,K.z-E.z,K.yaw-E.yaw],ie=om.get(y),fe=Kt,dt=ie===void 0?0:Math.max(0,fe-ie.at),Xt=Math.exp(-dt/dE),gt=fE(ie,ee,me,Xt);return om.set(y,{k:ee,shift:me,err:gt,at:fe}),{...E,x:K.x+gt[0],y:K.y+gt[1],z:K.z+gt[2],yaw:K.yaw+gt[3]}},Dd=null,BE=y=>{let E=Gc(y.entity);fr(y);let k=Gc(y.entity);Dd={dx:E.x-k.x,dy:E.y-k.y,dz:E.z-k.z,at:Kt}},Gc=y=>{let E=NE(y),k=N?.entity===y?Dd:null;if(k===null)return E;let V=bS(k,Kt-k.at);return V.done?(Dd=null,E):{...E,x:E.x+V.dx,y:E.y+V.dy,z:E.z+V.dz}},NE=y=>{let E=PE(y);if(E)return E;let k=Pd(y),V=S.value(y,"yaw"),U=(N?.entity!==y&&Es()?Gi.at(y,Ss()):void 0)??{x:S.value(y,"x"),y:S.value(y,"y"),z:S.value(y,"z"),yaw:Lc(y)??V,pitch:ce(S.value(y,"pitch"),ce(y.pitch,0)),duck:ce(S.value(y,"duck"),ce(y.duck,0))};return k===void 0?{...N?.entity===y?U:DE(y,U),epoch:y.epoch}:{...Ss()>k.from?k.pose:U,epoch:k.epoch}},im=(y,E,k)=>(E!==void 0&&em()&&Td(y)?(k??nm()).get(E):void 0)??Gc(y),LE=(y,E)=>{let k=re.entryFor(E),V=k?.local!==void 0&&E.src===t.sessionId?k.leadMs*F()/1e3:0,H=th(de(E),_e()+V,F());return{id:y,kind:E.kind,owner:E.owner,...H,yaw:ps(E.yaw),hp:E.hp,flags:E.flags,epoch:E.epoch,data:E.data,t0:E.t0,g:E.g,src:E.src,pitch:ce(E.pitch,0),duck:ce(E.duck,0),mstate:ce(E.mstate,0),cap:ce(E.cap,1),spin:ce(E.spin,0),fuel:ce(E.fuel,0),...$h}},Bd={text:"",limit:Math.PI},FE=()=>{let y=r.preset??"";if(Bd.text!==y){let E=Di(y)?.params.pitchLimit;Bd={text:y,limit:E===void 0?Math.PI:Math.fround(E)}}return Bd.limit},zE=y=>{let E=FE(),k=ps(y);return k<-E?-E:k>E?E:k},Nd=(y,E,k)=>N?.entity===y&&N.predicted?.fields.includes(E)?ce(N.predicted.reconciler.state[E],k):ce(y[E],k),Ld=(y,E,k)=>{let V=Kh(y);if(V!==void 0)return vd(y,V);if(Cr(E))return LE(y,E);let H=im(E,y,k);return{id:y,kind:E.kind,owner:E.owner,x:H.x,y:H.y,z:H.z,yaw:ps(H.yaw),vx:E.vx,vy:E.vy,vz:E.vz,hp:E.hp,flags:E.flags,epoch:H.epoch,data:E.data,t0:E.t0??0,g:E.g??0,src:E.src??"",pitch:zE(H.pitch),duck:H.duck<0?0:H.duck>1?1:H.duck,mstate:Nd(E,"mstate",0),cap:ce(E.cap,1),spin:Nd(E,"spin",0),fuel:Nd(E,"fuel",0),...$h,...H.correction===void 0?{}:{predicted:!0,correction:H.correction}}};return{id:t.sessionId,url:n,input:R,frame(y=performance.now()){if(X)return 0;Kt=y,c.poll(),pr.settle(),jn();let E=N?.predicted??null,k=E?xs(E):[],V=E?bo(E):null,H=E?Bc(E):null,U=E?.reconciler.reconcileSeq??0,te=ji(y),ee=S.tick(y)+te;if(!E){let me=xo(Fc(y)+te);return pr.afterSend(void 0,lt.serverNow()),wo=Sn(),me}ln=void 0,nt(E,Nc(E,U,k,H),U),Dc(E,U,V);let K=xo(ee);return pr.afterSend(Uc(),lt.serverNow()),wo=Sn(),K>0&&N&&(N.reseeded=!1),(hs?.takeMissed()??[]).length>0&&N!==null&&BE(N),K},me(){return X||jn(),N?Ld(N.id,N.entity):void 0},setWorld(y){let E=eo(y),k=E.hash!==A.hash;return A=E,k&&N&&!X&&fr(N),A.hash},setPhysics(y){if(typeof y!="string")throw new TypeError("setPhysics: the hash is a string (the world's physicsHash)");return $=y,$},get physics(){let y=r.physics??"",E=y!==""&&y!==$;return E&&j!==`${y}/${$}`&&(j=`${y}/${$}`,console.warn(`[multiplayer] the room's physics world (hash ${y}) is not this client's (hash ${$||"none"}): your copy is never stepped from the room's state. Pass your world's physicsHash to session.setPhysics().`)),{reason:E?"physics_mismatch":"",physics:$,roomPhysics:y}},get physicsPrediction(){return pr.status},drawTick(){return Yi.tick},drawLead(){return Yi.leadMs},liftPose(y){let E=Wt();return E===null?void 0:Tx(E.policy,y,rm(),Et())},viewCarry(){let y=Wt(),E=N?.predicted?N.predicted.reconciler.state:void 0;if(y===null||E===void 0)return Id=null,0;let k=Mi(r.tick??0,f(),a.sentCount)+1,V=wc(y,{x:E.x??0,y:E.y??0,z:E.z??0,duck:E.duck??0},k,Et()),H=y.policy.platforms[V],U=Id;return Id=H===void 0?null:{k:V,tick:k},H===void 0||U===null||U.k!==V?0:hh(H)*(k-U.tick)},get prediction(){X||jn();let y=N?.predicted!=null,E=y?"":N?W:e.predict===!1?"off":"no_entity";return{predicting:y,reason:E,world:A.hash,roomWorld:Hh(Di(r.preset??""))}},predictProjectile(y){if(!z)return"";let E=a.sentCount+1;(Vc.epoch!==a.epoch||Vc.seq!==E)&&(Vc={epoch:a.epoch,seq:E,n:0});let k=o().get(t.sessionId)?.seqBase??0,V=`${t.sessionId}.${k+E}.${Vc.n++}`,H=lt.serverNow(),U=Rs(y.g),te={x:Rs(y.x),y:Rs(y.y),z:Rs(y.z),vx:Rs(y.vx),vy:Rs(y.vy),vz:Rs(y.vz),g:U<0?0:U>ic?ic:U,t0:nh(H,Z(),F())},ee={id:V,kind:String(y.kind),launch:te,at:H,seq:E,epoch:a.epoch},K=re.spawn(ee);return Je.set(ee,()=>K.cancel()),v.projectilesPredicted++,V},entity(y){let E=s().get(y);if(E)return Ld(y,E);let k=Kh(y);if(k!==void 0)return vd(y,k);let V=Jh().get(y);return V?Xh(V):void 0},entities(){let y=new Map,E=nm();for(let[k,V]of s())y.set(k,Ld(k,V,E));for(let[k,V]of Ct)y.has(k)||y.set(k,vd(k,V));for(let[k,V]of Jh())y.has(k)||y.set(k,Xh(V));return y},players(){let y=new Map;for(let[E,k]of o())y.set(E,{id:E,name:k.name,uid:k.uid,team:k.team,connected:k.connected,avatarUrl:k.avatarUrl});return y},get tick(){return r.tick??0},get connected(){return z},telemetry:v,fast:c.status,on(y,E){let k=M.get(y)??new Set;M.set(y,k);let V=E;return k.add(V),()=>{k.delete(V)}},async leave(){X||(Zh(),t.reconnection.enabled=!1,await t.leave(!0))}}}var ZO=3,EE={ready:t=>ra.ready(t),auth:()=>du(),urls:()=>Ym(),regions:()=>Km()},Mc=EE;function QO(t){Mc=t??EE}var _E;function eI(t){_E=t??void 0}var tI=rs.MAX_REWIND_MS,nI=5,rI=3e4,sI=["moveX","moveY","moveZ","yaw","pitch","buttons"],Ni=t=>typeof t=="number"&&Number.isFinite(t);function oI(t){return!Array.isArray(t)||t.length>nI?void 0:t.every(n=>Ni(n)&&n>=0&&n<=rI)?t:void 0}function iI(t){let e=Wn(t,"options"),n=typeof e.gameId=="string"?e.gameId:"";if(!n)throw new TypeError("genex bridge: `gameId` (the game slug) is required");let r=e.renderDelayMs,s=Ni(r)&&r>=0&&r<=tI;return{gameId:n,name:typeof e.name=="string"&&e.name?e.name:void 0,urls:Array.isArray(e.urls)?e.urls.filter(o=>typeof o=="string"&&o!==""):[],predict:e.predict!==!1,predictPhysics:e.predictPhysics!==!1,renderDelayMs:s?r:void 0,capacityRetryMs:oI(e.capacityRetryMs)}}var Gh=new Map,aI=2**30,cI=aI,Cc=t=>typeof t=="number"?Gh.get(t):void 0,po=t=>{let e=Cc(t);return e&&!e.closed?e.session:null};function Wh(t){t.closed=!0;for(let e of t.unwire.splice(0))e();t.session=null}function uI(t,e,n){ns(e)?e===xe.SERVER_RESTART&&pe(t,{type:"serverRestart"}):pe(t,{type:"message",kind:e,data:n??null})}async function lI(t){let e=t.opts;if(await Mc.ready(e.gameId),t.closed)return;let n=e.urls.length?e.urls:Mc.urls(),r=e.urls.length?[]:Mc.regions?.()??[];if(!n.length&&!r.length)throw Object.assign(new Error("genex bridge: no authority server URL (pass urls, or run on a Genex page that serves authority rooms)"),{code:0});let s=await SE({urls:n,regions:r,room:e.gameId,name:e.name,auth:()=>Mc.auth(),predict:e.predict?void 0:!1,physicsCore:_E,predictPhysics:e.predictPhysics,renderDelayMs:e.renderDelayMs,capacityRetryMs:e.capacityRetryMs,onEvent:(o,i)=>{t.closed||uI(t,o,i)}});if(t.closed){await s.leave();return}t.session=s,t.sessionId=s.id,t.world&&s.setWorld(t.world),t.unwire.push(s.on("reconnecting",({code:o})=>pe(t,{type:"reconnecting",code:o})),s.on("reconnected",()=>pe(t,{type:"reconnected"})),s.on("disconnect",o=>{Wh(t),pe(t,{type:"disconnected",code:o,reason:""})})),pe(t,{type:"joined",sessionId:s.id})}function dI(t){let e=iI(t),n=++cI,r={opts:e,q:[],overflowed:!1,session:null,unwire:[],roster:new Set,sessionId:"",closed:!1,world:null};return Gh.set(n,r),lI(r).catch(s=>{r.closed||(Wh(r),pe(r,{type:"joinFailed",code:No(s),message:Gn(s)}))}),n}function fI(t,e){let n=Wn(e,"input"),r=po(t);if(!r)return!1;for(let s of sI){let o=n[s];Ni(o)&&(r.input[s]=o)}return!0}function pI(t,e){let n=Wn(e,"projectile"),r=po(t);if(!r)return"";let s=o=>Ni(o)?o:0;return r.predictProjectile({kind:typeof n.kind=="string"?n.kind:"",x:s(n.x),y:s(n.y),z:s(n.z),vx:s(n.vx),vy:s(n.vy),vz:s(n.vz),...Ni(n.g)?{g:n.g}:{}})}function hI(t,e){let n=Wn(e,"world"),r=Cc(t);if(!r||r.closed)return!1;let s;try{s=eo(n)}catch(o){return pe(r,Bo(Gn(o))),!1}return r.world=s,r.session?.setWorld(s),!0}var mI=JSON.stringify({tick:0,sent:0,connected:!1,me:null,entities:[]});function yI(t,e){let n=po(t);if(!n)return mI;let r=n.frame(Ni(e)?e:performance.now());return JSON.stringify({tick:n.tick,sent:r,connected:n.connected,me:n.me()??null,entities:[...n.entities().values()]})}var jh=8,qh={PREDICTED:1,ASLEEP:2},gI=new Float32Array(0);function RE(t){return[...t.entities().values()].filter(e=>e.body).sort((e,n)=>e.id<n.id?-1:e.id>n.id?1:0)}function bI(t){let e=po(t);if(!e)return gI;let n=RE(e),r=new Float32Array(n.length*jh);return n.forEach((s,o)=>{let i=o*jh;r.set([s.x,s.y,s.z,s.qx,s.qy,s.qz,s.qw],i),r[i+7]=(s.predicted?qh.PREDICTED:0)|(s.sleep?qh.ASLEEP:0)}),r}function wI(t){let e=po(t);return JSON.stringify(e?RE(e).map(n=>n.id):[])}function xI(t){let e=Cc(t),n=po(t);return JSON.stringify({sessionId:e?.sessionId??"",connected:!!n&&n.connected,closed:!e||e.closed,tick:n?.tick??0,queued:e?.q.length??0,players:n?[...n.players().values()]:[],telemetry:n?{...n.telemetry}:null,prediction:n?n.prediction:null,physicsPrediction:n?n.physicsPrediction:null})}function SI(t,e){let n=new Set(e.players().keys());for(let r of n)t.roster.has(r)||pe(t,{type:"playerJoined",id:r});for(let r of t.roster)n.has(r)||pe(t,{type:"playerLeft",id:r});t.roster=n}function EI(t){let e=Cc(t);if(!e)return"[]";try{let n=po(t);n&&SI(e,n)}catch(n){pe(e,Bo(Gn(n)))}return mu(e)}function kE(t){let e=Cc(t);if(!e||e.closed)return;let n=e.session;Wh(e),n?.leave().catch(()=>{}),pe(e,{type:"disconnected",code:Xa.CONSENTED,reason:"left"})}function _I(t){kE(t),typeof t=="number"&&Gh.delete(t)}var RI=Object.freeze({...Bp,...Yh,initEmbed:lu});globalThis.GenexMultiplayerBridge=RI;})();
12
+ `);let s=new Uint8Array(r);return s.set(e),e===this.sharedBuffer&&(this.sharedBuffer=s),s}encodeAll(e={offset:0},n=this.sharedBuffer){return this.encodeFullSync(e,n,!1)}encodeAllView(e,n,r,s=this.sharedBuffer){let o=r.offset;return s=this.encodeFullSync(r,s,!0,e,o),qf(s.subarray(0,n),s.subarray(o,r.offset))}ensureCapacity(e,n){if(n+ir.BUFFER_SIZE<=e.byteLength)return e;let r=Math.ceil((n+ir.BUFFER_SIZE)/ir.BUFFER_SIZE)*ir.BUFFER_SIZE,s=new Uint8Array(r);return s.set(e.subarray(0,n)),e===this.sharedBuffer&&(this.sharedBuffer=s),s}encodeView(e,n,r,s=this.sharedBuffer){let o=r.offset;this._emitStreamPriority(e);for(let i of e.changes.keys()){let a=e.changes.get(i),c=this.root.changeTrees[i];if(c===void 0){e.changes.delete(i);continue}if(a.size===0)continue;let u=c.encDescriptor,l=u.encoder,d=u.metadata,f=c.ref,h=c.refTarget;s=this.ensureCapacity(s,r.offset),s[r.offset++]=255,Se.number(s,f[Q],r);for(let[p,y]of a){let S;if(p===wP){let R=h.tmpItems,A=h.deletedIndexes;for(let E=0;E<R.length;E++)R[E]===void 0||A[E]===!0||l(this,s,c,E,N.ADD,r,!1,!0,d);continue}if(typeof p=="number")S=p;else{let R=p.indexInParent(f);if(R===void 0)continue;if(S=R,y===N.ADD&&c.getChange(S)===N.DELETE){e.changes.delete(p.ref[Q]);continue}}let x=h[st](S)!==void 0&&y||N.DELETE;l(this,s,c,S,x,r,!1,!0,d)}}return e.changes.clear(),s=this.encode(r,e,s),qf(s.subarray(0,n),s.subarray(o,r.offset))}encodeUnreliableView(e,n,r,s=this.sharedBuffer){let o=r.offset;return s=this.encodeUnreliable(r,e,s,o),qf(s.subarray(0,n),s.subarray(o,r.offset))}_emitStreamBroadcast(e,n){let r=this.root.streamTrees;for(let s of r){let o=s,i=o[I],a=o[Q];if(a===void 0)continue;let c=o._stream,u=c.broadcastDeletes,l=c.broadcastPending,d=c.sentBroadcast,f=u.size>0,h=l.size>0,p=i.encDescriptor,y=p.encoder,S=p.metadata;if(f||h){if(e[n.offset++]=255,Se.number(e,a,n),f){for(let E of u)y(this,e,i,E,N.DELETE,n,!1,!1,S);u.clear()}let b=c.maxPerTick,x=[],R=0,A=[];for(let E of l){if(R>=b)break;let P=o[st](E);if(P===void 0){A.push(E);continue}y(this,e,i,E,N.ADD,n,!1,!1,S),d.add(E),x.push(P),A.push(E),R++}for(let E of A)l.delete(E);for(let E of x){let P=E[I];if(P===void 0)continue;let k=E[Q];if(k===void 0)continue;e[n.offset++]=255,Se.number(e,k,n);let M=P.encDescriptor,B=M.encoder,K=M.metadata;P.forEachLive(j=>{De.hasUnreliableAtIndex(K,j)||B(this,e,P,j,N.ADD,n,!1,!1,K)})}}for(let b of d){let x=o[st](b);if(x===void 0)continue;let R=x[I];if(R===void 0||!R.has())continue;let A=x[Q];if(A===void 0)continue;e[n.offset++]=255,Se.number(e,A,n);let E=R.encDescriptor,P=E.encoder,k=E.metadata;R.forEach((M,B)=>{M<0||De.hasUnreliableAtIndex(k,M)||P(this,e,R,M,B,n,!1,!1,k)})}}}_emitStreamPriority(e){let n=this.root.streamTrees;if(n.size===0)return;let r=e.id;for(let s of n){let o=s,i=o._stream,a=i.pendingByView.get(r);if(a===void 0||a.size===0)continue;let c=i.priorityByView?.get(r),u=c!==void 0,l=i.priority,d=i.maxPerTick,f=[],h=[];if(u||l!==void 0){let S=[],b=[],x=0;for(let R of a){let A=o[st](R);if(A===void 0){h.push(R);continue}let E=u?c(A):l(e,A);if(x<d){let P=x++;for(;P>0&&b[P-1]<E;)b[P]=b[P-1],S[P]=S[P-1],P--;b[P]=E,S[P]=R}else if(E>b[d-1]){let P=d-1;for(;P>0&&b[P-1]<E;)b[P]=b[P-1],S[P]=S[P-1],P--;b[P]=E,S[P]=R}}for(let R=0;R<x;R++)f.push(S[R])}else for(let S of a){if(f.length>=d)break;f.push(S)}for(let S of h)a.delete(S);let p=f.length,y=i.sentByView.get(r);y===void 0&&(y=new Set,i.sentByView.set(r,y));for(let S=0;S<p;S++){let b=f[S],x=o[st](b);if(x===void 0){a.delete(b);continue}e._addImmediate(x);let R=x[I];if(R!==void 0){let A=x[Q],E=e.changes.get(A);E===void 0&&(E=new Map,e.changes.set(A,E));let P=R.metadata;R.forEachLive(k=>{De.hasUnreliableAtIndex(P,k)||E.set(k,N.ADD)})}a.delete(b),y.add(b)}}}discardChanges(){let e=this.root.changes,n=e.next,r=this.root;for(;n;){let s=n.next;n.changeTree.endEncode(),r.releaseNode(n),n=s}e.next=void 0,e.tail=void 0}discardUnreliableChanges(){let e=this.root.unreliableChanges,n=e.next,r=this.root;for(;n;){let s=n.next;n.changeTree.endEncodeUnreliable(),r.releaseNode(n),n=s}e.next=void 0,e.tail=void 0}tryEncodeTypeId(e,n,r,s){let o=this.context.getTypeId(n),i=this.context.getTypeId(r);if(i===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}o!==i&&(e[s.offset++]=213,Se.number(e,i,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 n=e.activeViews.size===0;for(let r of e.streamTrees)if(n?fA(r):dA(r,e))return!0;return!1}get hasUnreliableChanges(){return this.root.unreliableChanges.next!==void 0}};m(ir,"BUFFER_SIZE",16*1024);Ta=ir,qu=class extends Error{constructor(e){super(e),this.name="DecodingWarning"}},sg={value:0,enumerable:!1,writable:!0},Qf=class{constructor(){m(this,"refs",new Map);m(this,"refCount",{});m(this,"deletedRefs",new Set);m(this,"callbacks",{});m(this,"nextUniqueId",0)}getNextUniqueId(){return this.nextUniqueId++}addRef(e,n,r=!0){this.refs.set(e,n),n[Q]===void 0?(sg.value=e,Object.defineProperty(n,Q,sg)):n[Q]!==e&&(n[Q]=e),r&&(this.refCount[e]=(this.refCount[e]||0)+1),this.deletedRefs.has(e)&&this.deletedRefs.delete(e)}removeRef(e){let n=this.refCount[e];if(n===void 0){try{throw new qu("trying to remove refId that doesn't exist: "+e)}catch(r){console.warn(r)}return}if(n===0){try{let r=this.refs.get(e);throw new qu(`trying to remove refId '${e}' with 0 refCount (${r.constructor.name}: ${JSON.stringify(r)})`)}catch(r){console.warn(r)}return}(this.refCount[e]=n-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 n=this.refs.get(e),r=n.constructor[Symbol.metadata];if(r!=null)for(let s in r){let o=r[s].name,i=n[o];if(typeof i=="object"&&i){let a=i[Q];a!==void 0&&!this.deletedRefs.has(a)&&this.removeRef(a)}}else typeof n[be]=="function"&&Array.from(n.values()).forEach(s=>{let o=s[Q];o!==void 0&&!this.deletedRefs.has(o)&&this.removeRef(o)});this.refs.delete(e),delete this.refCount[e],delete this.callbacks[e]}),this.deletedRefs.clear()}addCallback(e,n,r){if(e===void 0){let s=typeof n=="number"?N[n]:n;throw new Error(`Can't addCallback on '${s}' (refId is undefined)`)}return this.callbacks[e]||(this.callbacks[e]={}),this.callbacks[e][n]||(this.callbacks[e][n]=[]),this.callbacks[e][n].push(r),()=>this.removeCallback(e,n,r)}removeCallback(e,n,r){let s=this.callbacks?.[e]?.[n]?.indexOf(r);s!==void 0&&s!==-1&&gP(this.callbacks[e][n],s)}},Fn=class{constructor(e,n){m(this,"context");m(this,"state");m(this,"root");m(this,"currentRefId",0);m(this,"triggerChanges");m(this,"resyncVisited",null);m(this,"resyncDamaged",!1);this.setState(e),this.context=n||new Ks(e.constructor)}setState(e){this.state=e,this.root=new Qf,this.root.addRef(0,e)}decode(e,n={offset:0},r=this.state){let s=this.triggerChanges!==void 0?[]:null,o=this.root,i=e.byteLength,a=r.constructor[Dn];for(this.currentRefId=0;n.offset<i;){if(e[n.offset]==255){n.offset++,r[zu]?.();let u=Pe.number(e,n),l=o.refs.get(u);l?(r=l,a=r.constructor[Dn],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,n,i));continue}if(a(this,e,n,r,s)===fb){console.warn("@colyseus/schema: definition mismatch"),this.skipCurrentStructure(e,n,i);continue}}return r[zu]?.(),this.resyncVisited!==null&&YA(this,s),s!==null&&this.triggerChanges?.(s),o.garbageCollectDeletedRefs(),s}decodeResync(e,n={offset:0}){this.resyncVisited=new Map,this.resyncDamaged=!1;try{return this.decode(e,n)}finally{this.resyncVisited=null}}skipCurrentStructure(e,n,r){this.resyncVisited!==null&&(this.resyncDamaged=!0);let s={offset:n.offset};for(;n.offset<r&&!(e[n.offset]===255&&(s.offset=n.offset+1,this.root.refs.has(Pe.number(e,s))));)n.offset++}getInstanceType(e,n,r){let s;if(e[n.offset]===213){n.offset++;let o=Pe.number(e,n);s=this.context.get(o)}return s||r}createInstanceOfType(e){return e.initializeForDecoder()}removeChildRefs(e,n){let r=typeof e[be]!="string",s=e[Q];e.forEach((o,i)=>{n?.push({ref:e,refId:s,op:N.DELETE,field:i,value:void 0,previousValue:o}),r&&this.root.removeRef(o[Q])})}},yb=zt({min:Y.float64(),max:Y.float64(),bits:Y.uint8(),mode:Y.uint8()},"QuantizedDescriptor"),gb=zt({name:Y.string(),type:Y.string(),referencedType:Y.number(),childPrimitive:Y.string(),quantized:Y.ref(yb).optional()},"ReflectionField"),bb=zt({id:Y.number(),extendsId:Y.number(),fields:Y.array(gb)},"ReflectionType"),zn=zt({types:Y.array(bb),rootType:Y.number()},"Reflection");zn.encode=function(t,e={offset:0}){let n=t.context,r=new zn,s=new Ta(r),o=n.schemas.get(t.state.constructor);o>0&&(r.rootType=o);let i=new Set,a={},c=l=>{if(l.extendsId===void 0||i.has(l.extendsId)){i.add(l.id),r.types.push(l);let d=a[l.id];d!==void 0&&(delete a[l.id],d.forEach(f=>c(f)))}else a[l.extendsId]===void 0&&(a[l.extendsId]=[]),a[l.extendsId].push(l)};n.schemas.forEach((l,d)=>{let f=new bb;f.id=Number(l);let h=Object.getPrototypeOf(d);h!==Xe&&(f.extendsId=n.schemas.get(h));let p=d[Symbol.metadata];if(p!==h[Symbol.metadata]){let y=p[At]??-1;for(let S=0;S<=y;S++){let b=p[S];if(b===void 0)continue;let x=b.name;if(!Object.prototype.hasOwnProperty.call(p,x))continue;let R=new gb;R.name=x;let A;if(typeof b.type=="string")A=b.type;else if(Ys(b.type)){let E=b.type.quantized;A="quantized";let P=new yb;P.min=E.min,P.max=E.max,P.bits=E.bits,P.mode=E.wrap?1:0,R.quantized=P}else{let E;Xe.is(b.type)?(A="ref",E=b.type):(A=Object.keys(b.type)[0],typeof b.type[A]=="string"?R.childPrimitive=b.type[A]:E=b.type[A]),R.referencedType=E?n.getTypeId(E):-1}R.type=A,f.fields.push(R)}}c(f)});for(let l in a)a[l].forEach(d=>r.types.push(d));return s.encodeAll(e).slice(0,e.offset)};zn.decode=function(t,e){let n=new zn;new Fn(n).decode(t,e);let s=new Ks;n.types.forEach(a=>{let c=s.get(a.extendsId)??Xe,u=class extends c{};Ks.register(u),s.add(u,a.id)},{});let o=(a,c,u)=>{c.fields.forEach((l,d)=>{let f=u+d;if(l.quantized!==void 0){let h=l.quantized;De.addField(a,f,l.name,{quantized:rp({min:h.min,max:h.max,bits:h.bits,mode:h.mode===1?"wrap":"clamp"})})}else if(l.referencedType!==void 0){let h=l.type,p=s.get(l.referencedType)??l.childPrimitive;h==="ref"?De.addField(a,f,l.name,p):De.addField(a,f,l.name,{[h]:p})}else De.addField(a,f,l.name,l.type)})};n.types.forEach(a=>{let c=s.get(a.id),u=De.initialize(c),l=[],d=a;do l.push(d),d=n.types.find(h=>h.id===d.extendsId);while(d);let f=0;l.reverse().forEach(h=>{o(u,h,f),f+=h.fields.length})});let i=new(s.get(n.rootType||0));return new Fn(i,s)};zn.makeEncodable=function(t){let e=t[Symbol.metadata];if(!e)return t;let n=e[At];if(n===void 0)return t;for(let r=0;r<=n;r++){let s=e[r];s&&De.defineField(t,e,r,s.name,s.type)}return Object.prototype.hasOwnProperty.call(t,xa)&&delete t[xa],t};Yu=class{constructor(e){m(this,"decoder");m(this,"uniqueRefIds",new Set);m(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,n,r){return this.decoder.root.addCallback(e,n,r)}addCallbackOrWaitCollectionAvailable(e,n,r,s,o=!0){let i=()=>{},a=()=>i(),c=e[n];if(!c||c[Q]===void 0){let u;return u=this.addCallback(e[Q],n,(l,d)=>{l!=null&&(u(),i=this.addCallback(l[Q],r,s))}),i=u,a}else return o=o&&this.isTriggering===!1,r===N.ADD&&o&&c.forEach((u,l)=>{s(u,l)}),this.addCallback(c[Q],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,n,r,s=!0){s=s&&this.isTriggering===!1;let o=e[n];return s&&o!==null&&o!==void 0&&r(o,void 0),this.addCallback(e[Q],n,r)}onChange(...e){if(e.length===2&&typeof e[0]!="string"){let n=e[0],r=e[1];return this.addCallback(n[Q],N.REPLACE,r)}return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],N.REPLACE,e[1]):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],N.REPLACE,e[2])}onAdd(...e){return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],N.ADD,e[1],e[2]!==!1):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],N.ADD,e[2],e[3]!==!1)}onRemove(...e){return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],N.DELETE,e[1]):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],N.DELETE,e[2])}bindTo(e,n,r,s=!0){let o=e.constructor[Symbol.metadata];r||(r=Object.keys(o).filter(a=>!isNaN(Number(a))).map(a=>o[a].name));let i=()=>{for(let a of r){let c=e[a];c!==void 0&&(n[a]=c)}};return s&&i(),this.addCallback(e[Q],N.REPLACE,i)}triggerChanges(e){this.uniqueRefIds.clear(),this.isTriggering=!0;for(let n=0,r=e.length;n<r;n++){let s=e[n],o=s.refId,i=s.ref,a=this.callbacks[o];if(a){if((s.op&N.DELETE)===N.DELETE&&Xe.isSchema(s.previousValue)){let c=s.previousValue[Q],u=this.callbacks[c]?.[N.DELETE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l]()}catch(d){console.error(d)}}if(Xe.isSchema(i)){if(!this.uniqueRefIds.has(o)){let u=a[N.REPLACE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l]()}catch(d){console.error(d)}}let c=a[s.field];if(c)for(let u=c.length-1;u>=0;u--)try{c[u](s.value,s.previousValue)}catch(l){console.error(l)}}else{let c=s.dynamicIndex??s.field;if((s.op&N.DELETE)===N.DELETE){if(s.previousValue!==void 0){let u=a[N.DELETE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](s.previousValue,c)}catch(d){console.error(d)}}if((s.op&N.ADD)===N.ADD){let u=a[N.ADD];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](s.value,c)}catch(d){console.error(d)}}}else if((s.op&N.ADD)===N.ADD&&s.previousValue!==s.value){let u=a[N.ADD];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](s.value,c)}catch(d){console.error(d)}}if(s.value!==s.previousValue){let u=a[N.REPLACE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](c,s.value)}catch(d){console.error(d)}}}this.uniqueRefIds.add(o)}}this.isTriggering=!1}},dp={get(t){if(t instanceof Fn)return new Yu(t);if("decoder"in t.serializer)return new Yu(t.serializer.decoder);throw new Error("Invalid room or decoder")},getLegacy(t){if(t instanceof Fn)return Gu(t);if("decoder"in t.serializer)return Gu(t.serializer.decoder);throw new Error("Invalid room or decoder")},getRawChanges(t,e){return _P(t,e)}};Ir("map",{constructor:fs});Ir("array",{constructor:ds});Ir("set",{constructor:Pa});Ir("collection",{constructor:Aa})});function Ct(){return typeof performance<"u"?performance.now():Date.now()}var Ia=ht(()=>{"use strict"});function ol(t,e){let n=globalThis,r=n.__colyseusDebug;if(!r){let s=[];r=n.__colyseusDebug={__buffer:s,publish(o,i){s.push([o,RP(i)]),s.length>EP&&s.shift()}}}r.publish(t,e)}function il(){if(typeof globalThis>"u")return!1;let t=globalThis.__colyseusDebug;return t!=null&&t.__buffer===void 0}var RP,EP,Da=ht(()=>{"use strict";RP=typeof WeakRef<"u"?t=>new WeakRef(t):t=>({deref:()=>t}),EP=64});function qt(t){return t[Q]}function lr(t){return t.constructor[kP]}function Na(t,e){let n=lr(t)?.[e];return typeof n=="number"?n:-1}function Sb(t){let e=lr(t);if(!e)return[];let n=[];for(let r=0;;r++){let s=e[r];if(!s||typeof s.name!="string")break;typeof s.type=="string"&&n.push(s.name)}return n}function Ba(t){let e=lr(t),n=[],r=[];if(e)for(let s=0;;s++){let o=e[s];if(!o||typeof o.name!="string")break;typeof o.type=="string"&&(n.push(o.name),AP[o.type]===void 0&&r.push(o.name))}return{fields:n,numeric:r}}function TP(t){if(Number.isNaN(t))return 0;if(!Number.isFinite(t))return t>0?Number.MAX_SAFE_INTEGER:-Number.MAX_SAFE_INTEGER;if(t!==(t|0)&&Math.abs(t)<=34028235e31){let e=Math.fround(t);if(Math.abs(Math.abs(e)-Math.abs(t))<1e-4)return e}return t}function xb(t,e){let n=lr(t),r=n?.[e];switch((typeof r=="number"?n[r]:void 0)?.type){case"float32":return Math.fround;case"number":return TP;default:return PP}}function _b(t){if(t.length>vP){let b=t;return x=>{let R={};for(let A=0;A<b.length;A++)R[b[A]]=x[b[A]];return R}}let e=t[0],n=t[1],r=t[2],s=t[3],o=t[4],i=t[5],a=t[6],c=t[7],u=t[8],l=t[9],d=t[10],f=t[11],h=t[12],p=t[13],y=t[14],S=t[15];return b=>{let x={};return e!==void 0&&(x[e]=b[e]),n!==void 0&&(x[n]=b[n]),r!==void 0&&(x[r]=b[r]),s!==void 0&&(x[s]=b[s]),o!==void 0&&(x[o]=b[o]),i!==void 0&&(x[i]=b[i]),a!==void 0&&(x[a]=b[a]),c!==void 0&&(x[c]=b[c]),u!==void 0&&(x[u]=b[u]),l!==void 0&&(x[l]=b[l]),d!==void 0&&(x[d]=b[d]),f!==void 0&&(x[f]=b[f]),h!==void 0&&(x[h]=b[h]),p!==void 0&&(x[p]=b[p]),y!==void 0&&(x[y]=b[y]),S!==void 0&&(x[S]=b[S]),x}}var kP,al,AP,PP,vP,La=ht(()=>{"use strict";Pt();kP=Symbol.metadata??Symbol.for("Symbol.metadata"),al=Mt;AP={string:!0,boolean:!0,bigint64:!0,biguint64:!0};PP=t=>t;vP=16});var pp,MP,CP,Gt,oi,hp=ht(()=>{"use strict";Pt();Pr();Ia();Da();La();pp=9,MP=pp,CP=(t,e)=>(e?2:1)*(pp+4+pp*t),Gt=class Gt{constructor(e,n,r,s){m(this,"data");m(this,"_host");m(this,"_encoder");m(this,"_scratch",new Uint8Array(2048));m(this,"_framed",null);m(this,"_sentCount",0);m(this,"_lastProcessed",0);m(this,"_epoch",0);m(this,"_sendTimes");m(this,"_inputBufferSize");m(this,"_inputBuffer",null);m(this,"_reckonTimes",null);m(this,"_pendingReckon",0);m(this,"_lastStamp",0);m(this,"_stampRing",null);m(this,"_renderDeltaRing",null);m(this,"_ringSlots",0);m(this,"_warnedUnknownKeys",null);m(this,"_stampRender",!1);m(this,"_stampReckon",!1);m(this,"_allowRewind");m(this,"_sendListeners",null);m(this,"_renderDelay",0);m(this,"_renderDelayExplicit",!1);m(this,"_renderDelayProvider");m(this,"_tickRate");m(this,"_patchRate");m(this,"_subSteps",1);this._host=e,this.data=n,this._encoder=r,this._stampRender=s?.stampRender??!1,this._stampReckon=s?.stampReckon??!1,this._allowRewind=s?.allowRewind,this._allowRewind!==void 0&&r.mode==="unreliable"&&!Gt._warnedAllowRewindIgnored&&(Gt._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 o=this._tickRate?1e3/this._tickRate:1e3/60,i=Gt.BUFFER_RTT_BUDGET_MS+(this._patchRate??0);this._inputBufferSize=Math.max(Gt.BUFFER_FLOOR,Math.ceil(i/o*Gt.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){Gt._warnedBufferOverflow||(Gt._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=lr(this.data);if(e)for(let n of Object.keys(this.data))e[n]!==void 0||this._warnedUnknownKeys?.has(n)||((this._warnedUnknownKeys??(this._warnedUnknownKeys=new Set)).add(n),console.warn(`@colyseus/sdk input: "${n}" 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;il()&&this._warnUnknownFields();let n=this._encoder.encode(),r=this._encoder.mode==="reliable",s=this._stampReckon||this._stampRender,o=s&&r&&(this._allowRewind===void 0||this._allowRewind(this.data)),i=s&&!r,a=this._stampReckon&&this._stampRender,u=1+(o?MP+(a?2:0):i?CP(this._encoder.historySize,a):0)+n.length;u>this._scratch.byteLength&&(this._scratch=new Uint8Array(Math.max(u,this._scratch.byteLength*2)),this._framed=null),this._scratch[0]=(r?Ke.ROOM_INPUT_RELIABLE:Ke.ROOM_INPUT_UNRELIABLE)|(o||i?Zo.TIMED:0);let l={offset:1};if(i)this._writeRingStamps(l);else if(o){let{stamp:p,renderDelta:y}=this._sampleStamp();Se.number(this._scratch,p-this._lastStamp,l),this._lastStamp=p,a&&Se.uint16(this._scratch,y,l)}else this._pendingReckon=0;this._scratch.set(n,l.offset);let d=l.offset+n.length;(this._framed===null||this._framed.byteLength!==d)&&(this._framed=this._scratch.subarray(0,d));let f=this._framed,h;return r?(e.send(f),h=++this._sentCount):(e.sendUnreliable(f),h=this._sentCount=this._encoder.seq),this._recordSent(h),h}_writeRingStamps(e){let{stamp:n,renderDelta:r}=this._sampleStamp(),s=this._encoder.historySize,o=this._encoder.seq,i=this._ringSlots=Math.min(this._ringSlots+1,s),a=this._stampRing??(this._stampRing=new Float64Array(s));if(a[o%s]=n,Se.number(this._scratch,i,e),Se.uint32(this._scratch,n,e),this._writeSeriesDeltas(a,o,i,e),this._stampReckon&&this._stampRender){let c=this._renderDeltaRing??(this._renderDeltaRing=new Uint16Array(s));c[o%s]=r,Se.uint16(this._scratch,r,e),this._writeSeriesDeltas(c,o,i,e)}}_writeSeriesDeltas(e,n,r,s){let o=e.length;for(let i=1;i<r;i++)Se.number(this._scratch,e[(n-i+1)%o]-e[(n-i)%o],s)}_sampleStamp(){let e=this._host.clock,n=(e?.lastServerTime?.()??0)>0,r=n?Math.max(0,Math.round(e.serverNow()))>>>0:0,s=n?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]=Ct(),this._stampReckon&&((this._reckonTimes??(this._reckonTimes=new Float64Array(this._inputBufferSize)))[e%this._inputBufferSize]=this._pendingReckon);let n=this._sendListeners;if(n!==null)for(let r=0;r<n.length;r++)n[r](e)}onSend(e){let n=this._sendListeners;return this._sendListeners=n!==null?[...n,e]:[e],()=>{let r=this._sendListeners;if(r===null)return;let s=r.indexOf(e);if(s<0)return;let o=r.slice();o.splice(s,1),this._sendListeners=o.length>0?o:null}}ackInput(e){if(e<=this._lastProcessed)return-1;let n=this._sentCount-e>=this._inputBufferSize;if(this._lastProcessed=e,n)return-1;let r=this._sendTimes[e%this._inputBufferSize];return r>0?Ct()-r:-1}};m(Gt,"BUFFER_FLOOR",64),m(Gt,"BUFFER_RTT_BUDGET_MS",1e3),m(Gt,"BUFFER_HEADROOM",1.5),m(Gt,"_warnedBufferOverflow",!1),m(Gt,"_warnedAllowRewindIgnored",!1);oi=Gt});var ii,dt,cl,ul=ht(()=>{"use strict";Ia();ii=Object.freeze({now:()=>Ct(),serverNow:()=>Ct(),renderNow:()=>Ct(),rtt:()=>0,smoothedRtt:()=>0,jitter:()=>0,lastServerTime:()=>0,patchInterval:()=>0,setPatchInterval:t=>{},sample:(t,e)=>{}}),dt=class dt{constructor(){m(this,"_clockOffset",0);m(this,"_clockHasSample",!1);m(this,"_offsetCount",0);m(this,"_rttFloorT",[]);m(this,"_rttFloorV",[]);m(this,"_rtt",0);m(this,"_smoothedRtt",0);m(this,"_rttHasSample",!1);m(this,"_jitter",0);m(this,"_lastRecvTime",-1);m(this,"_lastServerTime",0);m(this,"_patchInterval",0);m(this,"_renderTau",dt.RENDER_TAU);m(this,"_renderSn",0);m(this,"_renderSnAt",0)}serverNow(){return Ct()+this._clockOffset}renderNow(){let e=this.serverNow();if(this._renderTau<=0)return e;let n=Ct();if(this._renderSn===0)return this._renderSn=e,this._renderSnAt=n,this._renderSn;let r=Math.min(n-this._renderSnAt,100);return r<.5?this._renderSn:(this._renderSnAt=n,this._renderSn+=r,Math.abs(e-this._renderSn)>dt.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 Ct()}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,n){let r=Ct(),s=dt.EMA_ALPHA,o=this._patchInterval;if(this._lastRecvTime>=0&&o>0){let a=r-this._lastRecvTime,c=Math.round(a/o);c>=1&&c<=dt.JITTER_STALL_X&&(this._jitter+=(Math.abs(a-c*o)-this._jitter)*dt.JITTER_GAIN)}this._lastRecvTime=r,this._lastServerTime=e,(n<0||this._smoothedRtt>0&&n>this._smoothedRtt*dt.RTT_OUTLIER_X)&&(n=-1);let i=n>=0?e+n/2-r:e-r;if(!this._clockHasSample)this._clockOffset=i,this._clockHasSample=!0,n>=0&&(this.pushRttFloor(n,r),this._offsetCount=1);else if(n>=0){let a=this.pushRttFloor(n,r),c=this._offsetCount<dt.RTT_GATE_WARMUP;this._offsetCount++,(c||n<=a*dt.RTT_GATE_FACTOR)&&(this._clockOffset=this._clockOffset*(1-s)+i*s)}n>=0&&(this._rtt=n,this._rttHasSample?this._smoothedRtt=this._smoothedRtt*(1-s)+n*s:(this._smoothedRtt=n,this._rttHasSample=!0))}pushRttFloor(e,n){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(n);let o=n-dt.RTT_GATE_WINDOW;for(;r.length>0&&r[0]<o;)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}};m(dt,"EMA_ALPHA",.1),m(dt,"RENDER_TAU",250),m(dt,"RENDER_SNAP",250),m(dt,"RTT_OUTLIER_X",4),m(dt,"JITTER_GAIN",1/16),m(dt,"JITTER_STALL_X",4),m(dt,"RTT_GATE_FACTOR",1.2),m(dt,"RTT_GATE_WINDOW",1e4),m(dt,"RTT_GATE_WARMUP",30);cl=dt});var Yb=cE((GL,Gb)=>{"use strict";Gb.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});function nT(t,e){return{now:()=>t?.serverNow()??performance.now(),ttlMs:typeof e=="function"?()=>e(t?.smoothedRtt()??0):e}}var rc,Tl,Bp=ht(()=>{"use strict";rc=t=>Math.max(t*2,600),Tl=class t{constructor(){m(this,"entries",new Map);m(this,"accepted",new Set);m(this,"cfg",{});m(this,"dead",!1)}static get(e,n={}){let r=new t;return r.configure(nT(e.clock??null,n.ttlMs??rc)),n.onReject&&r.configure({onReject:n.onReject}),r}configure(e){this.cfg={...this.cfg,...e}}predict(e,n){return this.entries.set(e,n??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,n){let r=e??this.cfg.now?.()??performance.now(),s=this.cfg.ttlMs,o=n??(typeof s=="function"?s():s)??1/0;for(let[i,a]of this.entries)this.accepted.has(i)||r-a>o&&(this.entries.delete(i),this.cfg.onReject?.(i))}clear(){this.entries.clear(),this.accepted.clear()}get size(){return this.entries.size}dispose(){this.dead=!0,this.entries.clear(),this.accepted.clear()}}});function f0(){return{ema:0,peak:0}}function Lp(t,e){t.ema+=(e-t.ema)*.1,t.peak=Math.max(e,t.peak*.9)}function p0(t){t.ema=0,t.peak=0}function bi(t,e){let n=e!==void 0&&e>d0?e:d0;return t.ema>=n?"diverging":t.peak>=n?"jitter":"matched"}var d0,vl=ht(()=>{"use strict";d0=.001});function sc(){return il()}function m0(){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 y0(t,e){console.warn(e===""?`@colyseus/sdk predict: two key-less ctx.memo calls ran in one step (input seq ${t}) \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 ${t}) \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 g0(t,e,n,r){let s=Ct();if(s-h0<rT)return;h0=s;let o="",i=-1;for(let c in e){let u=e[c],l=u<0?-u:u;l>i&&(i=l,o=c)}let a=o?e[o]:n;console.warn(`@colyseus/sdk predict: prediction is diverging at input seq ${t} \u2014 rolling drift ${n.toFixed(3)} \u2265 tolerance ${r}; "${o}" 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 h0,rT,Fp=ht(()=>{"use strict";Ia();Da();h0=-1/0,rT=1e3});function b0(){return Up>0}var zp,Up,wi,Ml=ht(()=>{"use strict";vl();Fp();zp=class{constructor(){m(this,"byTick",new Map);m(this,"diagTick",-1);m(this,"diagKeys",new Set);m(this,"warnedKeys",new Set)}run(e,n,r,s){if(n)return this.byTick.get(e)?.get(r);sc()&&(e!==this.diagTick?(this.diagTick=e,this.diagKeys.clear()):this.diagKeys.has(r)&&!this.warnedKeys.has(r)&&(this.warnedKeys.add(r),y0(e,r)),this.diagKeys.add(r));let o=s();if(o!==void 0){let i=this.byTick.get(e);i===void 0&&(i=new Map,this.byTick.set(e,i)),i.set(r,o)}return o}prune(e){for(let n of this.byTick.keys())n<=e&&this.byTick.delete(n)}clear(){this.byTick.clear(),this.diagTick=-1,this.diagKeys.clear()}},Up=0;wi=class{constructor(e){m(this,"lastCorrection",{});m(this,"lastCorrectionMag",0);m(this,"reconcileSeq",0);m(this,"drift",f0());m(this,"error",{});m(this,"prev",{});m(this,"renderedBefore",{});m(this,"lastTick",-1);m(this,"lastAcked",0);m(this,"lastEpoch");m(this,"replayFrom",0);m(this,"predictedSeq",0);m(this,"catching",!1);m(this,"unsubscribeSend",()=>{});m(this,"renderAcc",0);m(this,"tickSeq",0);m(this,"clampedReadTick",-1);m(this,"warnedStaleRead",!1);m(this,"stepCtx");m(this,"ackWatermark",()=>this.input_.lastProcessed);m(this,"memos",new zp);m(this,"smoothMs");m(this,"snapThreshold");m(this,"stepMs");m(this,"input_");m(this,"onReconcile");m(this,"warnTolerance");m(this,"clock");m(this,"dead",!1);m(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 n=e.stepMs??this.input_.stepMs??(e.stepSeconds!==void 0?e.stepSeconds*1e3:void 0);if(n===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=n;let r=e.stepSeconds??this.input_.stepSeconds??n/1e3,s=e.subSteps??this.input_.subSteps??1;this.stepCtx={dt:r,dtMs:n,tick:0,isReplay:!1,reckonTime:0,lagCompActive:!1,subSteps:s,subDt:r/s,subDtMs:n/s,memo:(o,i)=>typeof o=="string"?this.memos.run(this.stepCtx.tick,this.stepCtx.isReplay,o,i):this.memos.run(this.stepCtx.tick,this.stepCtx.isReplay,"",o),predict:(o,i)=>{this.stepCtx.isReplay||o._predictFromSim(this.stepCtx.tick,i,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 n=this.lastTick<0?0:e-this.lastTick;this.lastTick=e,n>0&&this.stepMs>0&&(this.renderAcc+=n);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(),n<=0)return;let o=this.smoothMs<=0?1:1-Math.exp(-n/this.smoothMs);for(let i of this.smoothedFields())this.error[i]-=this.error[i]*o}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,m0()),this.catching=!0,this.stepCtx.isReplay=!1;for(let n=this.predictedSeq+1;n<=e;n++){let r=this.input_.at(n);r!==void 0&&(this.snapshotPrev(),this.runStep(n,r),this.refreshRender(),this.renderAcc-=this.stepMs,this.renderAcc<0?this.renderAcc=0:this.renderAcc>=this.stepMs&&(this.renderAcc%=this.stepMs)),this.predictedSeq=n}this.catching=!1}}runStep(e,n){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(n)}reconcile(e){let n=this.warnTolerance!==void 0||sc();if(this.truthMatchesAt(e)){if(n){for(let u of this.smoothedFields())this.lastCorrection[u]=0;this.lastCorrectionMag=0,Lp(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,Up++;try{for(let u=s+1;u<=this.input_.sentCount;u++){let l=this.input_.at(u);l!==void 0&&this.runStep(u,l)}}finally{Up--}this.catching=!1,this.refreshRender(),this.predictedSeq=this.input_.sentCount;let o=this.smoothMs<=0,i=n||this.snapThreshold>0,a=0;for(let u of this.smoothedFields()){let l=r[u]-this.readCurrent(u);if(this.error[u]=o?0:l,i){let d=l<0?-l:l;d>a&&(a=d)}n&&(this.lastCorrection[u]=l)}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++,n&&(this.lastCorrectionMag=a,c||(Lp(this.drift,a),this.warnTolerance!==void 0&&bi(this.drift,this.warnTolerance)==="diverging"&&g0(e,this.lastCorrection,this.drift.ema,this.warnTolerance))),this.memos.prune(e),this.onReconcile?.(e)}get pendingCount(){return this.input_.pendingCount}reset(){this.reseedState(),p0(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 sT,Vp,Si,Hp=ht(()=>{"use strict";Bp();Ml();sT=0,Vp=10,Si=class{constructor(e,n){m(this,"opts");m(this,"store");m(this,"entries",new Map);m(this,"now");m(this,"cooldownUntil",-1/0);m(this,"warnedReplayPredict",!1);m(this,"dead",!1);m(this,"teardowns",[]);this.opts=e,this.now=()=>n?.serverNow()??performance.now(),this.store=Tl.get({clock:n},{ttlMs:e.ttlMs??rc,onReject:r=>{let s=this.entries.get(r);this.entries.delete(r),s&&this.opts.onReject?.(s.payload)}})}_predictFromSim(e,n,r){this.add(e,n,r)}predict(e){if(b0()){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,n,r){let s=this.opts.uniqueBy!==void 0?this.opts.uniqueBy(n):typeof n=="string"||typeof n=="number"?n:sT;if(this.entries.has(s))return;let o=this.now();if(this.opts.cooldownMs!==void 0){if(o<this.cooldownUntil)return;this.cooldownUntil=o+this.opts.cooldownMs}let i=this.store.predict(s,o);r!==void 0&&i.accept(),this.entries.set(s,{payload:n,seq:e,acked:r}),this.opts.onPredict?.(n)}has(e){return e===void 0?this.entries.size>0:this.entries.has(e)}get pendingCount(){return this.entries.size}confirm(e){let n=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),n++)}return n===0&&this.opts.onUnpredicted?.(e),n}reject(e){let n=0;for(let r of this.settleKeys(e))this.entries.has(r)&&(this.store.reject(r),n++);return n}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??Vp;for(let[n,r]of[...this.entries])r.acked!==void 0&&r.acked()>=r.seq+e&&this.store.reject(n)}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 no,Cl=ht(()=>{"use strict";Bp();no=class{constructor(e={},n=null){m(this,"opts");m(this,"clock");m(this,"correlate");m(this,"ttl");m(this,"byId",new Map);m(this,"byServer",new Map);m(this,"nextId",1);m(this,"lastTickAt");m(this,"detach");m(this,"dead",!1);m(this,"handleAdd",(e,n)=>{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)}});m(this,"handleRemove",(e,n)=>{let r=this.byServer.get(e);r&&(this.byServer.delete(e),this.byId.delete(r.id))});m(this,"readServer",(e,n)=>e[n]);this.opts=e,this.clock=n,this.correlate=e.correlate??"fifo",this.ttl=e.ttl??rc}attach(e){this.detach?.(),this.detach=e(this.handleAdd,this.handleRemove)}spawn(e){let n=this.nextId++,r=this.makeData(),s={id:n,server:void 0,local:e,state:"pending",at:this.now(),leadMs:0,accepted:!1,data:r};return this.byId.set(n,s),{id:n,local:e,data:r,cancel:()=>{let o=this.byId.get(n);o&&o.state==="pending"&&this.byId.delete(n)},accept:()=>{let o=this.byId.get(n);o&&(o.accepted=!0)}}}confirmEntry(e,n){e.server=n,e.state="confirmed";let r=this.opts.spawnTime;r!==void 0&&e.at!==void 0&&(e.leadMs=r(n)-e.at),this.byServer.set(n,e)}takeMatch(e){let n=this.correlate;if(typeof n!="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"&&n(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 n=this.opts.step,r=this.clock!==null?this.clock.serverNow():e;if(n!==void 0&&this.lastTickAt!==void 0){let s=Math.max(0,(r-this.lastTickAt)/1e3);if(s>0)for(let o of this.byId.values())o.state==="pending"&&n(o.local,s)}this.lastTickAt=r}prune(){if(this.byId.size===0)return;let e=this.now(),n=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>n&&(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,n){return e.server!==void 0?this.readServer(e.server,n):e.local[n]}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 w0,ro,Ol=ht(()=>{"use strict";Ml();La();Fp();w0=t=>typeof t=="number"?t:typeof t=="boolean"?t?1:0:NaN,ro=class extends wi{constructor(n,r){super(r);m(this,"local",{});m(this,"fields");m(this,"numericFields",[]);m(this,"step");m(this,"instance");m(this,"wireRound",[]);m(this,"history");m(this,"historySeq");m(this,"historySize");m(this,"historyOn");m(this,"undeclared",null);m(this,"devView",null);this.instance=n;let s=r.fields,o=s??Ba(n).fields;if(s===void 0&&o.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=o,this.step=r.step;let i=this.fields.length>0;for(let a of this.fields){let c=n[a];this.local[a]=c,typeof c=="number"?(this.numericFields.push(a),this.prev[a]=c,this.error[a]=0):typeof c!="boolean"&&(i=!1),this.wireRound.push(xb(n,a))}if(this.historyOn=i,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=Ba(n).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(n){this.noteRenderRead();let r=this.local[n];if(typeof r!="number")return r;let s=r+(this.error[n]??0),o=this.prev[n]??s;return o+(s-o)*this.renderAlpha()}smoothedFields(){return this.numericFields}readCurrent(n){return this.local[n]}applyStep(n){let r=this.undeclared!==null&&sc()?this.stepView():this.local;if(this.step(this.stepCtx,r,n),this.historyOn){let s=this.stepCtx.tick,o=s%this.historySize,i=o*this.fields.length;for(let a=0;a<this.fields.length;a++)this.history[i+a]=w0(this.local[this.fields[a]]);this.historySeq[o]=s}}stepView(){if(this.devView!==null)return this.devView;let n=this.undeclared,r=new Set,s=(o,i)=>{typeof i!="string"||!n.has(i)||r.has(i)||(r.add(i),console.warn(`@colyseus/sdk predict: step ${o} "${i}" \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 "${i}" 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(o,i,a){return s("read",i),Reflect.get(o,i,a)},set(o,i,a,c){return s("wrote",i),Reflect.set(o,i,a,c)}}),this.devView}truthMatchesAt(n){if(!this.historyOn)return!1;let r=n%this.historySize;if(this.historySeq[r]!==n)return!1;let s=r*this.fields.length,o=this.instance;for(let i=0;i<this.fields.length;i++)if(this.wireRound[i](this.history[s+i])!==w0(o[this.fields[i]]))return!1;return!0}snapshotPrev(){for(let n of this.numericFields)this.prev[n]=this.local[n]+this.error[n]}adoptTruth(){let n=this.instance;for(let r of this.fields)this.local[r]=n[r]}reseedState(){let n=this.instance;for(let r of this.fields)this.local[r]=n[r];for(let r of this.numericFields)this.prev[r]=this.local[r],this.error[r]=0;this.historySeq.fill(-1)}}});var so,Il=ht(()=>{"use strict";Ml();La();so=class extends wi{constructor(n){super(n);m(this,"worldHandle");m(this,"bindings",[]);m(this,"curPose",{});m(this,"poseFields",[]);m(this,"customFields",[]);m(this,"fieldsReady",!1);m(this,"poseA",{});m(this,"poseB",{});m(this,"renderPose",{});m(this,"poseDirty",!0);m(this,"step");m(this,"adopt");m(this,"readPose");m(this,"interpolate");let r=n.world;for(let s of Object.keys(r)){let o=r[s];if(o===null||typeof o!="object")continue;if(qt(o)===void 0){if(lr(o)!==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:i,numeric:a}=Ba(o);if(i.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 l of i)c[l]=o[l];r[s]=c;let u=a.map(l=>`${s}.${l}`);this.bindings.push({source:o,mirror:c,fields:i,numeric:a,poseKeys:u})}if(this.bindings.length===0&&n.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=n.world,this.step=n.step,this.adopt=n.adopt,this.readPose=n.pose,this.interpolate=n.interpolate,this.refreshPose();for(let s of this.poseFields)this.prev[s]=this.curPose[s],this.error[s]=0}refreshPose(){let n=this.curPose;for(let r of this.bindings){let{mirror:s,numeric:o,poseKeys:i}=r;for(let a=0;a<o.length;a++)n[i[a]]=s[o[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)n[s]=r[s]}if(!this.fieldsReady){let r=[];for(let s of this.bindings)for(let o of s.poseKeys)r.push(o);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(n=>({source:n.source,fields:n.numeric,poseKeys:n.poseKeys}))}value(n){if(this.noteRenderRead(),this.interpolate)return this.pose()[n];let r=this.curPose[n]+(this.error[n]??0),s=this.prev[n]??r;return s+(r-s)*this.renderAlpha()}pose(){if(this.noteRenderRead(),!this.poseDirty)return this.renderPose;let n=this.renderAlpha(),r=this.poseA,s=this.poseB;for(let o of this.poseFields)r[o]=this.prev[o]??this.curPose[o],s[o]=this.curPose[o]+(this.error[o]??0);if(this.interpolate){let o=this.interpolate(r,s,n);for(let i of this.poseFields)this.renderPose[i]=o[i]}else for(let o of this.poseFields)this.renderPose[o]=r[o]+(s[o]-r[o])*n;return this.poseDirty=!1,this.renderPose}smoothedFields(){return this.poseFields}readCurrent(n){return this.curPose[n]}applyStep(n){this.step(this.stepCtx,this.worldHandle,n)}adoptTruth(){for(let n of this.bindings){let{source:r,mirror:s,fields:o}=n;for(let i=0;i<o.length;i++)s[o[i]]=r[o[i]]}this.adopt?.(this.worldHandle)}refreshRender(){this.refreshPose()}markDirty(){this.poseDirty=!0}snapshotPrev(){for(let n of this.poseFields)this.prev[n]=this.curPose[n]+this.error[n]}reseedState(){this.adoptTruth(),this.refreshPose();for(let n of this.poseFields)this.prev[n]=this.curPose[n],this.error[n]=0}}});function S0(t,e,n,r){let s=[];if(n.field!==void 0){let o=new Map;s.push(t.onAdd(n.collection,(i,a)=>{o.has(i)||o.set(i,t.listen(i,n.field,c=>{c===n.equals&&e.confirm(a)},!1))})),s.push(t.onRemove(n.collection,i=>{o.get(i)?.(),o.delete(i)})),s.push(()=>{for(let i of o.values())i();o.clear()})}else n.event==="remove"?s.push(t.onRemove(n.collection,(o,i)=>{e.confirm(i)})):s.push(t.onAdd(n.collection,o=>{n.mine!==void 0&&o[n.mine]!==r?.()||e.confirm()},!1));return()=>{for(let o of s.splice(0))o?.()}}var x0=ht(()=>{"use strict"});function R0(t){return t===null||typeof t!="object"?!1:Array.isArray(t.fields)}function uT(){E0||(E0=!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 mt,ln,Rn,Lr,Vn,oc,ic,xi,_i,Ri,ac,It,oT,iT,_0,Kt,Ei,oo,io,ki,Ai,Pi,Ti,mr,uc,Bl,Ll,Fl,aT,Dl,$p,bs,Nl,cT,E0,vi,ao,jp=ht(()=>{"use strict";Pt();Hp();Cl();Ol();Il();hp();vl();ul();Da();La();x0();mt=16,ln=0,Rn=1,Lr=2,Vn=3,oc=4,ic=5,xi=6,_i=7,Ri=8,ac=9,It=ac+mt*2,oT=3,iT=1.5,_0=250,Kt=7,Ei=0,oo=1,io=2,ki=3,Ai=4,Pi=5,Ti=6,mr=0,uc=0,Bl=1,Ll=2,Fl=3,aT=4,Dl=5,$p={lerp:uc,extrapolate:Bl,damped:Ll,reckon:Fl,raw:aT},bs={mode:"lerp",delay:100,smoothMs:50,maxExtrapolate:200,tickInterval:0,snap:0,angle:!1},Nl={step:void 0,smoothMs:50,substep:16,snap:0};cT=0,E0=!1;vi=class vi{constructor(e,n){m(this,"callbacks");m(this,"sessionSource");m(this,"slotBuf",new Float64Array(64*It));m(this,"slotCount",0);m(this,"slotDetach",[]);m(this,"slotAngle",[]);m(this,"freeSlots",[]);m(this,"slotByRef",new Map);m(this,"simByRef",new Map);m(this,"boundBySlot",new Map);m(this,"boundProfileIdx",-1);m(this,"renderTime",0);m(this,"defaultMode");m(this,"reckonDefaults");m(this,"clock");m(this,"useRenderClock",!1);m(this,"fixedStepMs");m(this,"stepAcc",0);m(this,"lastFrameNow",-1);m(this,"profileBuf",new Float64Array(8*Kt));m(this,"profileCount",0);m(this,"profileKeys",new Map);m(this,"profileLabels",[]);m(this,"profileComputers",[]);m(this,"trackListeners",[]);m(this,"name");m(this,"disposeListeners",[]);m(this,"driven",[]);m(this,"computeDamped",e=>{let n=this.slotBuf,r=e*It,s=this.profileBuf,o=(n[r+Vn]|0)*Kt,i=this.renderTime,a=n[r+ln],c=n[r+Lr],u=i-c;n[r+Lr]=i;let l=n[r+Rn];if(u>0){let d=s[o+io],f=d>0?1-Math.exp(-u/d):1;l+=(a-l)*f,n[r+Rn]=l}return l});m(this,"computeLerp",e=>{let n=this.computeLerpRaw(e),r=this.slotBuf,s=e*It,o=this.profileBuf[(r[s+Vn]|0)*Kt+Ti],i=this.renderTime;if(o<=0)return r[s+Rn]=n,r[s+Ri]=n,r[s+Lr]=i,n;let a=r[s+Lr],c=i-a;if(c<=0)return r[s+Rn];let u=r[s+Ri],l=r[s+Rn],d=c/o,f=(n-u)/d,h=n-f+(l-u+f)*Math.exp(-d);return r[s+Rn]=h,r[s+Ri]=n,r[s+Lr]=i,h});m(this,"computeExtrapolate",e=>{let n=this.slotBuf,r=e*It,s=this.profileBuf,o=(n[r+Vn]|0)*Kt,i=this.renderTime,a=n[r+_i]|0;if(a===0)return n[r+ln];let c=n[r+xi]|0,u=r+ac,l=(c-a+mt)%mt,d=(l+a-1)%mt,f=u+d*2,h=n[f],p=n[f+1],y;if(a===1)y=p;else{let A=a>=3?2:1,E=(l+a-1-A+mt)%mt,P=u+E*2,k=n[P],M=n[P+1],B=h-k;if(B<=0)y=p;else{let K=(p-M)/B,j=s[o+ki],L=i-h;L<0?L=0:L>j&&(L=j),y=p+K*L}}let S=n[r+Lr];n[r+Lr]=i;let b=s[o+io];if(b<=0)return n[r+Rn]=y,y;let x=i-S,R=n[r+Rn];if(x>0){let A=1-Math.exp(-x/b);R+=(y-R)*A,n[r+Rn]=R}return R});m(this,"computeReckon",e=>{let n=this.slotBuf,r=e*It,s=n[r+oc],o=n[r+ic]|0,i=this.simByRef.get(s);if(i!==void 0){let a=o<i.posOf.length?i.posOf[o]:-1;if(a>=0)return this.applySimulation(i,a)}return n[r+ln]});m(this,"computeRaw",e=>this.slotBuf[e*It+ln]);m(this,"computeBound",e=>{let n=this.boundBySlot.get(e);return n!==void 0?n.ctrl.value(n.key):this.slotBuf[e*It+ln]});this.callbacks=dp.get(e),this.sessionSource=e;let{clock:r,...s}=n;this.defaultMode=s.mode??"lerp";let o=this.defaultMode!=="reckon"&&this.defaultMode!=="raw",i=o?(()=>{let u=s;return{mode:u.mode??bs.mode,delay:u.delay??bs.delay,smoothMs:u.smoothMs??bs.smoothMs,maxExtrapolate:u.maxExtrapolate??bs.maxExtrapolate,tickInterval:u.tickInterval??bs.tickInterval,snap:u.snap??bs.snap,angle:u.angle??bs.angle}})():{...bs},a=o?s.smoothMs??0:0;if(this.allocProfile(this.defaultMode,i.delay,i.smoothMs,a,i.maxExtrapolate,i.tickInterval,i.snap,!1)!==mr)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??Nl.smoothMs,substep:u.substep??Nl.substep,snap:u.snap??Nl.snap}}else this.reckonDefaults={...Nl};this.clock=r??e.clock??void 0,this.useRenderClock=s.renderPresent!==!1,this.clock===ii&&uT(),this.name=s.name??`predict#${++cT}`,ol("predict",this.makeCoreHandle())}static get(e,n={}){return new vi(e,n)}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,n)=>this.setProfile(e,n),onTrack:e=>(this.trackListeners.push(e),()=>{let n=this.trackListeners.indexOf(e);n>=0&&this.trackListeners.splice(n,1)}),onDispose:e=>(this.disposeListeners.push(e),()=>{let n=this.disposeListeners.indexOf(e);n>=0&&this.disposeListeners.splice(n,1)})}}snapshotReconcilers(){let e=[],n=0;for(let r of this.driven){let s=r;if(!s.drift)continue;let o=s.warnTolerance;e.push({label:`reconciler #${n++}`,status:bi(s.drift,o),severity:o!==void 0&&o>0?s.drift.ema/o: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,n=mr*Kt,r=e[n+Ei]|0;return{mode:r===uc?"lerp":r===Bl?"extrapolate":r===Ll?"damped":r===Fl?"reckon":"raw",delay:e[n+oo],smoothMs:e[n+io],lerpSmoothMs:e[n+Ti],maxExtrapolate:e[n+ki],tickInterval:e[n+Ai],snap:e[n+Pi]}}allocProfile(e,n,r,s,o,i,a,c,u){let l=typeof e=="number"?e:$p[e],d="";if(c){d=`${u??""}|${l}|${n}|${r}|${s}|${o}|${i}|${a}`;let y=this.profileKeys.get(d);if(y!==void 0)return y}let f=this.profileCount++;if((f+1)*Kt>this.profileBuf.length){let y=new Float64Array(this.profileBuf.length*2);y.set(this.profileBuf),this.profileBuf=y}let p=f*Kt;return this.profileBuf[p+Ei]=l,this.profileBuf[p+oo]=n,this.profileBuf[p+io]=r,this.profileBuf[p+Ti]=s,this.profileBuf[p+ki]=o,this.profileBuf[p+Ai]=i,this.profileBuf[p+Pi]=a,this.profileLabels[f]=u,this.profileComputers[f]=this.computerForMode(l),c&&this.profileKeys.set(d,f),f}computerForMode(e){return e===uc?this.computeLerp:e===Bl?this.computeExtrapolate:e===Ll?this.computeDamped:e===Fl?this.computeReckon:e===Dl?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 mr;let n=this.readSmoothingDefaults(),r=e.mode??n.mode,s=e.delay??n.delay,o=e.smoothMs??n.smoothMs,i=e.smoothMs??n.lerpSmoothMs,a=e.maxExtrapolate??n.maxExtrapolate,c=e.tickInterval??n.tickInterval,u=e.snap??n.snap;return r===n.mode&&s===n.delay&&o===n.smoothMs&&i===n.lerpSmoothMs&&a===n.maxExtrapolate&&c===n.tickInterval&&u===n.snap?mr:this.allocProfile(r,s,o,i,a,c,u,!0)}groupProfile(e,n){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,n)}setDefaults(e){let n=e.mode;if(n!==void 0){this.defaultMode=n;let a=mr*Kt,c=$p[n];this.profileBuf[a+Ei]=c,this.profileComputers[mr]=this.computerForMode(c)}let r=e,s=mr*Kt,o=this.profileBuf;r.delay!==void 0&&(o[s+oo]=r.delay),r.smoothMs!==void 0&&(o[s+io]=r.smoothMs,o[s+Ti]=r.smoothMs),r.maxExtrapolate!==void 0&&(o[s+ki]=r.maxExtrapolate),r.tickInterval!==void 0&&(o[s+Ai]=r.tickInterval),r.snap!==void 0&&(o[s+Pi]=r.snap,this.reckonDefaults.snap=r.snap);let i=e;i.step!==void 0&&(this.reckonDefaults.step=i.step),i.smoothMs!==void 0&&(this.reckonDefaults.smoothMs=i.smoothMs),i.substep!==void 0&&(this.reckonDefaults.substep=i.substep)}snapshotProfiles(){let e=[];for(let n=0;n<this.profileCount;n++){let r=n*Kt,s=this.profileBuf[r+Ei]|0;if(s===Dl)continue;let o=s===uc?"lerp":s===Bl?"extrapolate":s===Ll?"damped":s===Fl?"reckon":"raw";e.push({id:n,isDefault:n===mr,label:this.profileLabels[n],mode:o,delay:this.profileBuf[r+oo],smoothMs:this.profileBuf[r+(s===uc?Ti:io)],maxExtrapolate:this.profileBuf[r+ki],tickInterval:this.profileBuf[r+Ai],snap:this.profileBuf[r+Pi]})}return e}setProfile(e,n){if(e<0||e>=this.profileCount)return;let r=e*Kt,s=this.profileBuf;if((s[r+Ei]|0)!==Dl){if(n.mode!==void 0){let o=$p[n.mode];s[r+Ei]=o,this.profileComputers[e]=this.computerForMode(o),e===mr&&(this.defaultMode=n.mode)}n.delay!==void 0&&(s[r+oo]=n.delay),n.smoothMs!==void 0&&(s[r+io]=n.smoothMs,s[r+Ti]=n.smoothMs),n.maxExtrapolate!==void 0&&(s[r+ki]=n.maxExtrapolate),n.tickInterval!==void 0&&(s[r+Ai]=n.tickInterval),n.snap!==void 0&&(s[r+Pi]=n.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,n,r={}){return this.trackWithProfile(e,n,this.profileFromOpts(r),r.angle??!1)}trackWithProfile(e,n,r,s=!1){let o=qt(e);if(o===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 i=Na(e,n),a=e[n]??0,c,u=this.slotByRef.get(o)?.get(n);u!==void 0&&(c=this.boundBySlot.get(u),c!==void 0?this.freeStash(c):this.untrackSlot(o,n));let l=this.allocSlot(),d=this.slotBuf,f=l*It;if(d[f+ln]=a,d[f+Rn]=a,d[f+Lr]=performance.now(),d[f+Ri]=a,d[f+Vn]=r,d[f+oc]=o,d[f+ic]=i,d[f+xi]=0,d[f+_i]=0,this.slotAngle[l]=s,c!==void 0)c.stash=l;else{let p=this.slotByRef.get(o);p===void 0&&(p=new Map,this.slotByRef.set(o,p)),p.set(n,l)}for(let p=0;p<this.trackListeners.length;p++)this.trackListeners[p](r,n);let h=this.callbacks.listen(e,n,p=>{let y=this.clock&&this.clock.lastServerTime()>0?this.clock.lastServerTime():performance.now(),S=this.slotBuf,b=l*It;if(s){let j=S[b+ln];p=j+Math.atan2(Math.sin(p-j),Math.cos(p-j))}let x=(S[b+Vn]|0)*Kt,R=this.profileBuf[x+Ai],A=S[b+xi]|0,E=S[b+_i]|0,P=this.profileBuf[x+Pi];P>0&&E>0&&Math.abs(p-S[b+ln])>P&&(A=0,E=0,S[b+Rn]=p,S[b+Ri]=p);let k=E===0?Number.NEGATIVE_INFINITY:S[b+ac+(A===0?mt-1:A-1)*2],M=y;if(R>0&&isFinite(k)){let j=y-k,L=j>0?Math.max(1,Math.round(j/R)):1;M=k+L*R;let se=y+R;M>se&&(M=se)}S[b+ln]=p;let B=b+ac;if(E>=2&&isFinite(k)){let j=A===0?mt-1:A-1,L=j===0?mt-1:j-1,se=k-S[B+L*2],v=this.clock?.patchInterval?this.clock.patchInterval():0,$=v>0?v:se,G=v>0?iT*v:oT*se;if($>0&&M-k>G){let W=$<_0?$:_0,q=B+A*2;S[q]=M-W,S[q+1]=S[B+j*2+1],A=A+1>=mt?0:A+1,E<mt&&E++}}let K=B+A*2;S[K]=M,S[K+1]=p,S[b+xi]=A+1>=mt?0:A+1,E<mt&&(S[b+_i]=E+1)},!0);return this.slotDetach[l]=h,()=>this.untrackSlot(o,n)}untrack(e,n){let r=qt(e);r!==void 0&&this.untrackSlot(r,n)}untrackSlot(e,n){let r=this.slotByRef.get(e),s=r?.get(n);if(s===void 0)return;let o=this.boundBySlot.get(s);if(o!==void 0){this.freeStash(o);return}this.slotDetach[s]?.(),this.slotDetach[s]=void 0,this.freeSlots.push(s),r.delete(n),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)*It>this.slotBuf.length){let r=new Float64Array(this.slotBuf.length*2);r.set(this.slotBuf),this.slotBuf=r}return e}registerBound(e,n,r,s,o){let i=qt(n),a=this.slotByRef.get(i);a===void 0&&(a=new Map,this.slotByRef.set(i,a));let c=[];for(let u=0;u<r.length;u++){let l=r[u],d=a.get(l),f=-1;if(d!==void 0){let b=this.boundBySlot.get(d);b!==void 0?(console.warn(`@colyseus/sdk Predict: "${l}" (refId ${i}) is already bound to a controller \u2014 the newer registration wins.`),f=b.stash,this.boundBySlot.delete(d),this.freeSlots.push(d)):f=d}let h=this.allocSlot(),p=this.slotBuf,y=h*It,S=n[l]??0;p[y+ln]=S,p[y+Rn]=S,p[y+Lr]=0,p[y+Ri]=S,p[y+Vn]=o,p[y+oc]=i,p[y+ic]=Na(n,l),p[y+xi]=0,p[y+_i]=0,this.slotAngle[h]=!1,this.boundBySlot.set(h,{ctrl:e,key:s[u],stash:f}),a.set(l,h),c.push(h);for(let b=0;b<this.trackListeners.length;b++)this.trackListeners[b](o,l)}return()=>{for(let u=0;u<c.length;u++){let l=c[u],d=this.boundBySlot.get(l);if(d===void 0||d.ctrl!==e)continue;this.boundBySlot.delete(l),this.freeSlots.push(l);let f=this.slotByRef.get(i);f?.get(r[u])===l&&(d.stash>=0?f.set(r[u],d.stash):(f.delete(r[u]),f.size===0&&this.slotByRef.delete(i)))}}}installBoundOverlay(e){let n=[];for(let r of e.boundRegistrations)r.fields.length===0||qt(r.source)===void 0||(this.boundProfileIdx<0&&(this.boundProfileIdx=this.allocProfile(Dl,0,0,0,0,0,0,!1,"bound")),n.push(this.registerBound(e,r.source,r.fields,r.poseKeys,this.boundProfileIdx)));n.length>0&&e.onDisposed(()=>{for(let r of n)r()})}trackStepped(e,n){let r=n.substep??16,s=n.fields,o=s.map(p=>Na(e,p)),i=n.step,a=this.clock,c=this.presentFn(),u=n.forwardMs??(c?()=>{let p=a.lastServerTime();return p>0?Math.max(0,c()-p):0}:()=>0),l=n.elapsedMs??c??(()=>performance.now()),d=e[al],f=n.snapshot===void 0&&Array.isArray(d)&&o.every(p=>p>=0&&p<d.length),h;if(f){let p=new e.constructor,y=p[al];h=(S,b,x,R)=>{let A=S[al];for(let k=0;k<A.length;k++)y[k]=A[k];let E=b,P=R-b;for(;E>0;){let k=E<r?E:r;P+=k,i(p,k/1e3,P),E-=k}for(let k=0;k<o.length;k++)x[k]=y[o[k]]}}else{let p=Sb(e),y=n.snapshot??(p.length>0?_b(p):b=>({...b})),S=[...s];h=(b,x,R,A)=>{let E=y(b),P=x,k=A-x;for(;P>0;){let M=P<r?P:r;k+=M,i(E,M/1e3,k),P-=M}for(let M=0;M<S.length;M++)R[M]=E[S[M]]}}return this.trackSimulated(e,{fields:s,forwardMs:u,elapsedMs:l,smoothMs:n.smoothMs,snap:n.snap,advance:h})}trackSimulated(e,n){let r=qt(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=n.fields,o=s.length,i=s.map(h=>Na(e,h)),a=0;for(let h of i)h>a&&(a=h);let c=new Int8Array(a+1).fill(-1);for(let h=0;h<o;h++)i[h]>=0&&(c[i[h]]=h);let u=new Float64Array(o);for(let h=0;h<o;h++)u[h]=e[s[h]]??0;let l=this.presentFn(),d=n.elapsedMs??l??(()=>performance.now()),f={instance:e,fieldIds:i,posOf:c,forwardMs:n.forwardMs,elapsedMs:d,advance:n.advance,smoothMs:n.smoothMs??50,snap:n.snap??0,smoothed:u,out:new Float64Array(o),valueOut:new Float64Array(o),offset:new Float64Array(o),outPrev:new Float64Array(o),frameVel:new Float64Array(o),lastBaseT:NaN,lastApplyTime:-1/0};return this.simByRef.set(r,f),()=>this.untrackSimulated(r)}untrackSimulated(e){this.simByRef.delete(e)}attach(e,n){let r=this.makeGroup("(attach)",n);return this.attachWithPlan(e,this.planFor(r,e))}makeGroup(e,n){return{label:e,config:n,basePlan:this.buildGroupPlan(n,e),planByCtor:new Map}}planFor(e,n){let r=n.constructor,s=e.planByCtor.get(r);return s===void 0&&(s=this.resolveCtorPlan(e,n),e.planByCtor.set(r,s)),s}resolveCtorPlan(e,n){let r=lr(n),s=n.constructor?.name||"?",o=e.config;if(!R0(o)){if(r===void 0)return e.basePlan;let c=Object.keys(o).filter(l=>o[l]!==void 0);if(c.every(l=>typeof r[l]=="number"))return e.basePlan;let u={};for(let l of c)typeof r[l]=="number"&&(u[l]=o[l]);return this.buildGroupPlan(u,`${e.label}:${s}`)}let i=o,a=i.fields;if(r!==void 0){let c=a.filter(u=>typeof r[u]=="number");c.length!==a.length&&(a=c)}return a===i.fields?e.basePlan:this.buildGroupPlan({...i,fields:a},`${e.label}:${s}`)}buildGroupPlan(e,n){let r=[];if(R0(e)){let o=e;if(!Array.isArray(o.fields))throw new Error("Predict.attach(): `fields` must be a numeric-key array.");let i=o.mode??this.defaultMode,a=o.step??this.reckonDefaults.step,c=i==="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:i,snap:o.snap,smoothMs:o.smoothMs},n);for(let l of o.fields)r.push({field:l,profileIdx:u,angle:o.angle});return{label:n,isReckon:c,reckonFields:c?o.fields:void 0,reckonStep:c?a:void 0,reckonSmoothMs:o.smoothMs??this.reckonDefaults.smoothMs,reckonSubstep:o.substep??this.reckonDefaults.substep,reckonSnap:o.snap??this.reckonDefaults.snap,reckonSnapshot:o.snapshot,fieldProfiles:r}}let s=e;for(let o of Object.keys(s)){let i=s[o];if(i===void 0)continue;let a=typeof i=="string"?{mode:i}:i;r.push({field:o,profileIdx:this.groupProfile(a,n),angle:a.angle})}return{label:n,isReckon:!1,fieldProfiles:r}}attachToGroup(e,n,r){let s=[];n.isReckon&&s.push(this.trackStepped(e,{fields:n.reckonFields,step:n.reckonStep,smoothMs:n.reckonSmoothMs,substep:n.reckonSubstep,snap:n.reckonSnap,snapshot:n.reckonSnapshot,forwardMs:r}));for(let{field:o,profileIdx:i,angle:a}of n.fieldProfiles)s.push(this.trackWithProfile(e,o,i,!!a));return()=>{for(let o of s)o()}}attachWithPlan(e,n){let r=qt(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,n),()=>this.detachByRef(r)}detach(e){let n=qt(e);n!==void 0&&this.detachByRef(n)}detachByRef(e){let n=this.slotByRef.get(e);if(n){for(let r of[...n.keys()]){let s=n.get(r);if(s===void 0)continue;let o=this.boundBySlot.get(s);o!==void 0?(this.freeStash(o),this.boundBySlot.delete(s),this.freeSlots.push(s),n.delete(r)):this.untrackSlot(e,r)}n.size===0&&this.slotByRef.delete(e)}this.simByRef.delete(e)}attachAll(...e){let n=typeof e[0]=="string",r=n?void 0:e[0],s=n?e[0]:e[1],o=n?e[1]:e[2],i=this.makeGroup(s,o),a=new Set,c=f=>{this.attachWithPlan(f,this.planFor(i,f)),a.add(f)},u=f=>{a.delete(f),this.detach(f)},l=n?this.callbacks.onAdd(s,c):this.callbacks.onAdd(r,s,c),d=n?this.callbacks.onRemove(s,u):this.callbacks.onRemove(r,s,u);return()=>{l?.(),d?.();for(let f of a)this.detach(f);a.clear()}}tick(e=performance.now()){this.renderTime=e;let n=0,r=this.fixedStepMs;if(r!==void 0&&r>0){let i=this.lastFrameNow<0?0:e-this.lastFrameNow;this.stepAcc+=i,n=Math.floor(this.stepAcc/r),n>vi.MAX_STEPS_PER_FRAME?(this.stepAcc=0,n=vi.MAX_STEPS_PER_FRAME):this.stepAcc-=n*r}this.lastFrameNow=e;let s=this.driven,o=0;for(let i=0;i<s.length;i++){let a=s[i];a.dead||(a.tick?.(e),a.prune?.(),o!==i&&(s[o]=a),o++)}return o!==s.length&&(s.length=o),n}defineEvent(e){let{confirmOn:n,...r}=e,s=new Si(r,this.clock??null);if(n!==void 0){if(n.mine!==void 0&&typeof this.sessionSource.sessionId!="string")throw new Error(`Predict.defineEvent: confirmOn.mine ("${n.mine}") requires a Predict built from a Room (it compares against room.sessionId); confirm manually instead.`);s._addTeardown(S0(this.callbacks,s,n,()=>this.sessionSource.sessionId))}return this.driven.push(s),s}spawns(e,n={}){let r=new no(n,this.clock??null),s=n.fields,o=n.step,i=s!==void 0&&o!==void 0?this.makeGroup(String(e),{mode:"reckon",fields:s,step:o,smoothMs:n.smoothMs??0,substep:n.substep}):void 0,a=i!==void 0?new Map:void 0,c=this.clock;return r.attach((u,l)=>{let d=this.callbacks.onAdd(e,(h,p)=>{if(u(h,p),i===void 0||a.has(h))return;let y=r.entryFor(h)?.leadMs??0,S=c?()=>{let b=c.lastServerTime(),x=b>0?Math.max(0,c.serverNow()-b):0;return Math.max(0,x+y)}:()=>Math.max(0,y);a.set(h,this.attachToGroup(h,this.planFor(i,h),S))}),f=this.callbacks.onRemove(e,(h,p)=>{a?.get(h)?.(),a?.delete(h),l(h,p)});return()=>{if(d?.(),f?.(),a!==void 0){for(let h of a.values())h();a.clear()}}}),i!==void 0&&r.bindReader((u,l)=>this.value(u,l)),this.driven.push(r),r}canonicalDelay(){return this.profileBuf[mr*Kt+oo]}bindInputRenderDelay(e){e instanceof oi&&e.bindRenderDelay(()=>this.canonicalDelay())}reconciler(e,n){let r=new ro(e,{...n,clock:n.clock??this.clock});return this.adoptFixedStep(r.stepMs),this.bindInputRenderDelay(n.input),this.installBoundOverlay(r),this.driven.push(r),r}sim(e){let n=new so({...e,clock:e.clock??this.clock});return this.adoptFixedStep(n.stepMs),this.bindInputRenderDelay(e.input),this.installBoundOverlay(n),this.driven.push(n),n}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,n){let r=qt(e),s=r===void 0?void 0:this.slotByRef.get(r)?.get(n);if(s===void 0)return e[n];let o=this.slotBuf[s*It+Vn]|0;return this.profileComputers[o](s)}valueAt(e,n,r){let s=qt(e),o=s===void 0?void 0:this.slotByRef.get(s)?.get(n);if(o===void 0)return e[n];let i=o*It,a=this.slotBuf[i+Vn]|0;if(this.profileComputers[a]!==this.computeReckon)return this.profileComputers[a](o);let c=this.simByRef.get(this.slotBuf[i+oc]);if(c!==void 0){let u=this.slotBuf[i+ic]|0,l=u<c.posOf.length?c.posOf[u]:-1;if(l>=0){let d=this.clock?.lastServerTime?.()??NaN,f=Number.isNaN(d)?0:Math.max(0,r-d);return c.advance(c.instance,f,c.valueOut,r),c.valueOut[l]}}return this.slotBuf[i+ln]}read(e,n,r){let s=r??{},o=qt(e),i=o===void 0?void 0:this.slotByRef.get(o);for(let a=0;a<n.length;a++){let c=n[a],u=i?.get(c);s[c]=u===void 0?e[c]:this.profileComputers[this.slotBuf[u*It+Vn]|0](u)}return s}readAt(e,n,r,s){let o=s??{},i=qt(e),a=i===void 0?void 0:this.slotByRef.get(i),c,u=!1;for(let l=0;l<n.length;l++){let d=n[l],f=a?.get(d);if(f===void 0){o[d]=e[d];continue}let h=f*It,p=this.slotBuf[h+Vn]|0;if(this.profileComputers[p]!==this.computeReckon){o[d]=this.profileComputers[p](f);continue}if(!u&&(u=!0,c=this.simByRef.get(this.slotBuf[h+oc]),c!==void 0)){let y=this.clock?.lastServerTime?.()??NaN,S=Number.isNaN(y)?0:Math.max(0,r-y);c.advance(c.instance,S,c.valueOut,r)}if(c!==void 0){let y=this.slotBuf[h+ic]|0,S=y<c.posOf.length?c.posOf[y]:-1;if(S>=0){o[d]=c.valueOut[S];continue}}o[d]=this.slotBuf[h+ln]}return o}computeLerpRaw(e){let n=this.slotBuf,r=e*It,s=this.profileBuf,o=(n[r+Vn]|0)*Kt,i=this.renderTime,a=n[r+_i]|0;if(a===0)return n[r+ln];let c=n[r+xi]|0,u=r+ac,l=(c-a+mt)%mt,d=(l+a-1)%mt,f=u+d*2;if(a===1)return n[f+1];let h=s[o+oo],p=this.clock&&this.clock.lastServerTime()>0?this.clock.serverNow()-h-this.clock.smoothedRtt()/2:i-h,y=u+l*2;if(p<=n[y])return n[y+1];if(p>=n[f])return n[f+1];let S=a-2,b=(l+S)%mt;for(;S>0&&!(n[u+b*2]<=p);)S--,b=b===0?mt-1:b-1;let x=u+b*2,R=b+1>=mt?0:b+1,A=u+R*2,E=n[x],k=n[A]-E;if(k<=0)return n[A+1];let M=(p-E)/k,B=n[x+1],K=n[A+1];return B+(K-B)*M}applySimulation(e,n){let r=this.renderTime;if(e.lastApplyTime!==r){let s=e.out,o=e.smoothed,i=e.offset,a=o.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 d=0;d<a;d++)i[d]=0,o[d]=s[d];else if(Number.isNaN(c)){let d=Math.max(0,Math.min(r-e.lastApplyTime,100)),f=1-Math.exp(-d/e.smoothMs);for(let h=0;h<a;h++)o[h]+=(s[h]-o[h])*f}else{let d=Math.max(0,Math.min(r-e.lastApplyTime,100));if(c!==e.lastBaseT&&!Number.isNaN(e.lastBaseT)){let h=e.snap,p=e.frameVel;for(let y=0;y<a;y++){let S=o[y]+p[y]*d-s[y];i[y]=h>0&&Math.abs(S)>h?0:S}}else if(d>0){let h=e.outPrev,p=e.frameVel;for(let y=0;y<a;y++)p[y]=(s[y]-h[y])/d}let f=Math.exp(-d/e.smoothMs);for(let h=0;h<a;h++)i[h]*=f,o[h]=s[h]+i[h]}let l=e.outPrev;for(let d=0;d<a;d++)l[d]=s[d];e.lastBaseT=c,e.lastApplyTime=r}return e.smoothed[n]}};m(vi,"MAX_STEPS_PER_FRAME",5);ao=vi});var Y0={};of(Y0,{DEFAULT_GRACE_TICKS:()=>Vp,Predict:()=>ao,PredictedEventChannel:()=>Si,PredictedSpawns:()=>no,Reconciler:()=>ro,SimReconciler:()=>so,classifyDrift:()=>bi});var Zp=ht(()=>{"use strict";jp();Ol();vl();Il();Hp();Cl()});var la="genex-native";var uu="genex_native";var lu="genex_protocol",du="genex_attempt",fu="genex_nonce",cf="genex_caps";var Uo="genex_";var uf="genex_r";var lf="entryRef",df="genex_hash",ff="genex_referrer",pf="genex_ref";var pu="__genexNative";var dE=/^[0-9a-f]{32}$/,fE=/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;function kr(t){return typeof t=="string"&&dE.test(t)}function hf(t){return typeof t=="string"&&fE.test(t)}var Vo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",pE=(()=>{let t=new Array(128).fill(-1);for(let e=0;e<Vo.length;e++)t[Vo.charCodeAt(e)]=e;return t})();function Vm(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(r>=55296&&r<=56319){let s=n+1<t.length?t.charCodeAt(n+1):0;s>=56320&&s<=57343?(r=65536+(r-55296<<10)+(s-56320),n++):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 hE(t){let e="";for(let n=0;n<t.length;){let r=t[n],s,o;if(r<128)s=r,o=1;else if((r&224)===192)s=r&31,o=2;else if((r&240)===224)s=r&15,o=3;else if((r&248)===240)s=r&7,o=4;else return null;if(n+o>t.length)return null;for(let i=1;i<o;i++){let a=t[n+i];if((a&192)!==128)return null;s=s<<6|a&63}if(o===2&&s<128||o===3&&(s<2048||s>=55296&&s<=57343)||o===4&&(s<65536||s>1114111))return null;if(s>65535){let i=s-65536;e+=String.fromCharCode(55296+(i>>10),56320+(i&1023))}else e+=String.fromCharCode(s);n+=o}return e}function mf(t){return Vm(t).length}function yf(t){let e=Vm(JSON.stringify(t)),n="";for(let r=0;r<e.length;r+=3){let s=e[r],o=e[r+1],i=e[r+2];if(n+=Vo[s>>2],n+=Vo[(s&3)<<4|(o??0)>>4],o===void 0||(n+=Vo[(o&15)<<2|(i??0)>>6],i===void 0))break;n+=Vo[i&63]}return n}function gf(t){if(t.length%4===1)return;let e=[],n=0,r=0;for(let o=0;o<t.length;o++){let i=t.charCodeAt(o),a=i<128?pE[i]:-1;if(a<0)return;n=n<<6|a,r+=6,r>=8&&(r-=8,e.push(n>>r&255))}if(r>0&&(n&(1<<r)-1)!==0)return;let s=hE(e);if(s!==null)try{return JSON.parse(s)}catch{return}}var Hm=2048,$m=32;var yE=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;function gE(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function hu(t,e){if(Object.keys(t).length!==e.length)return!1;for(let r of e)if(!Object.prototype.hasOwnProperty.call(t,r))return!1;return!0}var mu=["channel","v","type","slug","attemptId","nonce"];function bE(t){return t.channel===la&&t.v===1&&hf(t.slug)&&kr(t.attemptId)&&kr(t.nonce)}function bf(t){if(!(!gE(t)||!bE(t)))switch(t.type){case"ticket":return!hu(t,[...mu,"ticket","expiresAt"])||typeof t.ticket!="string"||t.ticket.length===0||t.ticket.length>Hm||typeof t.expiresAt!="string"||t.expiresAt.length>$m||!yE.test(t.expiresAt)?void 0:t;case"guest":case"cancel":return hu(t,mu)?t:void 0;case"foreground":return!hu(t,[...mu,"active"])||typeof t.active!="boolean"?void 0:t;case"network":return!hu(t,[...mu,"online"])||typeof t.online!="boolean"?void 0:t;default:return}}function SE(t,e){if(typeof t!="string"||t.length===0)return{ok:!1,reason:"undecodable"};if(mf(t)>4096)return{ok:!1,reason:"too-large"};let n=gf(t);if(n===void 0)return{ok:!1,reason:"undecodable"};let r=e(n);return r===void 0?{ok:!1,reason:"invalid"}:{ok:!0,message:r}}function Sf(t){return SE(t,bf)}function xf(t){let e=yf(t);if(!(e.length>4096))return e}function yu(t,e){let n=t.charAt(0)==="?"?t.slice(1):t;if(n.length===0)return null;for(let r of n.split("&")){let s=r.indexOf("=");if(s!==-1&&r.slice(0,s)===e)return r.slice(s+1)}return null}function gu(t){return yu(t,uu)==="1"}function Rf(t){if(!gu(t))return null;let e=yu(t,du),n=yu(t,fu),r=Number(yu(t,lu));return!kr(e)||!kr(n)||r!==1?null:{attemptId:e,nonce:n,protocol:r}}function Ym(t){return t.indexOf("%")===-1?t:t.replace(/%([0-9A-Fa-f]{2})/g,(e,n)=>{let r=parseInt(n,16);return r<128?String.fromCharCode(r):e})}function Km(t){let e=t.indexOf("="),n=e===-1?t:t.slice(0,e);return Ym(n.indexOf("+")===-1?n:n.split("+").join(" "))}function bu(t){return Xm(t,[uf])}var _E=[uu,lu,du,fu,cf];function Ef(t){return Xm(t,_E)}function Xm(t,e){let n=t.charAt(0)==="?"?t.slice(1):t;if(n.length===0)return"";let r=n.split("&"),s=r.filter(i=>!e.includes(Km(i)));if(s.length===r.length)return`?${n}`;let o=s.join("&");return o.length===0?"":`?${o}`}var RE=/^[!$-&(-;=?-~]+$/;function wu(t,e){if(typeof t!="string")return"";let n=t.charAt(0)==="?"?t.slice(1):t,r=n.indexOf("#");if(r!==-1&&(n=n.slice(0,r)),n.length===0||!RE.test(n))return"";let o=n.split("&").filter(i=>{if(i.length===0)return!1;let a=Km(i);return!a.startsWith(Uo)&&!e.includes(a)}).join("&");return o.length>1024?"":o}var EE=/^#[!#-;=?-_a-~]+$/;function Su(t){return typeof t!="string"||t.length<2||t.length>4096||!EE.test(t)||Ym(t).includes(Uo)?"":t}var kE=/^[a-z0-9._-]+$/,AE=/^\[[0-9a-f:.]+\]$/;function PE(t){return kE.test(t)&&/[a-z0-9]/.test(t)||AE.test(t)}function _f(t){let e=t.slice(0,8).toLowerCase(),n=e==="https://"?"https":e.slice(0,7)==="http://"?"http":null;if(n===null)return null;let r=n.length+3,s=t.length;for(let u=r;u<t.length;u++){let l=t.charAt(u);if(l==="/"||l==="?"||l==="#"||l==="\\"){s=u;break}}if(s-r>255)return null;let o=t.slice(r,s).toLowerCase();if(o.length===0||o.indexOf("@")!==-1)return null;let i=o,a="",c=o.lastIndexOf(":");if(c!==-1&&o.charAt(o.length-1)!=="]"&&(i=o.slice(0,c),a=o.slice(c+1)),!PE(i))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===(n==="https"?443:80)?"":`:${u}`}return`${n}://${i}${a}`}function $o(t,e){if(typeof t!="string"||t.length===0)return null;let n=_f(t);return n===null||n.length>255||typeof e=="string"&&_f(e)===n?null:n}var Jm=["open","save","fullscreen"];var Zm=50*1024*1024,TE=16;function Qm(t){return typeof t=="string"&&Jm.includes(t)}function kf(t){if(!Array.isArray(t))return[];let e=[],n=Math.min(t.length,TE);for(let r=0;r<n;r++){let s=t[r];Qm(s)&&!e.includes(s)&&e.push(s)}return e}var UE=null;function ty(t){UE=t}var HE=null;function ny(t){HE=t}var $E=null;function ry(t){$E=t}var ha=1,Mf="genex:embed:retry",gy="genex:guest:popover-dismissed",by="genex:embed:local-auth",wy="genex:embed:entry-referrer",jE="none",sy="genex:player",WE="0.35.0",Be=null,Ue="pending",sn=null,os=!1,rs=null,jo=!1,ss,Wo,Sy=0,jt,xy,Cf,_y,Ry=!1,is=null,Ey=[],Go=!1,Vs=!1,fa=!1,rn=0,Yo=1e4,qE=2e3,GE=10*6e4,YE=6e4,oy=500,KE=3e4,XE=3e4,Ye,vn,qo,iy=!1,ay,xu=null,cy=new Set;var uy=!1,JE=new Map,ky=[],ma=[],pa=null,_u=null,Us,Af,Pf=!1,Ru=new Map;function et(){return globalThis.window}function Of(){return globalThis.document}function ya(t,e,n){let r;if(n!==void 0)try{let s=globalThis.AbortSignal;s&&typeof s.timeout=="function"&&(r=s.timeout(n))}catch{}return globalThis.fetch(t,r?{...e,signal:r}:e)}function ZE(){try{return et()?.sessionStorage?.getItem(Mf)==="1"}catch{return!1}}function QE(){try{et()?.sessionStorage?.setItem(Mf,"1")}catch{}}function If(){try{et()?.sessionStorage?.removeItem(Mf)}catch{}}function ek(){try{return et()?.sessionStorage?.getItem(by)==="1"}catch{return!1}}function tk(){try{et()?.sessionStorage?.setItem(by,"1")}catch{}}function nk(){try{let t=et()?.sessionStorage?.getItem(wy);return t==null?void 0:$o(t)}catch{return}}function rk(t){try{et()?.sessionStorage?.setItem(wy,t??jE)}catch{}}function sk(){try{return et()?.sessionStorage?.getItem(gy)==="1"}catch{return!1}}function ok(){try{et()?.sessionStorage?.setItem(gy,"1")}catch{}}function ik(){try{let t=et()?.localStorage;if(!t)return"no-storage";let e=t.getItem(sy);return e||(e=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,t.setItem(sy,e)),e}catch{return"no-storage"}}function ku(t){let e=et();if(!e||Go)return;if(Go=!0,qo!==void 0&&(clearTimeout(qo),qo=void 0),Be={slug:t.slug,apiUrl:t.apiUrl.replace(/\/$/,""),dashboardOrigins:[...t.dashboardOrigins]},Ue="pending",Oy(e),ny({apiUrl:Be.apiUrl,dashboardOrigins:Be.dashboardOrigins,getToken:()=>jt,getParentOrigin:()=>is,isEmbedded:Wt,isNative:Sn,isLocalTest:()=>os}),ry({apiUrl:Be.apiUrl,dashboardOrigins:Be.dashboardOrigins,getToken:()=>jt,getParentOrigin:()=>is,isEmbedded:Wt,isNative:Sn,isLocalTest:()=>os}),zf(e)){Ik(e);return}Tu("connecting");let n=Iy(e);if(n){xk(e,n);return}Wt()?wk(e):Ek(e)}function Wt(){let t=et();if(!t)return!1;try{return t.self!==t.top}catch{return!0}}function ak(){let t=et();return t?Wt()?"page":Sn()||Nf(t)?"app":Go?os?"local":"standalone":zf(t,!1)?"local":"standalone":"standalone"}function Au(){return Ry?{embedToken:Tk}:jt?{embedToken:jt}:void 0}function Ay(){return xy??[]}function Py(){return Vy(Cf)??[]}function Ty(){return Ck(_y)}function Df(){return(Ue==="authenticated"||Ue==="guest")&&sn?Promise.resolve({user:sn,guest:Ue==="guest"}):Ue==="blocked"?Promise.reject(new Error("genex embed auth: blocked")):(ck("waitForPlayer"),new Promise((t,e)=>{ma.push({resolve:t,reject:e})}))}function ck(t){if(!Go){if(!iy){iy=!0;try{console.error(`[genex] ${t}() 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{}}qo===void 0&&(qo=setTimeout(()=>{qo=void 0,Go||Ar("no-identity")},Yo))}}var uk=32*1024;async function vy(){if(!Be)throw new Error("genex embed: call initEmbed() first");if(Ue==="pending"&&await Df(),Ue==="blocked")throw new Error("genex embed auth: blocked")}function My(t,e={}){let n={Authorization:`Bearer ${jt}`};return e.body!==void 0&&(n["Content-Type"]="application/json"),e.ifVersion!==void 0&&(n["If-Match"]=String(e.ifVersion)),ya(`${Be.apiUrl}/api/projects/${encodeURIComponent(Be.slug)}${t}`,{method:e.method??"GET",headers:n,body:e.body,keepalive:e.body!==void 0&&e.body.length<=uk?!0:void 0})}async function lk(t){return t.status!==403?!1:(await t.json().catch(()=>null))?.error==="staging_no_save"}async function dk(t){return t.status===409?{saved:!1,conflict:!0,version:(await t.json().catch(()=>({}))).version}:t.ok?{saved:!0,version:(await t.json()).version}:await lk(t)?{saved:!1,staging:!0}:(on("error",{error:new Error(`genex state save failed (${t.status})`)}),{saved:!1})}async function fk(t,e){return await vy(),Ue==="guest"?(Af=t,Pf=!0,{saved:!1,guest:!0,queued:!0}):dk(await My("/state/me",{method:"PUT",body:JSON.stringify(t),ifVersion:e?.ifVersion}))}async function pk(t,e){let n=e?.board??"main",r=e?.mode??"max";if(await vy(),Ue==="guest"){let i=Ru.get(n);return(!i||(r==="min"?t<i.score:t>i.score))&&Ru.set(n,{score:t,mode:r}),{submitted:!1,guest:!0,queued:!0}}let s=await My("/scores",{method:"POST",body:JSON.stringify({score:t,board:n,mode:r})});if(!s.ok)return on("error",{error:new Error(`genex score submit failed (${s.status})`)}),{submitted:!1};let o=await s.json();return{submitted:!0,best:o.best,improved:o.improved}}async function hk(){try{if(Pf){let e=Af;Af=void 0,Pf=!1,await fk(e)}let t=[...Ru.entries()];Ru.clear();for(let[e,{score:n,mode:r}]of t)await pk(n,{board:e,mode:r})}catch(t){on("error",{error:t})}}function on(t,e){let n=JE.get(t);if(n)for(let r of[...n])try{r(e)}catch{}}var mk=["embed"];function Cy(t,e){let n={ticket:null,guest:!1,entryHash:"",entryReferrer:null};if(!t||t.length<2)return n;try{let r=new URLSearchParams(t.slice(1));return{ticket:r.get("genex_ticket"),guest:r.get("genex_guest")==="1",entryHash:Su(r.get(df)),entryReferrer:$o(r.get(ff),e)}}catch{return n}}function yk(t,e){try{return new URLSearchParams(t).get(e)}catch{return null}}function Oy(t){if(xu)return xu;let e="",n="",r=null;try{e=t.location.search??"",n=Eu??t.location.hash??"",r=t.location.origin??null}catch{}let s=Wt(),o=Cy(n,r),i=!s&&(!!o.ticket||o.guest),a=wu(e,mk);return xu={search:a?`?${a}`:"",hash:i?o.entryHash:n.includes(Uo)?"":n,referrer:gk(e,s,i,o.entryReferrer,r)},xu}function gk(t,e,n,r,s){let o=nk();if(o!==void 0)return o;let i;return e?i=$o(yk(t,pf),s):n?i=r:i=$o(Of()?.referrer,s),rk(i),i}function bk(){if(!(uy||cy.size===0)){uy=!0;for(let t of[...cy])try{t()}catch{}}}function wk(t){ay=e=>{Sk(e)},t.addEventListener("message",ay),t.parent.postMessage({type:"genex:embed:ready",v:ha},"*"),Ye=setTimeout(()=>{Ko()},Yo)}function ly(){return(Ue==="pending"||Ue==="guest")&&!Vs}async function Sk(t){if(!Be)return;let e=t.data;if(!e||e.v!==ha)return;let n=e.type==="genex:embed:ticket",r=e.type==="genex:embed:guest";if(!(!n&&!r)&&!(n&&(!ly()||typeof e.ticket!="string"||!e.ticket))&&!(r&&(Ue!=="pending"||Vs||fa))){if(!Be.dashboardOrigins.includes(t.origin)){let s=await Tf();if(n&&!ly()||r&&(Ue!=="pending"||Vs||fa)||!s.includes(t.origin))return}if(Ye!==void 0&&clearTimeout(Ye),is=t.origin,Ey=kf(e.caps),r){await Ko();return}await Ff(e.ticket)}}function Nf(t){let e=t.ReactNativeWebView;return!e||typeof e!="object"?null:typeof e.postMessage=="function"?e:null}function Iy(t){if(Wt())return null;let e;try{e=t.location.search??""}catch{return null}return!gu(e)||!Nf(t)?null:Rf(e)}function Sn(){return rs!==null}function Hs(t){let e=et();if(!e||!Be||!rs)return;let n=Nf(e);if(!n)return;let r=xf({channel:la,v:1,slug:Be.slug,attemptId:rs.attemptId,nonce:rs.nonce,...t});if(r)try{n.postMessage(r)}catch{}}function Dy(t){Sn()&&Hs({type:"error",code:t})}function xk(t,e){rs=e,Sy=Date.now(),t[pu]=r=>{_k(r)},Hs({type:"ready",sdkVersion:WE,capabilities:["native-ticket","native-guest","heartbeat"]}),Ye=setTimeout(()=>{Ko()},Yo)}async function _k(t){if(!Be||!rs)return;let e=Sf(t);if(!e.ok)return;let n=e.message;if(!(n.slug!==Be.slug||n.attemptId!==rs.attemptId||n.nonce!==rs.nonce))switch(n.type){case"ticket":Ye!==void 0&&clearTimeout(Ye),await Ff(n.ticket);return;case"guest":Ye!==void 0&&clearTimeout(Ye),await Ko();return;case"cancel":Ny(),bk();return;case"foreground":case"network":return}}function Ny(){Ye!==void 0&&clearTimeout(Ye),Ye=void 0,vn!==void 0&&clearTimeout(vn),vn=void 0,ss!==void 0&&clearTimeout(ss),ss=void 0,Wo!==void 0&&clearInterval(Wo),Wo=void 0}function By(){!Sn()||Wo!==void 0||(Wo=setInterval(()=>{Hs({type:"heartbeat",uptimeMs:Math.max(0,Date.now()-Sy)})},XE),Wo.unref?.())}function Rk(){!Sn()||jo||(jo=!0,Hs({type:"reauth-required"}),ss=setTimeout(()=>{ss=void 0,jo&&(jo=!1,on("error",{error:new Error("embed session expired")}),Ar("session-expired"))},KE))}function Bf(){jo=!1,ss!==void 0&&clearTimeout(ss),ss=void 0}function Lf(t,e){let n=et();if(!(!n||!Wt()))try{n.parent.postMessage(t,e)}catch{}}async function Ek(t){let e=Ly(t);if(e.ticket){dy(),await Ff(e.ticket);return}if(e.guest){dy(),await Ko();return}Tu("redirecting"),await Pu(t,{guestOk:!0})}function dy(){Ye!==void 0&&clearTimeout(Ye),Ye=setTimeout(()=>{Ye=void 0,Ue==="pending"&&Ar("no-identity")},Yo+qE)}var Eu=null;function kk(t){return t.location.pathname+bu(t.location.search)}function Ly(t){let e=Eu??t.location.hash;Eu=null;let{ticket:n,guest:r,entryHash:s}=Cy(e);if(n||r)try{t.history.replaceState(t.history.state??null,"",kk(t)+s)}catch{}return{ticket:n,guest:r}}async function Pu(t,e){if(!Be||os||Sn())return;let n=e?.guestOk?Be.dashboardOrigins[0]??(await Tf())[0]:(await Tf())[0]??Be.dashboardOrigins[0];if(!n){Ar();return}let r=t.location.origin+t.location.pathname,s=Ef(bu(t.location.search));s.length-1<=1024&&r.length+s.length<=2048&&s.indexOf("#")===-1&&(r+=s);let o=e?.guestOk?"&guest=ok":"",i=`${n}/play/authorize?returnTo=${encodeURIComponent(r)}&slug=${encodeURIComponent(Be.slug)}${o}`,a=Oy(t).referrer;a&&(i+=`&${lf}=${encodeURIComponent(a)}`),i+=Su(t.location.hash),t.location.replace(i)}async function Tf(){if(!Be)return[];try{let t=await ya(`${Be.apiUrl}/api/embed/dashboard-origins`);if(!t.ok)return Be.dashboardOrigins;let e=await t.json();if(Array.isArray(e.origins)&&e.origins.every(n=>typeof n=="string"))return e.origins}catch{}return Be.dashboardOrigins}async function Ff(t){if(!Be||os||Vs||Ue!=="pending"&&Ue!=="guest"&&!(jo&&Ue==="authenticated"))return;let n=Ue==="guest",r=++rn;Vs=!0;try{let s=await ya(`${Be.apiUrl}/api/embed/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ticket:t})},Yo);if(r!==rn)return;if(!s.ok){on("error",{error:new Error(`ticket redemption failed (${s.status})`)}),n||await fy();return}let o=await s.json();if(r!==rn)return;jt=o.embedToken,sn=o.user,Uy(o.colyseus),Ue="authenticated",Ye!==void 0&&clearTimeout(Ye),Ye=void 0,If(),vu(),Vf(),Uf(),Wt()&&is&&Lf({type:"genex:embed:authenticated",v:ha},is),Sn()&&(Bf(),Hs({type:"authenticated",guest:!1}),By()),n&&await hk();let i={user:sn};for(let a of ky.splice(0))a.resolve(i);for(let a of ma.splice(0))a.resolve({user:sn,guest:!1});on("authenticated",i)}catch(s){if(r!==rn)return;on("error",{error:s}),n||await fy()}finally{Vs=!1}}async function Ko(){if(!Be||os||fa||Vs||Ue!=="pending"&&Ue!=="guest")return;let t=++rn;fa=!0;try{let e=await ya(`${Be.apiUrl}/api/embed/guest-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:Be.slug,playerId:ik()})},Yo);if(t!==rn)return;if(!e.ok){on("error",{error:new Error(`guest session failed (${e.status})`)}),Dy("guest-failed"),Ar(e.status===404?"not-available":"no-identity");return}let n=await e.json();if(t!==rn)return;jt=n.embedToken,sn=n.user,Uy(n.colyseus),Ak()}catch(e){if(t!==rn)return;on("error",{error:e}),Ar()}finally{fa=!1}}function Ak(){let t=Ue!=="guest";if(Ue="guest",Ye!==void 0&&clearTimeout(Ye),vu(),Uf(),Wt()?Lf({type:"genex:embed:authenticated",v:ha,guest:!0},is??"*"):Sn()?(Hs({type:"authenticated",guest:!0}),By()):t&&!sk()&&Uk(),sn){let e={user:sn};for(let n of ma.splice(0))n.resolve({user:sn,guest:!0});on("guest",e)}}function Fy(t){try{let e=new URL(t.location.origin);return e.protocol==="http:"&&zy.has(e.hostname)}catch{return!1}}var zy=new Set(["localhost","127.0.0.1","[::1]"]),Pk="genex_authority_url",Tk="local:test",vk=64;function Mk(t){if(!t||t.length>vk)return null;let e;try{e=new URL(t)}catch{return null}let n=!e.username&&!e.password&&e.pathname==="/"&&!e.search&&!e.hash;return e.protocol!=="ws:"||!zy.has(e.hostname)||!n?null:`ws://${e.host}`}function Uy(t){xy=t?.urls,Cf=t?.authorityUrls,_y=t?.authorityRegions}function Vy(t){if(Array.isArray(t))return t.filter(e=>typeof e=="string"&&e.length>0)}function Ck(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(n===null||typeof n!="object")continue;let{region:r,urls:s}=n,o=Vy(s)??[];typeof r=="string"&&r.length>0&&o.length>0&&e.push({region:r,urls:o})}return e}function zf(t,e=!0){if(Wt()||Iy(t)||!Fy(t))return!1;let n=null;try{n=new URLSearchParams(t.location.search)}catch{}return n?.get("genex_local_test")==="1"?!0:n?.get("genex_auth")==="1"?(e&&tk(),!1):ek()?!1:!Ok(t)}function Ok(t){let e=Eu??t.location.hash;return!!e&&e.includes("genex_")}function Ik(t){os=!0,Ly(t),Dk(t);let e={id:"local:test",name:"Local Tester"};sn=e,Ue="guest",vu();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 n of ma.splice(0))n.resolve({user:e,guest:!0});on("guest",{user:e})}function Dk(t){if(!Fy(t))return;let e=null;try{e=new URLSearchParams(t.location.search).get(Pk)}catch{return}let n=Mk(e);n&&(Cf=[n],Ry=!0)}async function fy(){let t=et();if(Ye!==void 0&&clearTimeout(Ye),Ye=void 0,Sn()){Bf(),Dy("ticket-rejected"),Ar();return}if(t&&!Wt()&&!ZE()){QE(),Tu("redirecting"),await Pu(t,{guestOk:!0});return}Ar()}function Uf(){vn!==void 0&&clearTimeout(vn),vn=setTimeout(()=>{Hy()},GE)}async function Hy(){if(!Be||Ue!=="authenticated"&&Ue!=="guest"||!jt)return;let t=rn,e=jt,n;try{let r=await ya(`${Be.apiUrl}/api/embed/session/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`},keepalive:!0});if(n=r.status,t!==rn||jt!==e)return;if(r.ok){let s=await r.json();if(t!==rn||jt!==e)return;jt=s.embedToken,Uf();return}}catch{n=void 0}if(!(t!==rn||jt!==e)){if(n===401){if(Ue==="guest"){Ko();return}if(Sn()){Rk();return}on("error",{error:new Error("embed session expired")}),Ar("session-expired");return}vn!==void 0&&clearTimeout(vn),vn=setTimeout(()=>{Hy()},YE)}}function Ar(t="no-identity"){if(Ue==="blocked")return;rn++,Ue="blocked",sn=null,jt=void 0,Ye!==void 0&&clearTimeout(Ye),vn!==void 0&&clearTimeout(vn),Vf(),Sn()?(Ny(),Bf(),vu(),Hs({type:"blocked",reason:t})):Tu(Wt()?"blocked-embedded":"blocked-standalone"),Wt()&&Lf({type:"genex:embed:blocked",v:ha},is??"*");let e=new Error("genex embed auth: blocked");for(let n of ky.splice(0))n.reject(e);for(let n of ma.splice(0))n.reject(e);on("blocked")}var Nk={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}},Bk="https://cdn.genex.technology/fonts/GeistMono-variable.woff2",$y="'Geist Mono',ui-monospace,SFMono-Regular,Menlo,monospace",py=!1,hy="!<>-_/[]{}=+*^?#$%&@",jy=50,my=10,yy=[{name:"churn",ticks:5},{name:"settle",ticks:10},{name:"hold",ticks:12},{name:"dissolve",ticks:8}];function vf(t){let e="";for(let n=0;n<t;n++)e+=hy[Math.floor(Math.random()*hy.length)];return e}function Wy(){try{let t=et();return!t||typeof t.matchMedia!="function"?!0:t.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!0}}function Lk(t,e){if(Wy())return t.textContent=e,()=>{};let n=0;t.textContent=vf(e.length);let r=setInterval(()=>{if(n++,n>=my){t.textContent=e,clearInterval(r);return}let s=Math.floor(n/my*e.length);t.textContent=e.slice(0,s)+vf(e.length-s)},jy);return()=>clearInterval(r)}function Fk(t,e){if(Wy())return t.textContent=e,()=>{};let n=0,r=0,s=()=>{let i=yy[n],a;i.name==="churn"?a=0:i.name==="settle"?a=Math.floor(r/i.ticks*e.length):i.name==="hold"?a=e.length:a=e.length-Math.floor(r/i.ticks*e.length),t.textContent=e.slice(0,a)+vf(e.length-a),r++,r>=i.ticks&&(r=0,n=(n+1)%yy.length)};s();let o=setInterval(s,jy);return()=>clearInterval(o)}function qy(t){if(!py){py=!0;try{let e=et()?.FontFace,n=t.fonts;if(!e||!n?.add)return;new e("Geist Mono",`url(${Bk}) format('woff2')`,{weight:"100 900",display:"swap"}).load().then(s=>n.add(s)).catch(()=>{})}catch{}}}function Tu(t){let e=Of();if(e?.createElement)try{pa||(pa=zk(e)),pa.setContent(t)}catch{}}function vu(t=!1){try{let e=pa;if(pa=null,!e)return;e.stopText();let n=e.root;if(t||!n.style){n.remove?.();return}n.style.pointerEvents="none",n.style.transition="opacity 180ms ease",n.style.opacity="0",setTimeout(()=>{try{n.remove?.()}catch{}},220)}catch{}}function zk(t){qy(t);let e=t.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:${$y};text-align:center;pointer-events:auto;user-select:none`;let n=t.createElement("div");n.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(n);let r=t.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=et();c&&(r.disabled=!0,If(),Pu(c))}),e.appendChild(r);let s=()=>{t.body&&!e.isConnected&&t.body.appendChild(e)};t.body?s():t.addEventListener?.("DOMContentLoaded",s);let o,i,a=()=>{o!==void 0&&(clearTimeout(o),o=void 0),i&&(i(),i=void 0)};return{root:e,stopText:a,setContent(c){let u=Nk[c];a(),n.textContent=u.title,n.style.letterSpacing=u.wordmark?"0.22em":"",n.style.marginRight=u.wordmark?"-0.22em":"";let l=()=>{n.style.opacity="1",i=u.wordmark?Fk(n,u.title):Lk(n,u.title)};u.instant||oy<=0?l():(n.style.opacity="0",o=setTimeout(()=>{o=void 0,l()},oy)),r.style.display=u.button?"inline-block":"none",u.button&&(r.textContent=u.button),s()}}}function Uk(){let t=Of();if(!(!t?.createElement||_u))try{_u=Vk(t)}catch{}}function Vf(){Us!==void 0&&(clearTimeout(Us),Us=void 0);try{_u?.root?.remove?.()}catch{}_u=null}function Vk(t){qy(t);let e=!1;try{let c=et(),u=c?.navigator;if(c&&u){let l=c.matchMedia?.("(pointer: coarse)").matches??!1,d=(u.maxTouchPoints??0)>1,f=u.userAgentData?u.userAgentData.mobile:/Mobi|Android/i.test(u.userAgent??"");e=d&&l||f}}catch{}let n=t.createElement("div");n.setAttribute("data-genex-guest-popover",""),n.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=t.createElement("div");r.style.cssText=`display:flex;align-items:center;border-radius:12px;background:rgba(0,0,0,0.85);color:#fff;font-family:${$y};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"),n.appendChild(r);let s=t.createElement("span");s.textContent=!e&&sn?.name?`Playing as ${sn.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 o=t.createElement("button");o.textContent="Sign in",o.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"),o.addEventListener("mouseenter",()=>{o.style.background="#3f51a8"}),o.addEventListener("mouseleave",()=>{o.style.background="#4b60bf"}),o.addEventListener("click",()=>{let c=et();c&&(o.disabled=!0,If(),Pu(c))}),r.appendChild(o);let i=t.createElement("button");if(i.textContent="\xD7",i.setAttribute("aria-label","Dismiss"),i.style.cssText="font-size:16px;line-height:1;padding:6px 8px;border:none;cursor:pointer;background:transparent;color:rgba(255,255,255,0.6)",i.addEventListener("click",()=>{ok(),Vf()}),r.appendChild(i),e){let c=t.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>',n.appendChild(c);let u=l=>{r.style.display=l?"none":"flex",c.style.display=l?"flex":"none"};Us=setTimeout(()=>u(!0),5e3),r.addEventListener("pointerdown",()=>{Us!==void 0&&clearTimeout(Us),Us=void 0}),c.addEventListener("click",()=>u(!1))}let a=()=>{t.body&&!n.isConnected&&t.body.appendChild(n)};return t.body?a():t.addEventListener?.("DOMContentLoaded",a),{root:n}}ty({getShell:ak,isLocalTest:()=>{let t=et();return!t||Wt()?!1:Go?os:zf(t,!1)},getConfig:()=>Be,getParentOrigin:()=>is,getShellCaps:()=>Ey});var rh={};of(rh,{chatSend:()=>yv,claim:()=>gv,claimAsHost:()=>bv,connect:()=>ov,destroy:()=>Sv,dispose:()=>iv,drainEventsJson:()=>Mv,leave:()=>lw,listen:()=>pv,objectsJson:()=>Tv,open:()=>sv,playersJson:()=>Pv,release:()=>wv,reportEliminated:()=>xv,reportFinish:()=>Rv,reportScore:()=>_v,send:()=>fv,sendInput:()=>hv,serverNow:()=>Ev,sessionJson:()=>Av,setIdentity:()=>ev,setMe:()=>av,setObject:()=>lv,setRoomOpen:()=>mv,setShared:()=>uv,sharedJson:()=>vv,snapMe:()=>cv,snapObject:()=>dv,timeUntil:()=>kv,version:()=>QT});var ga={ready(t){let e=globalThis.__GENEX__;return t&&e&&typeof e.apiUrl=="string"&&Array.isArray(e.dashboardOrigins)&&ku({slug:t,apiUrl:e.apiUrl,dashboardOrigins:e.dashboardOrigins.filter(n=>typeof n=="string")}),Df()},auth:()=>Au(),urls:()=>Ay()},Hk=4096;function ye(t,e){t.q.length>=Hk&&(t.overflowed?t.q.splice(1,1):(t.overflowed=!0,t.q.splice(0,2,{type:"warning",message:"genex bridge: event queue full; drain it every frame (oldest events dropped)"}))),t.q.push(e)}var Xo=t=>({type:"warning",message:`genex bridge: ${t}`});function $k(t){try{return JSON.stringify(t)}catch(e){let n=typeof t.kind=="string"?t.kind:t.type;return JSON.stringify(Xo(`event ${JSON.stringify(n)} dropped: JSON cannot carry it (${tr(e)})`))}}function Mu(t){return t.overflowed=!1,`[${t.q.splice(0).map($k).join(",")}]`}var Mn=t=>!!t&&typeof t=="object"&&!Array.isArray(t),Jo=t=>{let e=Mn(t)||t instanceof Error?t.code:void 0;return typeof e=="number"&&Number.isFinite(e)?e:0},tr=t=>t instanceof Error?t.message:typeof t=="string"?t:"join failed";function ba(t,e){if(typeof t!="string")throw new TypeError(`genex bridge: ${e} must be a JSON string`);return JSON.parse(t)}function nr(t,e){let n=ba(t,e);if(!Mn(n))throw new TypeError(`genex bridge: ${e} must be a JSON object`);return n}ArrayBuffer.isView||(ArrayBuffer.isView=t=>t!==null&&typeof t=="object"&&t.buffer instanceof ArrayBuffer);typeof globalThis>"u"&&typeof window<"u"&&(window.globalThis=window);typeof FormData>"u"&&(globalThis.FormData=class{});Pr();var rr=class extends Error{constructor(n,r,s){super(r);m(this,"code");m(this,"headers");m(this,"status");m(this,"response");m(this,"data");this.name="ServerError",this.code=n,s&&(this.headers=s.headers,this.status=s.status,this.response=s.response,this.data=s.data)}};var wa=class t extends Error{constructor(n,r){super(n);m(this,"code");this.code=r,this.name="MatchMakeError",Object.setPrototypeOf(this,t.prototype)}};Pr();Pt();Pt();Pt();Pt();Pt();Pt();Pt();Pt();var wb=256,fp=5,Js=class Js{constructor(e,n={}){m(this,"instance");m(this,"mode");m(this,"historySize");m(this,"_desc");m(this,"_numFields");m(this,"_slots");m(this,"_slotLens");m(this,"_slotHead",0);m(this,"_slotCount",0);m(this,"_outBuffer");m(this,"_seq",0);m(this,"_encoder");this.instance=e,this.mode=n.mode??"reliable",this.historySize=this.mode==="unreliable"?Math.max(1,n.historySize??3):1,this._desc=sp(e);let r=this._desc.metadata?.[At];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(wb);this._outBuffer=new Uint8Array((wb+fp)*this.historySize)}this._encoder=new Ta(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[I],n=this.instance[Mt];for(let r=0;r<=this._numFields;r++)n[r]===void 0||n[r]===null||e.markDirty(r)}copyInto(e){let n=this.instance[Mt],r=e[Mt];for(let s=0;s<=this._numFields;s++)r[s]=n[s]}_produceDelta(){let e=this._encoder.encode();return this._encoder.discardChanges(),e}_pushAndEmitRing(e){this._seq++;let n=this._slots[this._slotHead];return e.length>n.byteLength&&(n=this._slots[this._slotHead]=Js._grow(n,e.length,"unreliable ring slot")),n.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,n=fp;for(let i=0;i<this._slotCount;i++)n+=this._slotLens[i]+fp;let r=this._outBuffer;n>r.byteLength&&(r=this._outBuffer=Js._grow(r,n,"unreliable output packet"));let s={offset:0};Se.number(r,e,s);let o=(this._slotHead-this._slotCount+this.historySize)%this.historySize;for(let i=0;i<this._slotCount;i++){let a=(o+i)%this.historySize,c=this._slotLens[a];Se.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,n,r){let s=Math.max(n,e.byteLength*2);return Js._warned||(Js._warned=!0,console.warn(`@colyseus/schema/input: InputEncoder buffer overflow in ${r}. Growing to ${s} bytes.`)),new Uint8Array(s)}};m(Js,"_warned",!1);var sl=Js;Pr();hp();ul();var Zs,Un,ai,Fa,za,Ua,Va,Ha,$a,ci,ja,ll,Rb,ui=class{constructor(e){He(this,ll);He(this,Zs);He(this,Un);He(this,ai);He(this,Fa);He(this,za,!1);He(this,Ua);He(this,Va,!1);He(this,Ha,!1);He(this,$a);He(this,ci);He(this,ja);$e(this,Zs,e)}get patchRate(){return de(this,ci)}applyReflection(e,n,r){let s=zn.decode(e.subarray(0,r),n);zn.makeEncodable(s.state.constructor),$e(this,Ua,s.state.constructor),de(this,Zs).clock===ii&&(de(this,Zs).clock=new cl)}applyOptions(e,n){let r=e[n.offset++];$e(this,Va,(r&$s.RENDER_TIME)!==0),$e(this,Ha,(r&$s.RECKON_TIME)!==0),r&$s.FIXED_TIMESTEP&&$e(this,$a,Pe.number(e,n)),r&$s.PATCH_RATE&&$e(this,ci,Pe.number(e,n)),r&$s.SUB_STEPS&&$e(this,ja,Pe.number(e,n))}ackInput(e){return de(this,Un)?de(this,Un).ackInput(e):-1}reset(){de(this,Un)?.reset()}handle(e){if(de(this,Un))return e!==void 0&&zs(this,ll,Rb).call(this,e),de(this,Un);let n=e?.type??de(this,Ua);if(!n)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 n,s=new sl(r,e);return $e(this,Un,new oi(de(this,Zs),r,s,{stampRender:de(this,Va),stampReckon:de(this,Ha),renderDelay:e?.renderDelay,allowRewind:e?.allowRewind,tickRate:de(this,$a),patchRate:de(this,ci),subSteps:de(this,ja)})),$e(this,ai,e),$e(this,Fa,s),de(this,Un)}};Zs=new WeakMap,Un=new WeakMap,ai=new WeakMap,Fa=new WeakMap,za=new WeakMap,Ua=new WeakMap,Va=new WeakMap,Ha=new WeakMap,$a=new WeakMap,ci=new WeakMap,ja=new WeakMap,ll=new WeakSet,Rb=function(e){if(de(this,za))return;let n=de(this,Un),r=[];e.type!==void 0&&e.type!==n.data?.constructor&&r.push("type"),e.mode!==void 0&&e.mode!==n.mode&&r.push("mode"),e.historySize!==void 0&&n.mode==="unreliable"&&e.historySize!==de(this,Fa).historySize&&r.push("historySize"),e.renderDelay!==void 0&&e.renderDelay!==de(this,ai)?.renderDelay&&r.push("renderDelay"),e.allowRewind!==void 0!=(de(this,ai)?.allowRewind!==void 0)&&r.push("allowRewind"),r.length!==0&&($e(this,za,!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 yp;try{yp=new TextDecoder}catch{}var Z,_n,O=0;var Db=[],gp=Db,bp=0,Le={},Ce,hs,xn=0,dr=0,_t,Dr,Yt=[],ve,Eb={useRecords:!1,mapsAsObjects:!0},Wa=class{},Sp=new Wa;Sp.name="MessagePack 0xC1";var ms=!1,kb=2;var ys=class t{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,n){if(Z)return zb(()=>(fl(),this?this.unpack(e,n):t.prototype.unpack.call(Eb,e,n)));!e.buffer&&e.constructor===ArrayBuffer&&(e=typeof Buffer<"u"?Buffer.from(e):new Uint8Array(e)),typeof n=="object"?(_n=n.end||e.length,O=n.start||0):(O=0,_n=n>-1?n:e.length),bp=0,dr=0,hs=null,gp=Db,_t=null,Z=e;try{ve=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(r){throw Z=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 t){if(Le=this,this.structures)return Ce=this.structures,dl(n);(!Ce||Ce.length>0)&&(Ce=[])}else Le=Eb,(!Ce||Ce.length>0)&&(Ce=[]);return dl(n)}unpackMultiple(e,n){let r,s=0;try{ms=!0;let o=e.length,i=this?this.unpack(e,o):hl.unpack(e,o);if(n){if(n(i,s,O)===!1)return;for(;O<o;)if(s=O,n(dl(),s,O)===!1)return}else{for(r=[i];O<o;)s=O,r.push(dl());return r}}catch(o){throw o.lastPosition=s,o.values=r,o}finally{ms=!1,fl()}}_mergeStructures(e,n){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 o=e[r];o&&(o.isShared=!0,r>=32&&(o.highByte=r-32>>5))}e.sharedLength=e.length;for(let r in n||[])if(r>=0){let s=e[r],o=n[r];o&&(s&&((e.restoreStructures||(e.restoreStructures=[]))[r]=s),e[r]=o)}return this.structures=e}decode(e,n){return this.unpack(e,n)}};function dl(t){try{if(!Le.trusted&&!ms){let n=Ce.sharedLength||0;n<Ce.length&&(Ce.length=n)}let e;if(Le._readStruct&&Z[O]<64&&Z[O]>=32?(e=Le._readStruct(Z,O,_n),Z=null,!(t&&t.lazy)&&e&&(e=e.toJSON()),O=_n):e=ot(),_t&&(O=_t.postBundlePosition,_t=null),ms&&(Ce.restoreStructures=null),O==_n)Ce&&Ce.restoreStructures&&Ab(),Ce=null,Z=null,Dr&&(Dr=null);else{if(O>_n)throw new Error("Unexpected end of MessagePack data");if(!ms){let n;try{n=JSON.stringify(e,(r,s)=>typeof s=="bigint"?`${s}n`:s).slice(0,100)}catch(r){n="(JSON view not available "+r+")"}throw new Error("Data read, but end of buffer not reached "+n)}}return e}catch(e){throw Ce&&Ce.restoreStructures&&Ab(),fl(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")||O>_n)&&(e.incomplete=!0),e}}function Ab(){for(let t in Ce.restoreStructures)Ce[t]=Ce.restoreStructures[t];Ce.restoreStructures=null}function ot(){let t=Z[O++];if(t<160)if(t<128){if(t<64)return t;{let e=Ce[t&63]||Le.getStructures&&Nb()[t&63];return e?(e.read||(e.read=xp(e,t&63)),e.read()):t}}else if(t<144)if(t-=128,Le.mapsAsObjects){let e={};for(let n=0;n<t;n++){let r=Lb();r==="__proto__"&&(r="__proto_"),e[r]=ot()}return e}else{let e=new Map;for(let n=0;n<t;n++)e.set(ot(),ot());return e}else{t-=144;let e=new Array(t);for(let n=0;n<t;n++)e[n]=ot();return Le.freezeData?Object.freeze(e):e}else if(t<192){let e=t-160;if(dr>=O)return hs.slice(O-xn,(O+=e)-xn);if(dr==0&&_n<140){let n=e<16?_p(e):Bb(e);if(n!=null)return n}return wp(e)}else{let e;switch(t){case 192:return null;case 193:return _t?(e=ot(),e>0?_t[1].slice(_t.position1,_t.position1+=e):_t[0].slice(_t.position0,_t.position0-=e)):Sp;case 194:return!1;case 195:return!0;case 196:if(e=Z[O++],e===void 0)throw new Error("Unexpected end of buffer");return mp(e);case 197:return e=ve.getUint16(O),O+=2,mp(e);case 198:return e=ve.getUint32(O),O+=4,mp(e);case 199:return Qs(Z[O++]);case 200:return e=ve.getUint16(O),O+=2,Qs(e);case 201:return e=ve.getUint32(O),O+=4,Qs(e);case 202:if(e=ve.getFloat32(O),Le.useFloat32>2){let n=pl[(Z[O]&127)<<1|Z[O+1]>>7];return O+=4,(n*e+(e>0?.5:-.5)>>0)/n}return O+=4,e;case 203:return e=ve.getFloat64(O),O+=8,e;case 204:return Z[O++];case 205:return e=ve.getUint16(O),O+=2,e;case 206:return e=ve.getUint32(O),O+=4,e;case 207:return Le.int64AsType==="number"?(e=ve.getUint32(O)*4294967296,e+=ve.getUint32(O+4)):Le.int64AsType==="string"?e=ve.getBigUint64(O).toString():Le.int64AsType==="auto"?(e=ve.getBigUint64(O),e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=ve.getBigUint64(O),O+=8,e;case 208:return ve.getInt8(O++);case 209:return e=ve.getInt16(O),O+=2,e;case 210:return e=ve.getInt32(O),O+=4,e;case 211:return Le.int64AsType==="number"?(e=ve.getInt32(O)*4294967296,e+=ve.getUint32(O+4)):Le.int64AsType==="string"?e=ve.getBigInt64(O).toString():Le.int64AsType==="auto"?(e=ve.getBigInt64(O),e>=BigInt(-2)<<BigInt(52)&&e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=ve.getBigInt64(O),O+=8,e;case 212:if(e=Z[O++],e==114)return Ob(Z[O++]&63);{let n=Yt[e];if(n)return n.read?(O++,n.read(ot())):n.noBuffer?(O++,n()):n(Z.subarray(O,++O));throw new Error("Unknown extension "+e)}case 213:return e=Z[O],e==114?(O++,Ob(Z[O++]&63,Z[O++])):Qs(2);case 214:return Qs(4);case 215:return Qs(8);case 216:return Qs(16);case 217:return e=Z[O++],dr>=O?hs.slice(O-xn,(O+=e)-xn):IP(e);case 218:return e=ve.getUint16(O),O+=2,dr>=O?hs.slice(O-xn,(O+=e)-xn):DP(e);case 219:return e=ve.getUint32(O),O+=4,dr>=O?hs.slice(O-xn,(O+=e)-xn):NP(e);case 220:return e=ve.getUint16(O),O+=2,Tb(e);case 221:return e=ve.getUint32(O),O+=4,Tb(e);case 222:return e=ve.getUint16(O),O+=2,vb(e);case 223:return e=ve.getUint32(O),O+=4,vb(e);default:if(t>=224)return t-256;if(t===void 0){let n=new Error("Unexpected end of MessagePack data");throw n.incomplete=!0,n}throw new Error("Unknown MessagePack token "+t)}}}var OP=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function xp(t,e){function n(){if(n.count++>kb){let s;try{s=t.read=new Function("r","return function(){return "+(Le.freezeData?"Object.freeze":"")+"({"+t.map(o=>o==="__proto__"?"__proto_:r()":OP.test(o)?o+":r()":"["+JSON.stringify(o)+"]:r()").join(",")+"})}")(ot)}catch{return kb=1/0,n()}return t.read0=s,t.highByte===0&&(t.read=Pb(e,t.read)),s()}let r={};for(let s=0,o=t.length;s<o;s++){let i=t[s];i==="__proto__"&&(i="__proto_"),r[i]=ot()}return Le.freezeData?Object.freeze(r):r}return n.count=0,t.read0=n,t.highByte===0?Pb(e,n):n}var Pb=(t,e)=>function(){let n=Z[O++];if(n===0)return e();let r=t<32?-(t+(n<<5)):t+(n<<5),s=Ce[r]||Nb()[r];if(!s)throw new Error("Record id is not defined for "+r);return s.read||(s.read=xp(s,t)),s.read()};function Nb(){let t=zb(()=>(Z=null,Le.getStructures()));return Ce=Le._mergeStructures(t,Ce)}var wp=qa,IP=qa,DP=qa,NP=qa;function qa(t){let e;if(t<16&&(e=_p(t)))return e;if(t>64&&yp)return yp.decode(Z.subarray(O,O+=t));let n=O+t,r=[];for(e="";O<n;){let s=Z[O++];if((s&128)===0)r.push(s);else if((s&224)===192){let o=Z[O++]&63,i=(s&31)<<6|o;i<128?r.push(65533):r.push(i)}else if((s&240)===224){let o=Z[O++]&63,i=Z[O++]&63,a=(s&31)<<12|o<<6|i;a<2048||a>=55296&&a<=57343?r.push(65533):r.push(a)}else if((s&248)===240){let o=Z[O++]&63,i=Z[O++]&63,a=Z[O++]&63,c=(s&7)<<18|o<<12|i<<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+=xt.apply(String,r),r.length=0)}return r.length>0&&(e+=xt.apply(String,r)),e}function Tb(t){let e=new Array(t);for(let n=0;n<t;n++)e[n]=ot();return Le.freezeData?Object.freeze(e):e}function vb(t){if(Le.mapsAsObjects){let e={};for(let n=0;n<t;n++){let r=Lb();r==="__proto__"&&(r="__proto_"),e[r]=ot()}return e}else{let e=new Map;for(let n=0;n<t;n++)e.set(ot(),ot());return e}}var xt=String.fromCharCode;function Bb(t){let e=O,n=new Array(t);for(let r=0;r<t;r++){let s=Z[O++];if((s&128)>0){O=e;return}n[r]=s}return xt.apply(String,n)}function _p(t){if(t<4)if(t<2){if(t===0)return"";{let e=Z[O++];if((e&128)>1){O-=1;return}return xt(e)}}else{let e=Z[O++],n=Z[O++];if((e&128)>0||(n&128)>0){O-=2;return}if(t<3)return xt(e,n);let r=Z[O++];if((r&128)>0){O-=3;return}return xt(e,n,r)}else{let e=Z[O++],n=Z[O++],r=Z[O++],s=Z[O++];if((e&128)>0||(n&128)>0||(r&128)>0||(s&128)>0){O-=4;return}if(t<6){if(t===4)return xt(e,n,r,s);{let o=Z[O++];if((o&128)>0){O-=5;return}return xt(e,n,r,s,o)}}else if(t<8){let o=Z[O++],i=Z[O++];if((o&128)>0||(i&128)>0){O-=6;return}if(t<7)return xt(e,n,r,s,o,i);let a=Z[O++];if((a&128)>0){O-=7;return}return xt(e,n,r,s,o,i,a)}else{let o=Z[O++],i=Z[O++],a=Z[O++],c=Z[O++];if((o&128)>0||(i&128)>0||(a&128)>0||(c&128)>0){O-=8;return}if(t<10){if(t===8)return xt(e,n,r,s,o,i,a,c);{let u=Z[O++];if((u&128)>0){O-=9;return}return xt(e,n,r,s,o,i,a,c,u)}}else if(t<12){let u=Z[O++],l=Z[O++];if((u&128)>0||(l&128)>0){O-=10;return}if(t<11)return xt(e,n,r,s,o,i,a,c,u,l);let d=Z[O++];if((d&128)>0){O-=11;return}return xt(e,n,r,s,o,i,a,c,u,l,d)}else{let u=Z[O++],l=Z[O++],d=Z[O++],f=Z[O++];if((u&128)>0||(l&128)>0||(d&128)>0||(f&128)>0){O-=12;return}if(t<14){if(t===12)return xt(e,n,r,s,o,i,a,c,u,l,d,f);{let h=Z[O++];if((h&128)>0){O-=13;return}return xt(e,n,r,s,o,i,a,c,u,l,d,f,h)}}else{let h=Z[O++],p=Z[O++];if((h&128)>0||(p&128)>0){O-=14;return}if(t<15)return xt(e,n,r,s,o,i,a,c,u,l,d,f,h,p);let y=Z[O++];if((y&128)>0){O-=15;return}return xt(e,n,r,s,o,i,a,c,u,l,d,f,h,p,y)}}}}}function Mb(){let t=Z[O++],e;if(t<192)e=t-160;else switch(t){case 217:e=Z[O++];break;case 218:e=ve.getUint16(O),O+=2;break;case 219:e=ve.getUint32(O),O+=4;break;default:throw new Error("Expected string")}return qa(e)}function mp(t){return Le.copyBuffers?Uint8Array.prototype.slice.call(Z,O,O+=t):Z.subarray(O,O+=t)}function Qs(t){let e=Z[O++];if(Yt[e]){let n;return Yt[e](Z.subarray(O,n=O+=t),r=>{O=r;try{return ot()}finally{O=n}})}else throw new Error("Unknown extension type "+e)}var Cb=new Array(4096);function Lb(){let t=Z[O++];if(t>=160&&t<192){if(t=t-160,dr>=O)return hs.slice(O-xn,(O+=t)-xn);if(!(dr==0&&_n<180))return wp(t)}else return O--,Fb(ot());let e=(t<<5^(t>1?ve.getUint16(O):t>0?Z[O]:0))&4095,n=Cb[e],r=O,s=O+t-3,o,i=0;if(n&&n.bytes==t){for(;r<s;){if(o=ve.getUint32(r),o!=n[i++]){r=1879048192;break}r+=4}for(s+=3;r<s;)if(o=Z[r++],o!=n[i++]){r=1879048192;break}if(r===s)return O=r,n.string;s-=3,r=O}for(n=[],Cb[e]=n,n.bytes=t;r<s;)o=ve.getUint32(r),n.push(o),r+=4;for(s+=3;r<s;)o=Z[r++],n.push(o);let a=t<16?_p(t):Bb(t);return a!=null?n.string=a:n.string=wp(t)}function Fb(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return t.toString();if(t==null)return t+"";if(Le.allowArraysInMapKeys&&Array.isArray(t)&&t.flat().every(e=>["string","number","boolean","bigint"].includes(typeof e)))return t.flat().toString();throw new Error(`Invalid property type for record: ${typeof t}`)}var Ob=(t,e)=>{let n=ot().map(Fb),r=t;e!==void 0&&(t=t<32?-((e<<5)+t):(e<<5)+t,n.highByte=e);let s=Ce[t];return s&&(s.isShared||ms)&&((Ce.restoreStructures||(Ce.restoreStructures=[]))[t]=s),Ce[t]=n,n.read=xp(n,r),(n.read0||n.read)()};Yt[0]=()=>{};Yt[0].noBuffer=!0;Yt[66]=t=>{let e=t.byteLength%8||8,n=BigInt(t[0]&128?t[0]-256:t[0]);for(let r=1;r<e;r++)n<<=BigInt(8),n+=BigInt(t[r]);if(t.byteLength!==e){let r=new DataView(t.buffer,t.byteOffset,t.byteLength),s=(o,i)=>{let a=i-o;if(a<=40){let d=r.getBigUint64(o);for(let f=o+8;f<i;f+=8)d<<=BigInt(64),d|=r.getBigUint64(f);return d}let c=o+(a>>4<<3),u=s(o,c),l=s(c,i);return u<<BigInt((i-c)*8)|l};n=n<<BigInt((r.byteLength-e)*8)|s(e,r.byteLength)}return n};var Ib={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError=="function"?AggregateError:null};Yt[101]=()=>{let t=ot();if(!Ib[t[0]]){let e=Error(t[1],{cause:t[2]});return e.name=t[0],e}return Ib[t[0]](t[1],{cause:t[2]})};Yt[105]=t=>{if(Le.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=ve.getUint32(O-4);Dr||(Dr=new Map);let n=Z[O],r;n>=144&&n<160||n==220||n==221?r=[]:n>=128&&n<144||n==222||n==223?r=new Map:(n>=199&&n<=201||n>=212&&n<=216)&&Z[O+1]===115?r=new Set:r={};let s={target:r};Dr.set(e,s);let o=ot();if(s.used)Object.assign(r,o);else return s.target=o;if(r instanceof Map)for(let[i,a]of o.entries())r.set(i,a);if(r instanceof Set)for(let i of Array.from(o))r.add(i);return r};Yt[112]=t=>{if(Le.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=ve.getUint32(O-4),n=Dr.get(e);return n.used=!0,n.target};Yt[115]=()=>new Set(ot());var Rp=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(t=>t+"Array"),BP=typeof globalThis=="object"?globalThis:window;Yt[116]=t=>{let e=t[0],n=Uint8Array.prototype.slice.call(t,1).buffer,r=Rp[e];if(!r){if(e===16)return n;if(e===17)return new DataView(n);throw new Error("Could not find typed array for code "+e)}return new BP[r](n)};Yt[120]=()=>{let t=ot();return new RegExp(t[0],t[1])};var LP=[];Yt[98]=t=>{let e=(t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3],n=O;return O+=e-t.length,_t=LP,_t=[Mb(),Mb()],_t.position0=0,_t.position1=0,_t.postBundlePosition=O,O=n,ot()};Yt[255]=t=>t.length==4?new Date((t[0]*16777216+(t[1]<<16)+(t[2]<<8)+t[3])*1e3):t.length==8?new Date(((t[0]<<22)+(t[1]<<14)+(t[2]<<6)+(t[3]>>2))/1e6+((t[3]&3)*4294967296+t[4]*16777216+(t[5]<<16)+(t[6]<<8)+t[7])*1e3):t.length==12?new Date(((t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3])/1e6+((t[4]&128?-281474976710656:0)+t[6]*1099511627776+t[7]*4294967296+t[8]*16777216+(t[9]<<16)+(t[10]<<8)+t[11])*1e3):new Date("invalid");function zb(t){Le&&Le._onSaveState&&Le._onSaveState();let e=_n,n=O,r=bp,s=xn,o=dr,i=hs,a=gp,c=Dr,u=_t,l=new Uint8Array(Z.slice(0,_n)),d=Ce,f=Ce.slice(0,Ce.length),h=Le,p=ms,y=t();return _n=e,O=n,bp=r,xn=s,dr=o,hs=i,gp=a,Dr=c,_t=u,Z=l,ms=p,Ce=d,Ce.splice(0,Ce.length,...f),Le=h,ve=new DataView(Z.buffer,Z.byteOffset,Z.byteLength),y}function fl(){Z=null,Dr=null,Ce=null}var pl=new Array(147);for(let t=0;t<256;t++)pl[t]=+("1e"+Math.floor(45.15-t*.30103));var hl=new ys({useRecords:!1}),ml=hl.unpack,FP=hl.unpackMultiple,zP=hl.unpack,yl={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},UP=new Float32Array(1),_L=new Uint8Array(UP.buffer,0,4);ys.SUPPORTS_STRUCT_HOOKS=!0;var bl;try{bl=new TextEncoder}catch{}var Ap,Pp,di=typeof Buffer<"u",gl=di?function(t){return Buffer.allocUnsafeSlow(t)}:Uint8Array,$b=di?Buffer:Uint8Array,Ub=di?4294967296:2144337920,F,Ga,je,D=0,Ot,Ze=null,VP=21760,HP=/[\u0080-\uFFFF]/,li=Symbol("record-id"),gs=class extends ys{constructor(e){super(e),this.offset=0;let n,r,s,o,i,a=$b.prototype.utf8Write?function(v,$){return F.utf8Write(v,$,F.byteLength-$)}:bl&&bl.encodeInto?function(v,$){return bl.encodeInto(v,F.subarray($)).written}:!1,c=this;e||(e={});let u=e&&e.sequential,l=e.structures||e.saveStructures,d=e.maxSharedStructures;if(d==null&&(d=l?32:0),d>8160)throw new Error("Maximum maxSharedStructure is 8160");e.structuredClone&&e.moreTypes==null&&(this.moreTypes=!0);let f=e.maxOwnStructures;f==null&&(f=l?32:64),!this.structures&&e.useRecords!=!1&&(this.structures=[]);let h=d>32||f+d>64,p=d+64,y=d+f+64;if(y>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let S=[],b=0,x=0;this.pack=this.encode=function(v,$){if(F||(F=new gl(8192),je=F.dataView||(F.dataView=new DataView(F.buffer,0,8192)),D=0),Ot=F.length-10,Ot-D<2048?(F=new gl(F.length),je=F.dataView||(F.dataView=new DataView(F.buffer,0,F.length)),Ot=F.length-10,D=0):D=D+7&2147483640,r=D,$&fi&&(D+=$&255),i=c.structuredClone?new Map:null,c.bundleStrings&&typeof v!="string"?(Ze=[],Ze.size=1/0):Ze=null,o=c.structures,o){o.uninitialized&&(o=c._mergeStructures(c.getStructures()));let W=o.sharedLength||0;if(W>d)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+o.sharedLength);if(!o.transitions){o.transitions=Object.create(null);for(let q=0;q<W;q++){let ae=o[q];if(!ae)continue;let ce,ne=o.transitions;for(let Re=0,oe=ae.length;Re<oe;Re++){let ee=ae[Re];ce=ne[ee],ce||(ce=ne[ee]=Object.create(null)),ne=ce}ne[li]=q+64}this.lastNamedStructuresLength=W}u||(o.nextId=W+64)}s&&(s=!1);let G;try{c._writeStruct&&v&&typeof v=="object"?v.constructor===Object?K(v):v.constructor!==Map&&!Array.isArray(v)&&!Pp.some(q=>v instanceof q)?K(v.toJSON?v.toJSON():v):E(v):E(v);let W=Ze;if(Ze&&Hb(r,E,0),i&&i.idsToInsert){let q=i.idsToInsert.sort((Re,oe)=>Re.offset>oe.offset?1:-1),ae=q.length,ce=-1;for(;W&&ae>0;){let Re=q[--ae].offset+r;Re<W.stringsPosition+r&&ce===-1&&(ce=0),Re>W.position+r?ce>=0&&(ce+=6):(ce>=0&&(je.setUint32(W.position+r,je.getUint32(W.position+r)+ce),ce=-1),W=W.previous,ae++)}ce>=0&&W&&je.setUint32(W.position+r,je.getUint32(W.position+r)+ce),D+=q.length*6,D>Ot&&j(D),c.offset=D;let ne=$P(F.subarray(r,D),q);return i=null,ne}return c.offset=D,$&Wb?(F.start=r,F.end=D,F):F.subarray(r,D)}catch(W){throw G=W,W}finally{if(o&&(R(),s&&c.saveStructures)){let W=o.sharedLength||0,q=F.subarray(r,D),ae=(c._prepareStructures||jP)(o,c);if(!G)return c.saveStructures(ae,ae.isCompatible)===!1?(o.uninitialized=!0,c.pack(v,$)):(c.lastNamedStructuresLength=W,F.length>1073741824&&(F=null),q)}F.length>1073741824&&(F=null),$&qb&&(D=r)}};let R=()=>{x<10&&x++;let v=o.sharedLength||0;if(o.length>v&&!u&&(o.length=v),b>1e4)o.transitions=null,x=0,b=0,S.length>0&&(S=[]);else if(S.length>0&&!u){for(let $=0,G=S.length;$<G;$++)S[$][li]=0;S=[]}},A=v=>{var $=v.length;$<16?F[D++]=144|$:$<65536?(F[D++]=220,F[D++]=$>>8,F[D++]=$&255):(F[D++]=221,je.setUint32(D,$),D+=4);for(let G=0;G<$;G++)E(v[G])},E=v=>{D>Ot&&(F=j(D));var $=typeof v,G;if($==="string"){let W=v.length;if(Ze&&W>=4&&W<4096){if((Ze.size+=W)>VP){let ne,Re=(Ze[0]?Ze[0].length*3+Ze[1].length:0)+10;D+Re>Ot&&(F=j(D+Re));let oe;Ze.position?(oe=Ze,F[D]=200,D+=3,F[D++]=98,ne=D-r,D+=4,Hb(r,E,0),je.setUint16(ne+r-3,D-r-ne)):(F[D++]=214,F[D++]=98,ne=D-r,D+=4),Ze=["",""],Ze.previous=oe,Ze.size=0,Ze.position=ne}let ce=HP.test(v);Ze[ce?0:1]+=v,F[D++]=193,E(ce?-W:W);return}let q;W<32?q=1:W<256?q=2:W<65536?q=3:q=5;let ae=W*3;if(D+ae>Ot&&(F=j(D+ae)),W<64||!a){let ce,ne,Re,oe=D+q;for(ce=0;ce<W;ce++)ne=v.charCodeAt(ce),ne<128?F[oe++]=ne:ne<2048?(F[oe++]=ne>>6|192,F[oe++]=ne&63|128):(ne&64512)===55296&&((Re=v.charCodeAt(ce+1))&64512)===56320?(ne=65536+((ne&1023)<<10)+(Re&1023),ce++,F[oe++]=ne>>18|240,F[oe++]=ne>>12&63|128,F[oe++]=ne>>6&63|128,F[oe++]=ne&63|128):(F[oe++]=ne>>12|224,F[oe++]=ne>>6&63|128,F[oe++]=ne&63|128);G=oe-D-q}else G=a(v,D+q);G<32?F[D++]=160|G:G<256?(q<2&&F.copyWithin(D+2,D+1,D+1+G),F[D++]=217,F[D++]=G):G<65536?(q<3&&F.copyWithin(D+3,D+2,D+2+G),F[D++]=218,F[D++]=G>>8,F[D++]=G&255):(q<5&&F.copyWithin(D+5,D+3,D+3+G),F[D++]=219,je.setUint32(D,G),D+=4),D+=G}else if($==="number")if(v>>>0===v)v<32||v<128&&this.useRecords===!1||v<64&&!this._writeStruct?F[D++]=v:v<256?(F[D++]=204,F[D++]=v):v<65536?(F[D++]=205,F[D++]=v>>8,F[D++]=v&255):(F[D++]=206,je.setUint32(D,v),D+=4);else if(v>>0===v)v>=-32?F[D++]=256+v:v>=-128?(F[D++]=208,F[D++]=v+256):v>=-32768?(F[D++]=209,je.setInt16(D,v),D+=2):(F[D++]=210,je.setInt32(D,v),D+=4);else{let W;if((W=this.useFloat32)>0&&v<4294967296&&v>=-2147483648){F[D++]=202,je.setFloat32(D,v);let q;if(W<4||(q=v*pl[(F[D]&127)<<1|F[D+1]>>7])>>0===q){D+=4;return}else D--}F[D++]=203,je.setFloat64(D,v),D+=8}else if($==="object"||$==="function")if(!v)F[D++]=192;else{if(i){let q=i.get(v);if(q){if(!q.id){let ae=i.idsToInsert||(i.idsToInsert=[]);q.id=ae.push(q)}F[D++]=214,F[D++]=112,je.setUint32(D,q.id),D+=4;return}else i.set(v,{offset:D-r})}let W=v.constructor;if(W===Object)B(v);else if(W===Array)A(v);else if(W===Map)if(this.mapAsEmptyObject)F[D++]=128;else{G=v.size,G<16?F[D++]=128|G:G<65536?(F[D++]=222,F[D++]=G>>8,F[D++]=G&255):(F[D++]=223,je.setUint32(D,G),D+=4);for(let[q,ae]of v)E(q),E(ae)}else{for(let q=0,ae=Ap.length;q<ae;q++){let ce=Pp[q];if(v instanceof ce){let ne=Ap[q];if(ne.write){ne.type&&(F[D++]=212,F[D++]=ne.type,F[D++]=0);let Ae=ne.write.call(this,v);Ae===v?Array.isArray(v)?A(v):B(v):E(Ae);return}let Re=F,oe=je,ee=D;F=null;let ue;try{ue=ne.pack.call(this,v,Ae=>(F=Re,Re=null,D+=Ae,D>Ot&&j(D),{target:F,targetView:je,position:D-Ae}),E)}finally{Re&&(F=Re,je=oe,D=ee,Ot=F.length-10)}ue&&(ue.length+D>Ot&&j(ue.length+D),D=Vb(ue,F,D,ne.type));return}}if(Array.isArray(v))A(v);else{if(v.toJSON){let q=v.toJSON();if(q!==v)return E(q)}if($==="function")return E(this.writeFunction&&this.writeFunction(v));B(v)}}}else if($==="boolean")F[D++]=v?195:194;else if($==="bigint"){if(v<9223372036854776e3&&v>=-9223372036854776e3)F[D++]=211,je.setBigInt64(D,v);else if(v<18446744073709552e3&&v>0)F[D++]=207,je.setBigUint64(D,v);else if(this.largeBigIntToFloat)F[D++]=203,je.setFloat64(D,Number(v));else{if(this.largeBigIntToString)return E(v.toString());if(this.useBigIntExtension||this.moreTypes){let W=v<0?BigInt(-1):BigInt(0),q;if(v>>BigInt(65536)===W){let ae=BigInt(18446744073709552e3)-BigInt(1),ce=[];for(;ce.push(v&ae),v>>BigInt(63)!==W;)v>>=BigInt(64);q=new Uint8Array(new BigUint64Array(ce).buffer),q.reverse()}else{let ae=v<0,ce=(ae?~v:v).toString(16);if(ce.length%2?ce="0"+ce:parseInt(ce.charAt(0),16)>=8&&(ce="00"+ce),di)q=Buffer.from(ce,"hex");else{q=new Uint8Array(ce.length/2);for(let ne=0;ne<q.length;ne++)q[ne]=parseInt(ce.slice(ne*2,ne*2+2),16)}if(ae)for(let ne=0;ne<q.length;ne++)q[ne]=~q[ne]}q.length+D>Ot&&j(q.length+D),D=Vb(q,F,D,66);return}else throw new RangeError(v+" 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")}D+=8}else if($==="undefined")this.encodeUndefinedAsNil?F[D++]=192:(F[D++]=212,F[D++]=0,F[D++]=0);else throw new Error("Unknown type: "+$)},P=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?v=>{let $;if(this.skipValues){$=[];for(let q in v)(typeof v.hasOwnProperty!="function"||v.hasOwnProperty(q))&&!this.skipValues.includes(v[q])&&$.push(q)}else $=Object.keys(v);let G=$.length;G<16?F[D++]=128|G:G<65536?(F[D++]=222,F[D++]=G>>8,F[D++]=G&255):(F[D++]=223,je.setUint32(D,G),D+=4);let W;if(this.coercibleKeyAsNumber)for(let q=0;q<G;q++){W=$[q];let ae=Number(W);E(isNaN(ae)?W:ae),E(v[W])}else for(let q=0;q<G;q++)E(W=$[q]),E(v[W])}:v=>{F[D++]=222;let $=D-r;D+=2;let G=0;for(let W in v)(typeof v.hasOwnProperty!="function"||v.hasOwnProperty(W))&&(E(W),E(v[W]),G++);if(G>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');F[$+++r]=G>>8,F[$+r]=G&255},k=this.useRecords===!1?P:e.progressiveRecords&&!h?v=>{let $,G=o.transitions||(o.transitions=Object.create(null)),W=D++-r,q;for(let ae in v)if(typeof v.hasOwnProperty!="function"||v.hasOwnProperty(ae)){if($=G[ae],$)G=$;else{let ce=Object.keys(v),ne=G;G=o.transitions;let Re=0;for(let oe=0,ee=ce.length;oe<ee;oe++){let ue=ce[oe];$=G[ue],$||($=G[ue]=Object.create(null),Re++),G=$}W+r+1==D?(D--,L(G,ce,Re)):se(G,ce,W,Re),q=!0,G=ne[ae]}E(v[ae])}if(!q){let ae=G[li];ae?F[W+r]=ae:se(G,Object.keys(v),W,0)}}:v=>{let $,G=o.transitions||(o.transitions=Object.create(null)),W=0;for(let ae in v)(typeof v.hasOwnProperty!="function"||v.hasOwnProperty(ae))&&($=G[ae],$||($=G[ae]=Object.create(null),W++),G=$);let q=G[li];q?q>=96&&h?(F[D++]=((q-=96)&31)+96,F[D++]=q>>5):F[D++]=q:L(G,G.__keys__||Object.keys(v),W);for(let ae in v)(typeof v.hasOwnProperty!="function"||v.hasOwnProperty(ae))&&E(v[ae])},M=typeof this.useRecords=="function"&&this.useRecords,B=M?v=>{M(v)?k(v):P(v)}:k,K=v=>{let $=c._writeStruct(v,F,r,D,o,j,(G,W,q)=>{if(q)return s=!0;D=W;let ae=F;return E(G),R(),ae!==F?{position:D,targetView:je,target:F}:D});if($===0)return B(v);D=$},j=v=>{let $;if(v>16777216){if(v-r>Ub)throw new Error("Packed buffer would be larger than maximum buffer size");$=Math.min(Ub,Math.round(Math.max((v-r)*(v>67108864?1.25:2),4194304)/4096)*4096)}else $=(Math.max(v-r<<2,F.length-1)>>12)+1<<12;let G=new gl($);return je=G.dataView||(G.dataView=new DataView(G.buffer,0,$)),v=Math.min(v,F.length),F.copy?F.copy(G,0,r,v):G.set(F.slice(r,v)),D-=r,r=0,Ot=G.length-10,F=G},L=(v,$,G)=>{let W=o.nextId;W||(W=64),W<p&&this.shouldShareStructure&&!this.shouldShareStructure($)?(W=o.nextOwnId,W<y||(W=p),o.nextOwnId=W+1):(W>=y&&(W=p),o.nextId=W+1);let q=$.highByte=W>=96&&h?W-96>>5:-1;v[li]=W,v.__keys__=$,o[W-64]=$,W<p?($.isShared=!0,o.sharedLength=W-63,s=!0,q>=0?(F[D++]=(W&31)+96,F[D++]=q):F[D++]=W):(q>=0?(F[D++]=213,F[D++]=114,F[D++]=(W&31)+96,F[D++]=q):(F[D++]=212,F[D++]=114,F[D++]=W),G&&(b+=x*G),S.length>=f&&(S.shift()[li]=0),S.push(v),E($))},se=(v,$,G,W)=>{let q=F,ae=D,ce=Ot,ne=r;F=Ga,D=0,r=0,F||(Ga=F=new gl(8192)),Ot=F.length-10,L(v,$,W),Ga=F;let Re=D;if(F=q,D=ae,Ot=ce,r=ne,Re>1){let oe=D+Re-1;oe>Ot&&j(oe);let ee=G+r;F.copyWithin(ee+Re,ee+1,D),F.set(Ga.slice(0,Re),ee),D=oe}else F[G+r]=Ga[0]}}useBuffer(e){F=e,F.dataView||(F.dataView=new DataView(F.buffer,F.byteOffset,F.byteLength)),je=F.dataView,D=0}set position(e){D=e}get position(){return D}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}};Pp=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,Wa];Ap=[{pack(t,e,n){let r=t.getTime()/1e3;if((this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:s,targetView:o,position:i}=e(6);s[i++]=214,s[i++]=255,o.setUint32(i,r)}else if(r>0&&r<4294967296){let{target:s,targetView:o,position:i}=e(10);s[i++]=215,s[i++]=255,o.setUint32(i,t.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),o.setUint32(i+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return e(0),n(this.onInvalidDate());let{target:s,targetView:o,position:i}=e(3);s[i++]=212,s[i++]=255,s[i++]=255}else{let{target:s,targetView:o,position:i}=e(15);s[i++]=199,s[i++]=12,s[i++]=255,o.setUint32(i,t.getMilliseconds()*1e6),o.setBigInt64(i+4,BigInt(Math.floor(r)))}}},{pack(t,e,n){if(this.setAsEmptyObject)return e(0),n({});let r=Array.from(t),{target:s,position:o}=e(this.moreTypes?3:0);this.moreTypes&&(s[o++]=212,s[o++]=115,s[o++]=0),n(r)}},{pack(t,e,n){let{target:r,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(r[s++]=212,r[s++]=101,r[s++]=0),n([t.name,t.message,t.cause])}},{pack(t,e,n){let{target:r,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(r[s++]=212,r[s++]=120,r[s++]=0),n([t.source,t.flags])}},{pack(t,e){this.moreTypes?Ep(t,16,e):kp(di?Buffer.from(t):new Uint8Array(t),e)}},{pack(t,e){let n=t.constructor;n!==$b&&this.moreTypes?Ep(t,Rp.indexOf(n.name),e):kp(t,e)}},{pack(t,e){this.moreTypes?Ep(t,17,e):kp(di?Buffer.from(t):new Uint8Array(t),e)}},{pack(t,e){let{target:n,position:r}=e(1);n[r]=193}}];function Ep(t,e,n,r){let s=t.byteLength;if(s+1<256){var{target:o,position:i}=n(4+s);o[i++]=199,o[i++]=s+1}else if(s+1<65536){var{target:o,position:i}=n(5+s);o[i++]=200,o[i++]=s+1>>8,o[i++]=s+1&255}else{var{target:o,position:i,targetView:a}=n(7+s);o[i++]=201,a.setUint32(i,s+1),i+=4}o[i++]=116,o[i++]=e,t.buffer||(t=new Uint8Array(t)),o.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i)}function kp(t,e){let n=t.byteLength;var r,s;if(n<256){var{target:r,position:s}=e(n+2);r[s++]=196,r[s++]=n}else if(n<65536){var{target:r,position:s}=e(n+3);r[s++]=197,r[s++]=n>>8,r[s++]=n&255}else{var{target:r,position:s,targetView:o}=e(n+5);r[s++]=198,o.setUint32(s,n),s+=4}r.set(t,s)}function Vb(t,e,n,r){let s=t.length;switch(s){case 1:e[n++]=212;break;case 2:e[n++]=213;break;case 4:e[n++]=214;break;case 8:e[n++]=215;break;case 16:e[n++]=216;break;default:s<256?(e[n++]=199,e[n++]=s):s<65536?(e[n++]=200,e[n++]=s>>8,e[n++]=s&255):(e[n++]=201,e[n++]=s>>24,e[n++]=s>>16&255,e[n++]=s>>8&255,e[n++]=s&255)}return e[n++]=r,e.set(t,n),n+=s,n}function $P(t,e){let n,r=e.length*6,s=t.length-r;for(;n=e.pop();){let o=n.offset,i=n.id;t.copyWithin(o+r,o,s),r-=6;let a=o+r;t[a++]=214,t[a++]=105,t[a++]=i>>24,t[a++]=i>>16&255,t[a++]=i>>8&255,t[a++]=i&255,s=o}return t}function Hb(t,e,n){if(Ze.length>0){je.setUint32(Ze.position+t,D+n-Ze.position-t),Ze.stringsPosition=D-t;let r=Ze;Ze=null,e(r[0]),e(r[1])}}function jP(t,e){return t.isCompatible=n=>{let r=!n||(e.lastNamedStructuresLength||0)===n.length;return r||e._mergeStructures(n),r},t}gs.SUPPORTS_STRUCT_HOOKS=!0;var jb=new gs({useRecords:!1}),WP=jb.pack,qP=jb.pack;var{NEVER:GP,ALWAYS:YP,DECIMAL_ROUND:KP,DECIMAL_FIT:XP}=yl,Wb=512,qb=1024,fi=2048;Pt();Pr();var JP=9,wl=class{constructor(){m(this,"pending",new Uint8Array(0))}push(e){if(!e||e.byteLength===0)return[];let n=this.pending.byteLength===0?e:ZP(this.pending,e),r=[],s=0;for(;s<n.byteLength;){let o={offset:s},i;try{i=Pe.number(n,o)}catch(c){if(n.byteLength-s<=JP)break;throw c}let a=o.offset+i;if(a>n.byteLength)break;r.push(n.subarray(o.offset,a)),s=a}return this.pending=s<n.byteLength?n.slice(s):new Uint8Array(0),r}};function ZP(t,e){let n=new Uint8Array(t.byteLength+e.byteLength);return n.set(t,0),n.set(e,t.byteLength),n}var Ya=class{constructor(e){m(this,"wt");m(this,"url");m(this,"isOpen",!1);m(this,"events");m(this,"reader");m(this,"writer");m(this,"unreliableReader");m(this,"unreliableWriter");m(this,"lengthPrefixBuffer",new Uint8Array(9));m(this,"reliableReassembler",new wl);m(this,"unreliableReassembler",new wl);this.events=e}connect(e,n={}){this.url=e;let r=n.fingerprint&&{serverCertificateHashes:[{algorithm:"sha-256",value:new Uint8Array(n.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 o=this.wt.datagrams;this.unreliableWriter=(o.createWritable?o.createWritable():o.writable).getWriter(),this.wt.incomingBidirectionalStreams.getReader().read().then(a=>{this.reader=a.value.readable.getReader(),this.writer=a.value.writable.getWriter(),this.sendSeatReservation(n.roomId,n.sessionId,n.reconnectionToken,n.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 n=e instanceof Uint8Array?e:new Uint8Array(e),r=Se.number(this.lengthPrefixBuffer,n.length,{offset:0}),s=new Uint8Array(r+n.length);return s.set(this.lengthPrefixBuffer.subarray(0,r),0),s.set(n,r),s}close(e,n){this.isOpen=!1;try{let r=this.wt?.close({closeCode:e,reason:n});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,n,r){for(;this.isOpen;){let s;try{s=await e.read()}catch(o){await this.onChannelFailure(r,o);return}if(s.done||!s.value)return;for(let o of n.push(s.value))this.events.onmessage({data:o})}}async onChannelFailure(e,n){await new Promise(r=>setTimeout(r,0)),this.isOpen&&(console.error(`H3Transport: stopped reading the ${e} channel while the session was open`,n),this.close(St.ABNORMAL_CLOSURE,`h3 ${e} channel failed`))}sendSeatReservation(e,n,r,s){let o={offset:0},i=[];Se.string(i,e,o),Se.string(i,n,o),r&&Se.string(i,r,o),s&&Se.boolean(i,1,o),this.writer.write(new Uint8Array(i).buffer)}_close(){this.isOpen=!1}};var Xb=lE(Yb(),1);Pr();var Tp=globalThis.WebSocket||Xb.default,Kb=!1,Sl=class{constructor(e){m(this,"ws");m(this,"protocols");m(this,"events");this.events=e}send(e){this.ws.send(e)}sendUnreliable(e){Kb||(Kb=!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,n){try{this.ws=new Tp(e,{headers:n,protocols:this.protocols})}catch{this.ws=new Tp(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,n){e===St.MAY_TRY_RECONNECT&&this.events.onclose&&(this.ws.onclose=null,this.events.onclose({code:e,reason:n})),this.ws.close(e,n)}get isOpen(){return this.ws.readyState===Tp.OPEN}};Pr();var Ka=[],vp=typeof addEventListener=="function"&&typeof removeEventListener=="function";vp&&addEventListener("offline",()=>{console.warn(`@colyseus/sdk: \u{1F6D1} Network offline. Closing ${Ka.length} connection(s)`),Ka.forEach(t=>t())},!1);var Xa,pi=class{constructor(e){m(this,"transport");m(this,"events",{});m(this,"url");m(this,"options");He(this,Xa,vp?()=>this.close(St.MAY_TRY_RECONNECT):null);e==="h3"?this.transport=new Ya(this.events):this.transport=new Sl(this.events)}connect(e,n){if(vp){let r=this.events.onopen;this.events.onopen=o=>{Ka.push(de(this,Xa)),r?.(o)};let s=this.events.onclose;this.events.onclose=o=>{Ka.splice(Ka.indexOf(de(this,Xa)),1),s?.(o)}}this.url=e,this.options=n,this.transport.connect(e,n)}send(e){this.transport.send(e)}sendUnreliable(e){this.transport.sendUnreliable(e)}reconnect(e){if(this.transport instanceof Ya){this.transport.connect(this.url,{...this.options,...e});return}let n=new URL(this.url);for(let r in e)n.searchParams.set(r,e[r]);this.transport.connect(n.toString(),this.options)}close(e,n){this.transport.close(e,n)}get isOpen(){return this.transport.isOpen}};Xa=new WeakMap;var Jb={};function Mp(t,e){Jb[t]=e}function Cp(t){let e=Jb[t];if(!e)throw new Error("missing serializer: "+t);return e}var xl=()=>({emit(t,...e){let n=this.events[t]||[];for(let r=0,s=n.length;r<s;r++)n[r](...e)},events:{},on(t,e){return this.events[t]?.push(e)||(this.events[t]=[e]),()=>{this.events[t]=this.events[t]?.filter(n=>e!==n)}}});var Zb=new WeakMap,Op=class{constructor(){m(this,"handlers",[])}register(e,n=!1){return this.handlers.push(e),this}invoke(...e){let n=this.handlers;for(let r=0,s=n.length;r<s;r++)n[r].apply(this,e)}invokeAsync(...e){return Promise.all(this.handlers.map(n=>n.apply(this,e)))}remove(e){let n=this.handlers.indexOf(e);n===-1&&(n=this.handlers.findIndex(r=>Zb.get(r)===e)),n!==-1&&(this.handlers=this.handlers.filter((r,s)=>s!==n))}clear(){this.handlers=[]}};function eo(){let t=new Op;function e(n){return t.register(n,this===null)}return e.once=n=>{let r=function(...s){t.remove(r),n.apply(this,s)};Zb.set(r,n),t.register(r)},e.remove=n=>t.remove(n),e.invoke=(...n)=>t.invoke(...n),e.invokeAsync=(...n)=>t.invokeAsync(...n),e.clear=()=>t.clear(),e}Pt();function Ja(t){try{return Gu(t.serializer.decoder)}catch{return}}var hi=class{constructor(){m(this,"state");m(this,"decoder")}setState(e,n){this.decoder.root.refs.size>1&&typeof this.decoder.decodeResync=="function"?this.decoder.decodeResync(e,n):this.decoder.decode(e,n)}getState(){return this.state}patch(e,n){return this.decoder.decode(e,n)}teardown(){this.decoder.root.clearRefs()}handshake(e,n){this.state?(zn.decode(e,n),this.decoder=new Fn(this.state)):(this.decoder=zn.decode(e,n),this.state=this.decoder.state)}};ul();function Qb(){return{enabled:!0,retryCount:0,maxRetries:15,delay:100,minDelay:100,maxDelay:5e3,minUptime:5e3,backoff:QP,maxEnqueuedMessages:10,enqueuedMessages:[],isReconnecting:!1}}var QP=(t,e)=>Math.floor(Math.pow(2,t)*e);function _l(t,e){t.reconnection.enqueuedMessages.push({data:e}),t.reconnection.enqueuedMessages.length>t.reconnection.maxEnqueuedMessages&&t.reconnection.enqueuedMessages.shift()}function e0(t,e){if(!e){let r=new Error("request rejected");return r.name="rejected",r.reason=t,r}let n=new Error(t?.message??"request failed");return t?.name&&(n.name=t.name),t?.code!==void 0&&(n.code=t.code),n}Ia();var Qa,mi,yi,fr,pr,gi,hr,t0,n0,r0,s0,Rl=class Rl{constructor(e,n){He(this,hr);m(this,"roomId");m(this,"sessionId");m(this,"reconnectionToken");m(this,"name");m(this,"connection");m(this,"onStateChange",eo());m(this,"onError",eo());m(this,"onLeave",eo());m(this,"onReconnect",eo());m(this,"onDrop",eo());m(this,"onJoin",eo());m(this,"serializerId");m(this,"serializer");m(this,"reconnection",Qb());m(this,"joinedAtTime",0);m(this,"clock",ii);m(this,"onMessageHandlers",xl());m(this,"packr");m(this,"sharedBuffer");He(this,Qa,0);He(this,mi);He(this,yi,0);He(this,fr,new Map);He(this,pr);He(this,gi,0);if(this.name=e,this.packr=new gs,this.sharedBuffer=new Uint8Array(8192),n){let r=new(Cp("schema"));this.serializer=r;let s=new n;r.state=s,r.decoder=new Fn(s)}this.onLeave(()=>{this.removeAllListeners(),this.destroy()})}connect(e,n,r){this.connection=new pi(n.protocol),this.connection.events.onmessage=this.onMessageCallback.bind(this),this.connection.events.onclose=o=>{if(zs(this,hr,r0).call(this,"connection closed before a response was received."),this.joinedAtTime===0){console.warn?.(`Room connection was closed unexpectedly (${o.code}): ${o.reason}`),this.onError.invoke(o.code,o.reason);return}o.code===St.NO_STATUS_RECEIVED||o.code===St.ABNORMAL_CLOSURE||o.code===St.GOING_AWAY||o.code===St.MAY_TRY_RECONNECT?(this.onDrop.invoke(o.code,o.reason),this.handleReconnection(o.code,o.reason)):this.onLeave.invoke(o.code,o.reason)},this.connection.events.onerror=o=>{this.onError.invoke(o.code,o.reason)};let s=this.serializer?.getState()!==void 0;if(n.protocol==="h3"){let o=new URL(e);this.connection.connect(o.origin,{...n,skipHandshake:s})}else this.connection.connect(`${e}${s?"&skipHandshake=1":""}`,r)}leave(e=!0){return new Promise(n=>{this.onLeave(r=>n(r)),this.connection?e?(this.sharedBuffer[0]=Ke.LEAVE_ROOM,this.connection.send(this.sharedBuffer.subarray(0,1))):this.connection.close():this.onLeave.invoke(St.CONSENTED)})}onMessage(e,n){return this.onMessageHandlers.on(this.getMessageHandlerKey(e),n)}ping(e){this.connection?.isOpen&&($e(this,Qa,Ct()),$e(this,mi,e),this.sharedBuffer[0]=Ke.PING,this.connection.send(this.sharedBuffer.subarray(0,1)))}send(e,n,r){if(r!==void 0){this.request(e,n).then(a=>r(a,void 0),a=>r(void 0,a));return}let s={offset:1};this.sharedBuffer[0]=Ke.ROOM_DATA,typeof e=="string"?Se.string(this.sharedBuffer,e,s):Se.number(this.sharedBuffer,e,s);let o=s.offset,i;n!==void 0?(i=this.packr.pack(n,fi|o),i.set(this.sharedBuffer.subarray(0,o),0)):i=this.sharedBuffer.subarray(0,o),this.connection.isOpen?this.connection.send(i):_l(this,new Uint8Array(i))}request(e,n,r){if(!this.connection.isOpen)return Promise.reject(new Error(`cannot send request "${e}": connection is not open.`));let s=r?.timeout??Rl.defaultRequestTimeout;return new Promise((o,i)=>{let a,c=this.sendRequest(e,n,{mode:r?.mode},(u,l,d)=>{clearTimeout(a),u?o(l):i(e0(l,d))},u=>{clearTimeout(a),i(new Error(u))});a=setTimeout(()=>{this.cancelRequest(c),i(new Error(`request "${e}" timed out after ${s}ms.`))},s)})}sendRequest(e,n,r,s,o){let i=zs(this,hr,t0).call(this),a=zs(this,hr,n0).call(this,i,e,n);if(r.mode==="unreliable"){if(!this.connection.isOpen)return-1;this.connection.sendUnreliable(a)}else this.connection.isOpen?this.connection.send(a):_l(this,new Uint8Array(a));return de(this,fr).set(i,{onReply:s,onClose:o}),i}cancelRequest(e){de(this,fr).delete(e)}sendUnreliable(e,n){if(!this.connection.isOpen)return;let r={offset:1};this.sharedBuffer[0]=Ke.ROOM_DATA,typeof e=="string"?Se.string(this.sharedBuffer,e,r):Se.number(this.sharedBuffer,e,r);let s=r.offset,o;n!==void 0?(o=this.packr.pack(n,fi|s),o.set(this.sharedBuffer.subarray(0,s),0)):o=this.sharedBuffer.subarray(0,s),this.connection.sendUnreliable(o)}sendBytes(e,n){let r={offset:1};this.sharedBuffer[0]=Ke.ROOM_DATA_BYTES,typeof e=="string"?Se.string(this.sharedBuffer,e,r):Se.number(this.sharedBuffer,e,r);let s=r.offset;if(s+n.byteLength>this.sharedBuffer.byteLength){let o=new Uint8Array(s+n.byteLength);o.set(this.sharedBuffer.subarray(0,s)),this.sharedBuffer=o}this.sharedBuffer.set(n,s),this.connection.isOpen?this.connection.send(this.sharedBuffer.subarray(0,s+n.byteLength)):_l(this,this.sharedBuffer.subarray(0,s+n.byteLength))}input(e){return(de(this,pr)??$e(this,pr,new ui(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 hi&&(this.serializer.decoder.root.callbacks={})}onMessageCallback(e){zs(this,hr,s0).call(this,new Uint8Array(e.data))}dispatchMessage(e,n){let r=this.getMessageHandlerKey(e);this.onMessageHandlers.events[r]?this.onMessageHandlers.emit(r,n):this.onMessageHandlers.events["*"]?this.onMessageHandlers.emit("*",e,n):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,n){if(!this.reconnection.enabled){this.onLeave.invoke(e,n);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(St.ABNORMAL_CLOSURE,"Room uptime too short for reconnection.");return}this.reconnection.isReconnecting||(this.reconnection.retryCount=0,this.reconnection.isReconnecting=!0,de(this,pr)?.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(St.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)}};Qa=new WeakMap,mi=new WeakMap,yi=new WeakMap,fr=new WeakMap,pr=new WeakMap,gi=new WeakMap,hr=new WeakSet,t0=function(){let e=de(this,yi);return $e(this,yi,de(this,yi)+1>>>0),e},n0=function(e,n,r){let s={offset:1};this.sharedBuffer[0]=Ke.ROOM_REQUEST,Se.number(this.sharedBuffer,e,s),typeof n=="string"?Se.string(this.sharedBuffer,n,s):Se.number(this.sharedBuffer,n,s);let o=s.offset;if(r!==void 0){let i=this.packr.pack(r,fi|o);return i.set(this.sharedBuffer.subarray(0,o),0),i}return this.sharedBuffer.subarray(0,o)},r0=function(e){if(de(this,fr).size!==0){for(let n of de(this,fr).values())n.onClose?.(e);de(this,fr).clear()}},s0=function(e){var o;let n={offset:1},r=e[0],s=r&Hf;if(r&Zo.TIMED){let i=Pe.uint32(e,n),a=Pe.uint32(e,n),c=de(this,pr)?de(this,pr).ackInput(a):-1;this.clock.sample(i,c)}if(s===Ke.JOIN_ROOM){let i=Pe.utf8Read(e,n,e[n.offset++]);if(this.serializerId=Pe.utf8Read(e,n,e[n.offset++]),!this.serializer){let u=Cp(this.serializerId);this.serializer=new u}let a=Pe.number(e,n);if(a>0&&this.serializer.handshake){let u=n.offset+a;this.serializer.handshake(e.subarray(0,u),n),n.offset=u}for(;n.offset<e.byteLength;){let u=e[n.offset++],l=Pe.number(e,n),d=n.offset+l;u===Ou.INPUT_REFLECTION?(de(this,pr)??$e(this,pr,new ui(this))).applyReflection(e,n,d):u===Ou.INPUT_OPTIONS&&(de(this,pr)??$e(this,pr,new ui(this))).applyOptions(e,n),n.offset=d}let c=de(this,pr)?.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}:${i}`,this.sharedBuffer[0]=Ke.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===Ke.ERROR){let i=Pe.number(e,n),a=Pe.string(e,n);this.onError.invoke(i,a)}else if(s===Ke.LEAVE_ROOM)this.leave();else if(s===Ke.ROOM_STATE)$e(this,gi,0),this.serializer.setState(e,n),this.onStateChange.invoke(this.serializer.getState());else if(s===Ke.ROOM_STATE_PATCH){if(r&Zo.UNRELIABLE){let i=Pe.uint16(e,n);if(i-de(this,gi)<<16>>16<=0)return;$e(this,gi,i)}this.serializer.patch(e,n),this.onStateChange.invoke(this.serializer.getState())}else if(s===Ke.ROOM_DATA){let i=Pe.stringCheck(e,n)?Pe.string(e,n):Pe.number(e,n),a=e.byteLength>n.offset?ml(e,{start:n.offset}):void 0;this.dispatchMessage(i,a)}else if(s===Ke.ROOM_DATA_BYTES){let i=Pe.stringCheck(e,n)?Pe.string(e,n):Pe.number(e,n);this.dispatchMessage(i,e.subarray(n.offset))}else if(s===Ke.ROOM_RESPONSE){let i=Pe.number(e,n),a=e[n.offset++],c=e.byteLength>n.offset?ml(e,{start:n.offset}):void 0,u=de(this,fr).get(i);u!==void 0&&(de(this,fr).delete(i),u.onReply(a===Cu.OK,c,a===Cu.ERROR))}else s===Ke.PING&&((o=de(this,mi))==null||o.call(this,Math.round(Ct()-de(this,Qa))),$e(this,mi,void 0))},m(Rl,"defaultRequestTimeout",1e4);var Za=Rl;function o0(t,e){return new Promise((n,r)=>{let s=new XMLHttpRequest,o=e?.method||"GET";s.open(o,t.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 i=new Headers,a=s.getAllResponseHeaders().trim();if(a)for(let u of a.split(/[\r\n]+/)){let l=u.indexOf(": ");l>0&&i.append(u.substring(0,l),u.substring(l+2))}let c=s.response??s.responseText;n(new Ip(c,{status:s.status,statusText:s.statusText,headers:i}))},s.onerror=()=>r(new TypeError("Network request failed")),s.ontimeout=()=>r(new TypeError("Network request timed out")),s.send(e?.body??null)})}var Ip=class{constructor(e,n){m(this,"status");m(this,"statusText");m(this,"headers");m(this,"ok");m(this,"body");this.body=e,this.status=n.status,this.statusText=n.statusText,this.headers=n.headers,this.ok=n.status>=200&&n.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 eT(t){if(t===void 0)return!1;let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(t)?!0:t.buffer?!1:t.constructor&&t.constructor.name==="Object"||typeof t.toJSON=="function"}function tT(t,e){let{params:n,query:r}=e||{},[s,o]=t.split("?"),i=s;if(n)if(Array.isArray(n)){let u=i.split("/").filter(l=>l.startsWith(":"));for(let[l,d]of u.entries()){let f=n[l];i=i.replace(d,f)}}else for(let[u,l]of Object.entries(n))i=i.replace(`:${u}`,String(l));let a=new URLSearchParams(o);if(r)for(let[u,l]of Object.entries(r))l!=null&&a.set(u,String(l));let c=a.toString();return c=c.length>0?`?${c}`.replace(/\+/g,"%20"):"",`${i}${c}`}var El=class{constructor(e,n,r){m(this,"authToken");m(this,"options");m(this,"sdk");m(this,"_fetchFn");m(this,"del",this.delete);this.sdk=e,this.options=n,this._fetchFn=r}get fetchFn(){return this._fetchFn||(this._fetchFn=typeof globalThis.fetch<"u"?globalThis.fetch.bind(globalThis):o0),this._fetchFn}async request(e,n,r){return this.executeRequest(e,n,r)}get(e,n){return this.request("GET",e,n)}post(e,n){return this.request("POST",e,n)}delete(e,n){return this.request("DELETE",e,n)}patch(e,n){return this.request("PATCH",e,n)}put(e,n){return this.request("PUT",e,n)}async executeRequest(e,n,r){let s=this.options.body?{...this.options.body,...r?.body||{}}:r?.body,o=this.options.query?{...this.options.query,...r?.query||{}}:r?.query,i=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}`),eT(s)&&typeof s=="object"&&s!==null){a.has("content-type")||a.set("content-type","application/json");for(let[h,p]of Object.entries(s))p instanceof Date&&(s[h]=p.toISOString());s=JSON.stringify(s)}let c={credentials:r?.credentials||"include",...this.options,...r,query:o,params:i,headers:a,body:s,method:e},u=tT(this.sdk.getHttpEndpoint(n.toString()),c),l;try{l=await this.fetchFn(u,c)}catch(h){if(h.name==="AbortError")throw h;let p=new rr(h.cause?.code||h.code,h.message);throw p.response=l,p.cause=h.cause,p}let d=l.headers.get("content-type"),f;if(d?.includes("json")?f=await l.json():d?.includes("text")?f=await l.text():f=await l.blob(),!l.ok)throw new rr(l.status,f.message??f.error??l.statusText,{headers:l.headers,status:l.status,response:l,data:f});return{raw:l,data:f,headers:l.headers,status:l.status,statusText:l.statusText}}};var to;function Np(){if(!to)try{to=typeof cc<"u"&&cc.sys&&cc.sys.localStorage?cc.sys.localStorage:window.localStorage}catch{}return!to&&typeof globalThis.indexedDB<"u"&&(to=new Dp),to||(to={cache:{},setItem:function(t,e){this.cache[t]=e},getItem:function(t){return this.cache[t]},removeItem:function(t){delete this.cache[t]}}),to}function i0(t,e){Np().setItem(t,e)}function a0(t){Np().removeItem(t)}function c0(t,e){let n=Np().getItem(t);typeof Promise>"u"||!(n instanceof Promise)?e(n):n.then(r=>e(r))}var Dp=class{constructor(){m(this,"dbPromise",new Promise(e=>{let n=indexedDB.open("_colyseus_storage",1);n.onupgradeneeded=()=>n.result.createObjectStore("store"),n.onsuccess=()=>e(n.result)}))}async tx(e,n){let s=(await this.dbPromise).transaction("store",e).objectStore("store");return n(s)}setItem(e,n){return this.tx("readwrite",r=>r.put(n,e)).then()}async getItem(e){let n=await this.tx("readonly",r=>r.get(e));return new Promise(r=>{n.onsuccess=()=>r(n.result)})}removeItem(e){return this.tx("readwrite",n=>n.delete(e)).then()}};var tc,Nr,nc,ec=class{constructor(e){m(this,"settings",{path:"/auth",key:"colyseus-auth-token"});He(this,tc,!1);He(this,Nr,null);He(this,nc,xl());m(this,"http");this.http=e,c0(this.settings.key,n=>this.token=n)}set token(e){this.http.authToken=e}get token(){return this.http.authToken}onChange(e){let n=de(this,nc).on("change",e);return de(this,tc)||this.getUserData().then(r=>{this.emitChange({...r,token:this.token})}).catch(r=>{this.emitChange({user:null,token:void 0})}),$e(this,tc,!0),n}async getUserData(){if(this.token)return(await this.http.get(`${this.settings.path}/userdata`)).data;throw new Error("missing auth.token")}async registerWithEmailAndPassword(e,n,r){let s=(await this.http.post(`${this.settings.path}/register`,{body:{email:e,password:n,options:r}})).data;return this.emitChange(s),s}async signInWithEmailAndPassword(e,n){let r=(await this.http.post(`${this.settings.path}/login`,{body:{email:e,password:n}})).data;return this.emitChange(r),r}async signInAnonymously(e){let n=(await this.http.post(`${this.settings.path}/anonymous`,{body:{options:e}})).data;return this.emitChange(n),n}async sendPasswordResetEmail(e){return(await this.http.post(`${this.settings.path}/forgot-password`,{body:{email:e}})).data}async signInWithProvider(e,n={}){return new Promise((r,s)=>{let o=n.width||480,i=n.height||768,a=this.token?`?token=${this.token}`:"",c=`Login with ${e[0].toUpperCase()+e.substring(1)}`,u=this.http.sdk.getHttpEndpoint(`${n.prefix||`${this.settings.path}/provider`}/${e}${a}`),l=screen.width/2-o/2,d=screen.height/2-i/2;$e(this,Nr,window.open(u,c,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width="+o+", height="+i+", top="+d+", left="+l));let f=p=>{if(!(p.data.user===void 0&&p.data.token===void 0))if(clearInterval(h),de(this,Nr)?.close(),$e(this,Nr,null),window.removeEventListener("message",f),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)},h=setInterval(()=>{(!de(this,Nr)||de(this,Nr).closed)&&($e(this,Nr,null),s("cancelled"),window.removeEventListener("message",f))},200);window.addEventListener("message",f)})}async signOut(){this.emitChange({user:null,token:null})}emitChange(e){e.token!==void 0&&(this.token=e.token,e.token===null?a0(this.settings.key):i0(this.settings.key,e.token)),de(this,nc).emit("change",e)}};tc=new WeakMap,Nr=new WeakMap,nc=new WeakMap;function u0(t){let e=window?.location?.hostname||"localhost",n=t.hostname.split("."),r=!t.hostname.includes("trycloudflare.com")&&!t.hostname.includes("discordsays.com")&&n.length>2?`/${n[0]}`:"";return t.pathname.startsWith("/.proxy")?`${t.protocol}//${e}${r}${t.pathname}${t.search}`:`${t.protocol}//${e}/.proxy/colyseus${r}${t.pathname}${t.search}`}Da();var l0=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",Al=class Al{constructor(e=l0,n){m(this,"http");m(this,"auth");m(this,"settings");m(this,"urlBuilder");if(typeof e=="string"){let r=e.startsWith("/")?new URL(e,l0):new URL(e),s=r.protocol==="https:"||r.protocol==="wss:",o=Number(r.port||(s?443:80));this.settings={hostname:r.hostname,pathname:r.pathname,port:o,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)),n?.protocol&&(this.settings.protocol=n.protocol),this.http=new El(this,{headers:n?.headers||{}},n?.fetchFn),this.auth=new ec(this.http),this.urlBuilder=n?.urlBuilder,!this.urlBuilder&&typeof window<"u"&&window?.location?.hostname?.includes("discordsays.com")&&(this.urlBuilder=u0,console.log("Colyseus SDK: Discord Embedded SDK detected. Using custom URL builder."))}static async selectByLatency(e,n,r={}){let s=e.map(i=>new Al(i,n)),o=(await Promise.allSettled(s.map((i,a)=>i.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(i=>i.status==="fulfilled").map(i=>i.value);if(o.length===0)throw new Error("All endpoints failed to respond");return s[o.sort((i,a)=>i[1]-a[1])[0][0]]}async joinOrCreate(e,n={},r){return await this.createMatchMakeRequest("joinOrCreate",e,n,r)}async create(e,n={},r){return await this.createMatchMakeRequest("create",e,n,r)}async join(e,n={},r){return await this.createMatchMakeRequest("join",e,n,r)}async joinById(e,n={},r){return await this.createMatchMakeRequest("joinById",e,n,r)}async reconnect(e,n){if(typeof e=="string"&&typeof n=="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},n)}async consumeSeatReservation(e,n){let r=this.createRoom(e.name,n);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((o,i)=>{let a=(c,u)=>i(new rr(c,u));r.onError.once(a),r.onJoin.once(()=>{r.onError.remove(a),ol("room",r),o(r)})})}getLatency(e={}){let n=e.protocol??"ws",r=e.pingCount??1,s=e.timeout??1500;return new Promise((o,i)=>{let a=new pi(n),c=[],u=0,l=!1,d,f=p=>{if(!l){l=!0,clearTimeout(d);try{a.close()}catch{}p()}},h=p=>f(()=>i(new rr(St.ABNORMAL_CLOSURE,`Failed to get latency: ${p}`)));d=setTimeout(()=>h(`timed out after ${s}ms`),s),a.events.onopen=()=>{u=Date.now(),a.send(new Uint8Array([Ke.PING]))},a.events.onmessage=p=>{if(c.push(Date.now()-u),c.length<r)u=Date.now(),a.send(new Uint8Array([Ke.PING]));else{let y=c.reduce((S,b)=>S+b,0)/c.length;f(()=>o(y))}},a.events.onclose=p=>h(`connection closed${p?.code?` (${p.code})`:""}${p?.reason?`: ${p.reason}`:""}`),a.events.onerror=p=>h(p.message);try{a.connect(this.getHttpEndpoint())}catch(p){h(p?.message??"failed to connect")}})}async createMatchMakeRequest(e,n,r={},s){try{if(!n)throw new Error("Must provide a room name");let i=(await this.http.post(`/matchmake/${e}/${n}`,{headers:{Accept:"application/json","Content-Type":"application/json"},body:r})).data;return e==="reconnect"&&(i.reconnectionToken=r.reconnectionToken),await this.consumeSeatReservation(i,s)}catch(o){throw o instanceof rr?new wa(o.message,o.code):o}}createRoom(e,n){return new Za(e,n)}buildEndpoint(e,n={}){let r=this.settings.protocol||"ws",s=this.settings.searchParams||"";this.http.authToken&&(n._authToken=this.http.authToken);for(let a in n)n.hasOwnProperty(a)&&(s+=(s?"&":"")+`${a}=${n[a]}`);r==="h3"&&(r="http");let o=this.settings.secure?`${r}s://`:`${r}://`;e.publicAddress?o+=`${e.publicAddress}`:o+=`${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}`;let i=`${o}/${e.processId}/${e.roomId}?${s}`;return this.urlBuilder?this.urlBuilder(new URL(i)):i}getHttpEndpoint(e=""){let n=e.startsWith("/")?e:`/${e}`,r=`${this.settings.secure?"https":"http"}://${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}${n}`;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}`:""}};m(Al,"VERSION","0.18");var kl=Al,Br=kl;Pr();var Pl=class{setState(e){}getState(){return null}patch(e){}teardown(){}handshake(e){}};Pt();jp();Ol();Il();Cl();Mp("schema",hi);Mp("none",Pl);var Q2=Object.freeze({min:3,max:3}),ez=Object.freeze({min:4,max:4});var co={PLAY:"play",QUEUE:"queue",MATCH:"match",AUTHORITY:"authority"};var Wp={CAPS:"caps",SDK:"sdk",MATCH_KEY:"matchKey",PRIVATE:"private",SUCCESSOR_OF:"successorOf",SUCCESSOR_CLOSED:"successorClosed"},k0="ts/0.17.9",dn={PHYSICS:"physics@1",PHYSICS_PREDICT:"physics@2",INPUT_REPEAT:"repeat@1",LIFTS:"lifts@1",INPUT_TICK:"tick@1",FAST:"fast@1",FAST_RETURN:"fast-return@1",MAX_CAPS:16,MAX_CAP_CHARS:32};var lT=["clients","preset","winCondition","config","matchmade"],tz=[...lT,"moduleSha","tickHz","maxPlayers","lagComp","seed","units","leaseId","region","createdBy"],fn={BAD_OPTION:400,AUTH_REQUIRED:401,FORBIDDEN:403,WRONG_REGION:421,PROTOCOL_UNSUPPORTED:426,NOT_ENTITLED:402,ROOM_QUOTA:429,MODULE_UNAVAILABLE:424,AUTHORITY_CAPACITY:503},A0="free_quota_exhausted";var he={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"},xe={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"},dT=["__","match:","server:","rate:"],fT=["state","shared","claim","release","destroy","obj","queue","seat"];function ws(t){return fT.includes(t)||dT.some(e=>t.startsWith(e))}var zl="__",yr="__t";var nz=4*1024;var rz={[he.STATE]:"state",[he.STATE_SNAP]:"state",[he.SHARED]:"bulk",[he.CLAIM]:"control",[he.RELEASE]:"control",[he.DESTROY]:"control",[he.OBJECT]:"bulk",[he.OBJECT_SNAP]:"bulk",[he.INPUT]:"input",[he.ROOM_OPEN]:"control",[he.CHAT]:"chat",[he.CHAT_HISTORY_REQUEST]:"control",[he.VOICE_ICE_REQUEST]:"voice",[he.VOICE_JOIN]:"voice",[he.VOICE_LEAVE]:"voice",[he.VOICE_SIGNAL]:"voice",[he.MATCH_ELIMINATED]:"bulk",[he.MATCH_SCORE]:"bulk",[he.MATCH_FINISH]:"bulk",[he.POSE]:"pose",[he.POSE_SNAP]:"pose"},pn={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,IDLE:4408,MODULE_HALTED:4500,MODULE_FAULT:4501},pT={ModuleTimeout:"module_timeout",ModuleMemory:"module_memory",ModuleError:"module_error",ModuleOutputInvalid:"module_output_invalid",ModuleBudget:"module_budget",Halted:"halted",HostStall:"host_stall",PhysicsBudget:"physics_budget",RoomAge:"room_age",ModuleBandwidth:"module_bandwidth",PhysicsInternal:"physics_internal"};function P0(t){return Object.values(pT).includes(t)?t:null}var Xt={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},sz={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},Ss={TICK_HZ:30,RENDER_DELAY_MS:100,MAX_REWIND_MS:500,INPUT_BUFFER:32,PATCH_INTERVAL_MS:50,INPUT_REPEAT_MAX_MS:100,INPUT_REPEAT_RUN_MS:33},hn={enabled:!0,minUptime:0,delay:125,minDelay:100,maxDelay:4e3,maxRetries:9,maxEnqueuedMessages:0,firstStateTimeoutMs:2e3},T0=["x","y","z","yaw","vx","vy","vz","anim"],Ge={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},Fr={HEARTBEAT_HZ:10,MIN_HEARTBEAT_HZ:5,MAX_HEARTBEAT_HZ:20,HEARTBEAT_DITHER:.15,RELAY_BUFFER:4,WARMUP_ACKS:30};var uo={SAMPLES:3,TIMEOUT_MS:4e3,GRACE_MS:1e3};async function v0(t,e={}){let n=t[0];if(n===void 0)throw new Error("genex multiplayer: `urls` must contain at least one relay URL");if(t.length===1)return n;let r=e.probe??qp,s=Math.max(1,e.samples??uo.SAMPLES),o=e.timeoutMs??uo.TIMEOUT_MS,i=e.graceMs??uo.GRACE_MS,a=t.map(()=>{});await new Promise(u=>{let l=t.length*s,d,f=setTimeout(h,o);function h(){clearTimeout(f),clearTimeout(d),u()}let p=()=>{--l===0&&h()};t.forEach((y,S)=>{for(let b=0;b<s;b++){let x;try{x=r(y,o)}catch(R){x=Promise.reject(R)}x.then(R=>{Number.isFinite(R)&&R>=0&&(a[S]=Math.min(a[S]??1/0,R),d??(d=setTimeout(h,i))),p()},p)}})});let c=-1;return a.forEach((u,l)=>{u!==void 0&&(c<0||u<a[c])&&(c=l)}),c<0?(console.warn(`genex multiplayer: no relay answered the latency probe \u2014 connecting to ${n}`),n):t[c]}var qp=(t,e)=>new Br(t).getLatency({pingCount:1,timeout:e});var hT=t=>typeof t=="function"?t():t;async function lc(t){return t.url?new Br(t.url):new Br(await v0(t.urls))}function dc(t,e,n){return{gameId:t,name:e,embedToken:hT(n)?.embedToken,protocol:3}}var fc=t=>!!t&&typeof t=="object"&&t.code===fn.PROTOCOL_UNSUPPORTED,Gp=()=>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.`),M0=t=>{throw fc(t)&&Gp(),t};function C0(t,e){let n=null,r=null;return{request(){return n||(n=new Promise(s=>{let o,i=a=>{r&&(r=null,n=null,o&&clearTimeout(o),s(a))};r=i,o=setTimeout(()=>i(null),e),t()}),n)},deliver(s){r?.(s)},get pending(){return n!==null}}}var O0=["x","y","z","yaw","vx","vy","vz"],I0=[["x","vx"],["y","vy"],["z","vz"]],Yp=Math.PI*2,mT=t=>T0.includes(t);function Kp(t){if(!Number.isFinite(t))return 0;let e=t%Yp;return e<=-Math.PI?e+=Yp:e>Math.PI&&(e-=Yp),e}var D0=t=>typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=Xt.MAX_POSE_ABS;function N0(t){let e={},n={},r=[];for(let s of Object.keys(t)){let o=t[s];if(!mT(s)){n[s]=o;continue}o!==void 0&&(s==="anim"?typeof o=="string"&&o.length<=Xt.MAX_ANIM_CHARS?e.anim=o:r.push(s):D0(o)?e[s]=o:r.push(s))}return{pose:e,data:n,invalid:r}}function B0(t){for(let e in t)if(t[e]!==void 0)return!0;return!1}function L0(t,e,n){let r={...t},s={t:e},o=n?e-n.t:0,i=n!==void 0&&o>Ge.MIN_GAP_MS&&o<Ge.MAX_GAP_MS;for(let[a,c]of I0){let u=t[a];if(u===void 0||(s[a]=u,t[c]!==void 0))continue;let l=n?.[a],d=i&&l!==void 0?(u-l)/o*1e3:0;r[c]=D0(d)?d:0}return{pose:r,memory:s}}function $l(t){let e=n=>typeof n=="number"&&Number.isFinite(n)?n:0;return{x:e(t.x),y:e(t.y),z:e(t.z),yaw:e(t.yaw),vx:e(t.vx),vy:e(t.vy),vz:e(t.vz),anim:typeof t.anim=="string"?t.anim:""}}var Mi=(t,e)=>{let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:0};function F0(t,e){let n=t.length;if(n===0)return;let r=0;for(;r<n&&t[r].t<=e;)r++;if(r===0)return t[0].state;if(r>=n){let u=t[n-1],l={...u.state},d=Math.min(Math.max(0,e-u.t),Ge.MAX_EXTRAP_MS)/1e3;for(let[f,h]of I0)l[f]=Mi(u.state,f)+Mi(u.state,h)*d;if(n>=2){let f=t[n-2],h=u.t-f.t;if(h>0){let p=Math.min(Math.max(0,e-u.t),Ge.ROT_EXTRAP_MS)/h,y=Mi(u.state,"yaw");l.yaw=y+Kp(y-Mi(f.state,"yaw"))*p}}return l}let s=t[r-1],o=t[r],i=o.t-s.t,a=i>0?(e-s.t)/i:1,c={...s.state};for(let u of O0){let l=Mi(s.state,u),d=Mi(o.state,u);c[u]=u==="yaw"?l+Kp(d-l)*a:l+(d-l)*a}return c}function z0(t,e,n,r){let s={...e};for(let o of O0){let i=t[o],a=e[o];typeof i!="number"||typeof a!="number"||!Number.isFinite(i)||!Number.isFinite(a)||(s[o]=o==="yaw"?i+Kp(a-i)*r:i+(a-i)*n)}return s}var Hl=class Hl{constructor(){m(this,"pending",[]);m(this,"current")}push(e,n){for(this.pending.push({t:e,state:n});this.pending.length>Hl.MAX_PENDING;)this.current=this.pending.shift()?.state}at(e){for(;this.pending.length>0;){let n=this.pending[0];if(this.current!==void 0&&e!==void 0&&n.t!==void 0&&n.t>e)break;this.current=n.state,this.pending.shift()}return this.current}flush(){this.at(void 0)}};m(Hl,"MAX_PENDING",64);var Vl=Hl;function U0(t){try{let e=t.input();return e&&typeof e.send=="function"?e:null}catch{return null}}function V0(t,e,n=Fr.HEARTBEAT_HZ,r=Math.random){let o=1e3/Math.min(Fr.MAX_HEARTBEAT_HZ,Math.max(Fr.MIN_HEARTBEAT_HZ,n)),i=1e3/Fr.MAX_HEARTBEAT_HZ,a=1e3/Fr.MIN_HEARTBEAT_HZ,c=!1,u=!1,l,d=()=>{if(u)return;if(e()){try{t.send()}catch{}!c&&t.lastProcessed>=Fr.WARMUP_ACKS&&(c=!0)}let f=o*(1+(r()*2-1)*Fr.HEARTBEAT_DITHER);l=setTimeout(d,Math.min(a,Math.max(i,f)))};return d(),{get synced(){return!c&&t.lastProcessed>=Fr.WARMUP_ACKS&&(c=!0),c},stop(){u=!0,l&&clearTimeout(l)}}}function H0(t,e){return e.synced&&e.clockOrigin>0&&e.serverNow!==void 0&&Number.isFinite(e.serverNow)?t-e.clockOrigin-e.serverNow:t-e.wallNow}function xs(t){let e=t.reconnection;return e.enabled=hn.enabled,e.minUptime=hn.minUptime,e.delay=hn.delay,e.minDelay=hn.minDelay,e.maxDelay=hn.maxDelay,e.maxRetries=hn.maxRetries,e.maxEnqueuedMessages=hn.maxEnqueuedMessages,e.enqueuedMessages.length=0,t}function $0(t){return t.reconnection.enabled=!1,t}function pc(t,e){return new Promise(n=>{let r=()=>{clearTimeout(s),n(!0)},s=setTimeout(()=>{t.onStateChange.remove(r),n(!1)},e);t.onStateChange.once(r)})}function j0(t,e,n){return t!==e&&n!=null}var yT="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.",Xp=class extends Error{constructor(e){super(yT,{cause:e}),this.name="VoiceNotDelegatedError"}},W0=[{urls:"stun:stun.l.google.com:19302"}],gT=120,q0=.02,bT=.6,jl=class{constructor(e){m(this,"transport");m(this,"peers",new Map);m(this,"listeners",new Set);m(this,"roster",[]);m(this,"local",null);m(this,"audio",null);m(this,"localAnalyser",null);m(this,"levelTimer",null);m(this,"iceServers",W0);m(this,"spatial",!1);m(this,"threshold",q0);m(this,"micOn",!0);m(this,"selfSpeaking",!1);m(this,"running",!1);m(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={},n=!1){if(!this.running){this.peeringHeld=n,this.iceServers=e.iceServers?.length?e.iceServers:W0,this.spatial=e.spatial===!0,this.threshold=e.speakingThreshold??q0,this.micOn=e.startMuted!==!0;try{this.local=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1})}catch(r){throw ST(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(),gT)}}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 n of this.peers.values())try{n.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 n=this.transport.selfId(),r=new Set(e.filter(s=>s!==n));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 n of this.local?.getAudioTracks()??[])n.enabled=e;!e&&this.selfSpeaking&&(this.selfSpeaking=!1,this.emit())}mute(e){this.setMuted(e,!0)}unmute(e){this.setMuted(e,!1)}setVolume(e,n){let r=this.peers.get(e);r&&(r.volume=Math.max(0,Math.min(1,n)),r.el&&(r.el.volume=r.volume),this.emit())}async handleSignal(e,n){if(!this.running)return;let r=n;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 o=await s.pc.createAnswer();await s.pc.setLocalDescription(o),this.transport.sendSignal(e,{t:"answer",sdp:o})}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(o){console.warn(`[multiplayer] voice signaling failed with ${e}`,o)}}setMuted(e,n){let r=this.peers.get(e);!r||r.muted===n||(r.muted=n,r.el&&(r.el.muted=n||this.spatial),n&&r.speaking&&(r.speaking=!1),this.emit())}createPeer(e){let n=new RTCPeerConnection({iceServers:this.iceServers}),r={id:e,pc:n,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&&n.addTrack(s,this.local);return n.onicecandidate=s=>{s.candidate&&this.transport.sendSignal(e,{t:"ice",c:s.candidate.toJSON()})},n.ontrack=s=>{let o=s.streams[0]??new MediaStream([s.track]);r.stream=o,r.el=this.attachSink(o,r),r.analyser=this.makeAnalyser(o),this.emit()},n.onconnectionstatechange=()=>{let s=n.connectionState,o=s==="connected"?"connected":s==="failed"||s==="closed"?"failed":"connecting";if(o!==r.connection){if(r.connection=o,o==="failed"){let i=this.iceServers.some(a=>xT(a));console.warn(`[multiplayer] voice connection to ${e} failed`+(i?"":" \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 n=await e.pc.createOffer();await e.pc.setLocalDescription(n),this.transport.sendSignal(e.id,{t:"offer",sdp:n})}catch(n){console.warn(`[multiplayer] voice offer to ${e.id} failed`,n)}}async flushIce(e){let n=e.pendingIce.splice(0);for(let r of n)try{await e.pc.addIceCandidate(r)}catch{}}destroyPeer(e){let n=this.peers.get(e);if(n){this.peers.delete(e),n.pc.onicecandidate=null,n.pc.ontrack=null,n.pc.onconnectionstatechange=null;try{n.pc.close()}catch{}n.el&&(n.el.srcObject=null,n.el.remove())}}attachSink(e,n){let r=document.createElement("audio");return r.autoplay=!0,r.srcObject=e,r.muted=this.spatial||n.muted,r.volume=n.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 n=this.audio.createMediaStreamSource(e),r=this.audio.createAnalyser();return r.fftSize=512,n.connect(r),r}catch{return null}}pollLevels(){let e=!1,n=this.micOn?G0(this.localAnalyser):0,r=this.crossed(n,this.selfSpeaking);r!==this.selfSpeaking&&(this.selfSpeaking=r,e=!0);for(let s of this.peers.values()){let o=s.muted?!1:this.crossed(G0(s.analyser),s.speaking);o!==s.speaking&&(s.speaking=o,e=!0)}e&&this.emit()}crossed(e,n){return e>=(n?this.threshold*bT:this.threshold)}emit(){for(let e of[...this.listeners])try{e()}catch(n){console.error("[multiplayer] a voice listener threw",n)}}};function wT(){try{return window.self!==window.top}catch{return!0}}function ST(t){if(t?.name!=="NotAllowedError")return t;try{if(!wT()||document.featurePolicy?.allowsFeature?.("microphone")!==!1)return t}catch{return t}return new Xp(t)}function xT(t){return(Array.isArray(t.urls)?t.urls:[t.urls]).some(n=>typeof n=="string"&&n.startsWith("turn"))}function G0(t){if(!t)return 0;let e=new Uint8Array(t.fftSize);t.getByteTimeDomainData(e);let n=0;for(let r=0;r<e.length;r++){let s=((e[r]??128)-128)/128;n+=s*s}return Math.sqrt(n/e.length)}var Jp=Symbol("genex.roomRef"),zr=t=>t[Jp]();var _T=Ge.RATIO,RT=Ge.MIN_MS,ET=Ge.MAX_MS,Wl=Ge.DEFAULT_MS,kT=Ge.JITTER_SAFETY,AT=Ge.POISON_GUARD_MS,PT=Ge.EASE,TT=Ge.MAX_EXTRAP_MS,vT=Ge.ROT_EXTRAP_MS,K0=Ge.CLOCK_WINDOW,MT=Ge.CLOCK_WINDOW_MS,CT=Ge.CLOCK_WINDOW_MAX,OT=Ge.INTERVAL_WINDOW,IT=Ge.MIN_GAP_MS,DT=Ge.MAX_GAP_MS,NT=Ge.HISTORY_MS,BT=Ge.SMOOTH_TAU_POS_MS,LT=Ge.SMOOTH_TAU_ROT_MS,X0=Ge.MAX_HOST_TICK_DT_MS,FT=Ge.REBASE_AFTER_GAP_MS,gr="obj:",zT=3e3,UT=5e3,VT=6e4,HT=2e3;function Q0(t){if(t==="predict")return{mode:"lerp"};if(t&&typeof t=="object"&&t.engine==="predict")return{mode:t.mode==="damped"?"damped":"lerp",delay:t.delay,smoothMs:t.smoothMs}}var Yl=async t=>Q0(t)?Promise.resolve().then(()=>(Zp(),Y0)):void 0;function J0(t){if(!t)return{state:{}};try{let e=JSON.parse(t);if(!e||typeof e!="object")return{state:{}};let n=e,r=n[yr];if(typeof r=="number"&&Number.isFinite(r)){let s={...n};return delete s[yr],{state:s,sendTime:r}}return{state:n}}catch{return{state:{}}}}function ql(t){if(t!=null)try{return JSON.parse(t)}catch{return}}var $T=(t,e)=>typeof e=="number"?Number.isFinite(e)?e:0:typeof e=="bigint"?Number(e):e;function Ci(t){return JSON.parse(JSON.stringify(t,$T))}var lo=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function ew(t,e,n){let[r,s,o,i]=e,[a,c,u,l]=t,d=a*r+c*s+u*o+l*i;if(d<0&&(r=-r,s=-s,o=-o,i=-i,d=-d),d>.9995){let S=a+(r-a)*n,b=c+(s-c)*n,x=u+(o-u)*n,R=l+(i-l)*n,A=Math.hypot(S,b,x,R)||1;return[S/A,b/A,x/A,R/A]}let f=Math.acos(d),h=Math.sin(f),p=Math.sin(f-f*n)/h,y=Math.sin(f*n)/h;return[a*p+r*y,c*p+s*y,u*p+o*y,l*p+i*y]}function Gl(t){return Array.isArray(t)&&t.length===4&&t.every(e=>typeof e=="number"&&Number.isFinite(e))}function Z0(t,e,n,r){let s={},o=n<1;for(let i in e){let a=t[i],c=e[i];typeof a=="number"&&typeof c=="number"&&Number.isFinite(a)&&Number.isFinite(c)?s[i]=a+(c-a)*n:Gl(a)&&Gl(c)?s[i]=ew(a,c,r):s[i]=o&&i in t?a:c}return s}function jT(t,e,n,r){let s={};for(let o in e){let i=e[o],a=t[o];typeof a=="number"&&typeof i=="number"&&Number.isFinite(a)&&Number.isFinite(i)?s[o]=a+(i-a)*n:Gl(a)&&Gl(i)?s[o]=ew(a,i,r):s[o]=i}return s}function WT(t,e){let n=t.length;if(n===0)return;if(n===1)return t[0].state;let r=0;for(;r<n&&t[r].t<=e;)r++;if(r===0)return t[0].state;if(r>=n){let c=t[n-2],u=t[n-1],l=u.t-c.t;if(l<=0)return u.state;let d=(Math.min(e,u.t+TT)-c.t)/l,f=(Math.min(e,u.t+vT)-c.t)/l;return Z0(c.state,u.state,d,f)}let s=t[r-1],o=t[r],i=o.t-s.t,a=i>0?(e-s.t)/i:1;return Z0(s.state,o.state,a,a)}function qT(t){if(t.length===0)return 66;let e=[...t].sort((n,r)=>n-r);return e[e.length>>1]}function GT(t,e){if(t.length===0)return 0;let n=[...t].sort((s,o)=>s-o),r=Math.min(n.length-1,Math.max(0,Math.round(e*(n.length-1))));return n[r]}async function tw(t){let e=await lc(t),n=await Yl(t.smoothing),r=xs(await e.joinOrCreate(co.PLAY,{...dc(t.room,t.name,t.auth),...t.options,protocol:3}).catch(M0));return Qp(r,{pose:t.pose,smoothing:t.smoothing,predict:n})}var YT=t=>typeof t=="string"&&t.length>0&&t.length<=Xt.MAX_EVENT_TYPE_CHARS&&!ws(t),KT=new Set(["join","leave","change","shared","object","host","reconnecting","reconnected","disconnect","room:open","voice","voice:rejected"]),XT=new Set([xe.OBJECT_RESULT,xe.INPUT,xe.ROOM_OPEN,xe.CHAT,xe.CHAT_HISTORY,xe.VOICE_ICE,xe.VOICE_SIGNAL,xe.VOICE_REJECTED,xe.RATE_DROP,...Object.values(he)]),JT=[500,1e3,2e3,4e3,8e3];function Qp(t,e={}){let n=new Map,r=new Map,s=new Map,o=new Map,i=new Map,a=new Map,c=new Set,u=new Map,l=new Map,d=new Map,f=new Map,h,p=new Map,y=new Map,S=new Map,b=new Map,x=new Map,R=new Map,A=new Map,E=new Map,P=new Set,k=new Map,M,B=0,K=new Map,j=w=>{for(let C of K.values())if(C.id===w)return!0;return!1},L=typeof globalThis<"u"&&globalThis.__GENEX_MP_TEST_SKEW__||0,se=L?()=>lo()+L:lo,v=(w,C)=>{if(p.get(C)===t.sessionId)return!1;let V=`${w}:${C}`;return P.has(V)||(P.add(V),console.warn(`[multiplayer] objects.${w}('${C}') ignored because this session does not own the object \u2014 await objects.claimConfirmed('${C}') and check accepted before publishing`)),!0},$=(w,C,V,X)=>{let we=se(),pe=V,Me=we-V,ie=o.get(X);ie||o.set(X,ie={samples:[],mins:[],n:0});let Ne=++ie.n;for(ie.samples.push({at:we,n:Ne});ie.mins.length>0&&ie.mins[ie.mins.length-1].v>=Me;)ie.mins.pop();for(ie.mins.push({v:Me,n:Ne});ie.samples.length>CT||ie.samples.length>K0&&ie.samples[0].at<we-MT;)ie.samples.shift();let ze=ie.samples[0].n;for(;ie.mins[0].n<ze;)ie.mins.shift();s.set(X,ie.mins[0].v);let nt=i.get(w);nt||i.set(w,nt=[]),nt.push(Me),nt.length>K0&&nt.shift(),a.set(w,X);let ut=r.get(w);if(r.set(w,pe),ut!=null){let rt=pe-ut;if(rt>IT&&rt<DT){let Er=d.get(w);Er||d.set(w,Er=[]),Er.push(rt),Er.length>OT&&Er.shift();let Yd=nt.length>=8?Math.max(0,GT(nt,.9)-ie.mins[0].v):0,tu=Math.min(ET,Math.max(RT,_T*qT(Er),kT*Yd)),Qn=f.get(w)??Wl;f.set(w,Qn+(tu-Qn)*PT)}}let Qe=n.get(w);Qe||n.set(w,Qe=[]);let Jn=k.get(w);if(Jn&&Qe.length===0){let rt=f.get(w)??Wl;Qe.push({t:pe-Math.max(1,rt),state:Jn})}k.delete(w),Qe.push({t:pe,state:C});let Zn=pe-NT;for(;Qe.length>2&&Qe[0].t<Zn;)Qe.shift();for(;Qe.length>1&&Qe[0].t>Qe[Qe.length-1].t+AT;)Qe.shift()},G=(w,C)=>{let V=a.get(w),X=V===void 0?void 0:s.get(V);if(X!==void 0)return C-X-(f.get(w)??Wl)},W=(w,C)=>{let V=n.get(w),X=G(w,C)??C-Wl,we=c.has(w),pe=V&&(we?F0(V,X):WT(V,X));if(!pe)return u.get(w);let Me=u.get(w),ie;if(Me){let Ne=Math.min(X0,Math.max(0,C-(l.get(w)??C))),ze=1-Math.exp(-Ne/BT),nt=1-Math.exp(-Ne/LT);ie=we?z0(Me,pe,ze,nt):jT(Me,pe,ze,nt)}else ie=pe;return u.set(w,ie),l.set(w,C),ie},q=w=>{n.delete(w),r.delete(w),a.delete(w),u.delete(w),l.delete(w),d.delete(w),f.delete(w),i.delete(w),k.delete(w)},ae=w=>{n.delete(w),r.delete(w),a.delete(w),d.delete(w),f.delete(w),i.delete(w)},ce=w=>{s.delete(w),o.delete(w)},ne=new Map,Re=new Set,oe=(w,...C)=>ne.get(w)?.forEach(V=>{try{V(...C)}catch(X){console.error(`[multiplayer] a '${w}' listener threw:`,X)}}),ee=new Map,ue=(w,C)=>{ee.get(C)!==w&&(ee.set(C,w),oe("shared",C,ql(w)))},Ae=w=>{let C=w||void 0;C!==M&&(M=C,oe("host",M))},pt="",Bt=()=>{let w=t.state?.voice?[...t.state.voice.keys()].sort():[],C=w.join(`
14
+ `);C!==pt&&(pt=C,Ve.setRoster(w),oe("voice",Ve.participants))},_r=(w,C)=>{let V=gr+w,X=t.sessionId,we=b.has(w),pe=C.owner||void 0,Me=Number.isFinite(C.seq)?C.seq:0,ie=Number.isFinite(C.epoch)?C.epoch:0,Ne=Number.isFinite(C.t)?C.t:0,ze=typeof C.d=="string"?C.d:"",ut=pe!==y.get(w)||we&&Me!==b.get(w),Qe=S.has(w)&&ie!==S.get(w),Jn=Ne!==x.get(w);if(b.set(w,Me),S.set(w,ie),x.set(w,Ne),ze!==R.get(w)){R.set(w,ze);let rt=ze?ql(ze):void 0;rt&&typeof rt=="object"&&!Array.isArray(rt)&&A.set(w,rt)}pe?y.set(w,pe):y.delete(w),(ut||p.get(w)!==pe&&!j(w))&&(pe?p.set(w,pe):p.delete(w)),Qe&&q(V),ut&&pe!==X&&(E.delete(w),Qe||ae(V));let Zn=A.get(w);if(Zn&&pe!==X){let rt=Ne!==0&&Jn&&pe!==void 0;Qe?(u.set(V,Zn),l.set(V,se()),rt&&$(V,Zn,Ne,pe)):(ut&&k.set(V,u.get(V)??Zn),rt&&$(V,Zn,Ne,pe))}(!we||ut)&&oe("object",w)},Gn=w=>{let C=b.has(w)||p.has(w)||A.has(w)||E.has(w);q(gr+w),A.delete(w),p.delete(w),y.delete(w),S.delete(w),b.delete(w),x.delete(w),R.delete(w),E.delete(w),C&&oe("object",w)},Co=new Map,Ms=new Map,na=new Map,qd=(w,C)=>{if(!C)return{};let V=Co.get(w);if(V&&V.raw===C)return V.state;let{state:X}=J0(C);return Co.set(w,{raw:C,state:X}),X},An=new Map,bn=new Map,Yn=e.predict?Q0(e.smoothing):void 0,ct,Kn=new Map,Gd=(w,C)=>{if(!Yn||!e.predict)return;ct??(ct=e.predict.Predict.get(t));let V={mode:Yn.mode,delay:Yn.delay,smoothMs:Yn.smoothMs};ct.attach(C,{x:V,y:V,z:V,vx:V,vy:V,vz:V}),ct.attach(C,{yaw:{...V,angle:!0}}),Kn.set(w,C)},Wc=w=>{let C=Kn.get(w);C&&ct&&ct.detach(C),Kn.delete(w)},qc=w=>{let C=ct;return{x:C.value(w,"x"),y:C.value(w,"y"),z:C.value(w,"z"),yaw:C.value(w,"yaw"),vx:C.value(w,"vx"),vy:C.value(w,"vy"),vz:C.value(w,"vz"),anim:w.anim??""}},en=!1,Pn=!1,bt=!0,Xr=!1,ra=0,Jr=0,sa=0,oa=new Set,Cs=()=>oa.forEach(w=>w()),Os=(w,C)=>{if(K.delete(w.requestId),w.timeout&&clearTimeout(w.timeout),w.abort?.(),w.operation==="claim"&&w.optimistic&&!C.accepted){let V=C.owner??y.get(w.id);V?p.set(w.id,V):p.delete(w.id),V!==t.sessionId&&E.delete(w.id)}w.operation==="claim"&&C.accepted&&(p.set(w.id,t.sessionId),ae(gr+w.id)),w.operation==="release"&&C.accepted&&(E.delete(w.id),p.get(w.id)===t.sessionId&&p.delete(w.id),ae(gr+w.id)),w.operation==="remove"&&C.accepted&&(E.delete(w.id),A.delete(w.id),p.delete(w.id),q(gr+w.id)),w.resolve(C)},Is=(w,C)=>{let V=t.state?.objects?.get(w.id);return{requestId:w.requestId,operation:w.operation,id:w.id,accepted:!1,owner:V?.owner||void 0,sequence:V&&Number.isFinite(V.seq)?V.seq:0,reason:C}},Oo=w=>{for(let C of[...K.values()])Os(C,Is(C,w))},ia=(w,C=!1)=>{if(!C&&!bt)return;let V=w.operation==="claim"?he.CLAIM:w.operation==="release"?he.RELEASE:he.DESTROY;tt(V,w.payload)},Zr=(w,C,V={})=>{let X=String(C),we=`${t.sessionId.slice(0,12)}:${Date.now().toString(36)}:${(++B).toString(36)}`,pe=Math.max(250,Math.min(V.timeoutMs??UT,VT));return new Promise(Me=>{let ie={operation:w,id:X,requestId:we,payload:{id:X,requestId:we,...V.authority==="host"?{authority:"host"}:{}},optimistic:w==="claim"&&V.optimistic===!0,resolve:Me,timeout:null,abort:void 0};if(en||Pn){Me(Is(ie,en?"aborted":"disconnected"));return}if(ie.optimistic&&p.set(X,t.sessionId),ie.timeout=setTimeout(()=>Os(ie,Is(ie,"timeout")),pe),V.signal){let Ne=()=>Os(ie,Is(ie,"aborted"));V.signal.addEventListener("abort",Ne,{once:!0}),ie.abort=()=>V.signal?.removeEventListener("abort",Ne)}if(K.set(we,ie),V.signal?.aborted){Os(ie,Is(ie,"aborted"));return}ia(ie)})},Qr=0,tt=(w,C,V=!1)=>{if(t.connection?.isOpen)try{return t.send(w,C),!0}catch{}return V&&Qr++,!1},Io,Gc=0,Yc,Kc=new Set,Xc=(w,C)=>{let{pose:V,data:X,invalid:we}=N0(w);for(let ze of we)Kc.has(ze)||(Kc.add(ze),console.warn(`[multiplayer] me.set: '${ze}' is a typed pose key (pose: true) and its value is not a `+(ze==="anim"?`string of \u2264${Xt.MAX_ANIM_CHARS} chars`:"finite number")+" \u2014 it is not sent."));if(!B0(V))return!1;let pe=se(),Me=L0(V,pe,C?void 0:Yc);Yc=Me.memory;let ie=JSON.stringify(X),Ne=C||ie!==Io||pe-Gc>=HT;return Ne&&tt(he.STATE,JSON.stringify({...X,[yr]:pe}))?(Io=ie,Gc=pe):Ne&&(Io=void 0),tt(C?he.POSE_SNAP:he.POSE,{...Me.pose,t:pe})||(Io=void 0),!0},Ve=new jl({selfId:()=>t.sessionId,nameOf:w=>t.state?.players?.get(w)?.name??"",sendSignal:(w,C)=>tt(he.VOICE_SIGNAL,{to:w,data:C},!0)});Ve.onChange(()=>oe("voice",Ve.participants));let es=null,Ds=C0(()=>tt(he.VOICE_ICE_REQUEST,{},!0),zT),Do=()=>{es&&clearTimeout(es),es=null},Xn=w=>{Do(),!(typeof w!="number"||!Number.isFinite(w)||w<=0)&&(es=setTimeout(()=>{Ve.active&&Ds.request().then(C=>{!Ve.active||!C?.iceServers?.length||(Ve.setIceServers(C.iceServers),Xn(C.ttl))})},Math.max(6e4,Math.floor(w*800))))},Rr=[],No=new Set,Ns=new Set,Bs=new Set,Lt=w=>!!w&&typeof w=="object"&&typeof w.id=="number"&&typeof w.from=="string"&&typeof w.name=="string"&&typeof w.text=="string",Jc=w=>{if(!Lt(w)||No.has(w.id)||Bs.has(w.from))return;No.add(w.id);let C=Rr[Rr.length-1];if(!C||w.id>C.id)Rr.push(w);else{let V=Rr.length;for(;V>0&&(Rr[V-1]?.id??0)>w.id;)V--;Rr.splice(V,0,w)}for(let V of[...Ns])try{V(w)}catch(X){console.error("[multiplayer] a chat listener threw",X)}},Et=Ja(t);if(!Et)throw new Error("genex multiplayer: the relay room has no schema state");let Bo=(w,C,V)=>{let X=w===t.sessionId,{state:we,sendTime:pe}=J0(C.data),Me=Number.isFinite(C.epoch)?C.epoch:0,ie=Ms.has(w)&&Me!==Ms.get(w);Ms.set(w,Me);let Ne=V||C.data!==na.get(w);na.set(w,C.data);let ze=Number.isFinite(C.poseT)?C.poseT:0,nt=ze!==(bn.get(w)??0);bn.set(w,ze);let ut=C.posed===!0;if(!X&&ut&&!c.has(w)&&(q(w),c.add(w),An.set(w,new Vl)),!X&&ie&&(q(w),Kn.has(w)&&Wc(w)),oe(V?"join":"change",w,ut?{...we,...$l(C)}:we),!X){if(ut){let Qe=An.get(w);(Ne||ie)&&(Qe.push(pe,we),(ie||Yn)&&Qe.flush()),Yn?Kn.has(w)||Gd(w,C):ze!==0&&(nt||ie)&&$(w,$l(C),ze,w);return}(Ne||ie)&&j0(w,t.sessionId,pe)&&$(w,we,pe,w)}};Et(t.state).players.onAdd((w,C)=>{Bo(C,w,!0),Et(w).onChange(()=>Bo(C,w,!1))});let Lo=w=>{oe("leave",w),q(w),ce(w),Wc(w),Co.delete(w),Ms.delete(w),na.delete(w),bn.delete(w),c.delete(w),An.delete(w)};Et(t.state).players.onRemove((w,C)=>Lo(C)),Et(t.state).shared.onAdd(ue),Et(t.state).shared.onChange(ue),Et(t.state).objects.onAdd((w,C)=>{_r(C,w),Et(w).onChange(()=>_r(C,w))}),Et(t.state).objects.onRemove((w,C)=>Gn(C)),Et(t.state).listen("host",w=>Ae(w)),Et(t.state).voice.onAdd(Bt),Et(t.state).voice.onRemove(Bt);let Zc=()=>{let w=t.state;if(w){for(let C of new Set([...p.keys(),...A.keys(),...b.keys()]))w.objects?.has(C)||Gn(C);for(let C of[...Ms.keys()])w.players?.has(C)||Lo(C);Ae(w.host),Bt()}};t.onMessage(xe.VOICE_SIGNAL,w=>{w&&typeof w.from=="string"&&Ve.handleSignal(w.from,w.data)}),t.onMessage(xe.VOICE_REJECTED,w=>{Do(),Ve.stop(),oe("voice:rejected",w??{reason:"full"})}),t.onMessage(xe.VOICE_ICE,w=>{Ds.deliver(w??null)}),t.onMessage(xe.CHAT,w=>Jc(w)),t.onMessage(xe.CHAT_HISTORY,w=>{if(Array.isArray(w?.messages))for(let C of w.messages)Jc(C)}),t.onMessage(xe.OBJECT_RESULT,w=>{if(!w||typeof w.requestId!="string")return;let C=K.get(w.requestId);!C||w.operation!==C.operation||w.id!==C.id||Os(C,w)}),t.onMessage(xe.INPUT,w=>{w&&typeof w.from=="string"&&oe(xe.INPUT,w.from,w.d)}),t.onMessage(xe.ROOM_OPEN,w=>{typeof w?.open=="boolean"&&oe("room:open",{open:w.open})}),t.onMessage(xe.RATE_DROP,w=>{console.warn(`[multiplayer] the relay dropped ${w?.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).`)}),t.onMessage(xe.SERVER_RESTART,()=>{}),tt(he.CHAT_HISTORY_REQUEST,{});let Qc=U0(t),ts=Qc?V0(Qc,()=>!Pn&&!en):void 0,ns=()=>ts?t.clock.serverNow():void 0,aa=w=>H0(w,{synced:ts?.synced===!0,clockOrigin:Number.isFinite(t.state?.clockOrigin)?t.state?.clockOrigin:0,serverNow:ns(),wallNow:Date.now()}),eu=()=>{ts?.stop(),ct?.dispose(),ct=void 0,Kn.clear()};t.onDrop(w=>{if(en||Pn)return;sa++,Xr||(Xr=!0,ra=0,Jr=lo()),bt=!1,Cs();let{isReconnecting:C,retryCount:V,maxRetries:X}=t.reconnection;C&&V>=X||oe("reconnecting",{attempt:++ra,code:w})}),t.onReconnect(()=>{if(Pn)return;if(en){t.leave().catch(()=>{});return}let w=sa;if((Jr?lo()-Jr:0)>FT){for(let V of[...n.keys()])q(V);for(let V of[...o.keys()])ce(V)}(async()=>{if(await pc(t,hn.firstStateTimeoutMs),!(w!==sa||Pn||en)){Zc();for(let V of[...K.values()])ia(V,!0);tt(he.CHAT_HISTORY_REQUEST,{}),Xr=!1,Jr=0,bt=!0,Cs(),oe("reconnected"),Qr>0&&(console.warn(`[multiplayer] ${Qr} fire-and-forget event(s)/input(s) were dropped while reconnecting \u2014 they are not buffered; player/object state re-synced automatically.`),Qr=0)}})()}),t.onLeave(w=>{Pn||(Pn=!0,bt=!1,Xr=!1,eu(),Cs(),!en&&(Oo("disconnected"),oe("disconnect",w??1006)))}),t.onError(()=>{});let Fo=((w,C)=>{let V=ne.get(w);return V||ne.set(w,V=new Set),V.add(C),!KT.has(w)&&!XT.has(w)&&!Re.has(w)&&(Re.add(w),t.onMessage(w,X=>oe(w,X))),()=>{V?.delete(C)}}),Ls={id:t.sessionId,get players(){let w=new Map,C=se();return ct&&Kn.size>0&&ct.tick(lo()),t.state?.players?.forEach((V,X)=>{let we=qd(X,V.data),pe=we,Me=we,ie=An.get(X);if(X!==t.sessionId&&ie){let Ne=$l(V);if(Me={...we,...Ne},Kn.has(X))pe={...ie.at(void 0)??we,...qc(V)};else{let ze=W(X,C)??Ne;pe={...ie.at(G(X,C))??we,...ze}}}else X===t.sessionId?h&&(pe=h,Me=h):pe=W(X,C)??we;w.set(X,{id:X,name:V.name??"",avatarUrl:V.avatarUrl??"",connected:V.connected!==!1,uid:V.uid??"",team:Number.isFinite(V.team)?V.team:-1,state:pe,stateRaw:Me})}),w},get activePlayers(){return new Map([...Ls.players].filter(([,w])=>w.connected))},me:{set(w){yr in w&&console.warn(`[multiplayer] '${yr}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let C=Ci(w);h=C,!(e.pose&&Xc(C,!1))&&tt(he.STATE,JSON.stringify({...C,[yr]:se()}))},snap(w){yr in w&&console.warn(`[multiplayer] '${yr}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let C=Ci(w);h=C,!(e.pose&&Xc(C,!0))&&tt(he.STATE_SNAP,JSON.stringify({...C,[yr]:se()}))}},shared:{get(w){return ql(t.state?.shared?.get(w))},set(w,C){w.startsWith(zl)||tt(he.SHARED,{key:w,value:JSON.stringify(Ci(C))})},keys(){return t.state?.shared?Array.from(t.state.shared.keys()):[]}},objects:{claim(w){Zr("claim",w,{optimistic:!0})},claimConfirmed(w,C){return Zr("claim",w,C)},release(w){let C=String(w);E.delete(C),p.get(C)===t.sessionId&&p.delete(C),ae(gr+C),Zr("release",C)},releaseConfirmed(w,C){return Zr("release",w,C)},remove(w){let C=String(w);p.get(C)===t.sessionId&&(E.delete(C),A.delete(C),p.delete(C),q(gr+C)),Zr("remove",C)},removeConfirmed(w,C){return Zr("remove",w,C)},set(w,C){let V=String(w);if(v("set",V))return;let X=Ci(C);p.get(V)===t.sessionId&&E.set(V,X),tt(he.OBJECT,{id:V,d:X,t:se()})},snap(w,C){let V=String(w);if(v("snap",V))return;let X=Ci(C);p.get(V)===t.sessionId&&E.set(V,X),tt(he.OBJECT_SNAP,{id:V,d:X,t:se()})},get(w){let C=String(w),V=p.get(C),X=E.get(C);if(V===void 0&&!A.has(C)&&!X)return;let we=V!==void 0&&V===t.sessionId,pe,Me;return we&&X?(pe=X,Me=X,u.set(gr+C,X),l.set(gr+C,se())):(Me=A.get(C)??{},pe=W(gr+C,se())??Me),{id:C,epoch:S.get(C)??0,owner:V,isMine:we,state:pe,stateRaw:Me}},ids(){return[...new Set([...p.keys(),...A.keys(),...E.keys()])]}},get isHost(){return bt&&!en&&!Pn&&M!==void 0&&M===t.sessionId},get host(){return M},inputs:{send(w){tt(he.INPUT,Ci(w),!0)},on(w){let C=ne.get(xe.INPUT);C||ne.set(xe.INPUT,C=new Set);let V=(X,we)=>w(X,we);return C.add(V),()=>{C?.delete(V)}}},onHostTick(w,C){let V=null,X=0,we=Number.isFinite(w)&&w>0?Math.min(w,100):20,pe=Math.max(10,Math.round(1e3/we)),Me=()=>{let Ne=bt&&!en&&!Pn&&M!==void 0&&M===t.sessionId;Ne&&!V?(X=lo(),V=setInterval(()=>{let ze=lo();C(Math.min(ze-X,X0)),X=ze},pe)):!Ne&&V&&(clearInterval(V),V=null)},ie=Fo("host",Me);return oa.add(Me),Me(),()=>{ie(),oa.delete(Me),V&&clearInterval(V),V=null}},on:Fo,send(w,C){if(!YT(w)){console.warn(`[multiplayer] send('${w}') collides with a relay-internal channel \u2014 use a different event name`);return}tt(w,C,!0)},chat:{send(w){typeof w=="string"&&w.trim()&&tt(he.CHAT,{text:w},!0)},on(w){return Ns.add(w),()=>Ns.delete(w)},get history(){return[...Rr]},mute(w){typeof w=="string"&&w&&Bs.add(w)},unmute(w){Bs.delete(w)},get muted(){return[...Bs]}},voice:{async join(w){if(await Ve.start(w,!0),!w?.iceServers?.length){let C=await Ds.request();Ve.active&&C?.iceServers?.length&&(Ve.setIceServers(C.iceServers),Xn(C.ttl))}Ve.active&&(tt(he.VOICE_JOIN,{},!0),Ve.releasePeering())},leave(){Do(),tt(he.VOICE_LEAVE,{},!0),Ve.stop()},get active(){return Ve.active},get participants(){return Ve.participants},setMicEnabled(w){Ve.setMicEnabled(w===!0)},get micEnabled(){return Ve.micEnabled},get speaking(){return Ve.speaking},mute(w){Ve.mute(w)},unmute(w){Ve.unmute(w)},setVolume(w,C){Ve.setVolume(w,C)},get muted(){return Ve.participants.filter(w=>w.muted).map(w=>w.id)}},setRoomOpen(w){tt(he.ROOM_OPEN,{open:w===!0})},leave(){en=!0,eu(),Ve.stop(),Do(),bt=!1,Cs(),Oo("aborted"),t.reconnection.enabled=!1,t.leave().catch(()=>{})},serverNow:ns,get rtt(){if(!ts)return;let w=t.clock.smoothedRtt();return w>0?w:void 0},get clockSynced(){return ts?.synced===!0},timeUntil:aa};return Object.defineProperty(Ls,Jp,{value:()=>t,enumerable:!1}),Object.defineProperty(Ls,Symbol.for("genex.multiplayer.internals"),{enumerable:!1,value:{senderOf:w=>a.get(w),offsetOf:w=>{let C=a.get(w);return C===void 0?void 0:s.get(C)},offsetSamples:w=>o.get(w)?.samples.length??0,bufferLength:w=>n.get(w)?.length??0}}),Ls}var ZT=[1e3,2e3,4e3],eh=t=>dc(t.room,t.name,t.auth);function nw(t,e,n=r=>r-Date.now()){let r=t?.state?.match,s=r?ql(r):null,o=s&&typeof s=="object"?s:null;if(!o)return{status:t?"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:t?"Waiting for players\u2026":"Finding a match\u2026",startsAt:null,endsBy:null,startsInMs:null,endsInMs:null};let i=t?.sessionId,a=o.championId??null,c=o.challengerId??null,u=o.teams??{},l=Array.isArray(o.players)?o.players:[],d=o.connectedPlayers??l,f=i!=null&&l.includes(i),h=f?o.phase:"spectating",p=l.filter(P=>P!==i),y=i?Object.keys(u).find(P=>u[P]?.includes(i))??null:null,{winCondition:S,...b}=o.cfg??{},x=P=>typeof P=="number"&&Number.isFinite(P)&&P>0?P:null,R=x(o.startsAt),A=x(o.endsBy),E=P=>P===null?null:Math.max(0,n(P));return{status:h,role:f?"player":"spectator",queue:{position:0,size:0},players:l,connectedPlayers:d,opponents:p,teams:u,myTeam:y,scores:o.scores??{},config:b,winCondition:S?.type??"lastStanding",championId:a,challengerId:c,roundId:o.roundId??0,winnerId:o.winnerId??null,message:o.message??"",startsAt:R,endsBy:A,startsInMs:E(R),endsInMs:E(A)}}function Oi(t,e,n){if(t?.connection?.isOpen)try{t.send(e,n)}catch{}}async function rw(t){let e=await lc(t),n=await Yl(t.smoothing),r=new Map,s=(P,...k)=>r.get(P)?.forEach(M=>M(...k)),o=((P,k)=>{let M=r.get(P);return M||r.set(P,M=new Set),M.add(k),()=>{M?.delete(k)}}),i=null,a=null,c=null,u={position:0,size:0},l=!1,d=!1,f=0,h=!1,p=!1,y=async()=>{if(l||d)return;d=!0;let P=++f;try{i=null,a=null;for(let k=0;;k++){c&&(c.leave(),c=null),u={position:0,size:0};let M;try{M=$0(await e.joinOrCreate(co.QUEUE,eh(t)))}catch(B){if(l)return;let K=fc(B);K&&Gp();let j=K?void 0:ZT[k];if(j==null){if(k===0&&await new Promise(L=>setTimeout(L,0)),l)return;s("error",B);return}if(await new Promise(L=>setTimeout(L,j)),l)return;continue}if(l||P!==f){M.leave();return}c=M,M.onMessage(xe.QUEUE,B=>{u={position:B.position,size:B.size},s("queue",B)}),M.onMessage(xe.SEAT,B=>{l||P!==f||c!==M||h||(h=!0,c=null,M.leave(),S(B.reservation,B.role,P))}),M.onLeave(()=>{l||c!==M||(c=null,(async()=>{for(let B of JT)if(await new Promise(K=>setTimeout(K,B)),l||c||i||(await y(),c||i))return})())}),s("searching");return}}finally{d=!1}},S=async(P,k,M)=>{try{let B=xs(await e.consumeSeatReservation(P));if(l||M!==f){B.leave();return}a=B;let K=Qp(B,{pose:t.pose,smoothing:t.smoothing,predict:n});i=K,K.on(xe.MATCH_START,j=>s("matchStart",j)),K.on(xe.MATCH_ENDED,j=>s("matchEnded",j)),K.on(xe.MATCH_REQUEUE,()=>{i===K&&b()}),K.on("disconnect",j=>{if(!(l||i!==K)){if(j===pn.SUPERSEDED||j===pn.REVOKED){f++,h=!1,a=null,i=null,s("disconnect",j);return}b()}}),c&&(c.leave(),c=null),s("matched"),k==="spectator"&&s("spectate")}catch{!l&&M===f&&(h=!1,y())}finally{M===f&&(h=!1)}},b=async()=>{if(!(l||p)){p=!0;try{f++,h=!1,i?.leave(),a=null,i=null,await y()}finally{p=!1}}};y();let x=()=>i?zr(i):null,R=null,A=null,E=()=>{i!==R&&(R=i,A=null);let P=x(),k=!!P?.state?.match;if(!k&&i&&A)return A;let M=nw(P,u,i?i.timeUntil:void 0);return k&&(A=M),M};return{get session(){return i},get matchmaking(){return E()},on:o,eliminated(){Oi(x(),he.MATCH_ELIMINATED,{})},score(P=1){Oi(x(),he.MATCH_SCORE,{delta:P})},finish(){Oi(x(),he.MATCH_FINISH,{})},retry(){l||d||c||a||y()},cancel(){l=!0,f++,h=!1,i?.leave(),!i&&a&&a.leave(),c&&c.leave(),a=null,c=null,i=null}}}function sw(t,e){let n=new Map,r=(c,...u)=>n.get(c)?.forEach(l=>l(...u)),s=((c,u)=>{let l=n.get(c);return l||n.set(c,l=new Set),l.add(u),()=>{l?.delete(u)}}),o=!0,i=Qp(t,e);i.on(xe.MATCH_START,c=>r("matchStart",c)),i.on(xe.MATCH_ENDED,c=>r("matchEnded",c)),i.on(xe.MATCH_REQUEUE,()=>{o=!1}),i.on("disconnect",()=>{o=!1});let a=()=>o?zr(i):null;return{get session(){return o?i:null},get matchmaking(){return nw(a(),{position:0,size:0},i.timeUntil)},on:s,eliminated(){Oi(a(),he.MATCH_ELIMINATED,{})},score(c=1){Oi(a(),he.MATCH_SCORE,{delta:c})},finish(){Oi(a(),he.MATCH_FINISH,{})},retry(){},cancel(){i.leave(),o=!1}}}async function ow(t){let e=await lc(t),n=await Yl(t.smoothing),r=xs(await e.create(co.MATCH,eh(t))),s=sw(r,{pose:t.pose,smoothing:t.smoothing,predict:n});return Object.defineProperty(s,"code",{value:r.roomId,enumerable:!0}),s}async function iw(t,e){let n=await lc(e),r=await Yl(e.smoothing),s=xs(await n.joinById(t,eh(e)));return sw(s,{pose:e.pose,smoothing:e.smoothing,predict:r})}var QT=2,Kl=ga;function ev(t){Kl=t??ga}function tv(t){let e=JSON.parse(t);if(!Mn(e))throw new TypeError("genex bridge: options must be a JSON object");let n=typeof e.gameId=="string"?e.gameId:"";if(!n)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(Mn(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 o=typeof e.controlTimeoutMs=="number"&&Number.isFinite(e.controlTimeoutMs)?e.controlTimeoutMs:void 0,i=e.smoothing==="genex"||e.smoothing==="predict"||Mn(e.smoothing)?e.smoothing:void 0;return{gameId:n,name:typeof e.name=="string"&&e.name?e.name:void 0,urls:r,room:s,pose:e.pose===!0,smoothing:i,controlTimeoutMs:o,options:Mn(e.options)?e.options:void 0}}var th=new Map,nv=1,nh=t=>t.closed?null:t.mm?t.mm.session:t.session;function hc(t){t.closed=!0,t.connected=!1;for(let e of t.unwire.splice(0))e();t.wired=null,t.session=null,t.mm=null}function cw(t,e){if(t.wired===e)return;for(let i of t.unwire.splice(0))i();t.wired=e,t.connected=!0,t.lastConnected.clear(),t.lastMatch="";let n=zr(e);t.sessionId=e.id,t.roomId=n.roomId;let r=t.unwire,s=i=>n.state?.players?.get(i)?.connected!==!1,o=i=>{let a=s(i),c=t.lastConnected.get(i);t.lastConnected.set(i,a),c!==void 0&&c!==a&&ye(t,{type:"playerConnection",id:i,connected:a})};ye(t,{type:"joined",sessionId:e.id}),n.state?.players?.forEach((i,a)=>{t.lastConnected.set(a,s(a)),ye(t,{type:"playerJoined",id:a})});for(let i of e.objects.ids())ye(t,{type:"objectChanged",id:i,owner:e.objects.get(i)?.owner??null});e.host!==void 0&&ye(t,{type:"hostChanged",host:e.host}),r.push(e.on("join",i=>{t.lastConnected.set(i,s(i)),ye(t,{type:"playerJoined",id:i})}),e.on("change",i=>{o(i),t.changed.has(i)||(t.changed.add(i),ye(t,{type:"playerChanged",id:i}))}),e.on("leave",i=>{t.lastConnected.delete(i),ye(t,{type:"playerLeft",id:i})}),e.on("host",i=>ye(t,{type:"hostChanged",host:i??null})),e.on("shared",(i,a)=>ye(t,{type:"sharedChanged",key:i,value:a??null})),e.on("object",i=>{let a=e.objects.get(i);ye(t,a?{type:"objectChanged",id:i,owner:a.owner??null}:{type:"objectRemoved",id:i})}),e.on("room:open",({open:i})=>ye(t,{type:"roomOpen",open:i})),e.on("reconnecting",({attempt:i,code:a})=>{t.connected=!1,ye(t,{type:"reconnecting",code:a,attempt:i})}),e.on("reconnected",()=>{t.connected=!0,ye(t,{type:"reconnected"})}),e.on("disconnect",i=>{t.connected=!1,t.opts.room!=="queue"&&(hc(t),ye(t,{type:"disconnected",code:i,reason:""}))}),e.on(xe.SERVER_RESTART,()=>ye(t,{type:"serverRestart"})),e.on(xe.MATCH_START,i=>ye(t,{type:"matchStart",roundId:Mn(i)&&typeof i.roundId=="number"?i.roundId:0})),e.on(xe.MATCH_ENDED,i=>ye(t,{type:"matchEnded",data:i??null})),e.on(xe.MATCH_REQUEUE,i=>ye(t,{type:"matchRequeue",reason:Mn(i)&&typeof i.reason=="string"?i.reason:null})),e.inputs.on((i,a)=>ye(t,{type:"input",from:i,data:a??null})),e.chat.on(i=>ye(t,{type:"chat",id:i.id,from:i.from,name:i.name,text:i.text,at:i.at})),n.onMessage(xe.RATE_DROP,i=>ye(t,{type:"rateDrop",dropped:Mn(i)&&typeof i.dropped=="number"?i.dropped:0})),n.onMessage("*",(i,a)=>{typeof i=="string"&&!ws(i)&&ye(t,{type:"message",kind:i,data:a??null})}))}function Xl(t){let e=nh(t);e&&e!==t.wired&&cw(t,e)}async function rv(t){let e=t.opts;if(await Kl.ready(e.gameId),t.closed)return;let n=e.urls.length?e.urls:Kl.urls();if(!n.length)throw Object.assign(new Error("genex bridge: no relay URL (pass urls, or run on a Genex page)"),{code:0});let r=()=>Kl.auth(),s={urls:n,room:e.gameId,name:e.name,auth:r,pose:e.pose,smoothing:e.smoothing};if(e.room==="play"){let a=await tw({...s,options:e.options});if(t.closed)return void a.leave();t.session=a,cw(t,a);return}let o=s,i=e.room==="queue"?await rw(o):e.room==="private"?await ow(o):await iw(e.room.joinById,o);if(t.closed)return void i.cancel();t.mm=i,i.on("queue",a=>{Mn(a)&&ye(t,{type:"queue",position:Number(a.position)||0,size:Number(a.size)||0})}),i.on("matched",()=>{ye(t,{type:"seated"}),Xl(t)}),i.on("searching",()=>{if(t.wired){for(let a of t.unwire.splice(0))a();t.wired=null,t.connected=!1}}),i.on("error",a=>{let c=t.mm;hc(t),c?.cancel(),ye(t,{type:"joinFailed",code:Jo(a),message:tr(a)})}),i.on("disconnect",a=>{hc(t),ye(t,{type:"disconnected",code:typeof a=="number"?a:0,reason:""})}),Xl(t)}function uw(t){let e=tv(t),n=nv++,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};th.set(n,r);let s=rv(r).catch(o=>{throw hc(r),ye(r,{type:"joinFailed",code:Jo(o),message:tr(o)}),o});return{handle:n,done:s}}function sv(t){let{handle:e,done:n}=uw(t);return n.catch(()=>{}),e}async function ov(t){let{handle:e,done:n}=uw(t);try{await n}catch(r){let s=new Error(tr(r));throw s.code=Jo(r),s}return e}var _s=t=>th.get(t),Dt=t=>{let e=_s(t);return e?(Xl(e),nh(e)):null};function lw(t){let e=_s(t);if(!e||e.closed)return;let{mm:n,session:r}=e;hc(e),n?n.cancel():r?.leave(),ye(e,{type:"disconnected",code:4e3,reason:"left"})}function iv(t){lw(t),typeof t=="number"&&th.delete(t)}function av(t,e){let n=nr(e,"state"),r=Dt(t);return r?(r.me.set(n),!0):!1}function cv(t,e){let n=nr(e,"state"),r=Dt(t);return r?(r.me.snap(n),!0):!1}function uv(t,e,n){let r=ba(n,"value");if(typeof e!="string"||!e||e.startsWith(zl))return!1;let s=Dt(t);return s?(s.shared.set(e,r),!0):!1}function lv(t,e,n){let r=nr(n,"object state"),s=Dt(t);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.set(e,r),!0)}function dv(t,e,n){let r=nr(n,"object state"),s=Dt(t);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.snap(e,r),!0)}function fv(t,e,n){let r=ba(n,"event data");if(typeof e!="string"||!e||e.length>Xt.MAX_EVENT_TYPE_CHARS||ws(e))return!1;let s=Dt(t);return s?(s.send(e,r),!0):!1}function pv(t,e){}function hv(t,e){let n=ba(e,"input"),r=Dt(t);return r?(r.inputs.send(n),!0):!1}function mv(t,e){let n=Dt(t);return n?(n.setRoomOpen(e===!0),!0):!1}function yv(t,e){let n=Dt(t);return!n||typeof e!="string"?!1:(n.chat.send(e),!0)}function Jl(t,e,n,r,s=!1){if(typeof n!="string"||!n)throw new TypeError("genex bridge: object id must be a non-empty string");let o=_s(t),i=Dt(t),a=l=>{if(!o)return;let d={type:"controlResult",requestId:String(r),operation:e,id:n,accepted:l.accepted,owner:l.owner??null,sequence:l.sequence,reason:l.reason};typeof l.retryAfterMs=="number"&&(d.retryAfterMs=l.retryAfterMs),ye(o,d)};if(!i){a({accepted:!1,sequence:0,reason:"disconnected"});return}let c={timeoutMs:o?.opts.controlTimeoutMs,...s?{authority:"host"}:{}};(e==="claim"?i.objects.claimConfirmed(n,c):e==="release"?i.objects.releaseConfirmed(n,c):i.objects.removeConfirmed(n,c)).then(a,()=>a({accepted:!1,sequence:0,reason:"disconnected"}))}function gv(t,e,n){Jl(t,"claim",e,n)}function bv(t,e,n){Jl(t,"claim",e,n,!0)}function wv(t,e,n){Jl(t,"release",e,n)}function Sv(t,e,n){Jl(t,"remove",e,n)}function xv(t){let e=_s(t);return!e?.mm||e.closed?!1:(e.mm.eliminated(),!0)}function _v(t,e=1){let n=_s(t);return!n?.mm||n.closed||typeof e!="number"||!Number.isFinite(e)?!1:(n.mm.score(e),!0)}function Rv(t){let e=_s(t);return!e?.mm||e.closed?!1:(e.mm.finish(),!0)}function Ev(t){return Dt(t)?.serverNow()??null}function kv(t,e){let n=Dt(t);return n?n.timeUntil(e):e-Date.now()}var aw=t=>typeof t=="number"&&Number.isFinite(t)?t:null;function Av(t){let e=_s(t),n=Dt(t),r=n?zr(n):null,s=r?.state?.match,o=null;if(s)try{o=JSON.parse(s)}catch{o=null}return JSON.stringify({sessionId:n?.id??e?.sessionId??"",roomId:r?.roomId??e?.roomId??"",hostId:n?.host??null,isHost:n?.isHost??!1,connected:!!n&&!!e?.connected,closed:!e||e.closed,serverNow:aw(n?.serverNow()),rtt:aw(n?.rtt),clockSynced:n?.clockSynced??!1,clockOrigin:r?.state?.clockOrigin??0,matchState:o})}function Pv(t){let e=Dt(t);if(!e)return"[]";let n=zr(e).state?.players,r=[];for(let[s,o]of e.players){let i=n?.get(s);r.push({id:s,name:o.name,uid:o.uid,team:o.team,connected:o.connected,avatarUrl:o.avatarUrl,state:o.state??{},stateRaw:o.stateRaw??{},epoch:i?.epoch??0,isMe:s===e.id,posed:i?.posed===!0})}return JSON.stringify(r)}function Tv(t){let e=Dt(t);if(!e)return"[]";let n=zr(e).state?.objects,r=[];for(let s of e.objects.ids()){let o=e.objects.get(s);o&&r.push({id:s,owner:o.owner??null,isMine:o.isMine,seq:n?.get(s)?.seq??0,epoch:o.epoch,state:o.state??null,stateRaw:o.stateRaw??null})}return JSON.stringify(r)}function vv(t){let e=Dt(t),n={};if(e)for(let r of e.shared.keys())n[r]=e.shared.get(r)??null;return JSON.stringify(n)}function Mv(t){let e=_s(t);if(!e)return"[]";try{Xl(e);let n=nh(e);if(n){let r=zr(n).state?.match??"";if(r!==e.lastMatch){e.lastMatch=r;let s=null;try{s=r?JSON.parse(r):null}catch{s=null}ye(e,{type:"matchState",state:s})}}e.changed.clear()}catch(n){ye(e,Xo(tr(n)))}return Mu(e)}var Am={};of(Am,{BODY_F32_STRIDE:()=>_m,BodyF32Flag:()=>Rm,authorityJson:()=>ED,bodiesF32:()=>_D,bodyKeysJson:()=>RD,closeAuthority:()=>VR,disposeAuthority:()=>PD,drainAuthorityEventsJson:()=>AD,frame:()=>SD,openAuthority:()=>mD,predictProjectile:()=>gD,setAuthorityIdentity:()=>rD,setAuthorityPhysicsCore:()=>sD,setInput:()=>yD,setWorld:()=>bD,version:()=>nD});var dw=2*Math.PI,fw=Math.fround(Math.PI),Oe=t=>t===0?0:t;function Hn(t){if(typeof t!="number"||!Number.isFinite(t))return 0;let e=t<-1?-1:t>1?1:t;return Oe(Math.fround(e))}function Rs(t){if(typeof t!="number"||!Number.isFinite(t)||Math.abs(t)>1e9)return null;let e=Math.fround(t-dw*Math.floor((t+Math.PI)/dw));return e===fw?-fw:Oe(e)}function fo(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<16777216?t:0}function Zl(t,e){return typeof t!="number"||!Number.isFinite(t)||t<=0?0:t>e?e:t}var mn=(t,e,n)=>t<e?e:t>n?n:t,pw=5734161139222659/2**53,hw=1686629713/2**30,mw=2242054355/2**65,yw=5376105825661043/2**121,gw=-6004799503160649/2**55,bw=0x8888888887c53/2**58,ww=-7320136532976085/2**65,Sw=6506786730409597/2**71,xw=-7571127717829867/2**78,_w=0x5764e96b3f55f/2**83,Rw=0x5555555555553/2**55,Ew=-6405119470031223/2**62,kw=457508533350745/2**64,Aw=-5205429506036397/2**74,Pw=0x47ba7af6d2c71/2**79,Tw=-0x63eba6fa20e35/2**87,$z=Object.freeze({invpio2:pw,pio2_1:hw,pio2_2:mw,pio2_2t:yw,S1:gw,S2:bw,S3:ww,S4:Sw,S5:xw,S6:_w,C1:Rw,C2:Ew,C3:kw,C4:Aw,C5:Pw,C6:Tw});function Ut(t){if(!Number.isFinite(t)||Math.abs(t)>1e9)return[0,1];let e=Math.floor(t*pw+.5),n=e-4*Math.floor(e/4),r=t-e*hw-e*mw-e*yw,s=r*r,o=r+s*r*(gw+s*(bw+s*(ww+s*(Sw+s*(xw+s*_w))))),i=.5*s,a=1-i,c=a+(1-a-i+s*(s*(Rw+s*(Ew+s*(kw+s*(Aw+s*(Pw+s*Tw)))))));return n===0?[Oe(o),Oe(c)]:n===1?[Oe(c),Oe(-o)]:n===2?[Oe(-o),Oe(-c)]:[Oe(-c),Oe(o)]}var vw=t=>Ut(t)[0],Mw=t=>Ut(t)[1];var wr={TOPDOWN:"topdown",FIRSTPERSON:"firstperson",VEHICLE:"vehicle"},ch=.25,Cv=Object.freeze({speed:6,arena:20}),Ov={speed:{min:0,max:1e3,positive:!1},arena:{min:0,max:1e6,positive:!0}};var uh=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.getPrototypeOf(t)===Object.prototype;function Bw(t,e){if(e===void 0)return!0;let n=bc(t)?.ranges;return n===void 0||!uh(e)?!1:Object.keys(e).every(r=>{if(!Object.hasOwn(n,r))return!1;let s=n[r],o=e[r];return typeof o!="number"||!Number.isFinite(o)||o<s.min||o>s.max||s.integer===!0&&!Number.isInteger(o)?!1:!s.positive||o>0&&Math.fround(o)>0})}function Di(t,e){let n=bc(t);if(n===void 0)return{};let r={...n.defaults};if(!uh(e))return r;for(let s of Object.keys(n.ranges))Bw(t,{[s]:e[s]})&&(r[s]=e[s]);return r}var sh=t=>Number.isFinite(t)?t:0;function Iv(t,e,n,r){let s=Hn(e.moveX),o=Hn(e.moveY),i=Zl(n,ch),a=Math.sqrt(s*s+o*o),c=a>1?1/a:1,u=sh(t.x)+s*c*r.speed*i,l=sh(t.y)+o*c*r.speed*i;return{x:Oe(Math.fround(mn(u,-r.arena,r.arena))),y:Oe(Math.fround(mn(l,-r.arena,r.arena))),yaw:Rs(e.yaw)??Oe(Math.fround(sh(t.yaw)))}}var Lw=2615243109,Dv=Object.freeze({maxSpeed:250,walkSpeed:.52,crouchSpeed:.34,accelerate:5.5,airAccelerate:12,airMaxWishSpeed:30,friction:5.2,stopSpeed:80,gravity:800,jumpImpulse:301.993,maxVelocity:3500,radius:16,standHeight:72,crouchHeight:54,duckTime:.4,airDuck:1,stepHeight:18,standable:.7,groundTrace:2.5,groundSnap:1,skin:.03,pitchLimit:1.5533430576324463,jumpBit:1,duckBit:2,walkBit:4,substeps:2,capZeroJump:1,runBit:0,jogSpeed:1,world:Lw}),Ee=(t,e)=>({min:t,max:e,positive:!1}),ho=t=>({min:0,max:t,positive:!0}),Jt=(t,e)=>({min:t,max:e,positive:!1,integer:!0}),Nv={maxSpeed:Ee(0,1e4),walkSpeed:Ee(0,1),crouchSpeed:Ee(0,1),accelerate:Ee(0,1e3),airAccelerate:Ee(0,1e3),airMaxWishSpeed:Ee(0,1e4),friction:Ee(0,1e3),stopSpeed:Ee(0,1e4),gravity:Ee(0,1e5),jumpImpulse:Ee(0,1e5),maxVelocity:Ee(0,1e5),radius:ho(1e4),standHeight:ho(1e4),crouchHeight:ho(1e4),duckTime:ho(100),airDuck:Jt(0,1),stepHeight:Ee(0,1e4),standable:Ee(0,1),groundTrace:Ee(0,1e4),groundSnap:Ee(0,1e4),skin:Ee(0,100),pitchLimit:Ee(0,1.5707963705062866),jumpBit:Jt(0,16777215),duckBit:Jt(0,16777215),walkBit:Jt(0,16777215),substeps:Jt(1,8),capZeroJump:Jt(0,1),runBit:Jt(0,16777215),jogSpeed:Ee(0,1),world:Jt(0,2**32-1)};var Vt={ON_GROUND:1,DUCKING:2,JUMP_HELD:4},Bv=Vt.ON_GROUND|Vt.DUCKING|Vt.JUMP_HELD,Lv={MAX_BOXES:32768,MAX_RAMPS:4096,MAX_ABS:1e9},yn=class extends RangeError{constructor(n,r){super(`firstperson world: ${n} ${r}`);m(this,"path");this.name="WorldError",this.path=n}},mc=new WeakMap,Fv=(t,e)=>{if(typeof t!="number"||!Number.isFinite(t))throw new yn(e,"is not a finite number");if(Math.fround(t)!==t)throw new yn(e,"is not a float32");if(Math.abs(t)>1e9)throw new yn(e,`is past \xB1${1e9}`);return Oe(t)};function Cw(t,e,n){if(!Array.isArray(t)||t.length!==e)throw new yn(n,`is not an array of ${e} numbers`);let r=[];for(let s=0;s<e;s++)r.push(Fv(t[s],`${n}[${s}]`));if(!(r[0]<r[3]&&r[1]<r[4]&&r[2]<r[5]))throw new yn(n,"needs min < max on every axis");return r}function Ow(t,e,n){if(t===void 0)return[];if(!Array.isArray(t))throw new yn(e,"is not an array");if(t.length>n)throw new yn(e,`holds more than ${n}`);return t}function zv(t,e){let n=new DataView(new ArrayBuffer(8+4*(6*t.length+9*e.length)));n.setUint32(0,t.length,!0),n.setUint32(4,e.length,!0);let r=8;for(let o of[...t,...e])for(let i of o)n.setFloat32(r,i,!0),r+=4;let s=2166136261;for(let o=0;o<n.byteLength;o++)s=Math.imul(s^n.getUint8(o),16777619)>>>0;return s}function mo(t,e={}){let n=mc.has(t)?t:void 0;if(n!==void 0&&(e.broadphase===void 0||e.broadphase===n.broadphase))return n;if(t!==void 0&&!uh(t))throw new yn("$","is not an object");let r=t??{},s=e.caps??Lv,o=Ow(r.boxes,"boxes",s.MAX_BOXES).map((c,u)=>Object.freeze(Cw(c,6,`boxes[${u}]`))),i=Ow(r.ramps,"ramps",s.MAX_RAMPS).map((c,u)=>{let l=`ramps[${u}]`,d=Cw(c,9,l);if(d[6]!==0&&d[6]!==1)throw new yn(`${l}[6]`,"is not an axis (0 or 1)");let[f,h,p,y]=[d[2],d[5],d[7],d[8]];if(!(f<=p&&f<=y))throw new yn(l,"needs minZ \u2264 lo and minZ \u2264 hi");if(h!==Math.max(p,y))throw new yn(l,"needs maxZ = max(lo, hi)");return Object.freeze(d)}),a=Object.freeze({boxes:Object.freeze(o),ramps:Object.freeze(i),hash:zv(o,i),broadphase:e.broadphase!==!1});return mc.set(a,Uv(a)),a}var yc=mo(void 0),Hr={Box:0,OBox:1,Disc:2},ih=96,lh=new Int32Array(ih);function gc(t){let e=t.length;if(e>ih)throw new RangeError(`posed solids: at most ${ih} a tick`);let n=()=>new Float64Array(e),r={count:e,kind:new Uint8Array(e),minX:n(),minY:n(),minZ:n(),maxX:n(),maxY:n(),maxZ:n(),cx:n(),cy:n(),hx:n(),hy:n(),sin:n(),cos:n(),radius:n()};return t.forEach((s,o)=>{if(s.kind==="box"){r.kind[o]=Hr.Box,[r.minX[o],r.minY[o],r.minZ[o]]=s.min,[r.maxX[o],r.maxY[o],r.maxZ[o]]=s.max;return}if(r.cx[o]=s.c[0],r.cy[o]=s.c[1],r.minZ[o]=s.c[2]-(s.kind==="disc"?s.half:s.half[2]),r.maxZ[o]=s.c[2]+(s.kind==="disc"?s.half:s.half[2]),s.kind==="disc"){r.kind[o]=Hr.Disc,r.radius[o]=s.radius,r.minX[o]=s.c[0]-s.radius,r.maxX[o]=s.c[0]+s.radius,r.minY[o]=s.c[1]-s.radius,r.maxY[o]=s.c[1]+s.radius;return}r.kind[o]=Hr.OBox,r.hx[o]=s.half[0],r.hy[o]=s.half[1],r.sin[o]=s.sin,r.cos[o]=s.cos;let i=Math.abs(s.cos),a=Math.abs(s.sin),c=s.half[0]*i+s.half[1]*a,u=s.half[0]*a+s.half[1]*i;r.minX[o]=s.c[0]-c,r.maxX[o]=s.c[0]+c,r.minY[o]=s.c[1]-u,r.maxY[o]=s.c[1]+u}),r}var Fw=gc([]);function dh(t){let e=mc.get(t);if(e!==void 0)return e;let n=mo(t,{broadphase:t.broadphase!==!1}),r=mc.get(n);return mc.set(t,r),r}var Ii=8,Iw=2**23;function Uv(t){let e=[...t.boxes,...t.ramps],n=e.length,r=()=>new Float64Array(n),s={boxCount:t.boxes.length,count:n,minX:r(),minY:r(),minZ:r(),maxX:r(),maxY:r(),maxZ:r(),axis:new Uint8Array(n),lo:r(),hi:r(),m0:r(),span:r(),slope:r(),topZ:r()};return e.forEach((o,i)=>{if(s.minX[i]=o[0],s.minY[i]=o[1],s.minZ[i]=o[2],s.maxX[i]=o[3],s.maxY[i]=o[4],s.maxZ[i]=o[5],i<s.boxCount)return;let a=o[6],c=a===0?o[0]:o[1],l=(a===0?o[3]:o[4])-c,d=(o[8]-o[7])/l;s.axis[i]=a,s.lo[i]=o[7],s.hi[i]=o[8],s.m0[i]=c,s.span[i]=l,s.slope[i]=d,s.topZ[i]=1/Math.sqrt(1+d*d)}),{...s,tree:t.broadphase&&n>0?Hv(s):null}}function oh(t){let e=t&1023;return e=(e|e<<16)&50331903,e=(e|e<<8)&50393103,e=(e|e<<4)&51130563,e=(e|e<<2)&153391689,e}function Vv(t,e){let n=1/0,r=1/0,s=1/0,o=-1/0,i=-1/0,a=-1/0;for(let d=0;d<t;d++)n=Math.min(n,e.minX[d]),r=Math.min(r,e.minY[d]),s=Math.min(s,e.minZ[d]),o=Math.max(o,e.maxX[d]),i=Math.max(i,e.maxY[d]),a=Math.max(a,e.maxZ[d]);let c=(d,f,h)=>h>f?Math.min(1023,Math.floor((d-f)/(h-f)*1024)):0,u=new Float64Array(t);for(let d=0;d<t;d++){let f=c((e.minX[d]+e.maxX[d])/2,n,o),h=c((e.minY[d]+e.maxY[d])/2,r,i),p=c((e.minZ[d]+e.maxZ[d])/2,s,a);u[d]=(oh(f)|oh(h)<<1|oh(p)<<2)*Iw+d}u.sort();let l=new Int32Array(t);for(let d=0;d<t;d++)l[d]=u[d]%Iw;return l}function Hv(t){let e=t.count,n=Vv(e,t),r=[e];for(;r[r.length-1]>1;)r.push(Math.ceil(r[r.length-1]/Ii));let s=r.reduce((l,d)=>l+d,0),o=new Float64Array(s*6),i=new Int32Array(s),a=new Int32Array(r.length);for(let l=0;l<e;l++){let d=n[l],f=l*6;o[f]=t.minX[d],o[f+1]=t.minY[d],o[f+2]=t.minZ[d],o[f+3]=t.maxX[d],o[f+4]=t.maxY[d],o[f+5]=t.maxZ[d],i[l]=d}a[0]=e;let c=0,u=e;for(let l=1;l<r.length;l++){let d=a[l-1];for(let f=c;f<d;f+=Ii){let h=Math.min(f+Ii,d),p=1/0,y=1/0,S=1/0,b=-1/0,x=-1/0,R=-1/0;for(let E=f;E<h;E++){let P=E*6;p=Math.min(p,o[P]),y=Math.min(y,o[P+1]),S=Math.min(S,o[P+2]),b=Math.max(b,o[P+3]),x=Math.max(x,o[P+4]),R=Math.max(R,o[P+5])}let A=u*6;o[A]=p,o[A+1]=y,o[A+2]=S,o[A+3]=b,o[A+4]=x,o[A+5]=R,i[u]=f,u++}c=d,a[l]=u}return{boxes:o,ref:i,levelEnd:a,root:s-1}}var zw=16,Uw=50,$v=.5,fh=(t,e)=>t/e<$v?t/e:1,ph=(t,e,n,r,s,o)=>.001+1e-7*(Math.abs(t)+Math.abs(e)+Math.abs(n)+Math.abs(r)+Math.abs(s)+Math.abs(o)),br=null;function hh(t,e,n,r,s,o,i){jv(t,e,n,r,s,o,i);let a=t.w.tree;if(a===null){t.nCand=-1;return}let c=ph(e,n,r,s,o,i),u=t.r+c,l=e-u,d=s+u,f=n-u,h=o+u,p=r-c,y=i+c,{boxes:S,ref:b,levelEnd:x}=a,R=x[0],A=t.cand,E=t.stack,P=0,k=0,M=0;for(E[k++]=a.root;k>0;){let B=E[--k];M+=1;let K=B*6;if(S[K+3]<l||S[K]>d||S[K+4]<f||S[K+1]>h||S[K+5]<p||S[K+2]>y)continue;if(B<R){A[P++]=b[B];continue}let j=b[B],L=j+Ii;for(let se=0;se<x.length;se++)if(j<x[se]){L=Math.min(L,x[se]);break}for(let se=j;se<L;se++)E[k++]=se}t.nCand=P,br!==null&&(br.nodes+=M,br.tests+=P)}function jv(t,e,n,r,s,o,i){let a=t.p,c=0;if(a.count>0){let u=ph(e,n,r,s,o,i),l=t.r+u,d=e-l,f=s+l,h=n-l,p=o+l,y=r-u,S=i+u;for(let b=0;b<a.count;b++)a.maxX[b]<d||a.minX[b]>f||a.maxY[b]<h||a.minY[b]>p||a.maxZ[b]<y||a.minZ[b]>S||(t.pc[c++]=b)}t.nPosed=c}var mh=t=>(t.nCand<0?t.w.count:t.nCand)+t.nPosed,yh=(t,e)=>{let n=t.nCand<0?t.w.count:t.nCand;return e>=n?t.w.count+t.pc[e-n]:t.nCand<0?e:t.cand[e]},Ur=(t,e)=>t.standHeight+(t.crouchHeight-t.standHeight)*e;function Wv(t,e,n,r){let s=t.w,o=s.slope[e],i=s.axis[e]===0?n:r,a=o>0?i+t.r:o<0?i-t.r:i;return s.lo[e]+o*mn(a-s.m0[e],0,s.span[e])}function Vw(t,e,n,r){let s=t.w;return e<s.boxCount?s.maxZ[e]:e<s.count?Wv(t,e,n,r):t.p.maxZ[e-s.count]}var qv=(t,e)=>e<t.w.count?t.w.minZ[e]:t.p.minZ[e-t.w.count];function Hw(t,e,n,r){let s=t.w,o=t.r;return e>=s.count?Gw(t,e-s.count,n,r):n+o>s.minX[e]&&n-o<s.maxX[e]&&r+o>s.minY[e]&&r-o<s.maxY[e]}function $w(t,e,n,r,s){let o=t.w;hh(t,e,n,r,e,n,r+s);let i=mh(t);for(let a=0;a<i;a++){let c=yh(t,a);if(!Hw(t,c,e,n)||!(r+s>qv(t,c)))continue;let u=Vw(t,c,e,n);if(r<u-1e-4)return!1}return!0}function sd(t,e,n,r,s,o){let i=t.w;hh(t,e,n,r-s,e,n,r+o);let a=mh(t),c=Number.NaN,u=Number.NaN;for(let l=0;l<a;l++){let d=yh(t,l);if(!Hw(t,d,e,n))continue;let f=Vw(t,d,e,n);f<=r+o&&f>=r-s&&(d<i.boxCount||d>=i.count||i.topZ[d]>=t.standable?(c!==c||f>c)&&(c=f):(u!==u||f>u)&&(u=f))}return u>c?Number.NaN:c}function td(t){if(t.vz>.1*t.unit){t.onGround=!1;return}let e=sd(t,t.x,t.y,t.z,t.groundTrace,t.groundSnap);e===e?(t.z=e,t.onGround=!0):t.onGround=!1}function ed(t,e,n,r,s,o){if(Math.abs(n)<1e-9)return e>r&&e<s;let i=(r-e)/n,a=(s-e)/n,c=-1;if(i>a){let u=i;i=a,a=u,c=1}return i>=t.tMin&&(t.tMin=i,t.ax=o,t.sg=c),a<t.tMax&&(t.tMax=a),!(t.tMin>t.tMax)}var Je=new Float64Array(4);function Gv(t,e,n,r){let s=t.w,o=t.r,i=0,a=0,c=0,u;switch(n){case 0:i=1,u=s.maxX[e]+o;break;case 1:i=-1,u=-s.minX[e]+o;break;case 2:a=1,u=s.maxY[e]+o;break;case 3:a=-1,u=-s.minY[e]+o;break;case 4:c=-1,u=-s.minZ[e]+r;break;case 5:{let l=s.slope[e];s.axis[e]===0?i=-l:a=-l,c=1,u=s.lo[e]-l*s.m0[e]+o*Math.abs(l);break}default:c=1,u=s.maxZ[e]}Je[0]=i,Je[1]=a,Je[2]=c,Je[3]=u}function nd(t,e,n,r,s,o){let i=t.w,a=t.r,c=t.skin;if(s>=i.count)return Zv(t,e,n,r,s-i.count,o);if(s<i.boxCount)return e-(i.minX[s]-a)>c&&i.maxX[s]+a-e>c&&n-(i.minY[s]-a)>c&&i.maxY[s]+a-n>c&&r-(i.minZ[s]-o)>c&&i.maxZ[s]-r>c;for(let u=0;u<7;u++){Gv(t,s,u,o);let l=Je[0],d=Je[1],f=Je[2];if(!(-(l*e+d*n+f*r-Je[3])*(1/Math.sqrt(l*l+d*d+f*f))>c))return!1}return!0}function gh(t,e,n,r,s,o,i,a,c){let u=t.w.count,l=t.w.tree,d=0,f=0,h=y=>(f+=1,y!==a&&nd(t,e,n,r,y,c)&&!nd(t,s,o,i,y,c)),p=!1;if(l===null)for(let y=0;y<u&&!p;y++)p=h(y);else{let y=ph(e,n,r,e,n,r+c),S=t.r+y,b=e-S,x=e+S,R=n-S,A=n+S,E=r-y,P=r+c+y,{boxes:k,ref:M,levelEnd:B}=l,K=B[0],j=t.stack,L=0;for(j[L++]=l.root;L>0&&!p;){let se=j[--L];d+=1;let v=se*6;if(k[v+3]<b||k[v]>x||k[v+4]<R||k[v+1]>A||k[v+5]<E||k[v+2]>P)continue;if(se<K){p=h(M[se]);continue}let $=M[se],G=$+Ii;for(let W=0;W<B.length;W++)if($<B[W]){G=Math.min(G,B[W]);break}for(let W=$;W<G;W++)j[L++]=W}}for(let y=u;!p&&y<u+t.p.count;y++)p=h(y);return br!==null&&(br.nodes+=d,br.tests+=f),p}function jw(t,e,n,r,s,o,i,a,c,u){return gh(t,e+s*a,n+o*a,r+i*a,e,n,r,c,u)}function Yv(t,e,n,r,s,o,i,a){let c=t.r,u=t.skin,l=e-(s.minX[o]-c),d=s.maxX[o]+c-e,f=n-(s.minY[o]-c),h=s.maxY[o]+c-n,p=r-(s.minZ[o]-i),y=s.maxZ[o]-r;if(!(l>u&&d>u&&f>u&&h>u&&p>u&&y>u))return!1;let S=l,b=-1,x=0,R=0;return d<S&&([S,b,x,R]=[d,1,0,0]),f<S&&([S,b,x,R]=[f,0,-1,0]),h<S&&([S,b,x,R]=[h,0,1,0]),y<S&&!gh(t,e,n,r+y,e,n,r,a,i)&&([S,b,x,R]=[y,0,0,1]),t.tMin=0,t.nx=b,t.ny=x,t.nz=R,t.depth=S,!0}function bh(t,e,n,r,s,o,i,a,c,u=t.w,l=a){let d=t.r;return t.depth=0,Yv(t,e,n,r,u,a,c,l)?!0:(t.tMin=0,t.tMax=1,t.ax=-1,t.sg=0,!ed(t,e,s,u.minX[a]-d,u.maxX[a]+d,0)||!ed(t,n,o,u.minY[a]-d,u.maxY[a]+d,1)||!ed(t,r,i,u.minZ[a]-c,u.maxZ[a],2)||t.tMin>=1||t.ax<0?!1:(t.nx=t.ax===0?t.sg:0,t.ny=t.ax===1?t.sg:0,t.nz=t.ax===2?t.sg:0,!0))}function Kv(t,e,n,r,s,o,i,a,c){let u=t.w,l=t.r,d=u.slope[a],f=u.axis[a]===0,h=0,p=1,y=!1,S=!0,b=Number.POSITIVE_INFINITY,x=0,R=0,A=0;t.depth=0;for(let E=0;E<7;E++){let P=0,k=0,M=0,B;switch(E){case 0:P=1,B=u.maxX[a]+l;break;case 1:P=-1,B=-u.minX[a]+l;break;case 2:k=1,B=u.maxY[a]+l;break;case 3:k=-1,B=-u.minY[a]+l;break;case 4:M=-1,B=-u.minZ[a]+c;break;case 5:f?P=-d:k=-d,M=1,B=u.lo[a]-d*u.m0[a]+l*Math.abs(d);break;default:M=1,B=u.maxZ[a]}let K=P*e+k*n+M*r-B,j=P*s+k*o+M*i,L=1/Math.sqrt(P*P+k*k+M*M),se=-K*L;if(se>t.skin?E!==4&&se<b&&!(S&&E>=5&&jw(t,e,n,r,P*L,k*L,M*L,se,a,c))&&(b=se,x=P*L,R=k*L,A=M*L):S=!1,Math.abs(j)<1e-9){if(K>0)return!1;continue}let v=j<0&&K<=0&&K>-t.skin?0:-K/j;if(j<0?v>=h&&(h=v,t.nx=P*L,t.ny=k*L,t.nz=M*L,y=!0):p=Math.min(p,v),h>p)return!1}return S?(t.tMin=0,t.nx=x,t.ny=R,t.nz=A,t.depth=b,!0):!y||!(h<1)||!(p>=0)?!1:(t.tMin=h,!0)}function Ww(t,e,n,r){let s=t.p,o=s.cos[e],i=s.sin[e],a=s.cx[e],c=s.cy[e],u=s.hx[e],l=s.hy[e],d=t.r,f=d*(Math.abs(o)+Math.abs(i)),h=0,p=0,y=0,S;switch(n){case 0:h=o,p=i,S=o*a+i*c+u+f;break;case 1:h=-o,p=-i,S=-(o*a+i*c)+u+f;break;case 2:h=-i,p=o,S=-i*a+o*c+l+f;break;case 3:h=i,p=-o,S=i*a-o*c+l+f;break;case 4:h=1,S=a+d+u*Math.abs(o)+l*Math.abs(i);break;case 5:h=-1,S=-a+d+u*Math.abs(o)+l*Math.abs(i);break;case 6:p=1,S=c+d+u*Math.abs(i)+l*Math.abs(o);break;case 7:p=-1,S=-c+d+u*Math.abs(i)+l*Math.abs(o);break;case 8:y=-1,S=-s.minZ[e]+r;break;default:y=1,S=s.maxZ[e]}Je[0]=h,Je[1]=p,Je[2]=y,Je[3]=S}var Xv=10,qw=8,Jv=9;function Gw(t,e,n,r){let s=t.p,o=t.r;if(!(n+o>s.minX[e]&&n-o<s.maxX[e]&&r+o>s.minY[e]&&r-o<s.maxY[e]))return!1;let i=s.kind[e];if(i===Hr.Box)return!0;let a=n-s.cx[e],c=r-s.cy[e];if(i===Hr.Disc){let f=Math.max(Math.abs(a)-o,0),h=Math.max(Math.abs(c)-o,0);return f*f+h*h<s.radius[e]*s.radius[e]}let u=s.cos[e],l=s.sin[e],d=o*(Math.abs(u)+Math.abs(l));return Math.abs(u*a+l*c)<s.hx[e]+d&&Math.abs(-l*a+u*c)<s.hy[e]+d}function Yw(t,e,n,r){let s=t.p,o=t.r,i=n-s.cx[e],a=r-s.cy[e],c=Math.abs(i),u=Math.abs(a),l=s.radius[e];if(c<=o&&u<=o){let p=c>=u;return Je[0]=p?i<0?-1:1:0,Je[1]=p?0:a<0?-1:1,l+o-(p?c:u)}let d=c>o?i<0?-(c-o):c-o:0,f=u>o?a<0?-(u-o):u-o:0,h=Math.sqrt(d*d+f*f);return Je[0]=d/h,Je[1]=f/h,l-h}function Zv(t,e,n,r,s,o){let i=t.p,a=t.skin,c=i.kind[s];if(c===Hr.Box){let u=t.r;return e-(i.minX[s]-u)>a&&i.maxX[s]+u-e>a&&n-(i.minY[s]-u)>a&&i.maxY[s]+u-n>a&&r-(i.minZ[s]-o)>a&&i.maxZ[s]-r>a}if(!(r-(i.minZ[s]-o)>a&&i.maxZ[s]-r>a))return!1;if(c===Hr.Disc)return Yw(t,s,e,n)>a;for(let u=0;u<qw;u++){Ww(t,s,u,o);let l=Je[0],d=Je[1];if(!(-(l*e+d*n-Je[3])*(1/Math.sqrt(l*l+d*d))>a))return!1}return!0}function Qv(t,e,n,r,s,o,i,a,c,u){let l=0,d=1,f=!1,h=!0,p=Number.POSITIVE_INFINITY,y=0,S=0,b=0;t.depth=0;for(let x=0;x<Xv;x++){Ww(t,a,x,u);let R=Je[0],A=Je[1],E=Je[2],P=R*e+A*n+E*r-Je[3],k=R*s+A*o+E*i,M=1/Math.sqrt(R*R+A*A+E*E),B=-P*M;if(B>t.skin?x!==qw&&B<p&&!(h&&x===Jv&&jw(t,e,n,r,R*M,A*M,E*M,B,c,u))&&(p=B,y=R*M,S=A*M,b=E*M):h=!1,Math.abs(k)<1e-9){if(P>0)return!1;continue}let K=k<0&&P<=0&&P>-t.skin?0:-P/k;if(k<0?K>=l&&(l=K,t.nx=R*M,t.ny=A*M,t.nz=E*M,f=!0):d=Math.min(d,K),l>d)return!1}return h?(t.tMin=0,t.nx=y,t.ny=S,t.nz=b,t.depth=p,!0):!f||!(l<1)||!(d>=0)?!1:(t.tMin=l,!0)}function eM(t,e,n,r,s,o,i,a,c,u,l,d){t.tMin=0,t.tMax=1,t.ax=-1,t.sg=0;let f=e-a,h=n-c,p=s*s+o*o,y=f*f+h*h-u*u;if(p<1e-18){if(!(y<0))return!1}else{let S=f*s+h*o,b=S*S-p*y;if(b<0)return!1;let x=Math.sqrt(b),R=(-S-x)/p,A=(-S+x)/p;if(R>=t.tMin&&(t.tMin=R,t.ax=3),A<t.tMax&&(t.tMax=A),t.tMin>t.tMax)return!1}if(!ed(t,r,i,l,d,2)||t.tMin>=1||t.ax<0)return!1;if(t.ax===3){let S=f+s*t.tMin,b=h+o*t.tMin,x=Math.sqrt(S*S+b*b);t.nx=S/x,t.ny=b/x,t.nz=0}else t.nx=0,t.ny=0,t.nz=t.sg;return!0}var $n={minX:new Float64Array(2),minY:new Float64Array(2),minZ:new Float64Array(2),maxX:new Float64Array(2),maxY:new Float64Array(2),maxZ:new Float64Array(2)};function tM(t,e,n,r,s,o,i,a,c,u){let l=t.p,d=t.r,f=l.radius[a],h=l.cx[a],p=l.cy[a],y=l.minZ[a]-u,S=l.maxZ[a];t.depth=0;let b=Yw(t,a,e,n),x=r-y,R=S-r;if(b>t.skin&&x>t.skin&&R>t.skin)return t.tMin=0,R<b&&!gh(t,e,n,r+R,e,n,r,c,u)?[t.nx,t.ny,t.nz,t.depth]=[0,0,1,R]:[t.nx,t.ny,t.nz,t.depth]=[Je[0],Je[1],0,b],!0;let A=!1,E=0,P=0,k=0,M=0;$n.minX[0]=h-f,$n.maxX[0]=h+f,$n.minY[0]=p,$n.maxY[0]=p,$n.minX[1]=h,$n.maxX[1]=h,$n.minY[1]=p-f,$n.maxY[1]=p+f;for(let B=0;B<2;B++)$n.minZ[B]=l.minZ[a],$n.maxZ[B]=S,bh(t,e,n,r,s,o,i,B,u,$n,c)&&(!A||t.tMin<E)&&(A=!0,E=t.tMin,P=t.nx,k=t.ny,M=t.nz);for(let B=0;B<4;B++){let K=B%2===0?h-d:h+d,j=B<2?p-d:p+d;eM(t,e,n,r,s,o,i,K,j,f,y,S)&&(!A||t.tMin<E)&&(A=!0,E=t.tMin,P=t.nx,k=t.ny,M=t.nz)}return A?(t.tMin=E,t.nx=P,t.ny=k,t.nz=M,t.depth=0,!0):!1}function nM(t,e,n,r,s,o,i,a,c){let u=a-t.w.count,l=t.p.kind[u];return l===Hr.Box?bh(t,e,n,r,s,o,i,u,c,t.p,a):l===Hr.OBox?Qv(t,e,n,r,s,o,i,u,a,c):tM(t,e,n,r,s,o,i,u,a,c)}function wh(t,e,n,r,s,o,i){let a=t.w,c=Ur(t,t.duck),u=e+s,l=n+o,d=r+i;hh(t,e<u?e:u,n<l?n:l,r<d?r:d,e<u?u:e,n<l?l:n,(r<d?d:r)+c);let f=mh(t),h=!1,p=0,y=0,S=0,b=0,x=0,R=0;br!==null&&(br.sweeps+=f);for(let A=0;A<f;A++){let E=yh(t,A);br!==null&&E>=a.boxCount&&E<a.count&&(br.wedges+=1),(E<a.boxCount?bh(t,e,n,r,s,o,i,E,c):E<a.count?Kv(t,e,n,r,s,o,i,E,c):nM(t,e,n,r,s,o,i,E,c))&&(!h||t.tMin<p||t.tMin===p&&E<y)&&(h=!0,p=t.tMin,y=E,S=t.nx,b=t.ny,x=t.nz,R=t.depth)}t.hit=h,h?(t.tMin=Math.max(0,p-1e-4),t.nx=S,t.ny=b,t.nz=x,t.depth=R):(t.tMin=1,t.depth=0)}function rd(t,e,n=!1){let r=e,s=!1,o=0,i=0,a=0;for(let c=0;c<4&&r>1e-6;c++){if(t.vx*t.vx+t.vy*t.vy+t.vz*t.vz<1e-8)return;wh(t,t.x,t.y,t.z,t.vx*r,t.vy*r,t.vz*r);let u=t.tMin;if(u>0){let y=u*r;t.x=t.x+t.vx*y,t.y=t.y+t.vy*y,t.z=t.z+t.vz*y,r=r-y}if(!t.hit)return;t.depth>0&&(t.x=t.x+t.nx*t.depth,t.y=t.y+t.ny*t.depth,t.z=t.z+t.nz*t.depth);let l=t.nx,d=t.ny,f=t.nz,h=!1;if(n&&f>0)if(f>=t.standable)h=!0;else{let y=1/Math.sqrt(l*l+d*d);l=l*y,d=d*y,f=0}t.x=t.x+l*t.skin,t.y=t.y+d*t.skin,t.z=t.z+f*t.skin;let p=t.vx*l+t.vy*d+t.vz*f;if(p<0&&(h?t.vz=t.vz-p/f:(t.vx=t.vx+l*-p,t.vy=t.vy+d*-p,t.vz=t.vz+f*-p)),s){let y=i*f-a*d,S=a*l-o*f,b=o*d-i*l,x=y*y+S*S+b*b;if(x>1e-6){let R=1/Math.sqrt(x);y=y*R,S=S*R,b=b*R;let A=t.vx*y+t.vy*S+t.vz*b;t.vx=y*A,t.vy=S*A,t.vz=b*A}}if(s=!0,o=l,i=d,a=f,t.vx*t.vx+t.vy*t.vy+t.vz*t.vz<1e-8)return}}function Kw(t,e=!1){let n=t.x,r=t.y,s=t.z,o=t.vx,i=t.vy,a=t.vz;rd(t,t.h,e);let c=t.x,u=t.y,l=t.z,d=t.vx,f=t.vy,h=t.vz,p=c-n,y=u-r,S=p*p+y*y;t.x=n,t.y=r,t.z=s,t.vx=o,t.vy=i,t.vz=a;let b=t.stepHeight+t.skin;wh(t,n,r,s,0,0,b);let x=t.tMin,R=s+b*x;if(x>0&&$w(t,n,r,R,Ur(t,t.duck))){t.z=R,rd(t,t.h,e);let A=sd(t,t.x,t.y,t.z,t.stepHeight*2,.001);A===A&&(t.z=A);let E=t.x-n,P=t.y-r,k=E*E+P*P;if(A===A&&k>S+.001*t.unit*t.unit){t.vz=0;return}}t.x=c,t.y=u,t.z=l,t.vx=d,t.vy=f,t.vz=h}function Xw(t){let e=sd(t,t.x,t.y,t.z,t.stepHeight,t.groundSnap);e===e&&(t.z=e,t.vz=0)}function rM(t){let e=Math.sqrt(t.vx*t.vx+t.vy*t.vy);if(e<.1*t.unit){t.vx=0,t.vy=0;return}let r=(e<t.stopSpeed?t.stopSpeed:e)*t.friction*t.h,s=Math.max(0,e-r)/e;t.vx=t.vx*s,t.vy=t.vy*s}function sM(t){let e=t.wishSpeed-(t.vx*t.dirX+t.vy*t.dirY);if(e<=0)return;let n=t.accelerate*t.h*Math.max(t.wishSpeed,t.maxSpeed);n>e&&(n=e),t.vx=t.vx+n*t.dirX,t.vy=t.vy+n*t.dirY}function Dw(t){let e=Math.min(t.wishSpeed,t.airMaxWishSpeed)-(t.vx*t.dirX+t.vy*t.dirY);if(e<=0)return;let n=t.airAccelerate*t.wishSpeed*t.h;n>e&&(n=e),t.vx=t.vx+n*t.dirX,t.vy=t.vy+n*t.dirY}var En=t=>Oe(Math.fround(mn(t,-1e9,1e9)));function oM(t,e,n){let r=t.h/t.duckTime;if(!(e&&!t.onGround&&!t.airDuck)){if(e){let a=Math.min(1,t.duck+r);t.onGround||(t.z=t.z+(Ur(t,t.duck)-Ur(t,a))),t.duck=a,t.ducking=!0}else if(t.duck>0){let a=Math.max(0,t.duck-r),c=t.onGround?t.z:t.z-(Ur(t,a)-Ur(t,t.duck));$w(t,t.x,t.y,c,Ur(t,a))&&(t.duck=a,t.z=c,t.duck===0&&(t.ducking=!1))}}let s=t.onGround;td(t),t.onGround&&!s&&(t.vz=0),t.base=t.maxSpeed*t.cap;let o=t.ducking?t.base*t.crouchSpeed:n?t.base*t.walkSpeed:t.jogging?t.base*t.jogSpeed:t.base;t.wishSpeed=t.amount*o,t.onGround?t.pressed?(t.vz=t.jumpImpulse,t.onGround=!1,t.pressed=!1,Dw(t)):(rM(t),sM(t),t.vz=0):Dw(t);let i=!t.onGround;i&&(t.vz=t.vz-t.gravity*t.h*.5),t.vx=mn(t.vx,-t.maxVelocity,t.maxVelocity),t.vy=mn(t.vy,-t.maxVelocity,t.maxVelocity),t.vz=mn(t.vz,-t.maxVelocity,t.maxVelocity),t.onGround?(Kw(t),Xw(t)):rd(t,t.h),td(t),i&&!t.onGround?t.vz=t.vz-t.gravity*t.h*.5:t.onGround&&(t.vz=0),t.x=En(t.x),t.y=En(t.y),t.z=En(t.z),t.vx=En(t.vx),t.vy=En(t.vy),t.vz=En(t.vz),t.duck=Oe(Math.fround(t.duck))}var Tt=(t,e,n,r)=>Oe(Math.fround(mn(typeof t=="number"&&Number.isFinite(t)?t:e,n,r))),ah=t=>Oe(Math.fround(typeof t=="number"&&Number.isFinite(t)?t:0)),Ql={cand:new Int32Array(0),stack:new Int32Array(Ii*16)};function Sh(t){return Ql.cand.length<t.count&&(Ql={cand:new Int32Array(t.count),stack:Ql.stack}),Ql}function Jw(t,e,n=yc){let r=dh(n),s=Math.fround,o=a=>s(t==="vehicle"?e.height:e[a]),i=(a,c)=>{let u=Sh(r);return{w:r,p:gc(c),r:s(e.radius),unit:fh(s(e.radius),t==="vehicle"?Uw:zw),standHeight:o("standHeight"),crouchHeight:o("crouchHeight"),stepHeight:s(e.stepHeight),standable:s(e.standable),groundTrace:s(e.groundTrace),groundSnap:s(e.groundSnap),skin:s(e.skin),x:a.x,y:a.y,z:a.z,vx:0,vy:0,vz:a.vz??0,duck:t==="vehicle"?0:a.duck??0,onGround:!1,h:0,tMin:0,tMax:0,ax:-1,sg:0,nx:0,ny:0,nz:0,hit:!1,depth:0,cand:u.cand,nCand:-1,pc:lh,nPosed:0,stack:u.stack}};return{support(a,c){let u=i(a,c);if(u.vz>.1*u.unit)return-1;let l=sd(u,u.x,u.y,u.z,u.groundTrace,u.groundSnap);if(l!==l)return-1;for(let d=0;d<u.p.count;d++)if(u.p.maxZ[d]===l&&Gw(u,d,u.x,u.y))return d;return-1},inside(a,c,u){let l=i(a,c);return nd(l,l.x,l.y,l.z,r.count+u,Ur(l,l.duck))},pushOut(a,c){let u=i(a,c);for(let f=0;f<4&&(wh(u,u.x,u.y,u.z,0,0,0),!!u.hit);f++)u.x=u.x+u.nx*u.depth,u.y=u.y+u.ny*u.depth,u.z=u.z+u.nz*u.depth,u.x=u.x+u.nx*u.skin,u.y=u.y+u.ny*u.skin,u.z=u.z+u.nz*u.skin;let l=Ur(u,u.duck),d=!1;for(let f=0;f<r.count+u.p.count&&!d;f++)d=nd(u,u.x,u.y,u.z,f,l);return{x:u.x,y:u.y,z:u.z,inside:d}}}}function iM(t,e,n,r,s=yc,o=Fw){let i=dh(s),a=Sh(i),c=Math.fround,u=fo(t.mstate)&Bv,l={w:i,p:o,maxSpeed:c(r.maxSpeed),walkSpeed:c(r.walkSpeed),jogSpeed:c(r.jogSpeed),jogging:!1,crouchSpeed:c(r.crouchSpeed),accelerate:c(r.accelerate),airAccelerate:c(r.airAccelerate),airMaxWishSpeed:c(r.airMaxWishSpeed),friction:c(r.friction),stopSpeed:c(r.stopSpeed),gravity:c(r.gravity),jumpImpulse:c(r.jumpImpulse),maxVelocity:c(r.maxVelocity),r:c(r.radius),unit:fh(c(r.radius),zw),standHeight:c(r.standHeight),crouchHeight:c(r.crouchHeight),duckTime:c(r.duckTime),airDuck:r.airDuck!==0,stepHeight:c(r.stepHeight),standable:c(r.standable),groundTrace:c(r.groundTrace),groundSnap:c(r.groundSnap),skin:c(r.skin),x:Tt(t.x,0,-1e9,1e9),y:Tt(t.y,0,-1e9,1e9),z:Tt(t.z,0,-1e9,1e9),vx:Tt(t.vx,0,-1e9,1e9),vy:Tt(t.vy,0,-1e9,1e9),vz:Tt(t.vz,0,-1e9,1e9),duck:Tt(t.duck,0,0,1),cap:Tt(t.cap,1,0,4),onGround:(u&Vt.ON_GROUND)!==0,ducking:(u&Vt.DUCKING)!==0,jumpHeld:(u&Vt.JUMP_HELD)!==0,pressed:!1,h:0,dirX:0,dirY:0,amount:0,base:0,wishSpeed:0,tMin:0,tMax:0,ax:-1,sg:0,nx:0,ny:0,nz:0,hit:!1,depth:0,cand:a.cand,nCand:-1,pc:lh,nPosed:0,stack:a.stack},d=Hn(e.moveX),f=Hn(e.moveY),h=Math.sqrt(d*d+f*f);h>1e-4&&(l.dirX=d/h,l.dirY=f/h,l.amount=Math.min(h,1));let p=fo(e.buttons),y=(p&r.jumpBit)!==0,S=(p&r.duckBit)!==0,b=(p&r.walkBit)!==0;l.jogging=r.runBit!==0&&(p&r.runBit)===0;let x=Zl(n,ch);l.h=x/r.substeps;let R=Rs(e.yaw)??ah(t.yaw),A=c(r.pitchLimit),E=Oe(mn(Rs(e.pitch)??ah(t.pitch),-A,A));if(x>0){l.pressed=y&&!l.jumpHeld&&(r.capZeroJump!==0||l.cap!==0),l.jumpHeld=y;for(let P=0;P<r.substeps;P++)oM(l,S,b)}return{x:l.x,y:l.y,z:l.z,vx:l.vx,vy:l.vy,vz:l.vz,yaw:R,pitch:E,duck:l.duck,mstate:(l.onGround?Vt.ON_GROUND:0)+(l.ducking?Vt.DUCKING:0)+(l.jumpHeld?Vt.JUMP_HELD:0)}}var aM=Object.freeze({maxSpeed:1410,accel:1e3,brake:3500,coast:525,boostAccel:1e3,boostMaxSpeed:2300,boostBurn:.3333333432674408,grip:6e3,driftGrip:1500,turnRate:2.2,turnSpeed:400,spinAccel:30,airTurnRate:5.5,airSpinAccel:9,gravity:650,jumpImpulse:450,maxVelocity:6e3,radius:50,height:36,stepHeight:8,standable:.7,groundTrace:4,groundSnap:2,skin:.03,jumpBit:1,boostBit:2,driftBit:4,substeps:2,capZeroJump:1,world:Lw}),cM={maxSpeed:Ee(0,1e5),accel:Ee(0,1e5),brake:Ee(0,1e5),coast:Ee(0,1e5),boostAccel:Ee(0,1e5),boostMaxSpeed:Ee(0,1e5),boostBurn:Ee(0,1e3),grip:Ee(0,1e5),driftGrip:Ee(0,1e5),turnRate:Ee(0,100),turnSpeed:ho(1e5),spinAccel:Ee(0,1e4),airTurnRate:Ee(0,100),airSpinAccel:Ee(0,1e4),gravity:Ee(0,1e5),jumpImpulse:Ee(0,1e5),maxVelocity:Ee(0,1e5),radius:ho(1e4),height:ho(1e4),stepHeight:Ee(0,1e4),standable:Ee(0,1),groundTrace:Ee(0,1e4),groundSnap:Ee(0,1e4),skin:Ee(0,100),jumpBit:Jt(0,16777215),boostBit:Jt(0,16777215),driftBit:Jt(0,16777215),substeps:Jt(1,8),capZeroJump:Jt(0,1),world:Jt(0,2**32-1)};var uM=Vt.ON_GROUND|Vt.JUMP_HELD,po=(t,e,n)=>t<e?Math.min(e,t+n):t>e?Math.max(e,t-n):t,Zw=t=>Rs(t)??0;function lM(t){let e=t.maxSpeed*t.cap,n=t.boosting?1:t.throttle,r=n*e,s=t.f;if(n===0?s=po(s,0,t.coast*t.h):n>0&&s<0||n<0&&s>0?s=po(s,0,t.brake*t.h):Math.abs(s)<Math.abs(r)?s=po(s,r,t.accel*t.h):t.boosting||(s=po(s,r,t.coast*t.h)),t.boosting){let a=t.boostMaxSpeed*t.cap;s<a&&(s=Math.min(a,s+t.boostAccel*t.h))}let o=po(t.l,0,(t.drift?t.driftGrip:t.grip)*t.h),i=t.steer*t.turnRate*Math.min(1,Math.abs(s)/t.turnSpeed);s<0&&(i=-i),t.spin=po(t.spin,i,t.spinAccel*t.h),t.vx=s*t.c-o*t.s,t.vy=s*t.s+o*t.c,t.vz=0,t.f=s,t.l=o}function dM(t){if(t.spin=po(t.spin,t.steer*t.airTurnRate,t.airSpinAccel*t.h),t.boosting){let e=t.boostMaxSpeed*t.cap;if(t.f<e){let n=Math.min(t.boostAccel*t.h,e-t.f);t.vx=t.vx+n*t.c,t.vy=t.vy+n*t.s}}}function fM(t){let e=t.onGround;td(t),t.onGround&&!e&&(t.vz=0),t.c=Mw(t.yaw),t.s=vw(t.yaw),t.f=t.vx*t.c+t.vy*t.s,t.l=t.vy*t.c-t.vx*t.s,t.boosting=t.boost&&t.fuel>0,t.boosting&&(t.fuel=Math.max(0,t.fuel-t.boostBurn*t.h)),t.onGround&&t.pressed&&(t.vz=t.jumpImpulse,t.onGround=!1,t.pressed=!1),t.onGround?lM(t):dM(t);let n=!t.onGround;n&&(t.vz-=t.gravity*t.h*.5),t.vx=mn(t.vx,-t.maxVelocity,t.maxVelocity),t.vy=mn(t.vy,-t.maxVelocity,t.maxVelocity),t.vz=mn(t.vz,-t.maxVelocity,t.maxVelocity),t.yaw=Zw(t.yaw+t.spin*t.h),t.onGround?(Kw(t,!0),Xw(t)):rd(t,t.h),td(t),n&&!t.onGround?t.vz-=t.gravity*t.h*.5:t.onGround&&(t.vz=0),t.x=En(t.x),t.y=En(t.y),t.z=En(t.z),t.vx=En(t.vx),t.vy=En(t.vy),t.vz=En(t.vz),t.spin=Oe(Math.fround(t.spin)),t.fuel=Oe(Math.fround(t.fuel))}function pM(t,e,n,r,s=yc,o=Fw){let i=dh(s),a=Sh(i),c=Math.fround,u=fo(t.mstate)&uM,l=c(r.height),d=Oe(-Hn(e.moveX)),f=Hn(e.moveY),h=fo(e.buttons),p=(h&r.jumpBit)!==0,y=Zl(n,ch),S=ah(t.yaw),b={w:i,p:o,r:c(r.radius),unit:fh(c(r.radius),Uw),standHeight:l,crouchHeight:l,stepHeight:c(r.stepHeight),standable:c(r.standable),groundTrace:c(r.groundTrace),groundSnap:c(r.groundSnap),skin:c(r.skin),maxSpeed:c(r.maxSpeed),accel:c(r.accel),brake:c(r.brake),coast:c(r.coast),boostAccel:c(r.boostAccel),boostMaxSpeed:c(r.boostMaxSpeed),boostBurn:c(r.boostBurn),grip:c(r.grip),driftGrip:c(r.driftGrip),turnRate:c(r.turnRate),turnSpeed:c(r.turnSpeed),spinAccel:c(r.spinAccel),airTurnRate:c(r.airTurnRate),airSpinAccel:c(r.airSpinAccel),gravity:c(r.gravity),jumpImpulse:c(r.jumpImpulse),maxVelocity:c(r.maxVelocity),x:Tt(t.x,0,-1e9,1e9),y:Tt(t.y,0,-1e9,1e9),z:Tt(t.z,0,-1e9,1e9),vx:Tt(t.vx,0,-1e9,1e9),vy:Tt(t.vy,0,-1e9,1e9),vz:Tt(t.vz,0,-1e9,1e9),yaw:Math.abs(S)<=1e9?Zw(S):0,spin:Tt(t.spin,0,-1e3,1e3),fuel:Tt(t.fuel,0,0,1),cap:Tt(t.cap,1,0,4),duck:0,onGround:(u&Vt.ON_GROUND)!==0,jumpHeld:(u&Vt.JUMP_HELD)!==0,pressed:!1,boosting:!1,steer:d,throttle:f,boost:(h&r.boostBit)!==0,drift:(h&r.driftBit)!==0,h:y/r.substeps,c:1,s:0,f:0,l:0,tMin:0,tMax:0,ax:-1,sg:0,nx:0,ny:0,nz:0,hit:!1,depth:0,cand:a.cand,nCand:-1,pc:lh,nPosed:0,stack:a.stack};if(y>0){b.pressed=p&&!b.jumpHeld&&(r.capZeroJump!==0||b.cap!==0),b.jumpHeld=p;for(let x=0;x<r.substeps;x++)fM(b)}return{x:b.x,y:b.y,z:b.z,vx:b.vx,vy:b.vy,vz:b.vz,yaw:b.yaw,spin:b.spin,fuel:b.fuel,mstate:(b.onGround?Vt.ON_GROUND:0)+(b.jumpHeld?Vt.JUMP_HELD:0)}}var hM={defaults:Cv,ranges:Ov,fields:["x","y","yaw"],reads:[],world:!1,step:(t,e,n,r)=>Iv(t,e,n,r)},mM={defaults:Dv,ranges:Nv,fields:["x","y","z","vx","vy","vz","yaw","pitch","duck","mstate"],reads:["cap"],world:!0,step:(t,e,n,r,s,o)=>iM(t,e,n,r,s,o)},yM={defaults:aM,ranges:cM,fields:["x","y","z","vx","vy","vz","yaw","spin","fuel","mstate"],reads:["cap"],world:!0,step:(t,e,n,r,s,o)=>pM(t,e,n,r,s,o)},Nw=Object.freeze({[wr.TOPDOWN]:Object.freeze(hM),[wr.FIRSTPERSON]:Object.freeze(mM),[wr.VEHICLE]:Object.freeze(yM)});function bc(t){return typeof t=="string"&&Object.hasOwn(Nw,t)?Nw[t]:void 0}Zp();var gM=2,Qw=t=>typeof t=="string"&&t.length>0;function tS(t,e){let n=[],r=new Set;for(let s of Array.isArray(t)?t:[]){if(s===null||typeof s!="object")continue;let{region:o,urls:i}=s;if(typeof o!="string"||o.length===0||r.has(o))continue;let a=Array.isArray(i)?i.filter(Qw):[];a.length!==0&&(r.add(o),n.push({region:o,urls:a}))}return n.length>0?n:(Array.isArray(e)?e.filter(Qw):[]).map(s=>({region:s,urls:[s]}))}function bM(t,e){return Array.from({length:e},(n,r)=>t[r%t.length])}var nS=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0;function eS(t,e){let n=[],r=[];return t.forEach((s,o)=>{let i=null,a=s.urls[0];s.urls.forEach((c,u)=>{let l=e[o]?.[u];!nS(l)||i!==null&&l>=i||(i=l,a=c)}),(i===null?r:n).push({index:o,ms:i,pick:{region:s.region,url:a}})}),n.sort((s,o)=>s.ms-o.ms||s.index-o.index),[...n,...r].map(s=>s.pick)}var Ni={Capacity:"capacity",NextRegion:"next_region",Final:"final"},wM=new Set([503,4213]),SM=new Set([502,504,520,521,522,523,524,525,526,530]);function rS(t){return typeof t!="number"||t<=0||SM.has(t)?Ni.NextRegion:wM.has(t)?Ni.Capacity:Ni.Final}function sS(t,e,n){let r=t.refused+1;if(r>=gM&&t.region+1<e){let o=t.region+1;return{attempt:{region:o,waitMs:0},state:{region:o,refused:0,step:t.step}}}let s=n[t.step];return s===void 0?null:{attempt:{region:t.region,waitMs:s},state:{region:t.region,refused:r,step:t.step+1}}}async function oS(t,e={}){if(t.length===0)return[];if(t.length===1)return eS(t,[]);let n=Math.max(1,e.samples??uo.SAMPLES),r=t.map(i=>bM(i.urls,n)),s=await xM(r,e),o=t.map((i,a)=>i.urls.map(c=>{let u;return r[a]?.forEach((l,d)=>{let f=s[a]?.[d];l===c&&nS(f)&&(u=Math.min(u??Number.POSITIVE_INFINITY,f))}),u}));return eS(t,o)}async function xM(t,e={}){let n=e.probe??qp,r=e.timeoutMs??uo.TIMEOUT_MS,s=e.graceMs??uo.GRACE_MS,o=t.map(a=>a.map(()=>{})),i=t.reduce((a,c)=>a+c.length,0);return i===0||await new Promise(a=>{let c,u=!1,l=setTimeout(d,r);function d(){u=!0,clearTimeout(l),clearTimeout(c),a()}let f=()=>{--i===0&&d()};t.forEach((h,p)=>{h.forEach((y,S)=>{let b;try{b=n(y,r)}catch(x){b=Promise.reject(x)}b.then(x=>{!u&&Number.isFinite(x)&&x>=0&&(o[p][S]=x,c??(c=setTimeout(d,s))),f()},f)})})}),o}var Rh={MAX_MATCH_KEY_CHARS:32,MAX_CODE_CHARS:32,MAX_WORLDS:16},_M=522,_h=(t,e,n)=>t>=e.charCodeAt(0)&&t<=n.charCodeAt(0),iS=t=>_h(t,"a","z")||_h(t,"0","9"),RM="._:-",EM="_-";function aS(t){if(typeof t!="string"||t.length===0||t.length>Rh.MAX_MATCH_KEY_CHARS)return!1;for(let e=0;e<t.length;e++)if(!iS(t.charCodeAt(e))&&(e===0||!RM.includes(t.charAt(e))))return!1;return!0}function cS(t){if(typeof t!="string"||t.length===0||t.length>Rh.MAX_CODE_CHARS)return!1;for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(!iS(n)&&!_h(n,"A","Z")&&!EM.includes(t.charAt(e)))return!1}return!0}function kM(t){return t===void 0||t===""?"":aS(t)?t:null}var Sr={JoinOrCreate:"joinOrCreate",Create:"create",JoinById:"joinById"},xh={BadMatchKey:"bad_match_key",BadCode:"bad_code",Conflict:"conflict"};function uS(t){let e=t.matchKey??"";if(t.code!==void 0)return t.createPrivate===!0||e!==""?{refused:xh.Conflict}:cS(t.code)?{method:Sr.JoinById,roomId:t.code,options:{}}:{refused:xh.BadCode};let n=kM(e);if(n===null)return{refused:xh.BadMatchKey};let r=n===""?{}:{matchKey:n};return t.createPrivate===!0?{method:Sr.Create,options:{...r,private:!0}}:{method:Sr.JoinOrCreate,options:r}}function lS(t,e,n){return(t===fn.WRONG_REGION||t===_M)&&e+1<n?e+1:null}var Bi={scheduleMs:[0,250,500,1e3,2e3,4e3],jitterMs:250,budgetMs:18e4,regionStayMs:6e4,successorMs:9e4};var Li={Room:"room",Successor:"successor",Pool:"pool"},dS={Final:"final",Budget:"budget"},AM=new Set([pn.GOING_AWAY,pn.NO_STATUS,pn.ABNORMAL,1011,1012,1013,pn.SERVER_SHUTDOWN,pn.FAILED_TO_RECONNECT,pn.MAY_TRY_RECONNECT]),PM=new Set([fn.BAD_OPTION,fn.NOT_ENTITLED,fn.FORBIDDEN,fn.MODULE_UNAVAILABLE,fn.PROTOCOL_UNSUPPORTED]);function fS(t){return AM.has(t)}function pS(t){let{attempt:e,elapsedMs:n,refusal:r,lostCode:s,closed:o,regions:i,jitter:a}=t;if(r!==null&&PM.has(r))return{stop:dS.Final};if(n>=Bi.budgetMs)return{stop:dS.Budget};let c=Bi.scheduleMs.length-1,l=Bi.scheduleMs[Math.min(e,c)]+Math.floor(a*Bi.jitterMs);if(e===0&&s!==pn.SERVER_SHUTDOWN)return{waitMs:l,region:0,way:Li.Room};let d=i<1?0:Math.floor(n/Bi.regionStayMs)%i,f=o||n<Bi.successorMs?Li.Successor:Li.Pool;return{waitMs:l,region:d,way:f}}function hS(t){return{...t.matchKey===""?{}:{matchKey:t.matchKey},successorOf:t.lostRoomId,...t.closed?{successorClosed:!0}:{}}}var Es={Draining:"draining",Rejoining:"rejoining",Rejoined:"rejoined"},od="disconnect",TM=-1,vM=t=>new Promise(e=>setTimeout(e,t)),MM=t=>{let e=t!==null&&typeof t=="object"?t.code:void 0;return typeof e=="number"?e:null};function mS(t,e){let n=e.now??Date.now,r=e.random??Math.random,s=e.sleep??vM,o={...t.input},i=new Map,a=t,c=!1,u=null,l=null,d=(b,...x)=>{for(let R of i.get(b)??[])R(...x)},f=(b,x)=>{x===od||x===Es.Draining||x===Es.Rejoining||x===Es.Rejoined||b.on(x,(...R)=>{b===a&&d(x,...R)})},h=async(b,x)=>{let R=n(),A={roomId:a.code,matchKey:a.matchKey,closed:e.closed},E=e.targets.length,P=0,k=null;for(;!c;){let M=pS({attempt:P,elapsedMs:n()-R,refusal:k,lostCode:b,closed:e.closed,regions:E,jitter:r()});if("stop"in M){d(od,b,x);return}if(P+=1,d(Es.Rejoining,{attempt:P,code:b,waitMs:M.waitMs}),await s(M.waitMs),c)return;try{let B=await e.join(e.targets[M.region],M.way,A);if(c){await B.leave().catch(()=>{});return}p(B),d(Es.Rejoined,{code:B.code,url:B.url});return}catch(B){k=MM(B)}}},p=b=>{a=b,u!==null&&b.setPhysics(u),l!==null&&b.setWorld(l);for(let x of i.keys())f(b,x);y(b)},y=b=>{b.on(xe.SERVER_RESTART,x=>{if(b!==a)return;let R=x?.drainMs;d(Es.Draining,{closesInMs:typeof R=="number"?R:TM})}),b.on(od,(x,R)=>{b!==a||c||(fS(x)?h(x,R):d(od,x,R))})};y(t);let S={input:o,frame(b){return Object.assign(a.input,o),a.frame(b)},setWorld(b){let x=a.setWorld(b);return l=b,x},setPhysics(b){return u=b,a.setPhysics(b)},on(b,x){let R=i.get(b);R===void 0&&(R=new Set,i.set(b,R),f(a,b));let A=x;return R.add(A),()=>{R.delete(A)}},async leave(){c=!0,await a.leave()}};return new Proxy(t,{get(b,x){if(Object.hasOwn(S,x))return S[x];let R=a[x];return typeof R=="function"?R.bind(a):R}})}var Zt={EXTRAPOLATE:"extrapolate",HOLD:"hold",INPUT_DECAY:"inputDecay"};var OM=Object.freeze({bodies:512,collidersPerBody:8,hullVertices:64,triangles:65536,joints:64,ccdBodies:16,queriesPerStep:64,eventsPerStep:64,heightfieldSamples:1048576,staticPieces:4608,memoryBytes:64*1024*1024,worldExtent:1e5,maxSpeed:1e3,maxAngularSpeed:1e3}),cU=Object.freeze(Object.keys(OM)),uU=Object.freeze(["worldExtent","maxSpeed"]),lU=Object.freeze(["worldExtent","maxSpeed","maxAngularSpeed"]);var yS=Object.freeze({[wr.FIRSTPERSON]:39.37,[wr.VEHICLE]:100}),dU=Object.freeze([10,15,20,30,60]);var xr={DEFAULT_REMOTE_PREDICT:Zt.EXTRAPOLATE,DEFAULT_REMOTE_DECAY_MS:50,MAX_REMOTE_DECAY_MS:1e3,DEFAULT_LEAD_MS:250,MIN_LEAD_MS:50,MAX_LEAD_MS:1e3},fU=Object.values(Zt);var gS=64,bS=64;var pU=Object.freeze({20:3,30:2,60:1,120:1});var IM=Object.freeze(["qx","qy","qz","qw","lvx","lvy","lvz","avx","avy","avz","sleep"]),DM=Object.freeze(["x","y","z",...IM]),id={BITS:16,SPAN:65534,ORIENTATION:Object.freeze({min:-1,max:1}),VELOCITY:Object.freeze({min:-64,max:64})};function Qt(t,e){if(Number.isNaN(t))return 0;let n=t<e.min?e.min:t>e.max?e.max:t;return Math.floor((n-e.min)/(e.max-e.min)*id.SPAN+.5)}var wS=250,SS=1,xS=100,_S=1;var Ah=[0,0,0,1];function jn(t,e){return[t[3]*e[0]+t[0]*e[3]+t[1]*e[2]-t[2]*e[1],t[3]*e[1]-t[0]*e[2]+t[1]*e[3]+t[2]*e[0],t[3]*e[2]+t[0]*e[1]-t[1]*e[0]+t[2]*e[3],t[3]*e[3]-t[0]*e[0]-t[1]*e[1]-t[2]*e[2]]}function $r(t){let e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]+t[3]*t[3]);return e===0?Ah:[t[0]/e,t[1]/e,t[2]/e,t[3]/e]}function RS(t,e,n,r){let s=Math.sin(r/2);return[t*s,e*s,n*s,Math.cos(r/2)]}function Fi(t,e){let n=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);if(n===0)return Ah;let r=2*Math.atan2(n,t[3]);return RS(t[0]/n,t[1]/n,t[2]/n,e*r)}function ES(t,e){return{tick:e+1,p:[t.x,t.y,t.z],q:$r([t.qx,t.qy,t.qz,t.qw]),lv:[t.lvx,t.lvy,t.lvz],av:[t.avx,t.avy,t.avz],sleep:t.sleep,epoch:t.epoch}}function NM(t,e,n){if(t.sleep||!(n.tickHz>0))return 0;let s=((e-n.tickOrigin)*n.tickHz/1e3-t.tick)/n.tickHz,o=-SS/n.tickHz,i=wS/1e3;return s<o?o:s>i?i:s}function kS(t,e,n){let r=NM(t,e,n),s=n.lengthUnit,o=[t.p[0]+t.lv[0]*s*r,t.p[1]+t.lv[1]*s*r,t.p[2]+t.lv[2]*s*r],[i,a,c]=t.av,u=Math.sqrt(i*i+a*a+c*c);return u===0||r===0?{p:o,q:t.q}:{p:o,q:$r(jn(RS(i/u,a/u,c/u,u*r),t.q))}}var Eh={SPAWNED:"spawned",EPOCH:"epoch",DISTANCE:"distance"},kh=(t,e)=>({state:t,arrivedAt:e,dp:[0,0,0],dq:Ah});function Ph(t,e,n){let r=kS(t.state,e,n),s=e-t.arrivedAt,o=Math.exp(-(s<0?0:s)/xS),{dp:i}=t;return{p:[r.p[0]+i[0]*o,r.p[1]+i[1]*o,r.p[2]+i[2]*o],q:jn(Fi(t.dq,o),r.q)}}function AS(t,e,n,r){if(t===null)return{drawing:kh(e,n),snap:Eh.SPAWNED};if(e.epoch!==t.state.epoch)return{drawing:kh(e,n),snap:Eh.EPOCH};let s=Ph(t,n,r),o=kS(e,n,r),i=[s.p[0]-o.p[0],s.p[1]-o.p[1],s.p[2]-o.p[2]];if(Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2])>_S*r.lengthUnit)return{drawing:kh(e,n),snap:Eh.DISTANCE};let a=jn(s.q,[-o.q[0],-o.q[1],-o.q[2],o.q[3]]),c=a[3]<0?[-a[0],-a[1],-a[2],-a[3]]:a;return{drawing:{state:e,arrivedAt:n,dp:i,dq:c},snap:null}}function PS(t,e){let n=(r,s)=>r.every((o,i)=>Object.is(o,s[i]));return t.sleep===e.sleep&&t.epoch===e.epoch&&n(t.p,e.p)&&n(t.q,e.q)&&n(t.lv,e.lv)&&n(t.av,e.av)}var TS=2**32-1,wc=1e3,jr=t=>typeof t.t0=="number"&&t.t0>0;function Th(t,e,n){let r=(e-t.t0)/n,s=Number.isFinite(r)&&r>=0?r:0;return{x:Oe(Math.fround(t.x+t.vx*s)),y:Oe(Math.fround(t.y+t.vy*s)),z:Oe(Math.fround(t.z+t.vz*s-.5*t.g*s*s)),vx:Oe(t.vx),vy:Oe(t.vy),vz:Oe(Math.fround(t.vz-t.g*s))}}function vh(t,e,n){return(t-e)*n/1e3}function ad(t,e,n){return e+t*1e3/n}var gn={Predicted:"predicted",Separate:"separate",Timeline:"timeline"},yo={Shared:"shared",Mover:"mover"},Wn={Shooter:"shooter",Platformer:"platformer",VehicleArena:"vehicle-arena",PhysicsSandbox:"physics-sandbox",Party:"party"},it={Stand:"stand",Slide:"slide",Bounce:"bounce",Ghost:"ghost"},qn={Box:"box",Hull:"hull"},go={Slide:"slide",Carry:"carry"};var Mh=(t,e,n)=>({speed:t,step:e,share:n}),Sc=t=>({policy:it.Slide,...t}),xc=(t,e,n)=>({policy:it.Stand,ride:t,center:e,slide:n}),zi=Mh(300,150,1),Wr=Mh(950,480,1),BM=Mh(600,null,.5),LM=.25,SU=Object.freeze({speed:300,step:150}),xU={policy:it.Bounce,stompMin:150,bounceSpeed:450,jumpBoost:150,slide:zi},vS={[Wn.Shooter]:{character:xc(!1,LM,zi),vehicle:Sc(Wr),restitution:0,passes:16,vehicleOffWall:Wr,stopSpin:!1,drawing:gn.Separate,push:yo.Mover,headFriction:go.Slide},[Wn.Platformer]:{character:xc(!0,null,zi),vehicle:Sc(Wr),restitution:0,passes:16,vehicleOffWall:Wr,stopSpin:!1,drawing:gn.Separate,push:yo.Mover,headFriction:go.Slide},[Wn.VehicleArena]:{character:Sc(zi),vehicle:Sc(Wr),restitution:.6,passes:32,vehicleOffWall:BM,stopSpin:!0,drawing:gn.Predicted,push:yo.Shared,headFriction:go.Carry},[Wn.PhysicsSandbox]:{character:xc(!0,null,zi),vehicle:xc(!0,null,Wr),restitution:.2,passes:16,vehicleOffWall:Wr,stopSpin:!1,drawing:gn.Separate,push:yo.Shared,headFriction:go.Carry},[Wn.Party]:{character:xc(!0,null,zi),vehicle:Sc(Wr),restitution:.3,passes:16,vehicleOffWall:Wr,stopSpin:!1,drawing:gn.Separate,push:yo.Shared,headFriction:go.Slide}},_U=Object.freeze({supportCos:.7,entrySpeed:1,entryWindow:1/60,slop:.1,roofSkin:.01});var RU={[it.Stand]:new Set(["policy","ride","center","slide"]),[it.Slide]:new Set(["policy","speed","step","share"]),[it.Bounce]:new Set(["policy","stompMin","bounceSpeed","jumpBoost"]),[it.Ghost]:new Set(["policy"])};var FM=[[-1,0,0],[1,0,0],[0,-1,0],[0,1,0],[0,0,1],[0,0,-1]],zM=[0,3,1,4,5,2];function UM(t,e,n,r,s){let[o,i,a,c,u,l,d,f,h]=n,p=d===0?o:i,y=(h-f)/((d===0?c:u)-p),S=1/Math.sqrt(y*y+1),b=(f-y*p+r*Math.abs(y))*S,x=[1,0,0,c+r,-1,0,0,-o+r,0,1,0,u+r,0,-1,0,-i+r,d===0?-y*S:0,d===0?0:-y*S,S,b,0,0,1,l,0,0,-1,-a+s];t.set(x,e)}function IS(t,e,n,r){let s=t?.boxes??[],o=t?.ramps??[],i=s.length+o.length,a=new Float64Array(i*6),c=new Float64Array(o.length*28);for(let d=0;d<i;d++){let f=d<s.length?s[d]:o[d-s.length],h=d*6;a[h]=f[0]-e,a[h+1]=f[1]-e,a[h+2]=f[2]-n,a[h+3]=f[3]+e,a[h+4]=f[4]+e,a[h+5]=f[5],d>=s.length&&UM(c,(d-s.length)*28,f,e,n)}let u={count:i,boxCount:s.length,bounds:a,rampPlanes:c,skin:r},l=VM(u);return l===null?u:{...u,grid:l}}function MS(t,e){let n=e*6;return Number.isFinite(t[n])&&Number.isFinite(t[n+3])&&Number.isFinite(t[n+1])&&Number.isFinite(t[n+4])}function ks(t,e,n,r){let s=Math.floor((t-e)/n);return s<0?0:s>r-1?r-1:s}function VM(t){let{count:e,bounds:n}=t,r=0,s=Number.POSITIVE_INFINITY,o=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let x=0;x<e;x++){if(!MS(n,x))continue;r+=1;let R=x*6;s=Math.min(s,n[R]-1),o=Math.min(o,n[R+1]-1),i=Math.max(i,n[R+3]+1),a=Math.max(a,n[R+4]+1)}if(r<32)return null;let c=Math.max(64,(i-s)/32,(a-o)/32);if(!Number.isFinite(c))return null;let u=Math.min(32,Math.floor((i-s)/c)+1),l=Math.min(32,Math.floor((a-o)/c)+1),d=(x,R)=>{for(let A=0;A<e;A++){if(!MS(n,A)){x(A);continue}let E=A*6,P=ks(n[E]-1,s,c,u),k=ks(n[E+3]+1,s,c,u),M=ks(n[E+1]-1,o,c,l),B=ks(n[E+4]+1,o,c,l);if((k-P+1)*(B-M+1)>64){x(A);continue}for(let K=M;K<=B;K++)for(let j=P;j<=k;j++)R(j+K*u,A)}},f=new Int32Array(u*l+1),h=0;d(()=>{h+=1},x=>{f[x+1]+=1});for(let x=0;x<u*l;x++)f[x+1]=f[x+1]+f[x];let p=new Int32Array(f[u*l]),y=new Int32Array(h),S=f.slice(),b=0;return d(x=>{y[b]=x,b+=1},(x,R)=>{p[S[x]]=R,S[x]=S[x]+1}),{x0:s,y0:o,size:c,nx:u,ny:l,cellStart:f,cellSolids:p,wide:y,merged:new Array(b<=64?u*l:0)}}function CS(t,e,n,r){if(r===n)return t;let s=[],o=0,i=n;for(;o<t.length||i<r;){let a=i>=r||o<t.length&&t[o]<=e[i],c=a?t[o]:e[i];a?o+=1:i+=1,s[s.length-1]!==c&&s.push(c)}return s}function DS(t,e,n,r,s){let o=t.grid;if(o===void 0||!(Number.isFinite(e)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(s)))return null;let i=ks(e,o.x0,o.size,o.nx),a=n===e?i:ks(n,o.x0,o.size,o.nx),c=ks(r,o.y0,o.size,o.ny),u=s===r?c:ks(s,o.y0,o.size,o.ny);if((a-i+1)*(u-c+1)>16)return null;if(i===a&&c===u&&o.merged.length>0){let d=i+c*o.nx,f=o.merged[d];if(f!==void 0)return f;let h=CS(o.wide,o.cellSolids,o.cellStart[d],o.cellStart[d+1]);return o.merged[d]=h,h}let l=o.wide;for(let d=c;d<=u;d++)for(let f=i;f<=a;f++){let h=f+d*o.nx;l=CS(l,o.cellSolids,o.cellStart[h],o.cellStart[h+1])}return l}var yt={nx:0,ny:0,nz:0,e:0};function _c(t,e,n){if(e<t.boxCount){let o=FM[n],i=zM[n],a=t.bounds[e*6+i];yt.nx=o[0],yt.ny=o[1],yt.nz=o[2],yt.e=i<3?-a:a;return}let r=(e-t.boxCount)*28+n*4,s=t.rampPlanes;yt.nx=s[r],yt.ny=s[r+1],yt.nz=s[r+2],yt.e=s[r+3]}var cd=(t,e)=>e<t.boxCount?6:7;function Rc(t,e,n,r,s,o){let i=cd(t,e);for(let a=0;a<i;a++)if(_c(t,e,a),!(yt.e-(yt.nx*r+yt.ny*s+yt.nz*o)>n))return!1;return!0}var NS=(t,e,n)=>DS(t,e,e,n,n);function HM(t,e,n,r,s){let o=e*6;for(let i=0;i<3;i++){let a=n[i],c=a+r[i]*s,u=a<c?a:c;if((a<c?c:a)<t.bounds[o+i]-1||u>t.bounds[o+3+i]+1)return!1}return!0}function $M(t,e,n,r,s,o){let i=cd(t,e);for(let a=0;a<i;a++){_c(t,e,a);let{nx:c,ny:u,nz:l,e:d}=yt;if(d-(c*r[0]+u*r[1]+l*r[2])<=n&&c*s[0]+u*s[1]+l*s[2]<0){let h=[c,u,l,d];if(!o?.(h))return{t:0,face:h}}}return null}var BS=(t,e)=>n=>n[2]>=e&&n[0]*t[0]+n[1]*t[1]+n[2]*t[2]>=e;function jM(t,e,n,r,s,o,i){if(Rc(t,e,n,r[0],r[1],r[2]))return null;if(Rc(t,e,-n,r[0],r[1],r[2]))return $M(t,e,n,r,s,i);let a=0,c=o,u=Number.NEGATIVE_INFINITY,l=-1,d=cd(t,e);for(let h=0;h<d;h++){_c(t,e,h);let{nx:p,ny:y,nz:S,e:b}=yt,x=b+n-(p*r[0]+y*r[1]+S*r[2]),R=p*s[0]+y*s[1]+S*s[2];if(R===0){if(!(x>0))return null;continue}let A=x/R;R>0&&A<c&&(c=A),R<0&&A>u&&(u=A,l=h)}if(u>a&&(a=u),l<0||!(a<c))return null;_c(t,e,l);let f=[yt.nx,yt.ny,yt.nz,yt.e];return i?.(f)?null:{t:a,face:f}}function Ec(t,e,n,r,s){let o={t:r,face:null};if(!(r>0))return{t:0,face:null};let i=f=>{if(!HM(t,f,e,n,o.t))return;let h=jM(t,f,t.skin,e,n,o.t,s);h!==null&&h.t<o.t&&(o=h)},[a,c]=[e[0],e[1]],[u,l]=[a+n[0]*r,c+n[1]*r],d=DS(t,Math.min(a,u),Math.max(a,u),Math.min(c,l),Math.max(c,l));if(d===null)for(let f=0;f<t.count;f++)i(f);else for(let f=0;f<d.length;f++)i(d[f]);return o}function ud(t,e,n,r,s){if(t===null)return r;let o=Ec(t,e,n,r,s).t;return o<0?0:o}var OS=[0,0,1],WM=[0,0,-1];function Ch(t,e,n,r,s){if(t===null)return OS;let o=Ec(t,[e,n,r],WM,s);return o.face===null||!(o.face[2]>0)?OS:[o.face[0],o.face[1],o.face[2]]}function qM(t,e,n,r,s,o){let{count:i,skin:a}=t,c=NS(t,o[0],o[1]),u=c===null?i:c.length;for(let l=0;l<u;l++){let d=c===null?l:c[l];if(d!==e&&Rc(t,d,a,o[0],o[1],o[2])&&!Rc(t,d,a,n,r,s))return!0}return!1}function GM(t,e,n,r,s){let o=null,i=cd(t,e);for(let a=0;a<i-1;a++){_c(t,e,a);let{nx:c,ny:u,nz:l,e:d}=yt,f=d-(c*n+u*r+l*s);o!==null&&!(f<o[3])||l>0&&qM(t,e,n,r,s,[n+c*f,r+u*f,s+l*f])||(o=[c,u,l,f])}return o}function YM(t,e,n,r){let{count:s,skin:o}=t,i=NS(t,e,n),a=i===null?s:i.length;for(let c=0;c<a;c++){let u=i===null?c:i[c];if(Rc(t,u,o,e,n,r))return GM(t,u,e,n,r)}return null}function LS(t,e,n){let{x:r,y:s,z:o}=e,i=0;for(let a=0;a<4;a++){let c=YM(t,r,s,o);if(c===null)break;n?.(c);let[u,l,d,f]=c;i=Math.max(i,f),r+=u*(f+t.skin),s+=l*(f+t.skin),o+=d*(f+t.skin)}return i>0&&(e.x=r,e.y=s,e.z=o),i}var wo={Side:"side",Top:"top"},fd={Free:"free",LowerYields:"lower-yields",Pinned:"pinned"},KM={Stomp:"stomp"},Oh={j:0,way:null,w:null},kc=[0,0,1],Fe=(t,e)=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2],So=(t,e)=>[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]],ft=t=>[-t[0],-t[1],-t[2]];function XM(t,e,n){if(n.supportUp!==void 0)return n.supportUp(t.x,t.y,t.z);let r=n.supports;if(r===void 0)return Ch(n.world,t.x,t.y,t.z,e.groundTrace);let s=r.get(t);if(s!==void 0&&s.x===t.x&&s.y===t.y&&s.z===t.z)return s.up;let o=Ch(n.world,t.x,t.y,t.z,e.groundTrace);return r.set(t,{x:t.x,y:t.y,z:t.z,up:o}),o}function qr(t,e,n){let r=e.shape,s=XM(t,e,n);if(r.kind===qn.Hull)return{b:t,up:kc,support:s,hl:r.radius,hw:r.radius,top:r.height,s:0,c:1};let[o,i]=Ut(t.yaw);return{b:t,up:s,support:s,hl:r.length/2,hw:r.width/2,top:r.top,s:o,c:i}}var pd=t=>Math.sqrt(t.hl*t.hl+t.hw*t.hw),ld=(t,e,n)=>t.hl*Math.abs(t.c*e+t.s*n)+t.hw*Math.abs(t.c*n-t.s*e);function JM(t,e){let n=e.b.z-t.b.z+(e.top-t.top)/2,r=(t.top+e.top)/2;if(Math.abs(n)>=r)return null;let s=e.b.x-t.b.x,o=e.b.y-t.b.y,i=pd(t)+pd(e);if(Math.abs(s)>=i||Math.abs(o)>=i)return null;let a=[t.c,t.s,-t.s,t.c,e.c,e.s,-e.s,e.c],c=null,u=[];for(let d=0;d<8;d+=2){let f=a[d],h=a[d+1],p=s*f+o*h,y=ld(t,f,h)+ld(e,f,h)-Math.abs(p);if(y<=0)return null;let S=p<0?{depth:y,n:[-f,-h,0]}:{depth:y,n:[f,h,0]};u.push(S),(c===null||y<c.depth)&&(c=S)}let l=n<0?[0,0,-1]:kc;return{plane:kc,level:!0,side:c,axes:u,across:{depth:r-Math.abs(n),n:l},d:[s,o,0],half:d=>ld(t,d[0],d[1])+ld(e,d[0],d[1])}}function Dh(t,e,n){let r=t*n[0]+e*n[1],s=t-r*n[0],o=e-r*n[1],i=-r*n[2],a=Math.sqrt(s*s+o*o+i*i);return a<1e-9&&(s=-n[2]*n[0],o=-n[2]*n[1],i=1-n[2]*n[2],a=Math.sqrt(s*s+o*o+i*i)),[s/a,o/a,i/a]}function ZM(t,e){let n=[t.up[0]+e.up[0],t.up[1]+e.up[1],t.up[2]+e.up[2]],r=Math.sqrt(Fe(n,n));if(r<1e-9)return null;let s=[n[0]/r,n[1]/r,n[2]/r],o=t.top/2,i=e.top/2,a=[e.b.x+e.up[0]*i-t.b.x-t.up[0]*o,e.b.y+e.up[1]*i-t.b.y-t.up[1]*o,e.b.z+e.up[2]*i-t.b.z-t.up[2]*o],c=Fe(a,s),u=o+i;if(Math.abs(c)>=u)return null;let l=Dh(t.c,t.s,s),d=Dh(e.c,e.s,s),f=So(s,l),h=So(s,d),p=b=>t.hl*Math.abs(Fe(l,b))+t.hw*Math.abs(Fe(f,b))+(e.hl*Math.abs(Fe(d,b))+e.hw*Math.abs(Fe(h,b))),y=null,S=[];for(let b of[l,f,d,h]){let x=Fe(a,b),R=t.hl*Math.abs(Fe(l,b))+t.hw*Math.abs(Fe(f,b))+(e.hl*Math.abs(Fe(d,b))+e.hw*Math.abs(Fe(h,b)))-Math.abs(x);if(R<=0)return null;let A={depth:R,n:x<0?ft(b):b};S.push(A),(y===null||R<y.depth)&&(y=A)}return{plane:s,level:!1,side:y,axes:S,across:{depth:u-Math.abs(c),n:c<0?ft(s):s},d:a,half:p}}var QM=1e-6;function FS(t){let e=Dh(t.c,t.s,t.up),n=t.top/2;return{c:[t.b.x+t.up[0]*n,t.b.y+t.up[1]*n,t.b.z+t.up[2]*n],axes:[e,So(t.up,e),t.up],half:[t.hl,t.hw,n]}}function eC(t,e,n){let r=FS(t),s=FS(e),o=[s.c[0]-r.c[0],s.c[1]-r.c[1],s.c[2]-r.c[2]],i=(f,h)=>f.half[0]*Math.abs(Fe(f.axes[0],h))+f.half[1]*Math.abs(Fe(f.axes[1],h))+f.half[2]*Math.abs(Fe(f.axes[2],h)),a=f=>i(r,f)+i(s,f),c=[...r.axes,...s.axes];for(let f of r.axes)for(let h of s.axes){let p=So(f,h),y=Math.sqrt(Fe(p,p));y>QM&&c.push([p[0]/y,p[1]/y,p[2]/y])}let u=[];for(let f of c){let h=Fe(o,f),p=a(f)-Math.abs(h);if(p<=0)return null;u.push({depth:p,n:h<0?ft(f):f})}let l=u.reduce((f,h)=>h.depth<f.depth?h:f),d=Fe(o,n);return{plane:n,level:!1,side:l,axes:u,across:{depth:a(n)-Math.abs(d),n:d<0?ft(n):n},d:o,half:a}}function Nh(t,e){let n=pd(t)+pd(e),r=(t.top+e.top)/2,s=Math.sqrt(n*n+r*r)+r;if(Math.abs(e.b.x-t.b.x)>=s||Math.abs(e.b.y-t.b.y)>=s||Math.abs(e.b.z-t.b.z)>=s)return null;if(t.up[2]===1&&e.up[2]===1)return JM(t,e);if(t.up[0]===e.up[0]&&t.up[1]===e.up[1]&&t.up[2]===e.up[2])return ZM(t,e);let o=[t.up[0]+e.up[0],t.up[1]+e.up[1],t.up[2]+e.up[2]],i=Math.sqrt(Fe(o,o));return i<1e-9?null:eC(t,e,[o[0]/i,o[1]/i,o[2]/i])}var hd=(t,e,n)=>-((e.vx-t.vx)*n[0]+(e.vy-t.vy)*n[1]+((e.vz??0)-(t.vz??0))*n[2]);function tC(t,e,n,r){let s=t.across.depth/Math.max(hd(e.b,n.b,t.across.n),r.entrySpeed),i=s<=r.entryWindow&&t.across.depth<=(e.top+n.top)/4||!t.level&&t.across.depth<=r.groundTrace;if(!i)return{across:!1,landed:i};let a=t.side.depth/Math.max(hd(e.b,n.b,t.side.n),r.entrySpeed);return{across:s<a||s===a&&t.across.depth<t.side.depth,landed:i}}function zS(t){let e=[...t.tags??[]],n=t.flags??0;for(let r=0;r<24;r++)Math.floor(n/2**r)%2===1&&e.push(`flag:${r}`);return e}function xo(t,e,n){if(t.pairs.length===0)return t.top;let r=zS(e),s=zS(n),o=i=>r.includes(i.a)&&s.includes(i.b)||r.includes(i.b)&&s.includes(i.a);return t.pairs.find(o)?.top??t.top}function md(t,e,n){let r=Nh(t,e);if(r===null)return nC(t,e,n);let s=tC(r,t,e,n);if(!s.across){let l=Fe(r.d,r.plane)>=0;return{contact:{kind:wo.Side,n:r.side.n,depth:r.side.depth,upperIsB:l},g:r}}let o=r.across.n,i=o===r.plane||Fe(o,r.plane)>0,a=i?t:e,c=i?o:ft(o);return{contact:{kind:s.landed&&Fe(c,a.support)>=n.supportCos?wo.Top:wo.Side,n:o,depth:r.across.depth,upperIsB:i},g:r}}function nC(t,e,n){let r=e.b.z>=t.b.z,s=l=>({...l,b:{...l.b,z:l.b.z-n.groundTrace}}),o=r?Nh(t,s(e)):Nh(s(t),e);if(o===null||!(o.across.depth<o.side.depth))return null;let i=r?o.across.n:ft(o.across.n);if(!(Fe(i,o.plane)>0))return null;let a=r?t:e;if(a.support[2]<n.supportCos||Fe(i,a.support)<n.supportCos)return null;let[c,u]=r?[e.b,t.b]:[t.b,e.b];return-hd(u,c,i)>n.entrySpeed?null:{contact:{kind:wo.Top,n:o.across.n,depth:o.across.depth-n.groundTrace,upperIsB:r},g:o}}function rC(t,e,n,r){return yd(t,e,n)?null:md(qr(t,n,r),qr(e,n,r),n)?.contact??null}function sC(t){let e=t.shape;return e.kind===qn.Hull?Math.sqrt(2*e.radius*e.radius+e.height*e.height):Math.sqrt(e.length*e.length/4+e.width*e.width/4+e.top*e.top)}function yd(t,e,n){let r=2*sC(n)+n.groundTrace+1,s=e.x-t.x,o=e.y-t.y,i=e.z-t.z;return s*s+o*o+i*i>r*r}var qS=t=>e=>{let n=t.maxVelocity;return n===null?e:e<-n?-n:e>n?n:e},Gr=t=>[t.x,t.y,t.z],oC=.7,iC=.5,US=.5;function Ui(t,e,n,r,s,o){let i=Ec(t,e,n,r,Fe(n,o)<-iC?void 0:s),a=i.t,c=i.face;if(c===null||!(a<r))return{d:n,straight:a,slide:null,cos:1,sep:a};let u=[c[0],c[1],c[2]],l=aC(u,n,o);if(l===null)return{d:n,straight:a,slide:null,cos:1,sep:a};let d=Fe(l,n),f=[e[0]+n[0]*a,e[1]+n[1]*a,e[2]+n[2]*a],h=Ec(t,f,l,(r-a)/d,s).t;return{d:n,straight:a,slide:l,cos:d,sep:a+h*d}}function aC(t,e,n){if(Fe(t,n)>=oC){let a=Fe(e,t),c=[e[0]-a*t[0],e[1]-a*t[1],e[2]-a*t[2]],u=Math.hypot(c[0],c[1],c[2]);return u>=US?[c[0]/u,c[1]/u,c[2]/u]:null}let r=So(t,n),s=Math.hypot(r[0],r[1],r[2]),o=s>0?Fe(r,e)/s:0;if(!(Math.abs(o)>=US))return null;let i=o>0?1/s:-1/s;return[r[0]*i,r[1]*i,r[2]*i]}function VS(t,e){let n=t.d;if(t.slide===null||!(e>t.straight))return[n[0]*e,n[1]*e,n[2]*e];let r=(e-t.straight)/t.cos,s=t.slide;return[n[0]*t.straight+s[0]*r,n[1]*t.straight+s[1]*r,n[2]*t.straight+s[2]*r]}function cC(t,e,n=.5){let r=Math.min(e,1-Math.min(t,n));return[Math.min(t,1-r),r]}function uC(t,e,n,r,s,o,i,a=kc,c=kc,u=.5){if(s===null)return[u,1-u];let l=Ui(s,Gr(t),ft(n),r,o,a),d=Ui(s,Gr(e),n,r,i,c);return cC(l.sep/r,d.sep/r,u)}function GS(t,e,n,r){if(r.push!==yo.Mover)return .5;let s=t.vx*n[0]+t.vy*n[1],o=e.vx*n[0]+e.vy*n[1];n[2]!==0&&(s+=(t.vz??0)*n[2],o+=(e.vz??0)*n[2]);let i=s>0?s:0,a=o<0?-o:0;return i+a>0?i/(i+a):.5}function Bh(t,e,n,r,s,o){let[i,a]=uC(t.b,e.b,n,r,o.world,bo(t,s),bo(e,s),t.support,e.support,GS(t.b,e.b,n,s));return o.fixed===void 0?[i,a]:t.b.id===o.fixed?[0,o.world===null?1:Ui(o.world,Gr(e.b),n,r,bo(e,s),e.support).sep/r]:e.b.id===o.fixed?[o.world===null?1:Ui(o.world,Gr(t.b),ft(n),r,bo(t,s),t.support).sep/r,0]:[i,a]}var bo=(t,e)=>BS(t.support,e.supportCos);function lC(t,e,n,r,s,o){let i=r.axes.filter(l=>l.n!==n.n).sort((l,d)=>l.depth-d.depth);for(let l of i){let[d,f]=Bh(t,e,l.n,l.depth,s,o);if(!(d+f<1))return{n:l.n,depth:l.depth,sa:d,sb:f}}let[a,c]=Bh(t,e,n.n,n.depth,s,o),u=1-a-c;return t.b.id===o.fixed?{n:n.n,depth:n.depth,sa:a,sb:c+u}:e.b.id===o.fixed?{n:n.n,depth:n.depth,sa:a+u,sb:c}:{n:n.n,depth:n.depth,sa:a+u/2,sb:c+u/2}}function HS(t,e){t.x+=e[0],t.y+=e[1],e[2]!==0&&(t.z+=e[2])}function dC(t,e,n,r,s,o,i,a){let[c,u]=[t.b,e.b],l=a.world,d=ft(n),f=l===null?{d,straight:r,slide:null,cos:1,sep:r}:Ui(l,Gr(c),d,r,bo(t,i),t.support),h=l===null?{d:n,straight:r,slide:null,cos:1,sep:r}:Ui(l,Gr(u),n,r,bo(e,i),e.support);HS(c,VS(f,r*s)),HS(u,VS(h,r*o))}function fC(t,e,n,r,s,o,i){let a=qS(s),[c,u]=[t.b,e.b],[l,d]=Bh(t,e,n.n,n.depth,s,o),f=l+d<1?lC(t,e,n,r,s,o):null,{depth:h,n:p,sa:y,sb:S}=f??{depth:n.depth,n:n.n,sa:l,sb:d},[b,x,R]=p,A=(u.vx-c.vx)*b+(u.vy-c.vy)*x;R!==0&&(A+=((u.vz??0)-(c.vz??0))*R);let E=A<0&&!i?-(1+s.restitution)*A/2:0,P=GS(c,u,p,s),k=2*E*P,M=2*E*(1-P);return dC(t,e,p,h,y,S,s,o),c.vx=a(c.vx-k*b),c.vy=a(c.vy-k*x),s.stopSpin&&(c.spin=0),u.vx=a(u.vx+M*b),u.vy=a(u.vy+M*x),s.stopSpin&&(u.spin=0),R!==0&&(c.vz=a((c.vz??0)-k*R),u.vz=a((u.vz??0)+M*R)),{j:E,n:p,depth:h}}function YS(t,e){let n=e?t.side.n:ft(t.side.n),r=e?t.d:ft(t.d),s=So(t.plane,n);return[n,ft(n),s,ft(s)].map(i=>({w:i,move:t.half(i)-Fe(r,i)})).map((i,a)=>({way:i,k:a})).sort((i,a)=>i.way.move-a.way.move||i.k-a.k).map(i=>i.way)}var $S=(t,e,n)=>t.half(n)-Fe(e?t.d:ft(t.d),n);function pC(t,e,n,r,s){let o=[];for(let i of n){if(i===t.b||i===e||yd(t.b,i,r)||xo(r,t.b,i).policy===it.Ghost)continue;let a=md(t,qr(i,r,s),r);a!==null&&a.contact.kind===wo.Top&&!a.contact.upperIsB&&o.push(a.g)}return o}function hC(t,e,n){if(n.length===0)return YS(t,e);let r=e?t.side.n:ft(t.side.n),s=So(t.plane,r);return[r,ft(r),s,ft(s)].map(i=>({w:i,move:n.reduce((a,c)=>Math.max(a,$S(c,!1,i)),$S(t,e,i))})).map((i,a)=>({way:i,k:a})).sort((i,a)=>i.way.move-a.way.move||i.k-a.k).map(i=>i.way)}var jS=(t,e,n,r)=>n.move<=0||ud(t,Gr(e.b),n.w,n.move,bo(e,r))>=n.move;function Ih(t,e,n,r){t.vx=r(t.vx+n*e[0]),t.vy=r(t.vy+n*e[1]),e[2]!==0&&(t.vz=r((t.vz??0)+n*e[2]))}function WS(t,e){if(!(e<t.speed))return 0;let n=t.speed-e;return t.step===null?n:Math.min(n,t.step)}function dd(t,e,n,r,s,o,i,a){let[c,u]=[t.b,e.b],l=qS(o),d=YS(n,r),f=hC(n,r,pC(t,u,a,o,i)).find(S=>jS(i.world,t,S,o));if(f!==void 0){let S=(c.vx-u.vx)*f.w[0]+(c.vy-u.vy)*f.w[1]+((c.vz??0)-(u.vz??0))*f.w[2],b=WS(s,S);return Ih(c,f.w,b*s.share,l),s.share!==1&&Ih(u,f.w,-b*(1-s.share),l),{j:b,way:fd.Free,w:f.w}}let h=d.map(S=>({w:ft(S.w),move:S.move})).find(S=>jS(i.world,e,S,o));if(h===void 0)return{j:0,way:fd.Pinned,w:null};let p=(u.vx-c.vx)*h.w[0]+(u.vy-c.vy)*h.w[1]+((u.vz??0)-(c.vz??0))*h.w[2],y=WS(s,p);return Ih(u,h.w,y,l),{j:y,way:fd.LowerYields,w:h.w}}function mC(t,e,n,r,s,o,i,a){let c=r+i.roofSkin;if(!(c>0))return;let u=t.id===a.fixed?0:ud(a.world,Gr(t),n,c);if(u>=c&&s.level){t.z=e.z+o+i.roofSkin;return}if(t.x+=n[0]*u,t.y+=n[1]*u,t.z+=n[2]*u,u>=c)return;let l=e.id===a.fixed?0:ud(a.world,Gr(e),ft(n),c-u);e.x-=n[0]*l,e.y-=n[1]*l,e.z-=n[2]*l}function yC(t,e,n){let r=t.vx*n[0]+t.vy*n[1]+(t.vz??0)*n[2],s=e.vx*n[0]+e.vy*n[1]+(e.vz??0)*n[2];if(r<s){if(n[0]===0&&n[1]===0){t.vz=e.vz??0;return}t.vx+=n[0]*(s-r),t.vy+=n[1]*(s-r),t.vz=(t.vz??0)+n[2]*(s-r)}}function gC(t,e,n){let r=t.vx*e[0]+t.vy*e[1]+(t.vz??0)*e[2];t.vx+=e[0]*(n-r),t.vy+=e[1]*(n-r),t.vz=(t.vz??0)+e[2]*(n-r)}function Lh(t,e,n){let r=t.x-e.x,s=t.y-e.y,o=n.shape;if(o.kind===qn.Hull)return Math.max(Math.abs(r),Math.abs(s))/o.radius;let[i,a]=Ut(e.yaw);return Math.max(Math.abs(r*a+s*i)/(o.length/2),Math.abs(s*a-r*i)/(o.width/2))}function bC(t,e,n){if(n)return 0;let r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s);return o>0?-(e.vx*r+e.vy*s)/o:0}var wC=100,As={Stand:"stand",Release:"release",Slide:"slide"};function KS(t,e,n,r){if(n.center===null)return As.Stand;let s=Lh(t,e,r);return s<=n.center?As.Stand:(e.vz??0)-(t.vz??0)>wC?As.Slide:bC(t,e,n.ride)>=(n.slide.step??n.slide.speed)/2?As.Release:s>1?As.Slide:As.Stand}var XS=(t,e,n,r)=>n.policy===it.Stand&&KS(t,e,n,r)===As.Stand;function SC(t,e,n,r,s,o,i,a){let[c,u]=n.upperIsB?[e,t]:[t,e],l=c.b,d=u.b,f=n.upperIsB?n.n:ft(n.n),h=hd(d,l,f),p=s.policy===it.Stand&&KS(l,d,s,o)===As.Slide;return mC(l,d,f,n.depth,r,u.top,o,i),yC(l,d,f),u.support[2]<o.supportCos?dd(c,u,r,n.upperIsB,o.offWall,o,i,a):s.policy===it.Stand?p?dd(c,u,r,n.upperIsB,s.slide,o,i,a):Oh:s.policy===it.Slide?dd(c,u,r,n.upperIsB,s,o,i,a):s.policy===it.Bounce&&h>=s.stompMin?(gC(l,f,s.bounceSpeed+(l.jump?s.jumpBoost:0)),i.onContact?.(l,d,KM.Stomp),Oh):s.policy===it.Bounce?dd(c,u,r,n.upperIsB,s.slide,o,i,a):Oh}function JS(t,e,n,r,s=!1,o=[]){let i=xo(n,t,e);if(i.policy===it.Ghost||yd(t,e,n))return null;let a=qr(t,n,r),c=qr(e,n,r),u=md(a,c,n);return u===null?null:ZS(a,c,u,i,n,r,s,o)}function ZS(t,e,n,r,s,o,i,a){let{contact:c,g:u}=n;return c.kind===wo.Side?{...c,...fC(t,e,c,u,s,o,i),way:null,w:null}:{...c,...SC(t,e,c,u,r,s,o,a)}}function xC(t,e,n,r,s,o,i){let a=o.cooling?o.cooling(t,e):!1,c=n===0?o.first?.(t,e,a):void 0;return c===void 0?JS(t,e,r,s,a,i):c}var QS=(t,e)=>t!==null&&(t.depth>e.slop||t.kind===wo.Top&&t.depth>0),_C=t=>({moves:new Int32Array(t),still:new Int32Array(t*t).fill(-1)});function RC(t,e,n,r,s){if(yd(t,e,n))return null;let o=xo(n,t,e);if(o.policy===it.Ghost)return null;let i=qr(t,n,r),a=qr(e,n,r),c=md(i,a,n);return c===null||!QS(c.contact,n)?null:ZS(i,a,c,o,n,r,!1,s)}function EC(t,e,n,r,s,o,i){let a=!1,c=t.length;for(let u=0;u<c;u++)for(let l=u+1;l<c;l++){let d=t[u],f=t[l],h=u*c+l;if(i!==null&&e>0&&i.still[h]===i.moves[u]+i.moves[l])continue;let p;if(i!==null&&e>0)p=RC(d,f,n,r,t);else{if(e>0&&!QS(rC(d,f,n,r),n))continue;p=xC(d,f,e,n,r,s,t)}if(p===null){i!==null&&(i.still[h]=i.moves[u]+i.moves[l]);continue}i!==null&&(i.moves[u]=i.moves[u]+1,i.moves[l]=i.moves[l]+1),a=!0,p.way===fd.Pinned&&(o.pinned+=1),s.onPair?.(d,f,p)}return a}function kC(t,e,n,r={}){let s={passes:0,pushed:new Map,walls:new Map,pinned:0};n={...n,supports:new Map};let o=r.first===void 0&&r.onPair===void 0&&r.cooling===void 0?_C(t.length):null;for(let i=0;i<e.passes&&EC(t,i,e,n,r,s,o);i++)s.passes+=1,n.world!==null&&t.forEach((a,c)=>{let u=d=>{d[2]<e.supportCos&&d[3]>(s.walls.get(a.id)??0)&&s.walls.set(a.id,d[3])},l=LS(n.world,a,u);l>(s.pushed.get(a.id)??0)&&s.pushed.set(a.id,l),o!==null&&l>0&&(o.moves[c]=o.moves[c]+1)});return s}var Fh=(t,e)=>(n,r)=>{JS(n,r,t,e)},ex=(t,e)=>n=>{kC(n,t,e)};function tx(t){return t.top.policy===it.Stand||t.pairs.some(e=>e.top.policy===it.Stand)}function AC(t,e,n){let r=t.x+t.vx*n,s=t.y+t.vy*n,o=t.z+(t.vz??0)*n,i=e.shape,a=e.groundTrace;if(i.kind===qn.Hull){let l=i.radius;return{kind:"box",min:[r-l,s-l,o+i.height-a],max:[r+l,s+l,o+i.height]}}let[c,u]=Ut(t.yaw);return{kind:"obox",c:[r,s,o+i.top-a/2],half:[i.length/2,i.width/2,a/2],sin:c,cos:u}}var nx=t=>t.shape.kind===qn.Hull?t.shape.height:t.shape.top,rx=2;function PC(t,e,n,r){let s=xo(n,t,e);if(s.policy!==it.Stand)return!1;let o=nx(n);return t.z<e.z+o-n.groundTrace||t.z>e.z+2*o||!(Lh(t,e,n)<rx)||qr(e,n,r).support[2]<n.supportCos?!1:XS(t,e,s,n)}var TC=t=>rx*(t.shape.kind===qn.Hull?t.shape.radius:Math.hypot(t.shape.length,t.shape.width)/2);function vC(t,e,n=0){let r=nx(e),s=TC(e);for(let o of t)for(let i of t){if(i===o)continue;let a=i.z+(i.vz??0)*n;if(o.z<a+r-e.groundTrace||o.z>a+2*r)continue;let c=(Math.abs(i.vx)+Math.abs(i.vy))*n;if(Math.abs(o.x-i.x)<s+c&&Math.abs(o.y-i.y)<s+c)return!0}return!1}function Ac(t,e,n,r){return vC(t,e)?t.map(s=>{let o=[],i=[];for(let a of t)a===s||!PC(s,a,e,n)||(o.push(AC(a,e,r)),i.push(a.id));return{solids:o,lowers:i}}):t.map(()=>({solids:[],lowers:[]}))}function zh(t,e,n){let[r,s,o]=[e[0],e[1],e[2]],[i,a,c]=[n[0],n[1],n[2]];return t.find(u=>Math.abs(i-u.x)<=r&&Math.abs(a-u.y)<=s&&c>u.z+2*o&&c<=u.z+4*o)}function sx(t,e,n,r){let s=[];for(let o of n){let[i,a]=[o.p[0],o.p[1]],c=zh(t,e,o.p);if(c===void 0)continue;let u=i-c.x,l=a-c.y,d=Math.hypot(u,l),[f,h]=d>0?[u/d,l/d]:[1,0],[p,y,S]=[o.v[0],o.v[1],o.v[2]],b=(p-c.vx)*f+(y-c.vy)*h;if(!(b<r.speed))continue;let x=Math.min(r.step,r.speed-b);s.push({key:o.key,v:[p+f*x,y+h*x,S]})}return s}var _o={Box:"box",Disc:"disc"},ox={PingPong:"pingpong",Loop:"loop"},ix={Linear:"linear",Smooth:"smooth"},ax={All:"all",None:"none"},cx=Object.freeze({platforms:Object.freeze([]),bodies:!1});var NU=2**24;var BU=2*Math.PI;var dx=2*Math.PI,Nt=Math.fround,fx=(t,e)=>(t%e+e)%e;function MC(t,e,n,r,s){if(s===ix.Linear)return[Nt(t[0]+(e[0]-t[0])*n/r),Nt(t[1]+(e[1]-t[1])*n/r),Nt(t[2]+(e[2]-t[2])*n/r)];let o=n/r,i=o*o*(3-2*o);return[Nt(t[0]+(e[0]-t[0])*i),Nt(t[1]+(e[1]-t[1])*i),Nt(t[2]+(e[2]-t[2])*i)]}function CC(t,e){let n=t.legs.length,r=t.mode===ox.Loop,s=r?n:2*n,o=e;for(let i=0;i<s;i++){let a=i,c=i,u=i+1;r?u=(i+1)%n:i>=n&&(a=2*n-1-i,c=a+1,u=a);let l=t.legs[a],d=t.points[u];if(o<l)return MC(t.points[c],d,o,l,t.ease);o-=l;let f=t.waits[u];if(o<f)return d;o-=f}return t.points[0]}function OC(t,e,n,r){return t.called?r===void 0||n<r||n-r>=e.period?0:n-r:fx(n+e.phase,e.period)}function Ps(t,e,n){let r=t.path===null?t.at:CC(t.path,OC(t,t.path,e,n)),s=t.spin;return s===null?{c:r,yaw:0}:{c:r,yaw:Nt(s.dir*(dx*fx(e+s.phase,s.period)/s.period))}}function ux(t,e,n){return t.platforms.map(r=>Ps(r,e,n?.get(r.id)))}var Uh=t=>t.spin===null?0:t.spin.dir*dx/t.spin.period;function bd(t,e,n,r,s){let o=Ps(t,n,s),i=Ps(t,n+1,s),a=Uh(t),c,u;if(a===0)c=e.x+(i.c[0]-o.c[0]),u=e.y+(i.c[1]-o.c[1]);else{let[d,f]=Ut(a),h=e.x-o.c[0],p=e.y-o.c[1];c=i.c[0]+(f*h-d*p),u=i.c[1]+(d*h+f*p)}let l=e.z+(i.c[2]-o.c[2]);if(t.surface!==null){let[d,f]=t.surface;if(i.yaw===0)c+=d/r,u+=f/r;else{let[h,p]=Ut(i.yaw);c+=(p*d-h*f)/r,u+=(h*d+p*f)/r}}return{x:c,y:u,z:l,yaw:e.yaw+a,v:[(c-e.x)*r,(u-e.y)*r,(l-e.z)*r]}}function gd(t,e){return t.platforms.map((n,r)=>{let{c:s,yaw:o}=e[r],i=n.shape;if(i.kind===_o.Disc)return{kind:"disc",c:s,radius:i.radius,half:i.half};let a=i.half;if(n.spin===null)return{kind:"box",min:[s[0]-a[0],s[1]-a[1],s[2]-a[2]],max:[s[0]+a[0],s[1]+a[1],s[2]+a[2]]};let[c,u]=Ut(o);return{kind:"obox",c:s,half:a,sin:c,cos:u}})}var px=4;function wd(t,e,n){return{now:gd(t,ux(t,e,n)),next:gd(t,ux(t,e+1,n))}}var hx=(t,e)=>t?.get(e.id);function lx(t,e){t.x=Nt(e.x),t.y=Nt(e.y),t.z=Nt(e.z)}function IC(t,e,n,r,s){let o=[],i=[],a=s===void 0?null:Ac(e,s.policy,s.env,0);return e.forEach((c,u)=>{let l=a?.[u];if(n.length===0&&(l===void 0||l.solids.length===0)){o.push(-1),i.push(null);return}let d=l===void 0||l.solids.length===0?r.support(c,n):r.support(c,[...n,...l.solids]),f=d>=t.platforms.length&&l!==void 0?e.find(p=>p.id===l.lowers[d-t.platforms.length])??null:null,h=s!==void 0&&f!==null?xo(s.policy,c,f):null;o.push(d<t.platforms.length?d:-1),i.push(f!==null&&h?.policy==="stand"&&h.ride?f.id:null)}),{bases:o,on:i}}function DC(t,e,n,r,s,o,i){let a=e.map((l,d)=>{let f=n[d];if(f<0)return null;let h=t.platforms[f];return bd(h,l,s,o,hx(i,h))}),c=new Map(e.map((l,d)=>[l.id,d])),u=(l,d)=>{let f=a[l];if(f!=null)return[f.x-e[l].x,f.y-e[l].y,f.z-e[l].z];let h=r[l]===null||r[l]===void 0?void 0:c.get(r[l]);return h===void 0||d>=px?[0,0,0]:u(h,d+1)};return e.map((l,d)=>{if(a[d]!==null)return a[d];if(r[d]===null)return null;let f=u(d,0);return{x:l.x+f[0],y:l.y+f[1],z:l.z+f[2],yaw:l.yaw,v:[f[0]*o,f[1]*o,f[2]*o]}})}function mx(t,e,n,r,s,o,i,a=wd(t,n,s),c){let{now:u,next:l}=a,d=e.map(b=>({...b})),{bases:f,on:h}=IC(t,d,u,o,c),p=DC(t,d,f,h,n,r,s),y=[],S=[];return e.forEach((b,x)=>{let R=f[x],A=p[x]??null;A!==null&&(lx(b,A),i&&R>=0&&(b.yaw=Nt(A.yaw))),y.push(A===null?null:A.v),t.platforms.forEach((E,P)=>{if(P===R||!o.inside(b,l,P))return;let k=bd(E,b,n,r,hx(s,E)),M=o.pushOut({...b,x:k.x,y:k.y,z:k.z},l);lx(b,M),M.inside&&S.push({seat:b.id,lift:E.id})})}),{bases:f,on:h,v:y,crushed:S,from:e.map(b=>[b.x,b.y,b.z])}}function yx(t,e,n){if(e.on.every(c=>c===null))return e;let r=new Map(t.map((c,u)=>[c.id,u])),s=t.map((c,u)=>{let l=e.from[u];return[c.x-l[0],c.y-l[1]]}),o=(c,u)=>{let l=e.on[c],d=l==null?void 0:r.get(l);if(d===void 0||u>=px)return[0,0];let f=s[d],h=o(d,u+1);return[f[0]+h[0],f[1]+h[1]]},i=t.map((c,u)=>o(u,0)),a=e.v.map((c,u)=>{let l=i[u];return c===null||e.on[u]===null?c:[c[0]+l[0]*n,c[1]+l[1]*n,c[2]]});return t.forEach((c,u)=>{let l=i[u];e.on[u]!==null&&(c.x=Nt(c.x+l[0]),c.y=Nt(c.y+l[1]))}),{...e,v:a}}function NC(t,e,n,r,s,o){let i=Ac(t,o.policy,o.env,0)[e];if(i===void 0||i.solids.length===0)return!1;let a=s.support(t[e],[...r,...i.solids]);return a>=r.length&&i.lowers[a-r.length]===n}function gx(t,e,n,r,s,o,i=wd(t,r,s).next,a){if(n.v.every(u=>u===null))return;let c=e.map(u=>({...u}));e.forEach((u,l)=>{let d=n.bases[l]??-1,f=n.v[l],h=n.on[l]??null;if(f!=null){if(h!==null&&a!==void 0){if(NC(c,l,h,i,o,a))return}else if(d<0||t.platforms[d].impart!==ax.All||o.support(u,i)===d)return;u.vx=Nt(u.vx+f[0]),u.vy=Nt(u.vy+f[1]),u.vz=Nt(u.vz+f[2])}})}var Pc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function BC(t){return!Pc(t)||!Array.isArray(t.platforms)||typeof t.bodies!="boolean"?!1:t.platforms.every(e=>Pc(e)&&typeof e.id=="string"&&Pc(e.shape)&&Array.isArray(e.at)&&typeof e.called=="boolean")}function xx(t,e,n,r){if(!t)return null;let s;try{s=JSON.parse(t)}catch{return null}if(!Pc(s)||s.name!==wr.FIRSTPERSON&&s.name!==wr.VEHICLE)return null;let o=BC(s.lifts)?s.lifts:null;if(o===null&&n===void 0)return null;let i=Di(s.name,s.params);return{policy:o??cx,ops:Jw(s.name,i,e),vehicle:s.name===wr.VEHICLE,heads:n,tickHz:r}}function _x(t){if(!t)return;let e;try{e=JSON.parse(t)}catch{return}if(!Pc(e))return;let n=new Map;for(let[r,s]of Object.entries(e))typeof s=="number"&&Number.isInteger(s)&&n.set(r,s);return n}var LC=128,Vi=class{constructor(){m(this,"kept",new Map);m(this,"startsText","")}at(e,n,r){let s=r===void 0?"":JSON.stringify([...r]);s!==this.startsText&&(this.kept.clear(),this.startsText=s);let o=this.kept.get(n);if(o!==void 0)return o;let i=wd(e,n,r),a={solids:i,next:gc(i.next)};return this.kept.size>=LC&&this.kept.delete(this.kept.keys().next().value),this.kept.set(n,a),a}};function vc(t,e,n,r,s,o){let{solids:i,next:a}=o.at(t.policy,n,r),c=mx(t.policy,e,n,t.tickHz,r,t.ops,t.vehicle,i,t.heads),u=new Map;return t.heads!==void 0&&Ac(e,t.heads.policy,t.heads.env,s).forEach((d,f)=>{d.solids.length>0&&u.set(e[f].id,gc([...i.next,...d.solids]))}),{tick:n,solids:i,report:c,seats:e,posed:u,next:a}}function Rx(t,e){e.report=yx(e.seats,e.report,t.tickHz)}function Ex(t,e,n,r){let s=e.report.v;e.report={...e.report,v:s.map((o,i)=>i!==n||o===null?o:[o[0]+r[0]*t.tickHz,o[1]+r[1]*t.tickHz,o[2]])}}var Mc=(t,e)=>t.posed.get(e)??t.next;function Cc(t,e,n){gx(t.policy,e.seats,e.report,e.tick,n,t.ops,e.solids.next,t.heads)}function FC(t,e,n){return t.platforms.map((r,s)=>Tc(t,s,e,n))}function Tc(t,e,n,r){let s=t.platforms[e];if(s===void 0)return{c:[0,0,0],yaw:0};let o=Math.floor(n),i=Ps(s,o,r?.get(s.id)),a=Ps(s,o+1,r?.get(s.id)),c=s.spin===null?0:s.spin.dir*2*Math.PI/s.spin.period,u=n-o;return{c:[i.c[0]+(a.c[0]-i.c[0])*u,i.c[1]+(a.c[1]-i.c[1])*u,i.c[2]+(a.c[2]-i.c[2])*u],yaw:i.yaw+c*u}}function Oc(t,e,n,r){return t.policy.platforms.length===0?-1:t.ops.support({x:e.x,y:e.y,z:e.z,vz:0,duck:e.duck??0},gd(t.policy,FC(t.policy,n,r)))}function Vh(t,e,n,r,s,o){let i=Tc(t,e,r,o),a=Tc(t,e,s,o),c=a.yaw-i.yaw,[u,l]=[Math.sin(c),Math.cos(c)],d=n.x-i.c[0],f=n.y-i.c[1];return{x:a.c[0]+l*d-u*f,y:a.c[1]+u*d+l*f,z:n.z+a.c[2]-i.c[2],yaw:n.yaw+c}}function kx(t,e,n,r){let s=t.platforms.findIndex(i=>i.id===e);if(s<0)return;let o=Tc(t,s,n,r);return{x:o.c[0],y:o.c[1],z:o.c[2],yaw:o.yaw}}function Hh(t,e,n,r){let s=t.platforms[e];if(s===void 0)return 0;let o=s.shape.kind===_o.Box?s.shape.half[2]:s.shape.half;return Tc(t,e,n,r).c[2]+o}var bx=["x","y","z"],wx=["vx","vy","vz"];function Ax(t,e,n,r,s,o,i){let a={...t,heads:void 0},c={id:"",x:s.x??0,y:s.y??0,z:s.z??0,vx:s.vx??0,vy:s.vy??0,vz:s.vz??0,yaw:s.yaw??0,duck:s.duck??0,flags:0},u=vc(a,[c],o,e,i,n);for(let l of bx)s[l]=c[l];t.vehicle&&(s.yaw=c.yaw),r(s,Mc(u,c.id));for(let l of[...bx,...wx])c[l]=s[l]??0;Cc(a,u,e);for(let l of wx)s[l]=c[l]}var Ic=t=>`lift.${t}`,Sx=16;function zC(t){let e=t.surface===null?{}:{friction:0};if(t.shape.kind===_o.Box)return{key:"lift",shape:{kind:"box",half:[t.shape.half[0],t.shape.half[1],t.shape.half[2]]},...e};let{radius:n,half:r}=t.shape,s=[];for(let o=0;o<Sx;o++){let[i,a]=Ut(2*Math.PI*o/Sx);s.push([Math.fround(n*a),Math.fround(n*i),-r],[Math.fround(n*a),Math.fround(n*i),r])}return{key:"lift",shape:{kind:"hull",points:s},...e}}function Sd(t,e,n){let r=Ps(t,e,n?.get(t.id)),[s,o]=Ut(r.yaw/2);return{p:[r.c[0],r.c[1],r.c[2]],q:[0,0,Math.fround(s),Math.fround(o)]}}function Px(t,e,n){return{key:Ic(t.id),type:"kinematic",pose:Sd(t,e,n),colliders:[zC(t)]}}var UC=20;function VC(t,e,n,r){let s=n-e.c[0],o=r-e.c[1],[i,a]=e.yaw===0?[0,1]:Ut(e.yaw),c=a*s+i*o,u=a*o-i*s;return t.shape.kind===_o.Disc?c*c+u*u<=t.shape.radius*t.shape.radius:Math.abs(c)<=t.shape.half[0]&&Math.abs(u)<=t.shape.half[1]}var HC=(t,e)=>e+(t.shape.kind===_o.Disc?t.shape.half:t.shape.half[2]);function $h(t,e,n,r){let s=t.platforms.filter(i=>i.surface!==null),o=s.map(i=>Ps(i,e,n?.get(i.id)));return i=>{let[a,c,u]=[i[0],i[1],i[2]];return s.find((l,d)=>{let f=o[d],h=u-HC(l,f.c[2]);return h>0&&h<=r&&VC(l,f,a,c)})}}function Tx(t,e,n,r,s,o){let i=$h(t,e,n,o),a=Math.min(1,UC/r),c=[];for(let u of s){let[l,d,f]=[u.p[0],u.p[1],u.p[2]],h=i(u.p);if(h===void 0)continue;let p=bd(h,{x:l,y:d,z:f,yaw:0},e,r,n?.get(h.id)),[y,S,b]=[u.v[0],u.v[1],u.v[2]],x=p.v[0]-y,R=p.v[1]-S;x===0&&R===0||c.push({key:u.key,v:[y+x*a,S+R*a,b]})}return c}var Ro=15,$C=65535;var jC=Object.values(Zt),vx=(t,e,n)=>typeof t=="number"&&Number.isFinite(t)&&t>=e&&t<=n,Yr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Mx=t=>typeof t=="number"&&Number.isFinite(t)&&t>0;function Nc(t){if(t===void 0||t==="")return null;let e;try{e=JSON.parse(t)}catch{return null}if(!Yr(e)||!Yr(e.world))return null;let{keyframeTicks:n,maxLinear:r,maxAngular:s}=e;if(!(typeof n=="number"&&Number.isInteger(n)&&n>=1)||!Mx(r)||!Mx(s))return null;let i=e.presetBody,a=Yr(i)&&Array.isArray(i.half)&&i.half.length===3?{half:i.half,events:i.events===!0}:null,c=jC.includes(e.remotePredict)?e.remotePredict:xr.DEFAULT_REMOTE_PREDICT,u=e.remoteDecayMs,l=vx(u,0,xr.MAX_REMOTE_DECAY_MS)?u:xr.DEFAULT_REMOTE_DECAY_MS,d=e.leadMs,f=vx(d,xr.MIN_LEAD_MS,xr.MAX_LEAD_MS)?d:xr.DEFAULT_LEAD_MS;return{world:e.world,keyframeTicks:n,maxLinear:r,maxAngular:s,presetBody:a,remotePredict:c,remoteDecayMs:l,leadMs:f}}function jh(t){return Math.fround(Math.fround(t.dt)/t.substeps)}function WC(t,e){let n=Math.floor(t/e+.5);return Number.isNaN(n)||n<0?0:Math.min(n,$C)}var Dc=id.ORIENTATION,Ts=id.VELOCITY,Hi=t=>t===0?0:t;function Ix(t,e,n){e[n]=Hi(t.x),e[n+1]=Hi(t.y),e[n+2]=Hi(t.z),e[n+3]=Qt(t.qx,Dc),e[n+4]=Qt(t.qy,Dc),e[n+5]=Qt(t.qz,Dc),e[n+6]=Qt(t.qw,Dc),e[n+7]=Qt(t.lvx,Ts),e[n+8]=Qt(t.lvy,Ts),e[n+9]=Qt(t.lvz,Ts),e[n+10]=Qt(t.avx,Ts),e[n+11]=Qt(t.avy,Ts),e[n+12]=Qt(t.avz,Ts),e[n+13]=t.sleep?1:0,e[n+14]=t.rest}function Wh(t,e,n,r,s,o){s[o]=Hi(t[e]),s[o+1]=Hi(t[e+1]),s[o+2]=Hi(t[e+2]);for(let i=3;i<7;i++)s[o+i]=Qt(t[e+i],Dc);for(let i=7;i<10;i++)s[o+i]=Qt(t[e+i]/n,Ts);for(let i=10;i<13;i++)s[o+i]=Qt(t[e+i],Ts);s[o+13]=t[e+13]===1?1:0,s[o+14]=WC(t[e+14],r)}function Dx(t,e,n){let r=[...Array.from(t.p),...Array.from(t.q),...Array.from(t.v),...Array.from(t.w),t.sleeping?1:0,t.rest??0],s=[];return Wh(r,0,e,n,s,0),s}function Cx(t,e){let n=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);if(!(n>e))return null;let r=e/n;return[t[0]*r,t[1]*r,t[2]*r]}function Nx(t,e,n,r=gS,s=bS){let o=Cx(t,r*n),i=Cx(e,s);return o===null&&i===null?null:{linvel:o??[t[0],t[1],t[2]],angvel:i??[e[0],e[1],e[2]]}}var tV=16*1024;function Bx(t,e){let n;try{n=JSON.parse(t)}catch{return null}if(!Yr(n)||!Array.isArray(n.colliders))return null;for(let r of n.colliders){if(!Yr(r)||!Yr(r.shape))return null;let s=r.shape.ref;if(s===void 0)continue;let o=typeof s=="string"?e(s):void 0;if(o===void 0)return null;try{r.shape=JSON.parse(o)}catch{return null}}return n}var Lx=.5,xd=t=>{if(!Array.isArray(t)||t.length!==3)return 0;let[e,n,r]=t;return Math.sqrt(e*e+n*n+r*r)},Ox=t=>Array.isArray(t)?t.reduce((e,n)=>Math.max(e,xd(n)),0):0;function qC(t){switch(t.kind){case"box":return xd(t.half);case"sphere":return typeof t.radius=="number"?t.radius:0;case"capsule":return(typeof t.halfHeight=="number"?t.halfHeight:0)+(typeof t.radius=="number"?t.radius:0);case"hull":return Ox(t.points);case"trimesh":return Ox(t.vertices);case"heightfield":return xd(t.size);default:return 0}}function Bc(t){let e=Array.isArray(t.colliders)?t.colliders:[],n=0;for(let r of e){if(!Yr(r)||!Yr(r.shape))continue;let s=Yr(r.offset)?xd(r.offset.p):0;n=Math.max(n,s+qC(r.shape))}return n}function Fx(t,e,n){let r=new Map,s=u=>{let l=u;for(;r.get(l)!==l;)l=r.get(l);let d=u;for(;d!==l;){let f=r.get(d);r.set(d,l),d=f}return l},o=(u,l)=>{let d=s(u),f=s(l);d!==f&&(d<f?r.set(f,d):r.set(d,f))};for(let u of t)r.set(u.key,u.key);let i=[...t].sort((u,l)=>u.x-l.x||(u.key<l.key?-1:1)),a=i.reduce((u,l)=>Math.max(u,l.radius),0);for(let u=0;u<i.length;u++){let l=i[u];for(let d=u+1;d<i.length;d++){let f=i[d];if(f.x-l.x>l.radius+a+n)break;let h=f.x-l.x,p=f.y-l.y,y=f.z-l.z,S=l.radius+f.radius+n;h*h+p*p+y*y<=S*S&&o(l.key,f.key)}}for(let[u,l]of e)r.has(u)&&r.has(l)&&o(u,l);let c=new Map;for(let u of t)c.set(u.key,s(u.key));return c}function GC(t,e,n){if(n<=0)return t<=1?1:0;let r=1-(t-1)*(1e3/e)/n;return r<=0?0:r>=1?1:r}function Rd(t,e,n,r){let s=GC(e,n,r);return{...t,moveX:t.moveX*s,moveY:t.moveY*s,moveZ:t.moveZ*s}}var Rt={TAU_SMALL_MS:300,TAU_LARGE_MS:100,SMALL_METRES:.25,LARGE_METRES:1,SNAP_PLAYER_METRES:2,SNAP_OTHER_METRES:6,PLAYER_KINDS:Object.freeze(["player","vehicle"]),SEAT_TAU_MS:70,SEAT_CONTACT_TAU_MS:100,SEAT_SNAP_METRES:6,SEAT_HOLD_MS:120,SEAT_MOVING_UNITS_PER_MS:.2,SEAT_CLOCK_TAU_MS:100,SEAT_CLOCK_SNAP_INPUTS:1.5};function YC(t,e){let n=Math.max(t,0)/e;return(1+n)*Math.exp(-n)}function Ed(t,e,n,r){let s=Math.max(n,0),o=r/2,i=Math.exp(-s/o),a=e+t/o;return[(t+a*s)*i,(e-a*s/o)*i]}function $i(t){let{TAU_SMALL_MS:e,TAU_LARGE_MS:n,SMALL_METRES:r,LARGE_METRES:s}=Rt;return t<=r?e:t>=s?n:e+(t-r)/(s-r)*(n-e)}var _d=class{constructor(){m(this,"last",null);m(this,"offset",null)}draw(e,n,r,s,o,i){let a=this.last;a===null||a.epoch!==r?this.offset=null:a.predicted!==n&&this.startFrom(a,e,s,o,i);let c=this.apply(e,s);return this.last={p:c.p,q:c.q,predicted:n,epoch:r},c}startFrom(e,n,r,s,o){let i=[e.p[0]-n.p[0],e.p[1]-n.p[1],e.p[2]-n.p[2]],a=Math.hypot(i[0],i[1],i[2])/o;if(a>s){this.offset=null;return}let c=jn(e.q,[-n.q[0],-n.q[1],-n.q[2],n.q[3]]),u=c[3]<0?[-c[0],-c[1],-c[2],-c[3]]:c;this.offset={dp:i,dq:u,since:r,tau:$i(a)}}apply(e,n){let r=this.offset;if(r===null)return{p:[e.p[0],e.p[1],e.p[2]],q:[e.q[0],e.q[1],e.q[2],e.q[3]]};let s=YC(n-r.since,r.tau);return{p:[e.p[0]+r.dp[0]*s,e.p[1]+r.dp[1]*s,e.p[2]+r.dp[2]*s],q:jn(Fi(r.dq,s),e.q)}}};function kd(t){return typeof t=="string"&&Rt.PLAYER_KINDS.includes(t)?Rt.SNAP_PLAYER_METRES:Rt.SNAP_OTHER_METRES}function $x(t,e,n,r){let s=(n-r.tickOrigin)*r.tickHz/1e3,o=Math.floor(s),i=t(e,o),a=t(e,o+1);if(i===null||a===null)return null;let c=s-o;return{p:[i.p[0]+(a.p[0]-i.p[0])*c,i.p[1]+(a.p[1]-i.p[1])*c,i.p[2]+(a.p[2]-i.p[2])*c],q:$r([...i.q])}}var KC=.1,XC=30,Pd={desktop:4,mobile:5};function jx(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:e}var Xh=Object.freeze([128,64,32]),qh=60,JC=20,ZC=2,zx=.5,QC=500,eO=4;function tO(t,e){for(let n=t+1;n<Xh.length;n++)if(Xh[n]<e)return n;return null}function Ux(t,e){if(t.length===0)return 0;let n=[...t].sort((r,s)=>r-s);return n[Math.min(n.length-1,Math.floor(e*n.length))]}var Vx=500,nO=.02,rO=200,We={ON:"on",OFF:"off",LOADING:"loading",UNAVAILABLE:"unavailable",MISMATCH:"mismatch",SELF_TEST:"self_test",DIVERGED:"diverged",CPU:"cpu"},sO=600;function Hx(t,e){return[Ed(t.dp[0],t.dv[0],e,t.tau),Ed(t.dp[1],t.dv[1],e,t.tau),Ed(t.dp[2],t.dv[2],e,t.tau)]}var Lc=[0,0,0,1],oO=[32767,32767,32767,65534,32767,32767,32767,32767,32767,32767,0,0],iO=[32767,32767,32767,32767,32767,32767,0,0],aO=t=>Math.floor((t+1)/2*65534+.5),ji=[0,0,0],Wi=(t,e)=>t<e?-1:t>e?1:0,cO=(t,e)=>{for(let n=0;n<Ro;n++)if(!Object.is(t[n],e[n]))return!1;return!0},Ad=class{constructor(e,n){m(this,"status",We.LOADING);m(this,"core");m(this,"desc");m(this,"tickHz");m(this,"innerDt");m(this,"lengthUnit");m(this,"leadMax");m(this,"budgetMs");m(this,"clock");m(this,"remoteStep");m(this,"hashesKept");m(this,"world",null);m(this,"base",null);m(this,"seq",0);m(this,"simulated",new Map);m(this,"seats",new Map);m(this,"kinematic",new Map);m(this,"joints",new Map);m(this,"ring",new Map);m(this,"pure",new Set);m(this,"drawn",new Map);m(this,"kinds",new Map);m(this,"ruledClock",null);m(this,"ownPose",()=>{});m(this,"ownVelocity",()=>{});m(this,"bodyRule");m(this,"headSlide");m(this,"propStates",null);m(this,"propStale",!1);m(this,"kinematicRule");m(this,"lifts");m(this,"liftBodies",null);m(this,"seatRule");m(this,"seatPose");m(this,"contactPass");m(this,"posedBySeats",!1);m(this,"remoteBodies",new Map);m(this,"setSize",0);m(this,"costs",[]);m(this,"probedAt",Number.NEGATIVE_INFINITY);m(this,"calmProbes",0);m(this,"chosenCount",0);m(this,"fallbacks",0);m(this,"recoveries",0);m(this,"steppedAt",0);m(this,"canary",[]);m(this,"epochs",new Map);m(this,"hashes",[]);m(this,"chosenKeys",new Set);this.core=e,this.desc=n.desc,this.tickHz=n.tickHz,this.innerDt=jh(n.desc.world),this.lengthUnit=Math.fround(n.desc.world.lengthUnit);let r=n.leadMs??n.desc.leadMs;this.leadMax=Math.ceil(r*n.tickHz/1e3)+n.desc.keyframeTicks-1;let s=n.desc.remotePredict===Zt.INPUT_DECAY||n.desc.remotePredict===Zt.HOLD;this.remoteStep=s?n.remoteStep:void 0,this.seatPose=n.seatPose,this.contactPass=n.contactPass,this.budgetMs=n.budgetMs??Pd.desktop,this.clock=n.clock??(()=>performance.now()),this.hashesKept=n.hashesKept??sO,this.bodyRule=n.bodyRule,this.headSlide=n.headSlide??(()=>null),this.kinematicRule=n.kinematicRule,this.lifts=n.lifts??(()=>null),this.seatRule=n.seatRule;let o=e.World.create(n.desc.world);if(!o.ok){this.status=We.MISMATCH;return}let i=o.world,a=n.staticWorld;if(!(a==null||a.boxes.length===0&&a.ramps.length===0)&&!i.addStaticWorld(a).ok){i.free(),this.status=We.MISMATCH;return}if(i.physicsHash()!==n.physicsHash){i.free(),this.status=We.MISMATCH;return}this.world=i}get predicting(){return this.status===We.ON||this.status===We.LOADING}get stopped(){return this.world===null}draws(e){return this.status===We.ON&&(this.drawn.has(e)||this.ruledElsewhere(e))}ruledElsewhere(e){return this.base!==null&&!this.drawn.has(e)&&this.ruled(e)}stateHash(){return this.world?.stateHash()??""}stop(e){this.status=e,this.world?.free(),this.world=null,this.drawn.clear()}adopt(e,n,r,s,o=()=>{}){let i={kind:"none",replayed:0,ms:0,pure:0,mismatched:0},a=this.world;if(a===null)return i;let c=this.status===We.CPU;if(c&&s-this.probedAt<QC||!c&&!this.predicting)return i;this.ownPose=r,this.ownVelocity=o;let u=this.choose(e),l=new Set(u.filter(b=>b.epoch!==void 0&&this.epochs.has(b.key)&&this.epochs.get(b.key)!==b.epoch).map(b=>b.key));for(let b of u)b.epoch!==void 0&&this.epochs.set(b.key,b.epoch);let d=c?{...i,kind:"replay"}:this.compare(e,u,l);if(this.world===null)return{...d,kind:"none"};if(d.kind==="match"){this.base={tick:e.tick,ack:e.ack};for(let b of this.seatsOf(e))this.seats.set(b.key,b);for(let b of u)this.kinematic.has(b.key)&&this.kinematic.set(b.key,Array.from(b.row));return this.prune(e.tick),this.status=We.ON,d}c&&this.drawn.clear();let f=this.snapshotDrawn(s),h=this.clock();if(!this.rebuild(a,e,u))return this.stop(We.MISMATCH),i;this.base={tick:e.tick,ack:e.ack},this.seq=e.ack,this.ring.clear(),this.readAll(a);let p=Math.min(n,e.ack+this.leadMax),y=0;for(let b=e.ack+1;b<=p&&(this.stepOnce(a),this.world!==null);b++,y++);let S=this.clock()-h;return this.world===null?{...d,kind:"replay",replayed:y,ms:S}:(this.steppedAt=s,this.ease(f,s,l),c?this.judgeProbe(S,s):(this.status=We.ON,this.judgeBudget(S)),{...d,kind:"replay",replayed:y,ms:S})}advance(e,n){let r=this.world;r===null||this.base===null||this.status!==We.ON||e!==this.seq+1||e-this.base.ack>this.leadMax||(this.stepOnce(r),this.steppedAt=n)}draw(e,n){if(this.status!==We.ON)return null;let r=this.drawn.get(e);if(r===void 0)return this.ruledElsewhere(e)?this.ruledDrawn(e,n):null;let s=r.sleep?0:Math.min(Math.max((n-this.steppedAt)/1e3,0),1/this.tickHz),o=this.lengthUnit,i=[r.p[0]+r.lv[0]*o*s,r.p[1]+r.lv[1]*o*s,r.p[2]+r.lv[2]*o*s],a=lO(r.q,r.av,s),c=Math.max(n-r.since,0),u=Hx(r,c);return{p:[i[0]+u[0][0],i[1]+u[1][0],i[2]+u[2][0]],q:jn(Fi(r.dq,Math.exp(-c/r.tau)),a)}}choose(e){let n=Lx*this.lengthUnit,r=[],s=new Map;for(let p of e.bodies)s.set(p.key,p),r.push({key:p.key,x:p.row[0],y:p.row[1],z:p.row[2],radius:p.desc===null?0:Bc(p.desc)});for(let p of e.outside)r.push(p);let o=[];for(let p of e.joints)typeof p.desc.a=="string"&&typeof p.desc.b=="string"&&o.push([p.desc.a,p.desc.b]);let i=Fx(r,o,n),a=new Map;for(let p of r){let y=i.get(p.key),S=a.get(y);S===void 0?a.set(y,[p.key]):S.push(p.key)}let c=e.seats.find(p=>p.own),u=p=>{let y=s.get(p);return c===void 0?0:Math.hypot(y.row[0]-c.x,y.row[1]-c.y,y.row[2]-c.z)},l=[...a.entries()].filter(([,p])=>p.every(y=>s.get(y)?.desc!=null)).map(([p,y])=>({island:p,keys:y,near:Math.min(...y.map(u))})).sort((p,y)=>p.near-y.near||Wi(p.island,y.island)),d=Xh[this.setSize],f=[];this.pure.clear();let h=[...e.seats,...this.seats.values()];for(let{keys:p}of l){if(f.length+p.length>d)continue;for(let b of p)f.push(s.get(b));let y=h.some(b=>p.some(x=>uO(s.get(x),b,n,this.desc))),S=p.some(b=>s.get(b).desc?.type==="kinematic");if(!y&&!S)for(let b of p)this.pure.add(b)}return f.sort((p,y)=>Wi(p.key,y.key)),this.chosenKeys=new Set(f.map(p=>p.key)),this.chosenCount=l.reduce((p,{keys:y})=>p+y.length,0),f}compare(e,n,r){let s={kind:"replay",replayed:0,ms:0,pure:0,mismatched:0},o=this.base,i=this.ring.get(e.tick);if(o===null||i===void 0)return s;let a=0,c=0,u=!0;for(let p of n){if(p.desc?.type==="kinematic")continue;let y=i.get(p.key),S=y!==void 0&&cO(y,p.row);this.pure.has(p.key)&&!r.has(p.key)&&y!==void 0&&(a++,S||c++),S||(u=!1)}this.noteCanary(a,c);let l=n.length===this.simulated.size&&n.every(p=>this.simulated.get(p.key)?.desc===Gh(p.desc)),d=e.ack===o.ack+(e.tick-o.tick)&&this.seq>=e.ack,f={...s,pure:a,mismatched:c};return u&&l&&d&&this.sameJoints(e)&&this.sameSeats(e,i)?{...f,kind:"match"}:f}sameJoints(e){let n=this.jointsOf(e);if(n.size!==this.joints.size)return!1;for(let[r,s]of n){let o=this.joints.get(r);if(o===void 0||o.desc!==s.desc||o.motor!==s.motor)return!1}return!0}sameSeats(e,n){let r=this.seatsOf(e);return r.length!==this.seats.size?!1:r.every(s=>{let o=n.get(`seat:${s.key}`);if(o===void 0||this.seats.get(s.key)?.epoch!==s.epoch)return!1;let i=this.presetPosition(s.x,s.y,s.z);return o[0]===i[0]&&o[1]===i[1]&&o[2]===i[2]})}noteCanary(e,n){for(let s=0;s<e;s++)this.canary.push(s<n);if(this.canary.length>Vx&&this.canary.splice(0,this.canary.length-Vx),this.canary.length<rO)return;this.canary.filter(Boolean).length/this.canary.length>nO&&this.stop(We.DIVERGED)}judgeBudget(e){if(this.costs.push(e),this.costs.length>qh&&this.costs.splice(0,this.costs.length-qh),this.costs.length<JC)return;let n=Ux(this.costs,.5),r=Ux(this.costs,.9);if(n>this.budgetMs||r>ZC*this.budgetMs){this.costs=[];let i=tO(this.setSize,this.chosenCount);if(i!==null){this.setSize=i;return}this.fallBack();return}this.costs.length>=qh&&r<=zx*this.budgetMs&&this.setSize>0&&(this.setSize--,this.costs=[])}fallBack(){this.status=We.CPU,this.fallbacks++,this.drawn.clear(),this.probedAt=Number.NEGATIVE_INFINITY,this.calmProbes=0}judgeProbe(e,n){if(this.probedAt=n,this.calmProbes=e<=zx*this.budgetMs?this.calmProbes+1:0,this.calmProbes<eO){this.drawn.clear();return}this.status=We.ON,this.recoveries++,this.costs=[],this.calmProbes=0}jointsOf(e){let n=new Map;for(let r of e.joints){let s=r.desc.a,o=r.desc.b;!this.simulated.has(s)&&!this.chosenHas(s)||o!==null&&!this.simulated.has(o)&&!this.chosenHas(o)||n.set(r.key,{desc:JSON.stringify(r.desc),motor:r.motor===null?"":JSON.stringify(r.motor),parsed:r})}return n}chosenHas(e){return this.chosenKeys.has(e)}seatsOf(e){if(this.desc.presetBody===null)return[];let n=this.desc.world.limits.worldExtent;return e.seats.filter(r=>this.presetPosition(r.x,r.y,r.z).every(s=>Math.abs(s)<=n)).sort((r,s)=>Wi(r.key,s.key))}presetPosition(e,n,r){let s=this.desc.presetBody?.half[2]??0;return[Math.fround(e),Math.fround(n),Math.fround(Math.fround(r)+s)]}rebuild(e,n,r){let s=this.jointsOf(n);for(let c of[...this.joints.keys()]){let u=s.get(c);u!==void 0&&u.desc===this.joints.get(c).desc||(e.removeJoint(c),this.joints.delete(c))}for(let[c,u]of[...this.simulated]){let l=r.find(d=>d.key===c);l!==void 0&&Gh(l.desc)===u.desc||(e.remove(c),this.simulated.delete(c),this.kinematic.delete(c),this.drawn.delete(c))}for(let c of r)if(!(this.simulated.has(c.key)||c.desc===null)){if(!e.spawn(c.desc).ok)return!1;this.kinds.set(c.key,c.desc.kind),this.simulated.set(c.key,{type:String(c.desc.type),desc:Gh(c.desc)})}this.kinematic.clear();for(let c of r)c.desc?.type==="kinematic"&&(this.kinematic.set(c.key,Array.from(c.row)),this.ruled(c.key)||this.drawn.delete(c.key));if(this.propStates=null,!this.rebuildSeats(e,n))return!1;let o=this.rebuildLifts(e,n.tick);if(o===null)return!1;for(let[c,u]of s){if(!this.joints.has(c)&&!e.addJoint(u.parsed.desc).ok)return!1;let l=this.joints.get(c);if(u.parsed.motor!==null&&l?.motor!==u.motor&&!e.setMotor(c,u.parsed.motor).ok)return!1;this.joints.set(c,{desc:u.desc,motor:u.motor})}let i=[],a=[];for(let c of r){i.push(c.key);for(let u=0;u<Ro;u++)a.push(c.row[u])}for(let c of this.seats.values())i.push(c.key),a.push(...this.presetPosition(c.x,c.y,c.z),...oO);for(let[c,u]of o)i.push(c),a.push(...u);return i.length>0&&!e.importWire(i,a).ok?!1:e.canonicalize({quantize:!0}).ok}rebuildLifts(e,n){let r=this.lifts(),s=this.liftBodies;if(s!==null&&s.policy!==r?.policy){for(let o of s.keys)e.remove(o);this.liftBodies=null}if(r===null||r.policy.platforms.length===0)return[];if(this.liftBodies===null){for(let o of r.policy.platforms)if(!e.spawn(Px(o,n+1,r.starts)).ok)return null;this.liftBodies={policy:r.policy,keys:r.policy.platforms.map(o=>Ic(o.id))}}return r.policy.platforms.map(o=>{let{p:i,q:a}=Sd(o,n+1,r.starts);return[Ic(o.id),[...i,...a.map(aO),...iO]]})}rebuildSeats(e,n){let r=new Map(this.seatsOf(n).map(o=>[o.key,o]));for(let[o,i]of[...this.seats])r.get(o)?.epoch!==i.epoch&&(e.remove(o),this.seats.delete(o));let s=this.desc.presetBody;for(let[o,i]of r){if(!this.seats.has(o)&&s!==null){let a={key:"hull",shape:{kind:"box",half:[...s.half]},events:s.events,...this.headSlide()===null?{}:{friction:0}};if(!e.spawn({key:o,type:"kinematic",pose:{p:this.presetPosition(i.x,i.y,i.z),q:[...Lc]},colliders:[a]}).ok)return!1}this.seats.set(o,i)}return!0}stepOnce(e){let n=this.base,r=this.seq+1,s=n.tick+(r-n.ack),o=[],i=!1;for(let l of this.seats.values())o.push(this.seatAt(l,r,s-n.tick)),i||(i=this.posedBySeats);i||this.passSeats(o);for(let l of o)e.setNextKinematicPose(l.key,{p:this.presetPosition(l.x,l.y,l.z),q:[...Lc]});for(let[l,d]of this.kinematic){let f=this.kinematicRule?.(l,s+1)??null;e.setNextKinematicPose(l,f===null?dO(d):{p:[...f.p],q:[...f.q]})}let a=this.liftBodies===null?null:this.lifts();for(let l of a?.policy.platforms??[])e.setNextKinematicPose(Ic(l.id),Sd(l,s+1,a?.starts));this.applyBodyRule(e,s,o);let c=e.tick,u=e.step();if(!u.ok){this.stop(We.DIVERGED);return}for(let l of u.escaped)e.remove(l),this.simulated.delete(l),this.drawn.delete(l);this.clamp(e,c),s%this.desc.keyframeTicks===0&&(e.canonicalize({quantize:!0}),this.propStale=!0,this.ring.set(s,this.rowsNow(e))),this.seq=r,this.readDrawn(e,c),this.hashes.push({tick:s,hash:e.stateHash()}),this.hashes.length>this.hashesKept&&this.hashes.splice(0,this.hashes.length-this.hashesKept)}seatAt(e,n,r){this.posedBySeats=!1;let s=e.own?this.ownPose(n):void 0;if(s!==void 0){let f=this.ownVelocity(n)??[e.vx,e.vy,e.vz];return{key:e.key,x:s[0],y:s[1],z:s[2],vx:f[0],vy:f[1],vz:f[2]}}let o=e.own?void 0:this.seatPose?.(e.key,n);if(o!==void 0)return this.posedBySeats=!0,{...o,key:e.key};let i=this.remoteStep;if(e.own||i===void 0||e.input===void 0){let f=r/this.tickHz;return{key:e.key,x:e.x+e.vx*f,y:e.y+e.vy*f,z:e.z+e.vz*f,vx:e.vx,vy:e.vy,vz:e.vz}}let a=this.remoteBodies.get(e.key),c=a!==void 0&&a.from===e&&a.j<=r,u=c?a.body:{...e.body??{},x:e.x,y:e.y,z:e.z},l=1/this.tickHz,d=this.base?.tick??0;for(let f=(c?a.j:0)+1;f<=r;f++){this.seatRule?.(u,d+f);let h=this.desc.remotePredict===Zt.HOLD;i(u,h?e.input:Rd(e.input,f,this.tickHz,this.desc.remoteDecayMs),l,d+f)}return this.remoteBodies.set(e.key,{from:e,j:r,body:u}),{key:e.key,x:u.x,y:u.y,z:u.z,vx:u.vx??e.vx,vy:u.vy??e.vy,vz:u.vz??e.vz,...u.yaw===void 0?{}:{yaw:u.yaw}}}passSeats(e){let n=this.contactPass;if(n===void 0||e.length<2)return;let r=e.map(o=>({id:o.key,x:o.x,y:o.y,z:o.z,vx:o.vx,vy:o.vy,vz:o.vz,yaw:o.yaw??0}));r.sort((o,i)=>Wi(o.id,i.id)),n(r);let s=new Map(r.map(o=>[o.id,o]));for(let o of e){let i=s.get(o.key);o.x=i.x,o.y=i.y,o.z=i.z,o.vx=i.vx,o.vy=i.vy,o.vz=i.vz}}applyBodyRule(e,n,r){let s=this.bodyRule,o=this.headSlide(),i=this.liftBodies===null?null:this.lifts(),a=i!==null&&i.policy.platforms.some(d=>d.surface!==null)?i:null;if(s===void 0&&o===null&&a===null)return;r.sort((d,f)=>Wi(d.key,f.key));let c=d=>{if(this.simulated.get(d)?.type!=="dynamic")return null;let f=e.exportBodyState(d);return f===null?null:{p:[f.p[0],f.p[1],f.p[2]],v:[f.v[0],f.v[1],f.v[2]]}};for(let d of s?.({tick:n,seats:r,body:c})??[])this.simulated.get(d.key)?.type==="dynamic"&&e.setVelocity(d.key,[d.v[0],d.v[1],d.v[2]]);let u=this.desc.presetBody?.half;if(o===null&&a===null||u===void 0)return;if(this.propStates===null){this.propStates=new Map;for(let d of this.simulated.keys()){let f=c(d);f!==null&&this.propStates.set(d,{key:d,p:f.p,v:f.v})}this.propStale=!1}this.propStale&&this.freshenPicked(r,u,a===null?null:$h(a.policy,n,a.starts,2*u[2]),o!==null,c);let l=[...this.propStates.values()].filter(d=>this.simulated.get(d.key)?.type==="dynamic").sort((d,f)=>Wi(d.key,f.key));if(a!==null)for(let d of Tx(a.policy,n,a.starts,this.tickHz,l,2*u[2]))e.setVelocity(d.key,d.v);if(o!==null)for(let d of sx(r,u,l,o))e.setVelocity(d.key,d.v)}freshenPicked(e,n,r,s,o){let i=this.propStates;if(this.propStale=!1,i!==null)for(let[a,c]of i){if(!(s&&zh(e,n,c.p)!==void 0||r!==null&&r(c.p)!==void 0))continue;let l=o(a);l!==null&&i.set(a,{key:a,p:l.p,v:l.v})}}clamp(e,n){let{keys:r,data:s}=e.exportChanged(n,{rest:!0});for(let o=0;o<r.length;o++){let i=r[o];if(this.simulated.get(i)?.type!=="dynamic")continue;let a=o*Ro,c=[s[a+7],s[a+8],s[a+9]],u=[s[a+10],s[a+11],s[a+12]],l=Nx(c,u,this.lengthUnit,this.desc.maxLinear,this.desc.maxAngular);l!==null&&e.setVelocity(i,l.linvel,l.angvel),this.propStates?.set(i,{key:i,p:[s[a],s[a+1],s[a+2]],v:l===null?c:[l.linvel[0],l.linvel[1],l.linvel[2]]})}}rowsNow(e){let n=new Map,r=(s,o)=>{let i=e.exportBodyState(s,{rest:!0});i!==null&&n.set(o,Dx(i,this.lengthUnit,this.innerDt))};for(let s of this.simulated.keys())r(s,s);for(let s of this.seats.keys())r(s,`seat:${s}`);return n}ruledDrawn(e,n){let r=this.kinematicRule,s=this.ruledTick(n);if(r===void 0||s===null)return null;let o=Math.floor(s),i=r(e,o),a=r(e,o+1);if(i===null||a===null)return null;let c=s-o;return{p:[i.p[0]+(a.p[0]-i.p[0])*c,i.p[1]+(a.p[1]-i.p[1])*c,i.p[2]+(a.p[2]-i.p[2])*c],q:$r([...i.q])}}ruledTick(e){let n=this.base;if(n===null)return null;let r=Math.min(Math.max((e-this.steppedAt)/1e3*this.tickHz,0),1),s=n.tick+(this.seq-n.ack)+1+r,o=this.ruledClock;if(o===null||e<o.at||Math.abs(s-o.tick)>XC)return this.ruledClock={at:e,tick:s},s;let i=(e-o.at)/1e3*this.tickHz,a=o.tick+i,c=KC*i,u=a+Math.min(Math.max(s-a,-c),c);return this.ruledClock={at:e,tick:u},u}ruled(e){if(this.kinematicRule===void 0)return!1;let n=this.base,r=n===null?0:n.tick+(this.seq-n.ack);return this.kinematicRule(e,r)!==null}prune(e){for(let n of this.ring.keys())n<=e&&this.ring.delete(n)}readDrawn(e,n){let{keys:r,data:s}=e.exportChanged(n,{rest:!0});for(let o=0;o<r.length;o++){let i=r[o];if(!this.simulated.has(i)||this.kinematic.has(i)&&!this.ruled(i))continue;let a=o*Ro,c=this.drawn.get(i);this.drawn.set(i,{p:[s[a],s[a+1],s[a+2]],q:$r([s[a+3],s[a+4],s[a+5],s[a+6]]),lv:[s[a+7]/this.lengthUnit,s[a+8]/this.lengthUnit,s[a+9]/this.lengthUnit],av:[s[a+10],s[a+11],s[a+12]],sleep:s[a+13]===1,dp:c?.dp??ji,dv:c?.dv??ji,dq:c?.dq??Lc,since:c?.since??0,tau:c?.tau??$i(0),snap:c?.snap??this.snapOf(i)})}}builtInRules(){if(!this.desc.presetBody)return!1;if(this.headSlide()!==null)return!0;let e=this.liftBodies===null?null:this.lifts();return e!==null&&e.policy.platforms.some(n=>n.surface!==null)}readAll(e){let n=this.builtInRules()?new Map:null;for(let r of this.simulated.keys()){let s=this.kinematic.has(r)&&!this.ruled(r)?null:e.exportBodyState(r,{rest:!0});if(s===null)continue;n!==null&&this.simulated.get(r)?.type==="dynamic"&&n.set(r,{key:r,p:[s.p[0],s.p[1],s.p[2]],v:[s.v[0],s.v[1],s.v[2]]});let o=this.drawn.get(r),i=this.lengthUnit;this.drawn.set(r,{p:[s.p[0],s.p[1],s.p[2]],q:$r([s.q[0],s.q[1],s.q[2],s.q[3]]),lv:[s.v[0]/i,s.v[1]/i,s.v[2]/i],av:[s.w[0],s.w[1],s.w[2]],sleep:s.sleeping,dp:o?.dp??ji,dv:o?.dv??ji,dq:o?.dq??Lc,since:o?.since??0,tau:o?.tau??$i(0),snap:o?.snap??this.snapOf(r)})}n!==null&&(this.propStates=n,this.propStale=!1)}snapshotDrawn(e){let n=new Map;for(let[r,s]of this.drawn){let o=Math.max(e-s.since,0),i=Hx(s,o);n.set(r,{p:[s.p[0]+i[0][0],s.p[1]+i[1][0],s.p[2]+i[2][0]],q:jn(Fi(s.dq,Math.exp(-o/s.tau)),s.q),rate:[i[0][1],i[1][1],i[2][1]]})}return n}snapOf(e){return kd(this.kinds.get(e))*this.lengthUnit}ease(e,n,r){for(let[s,o]of this.drawn){let i=e.get(s),a={...o,dp:ji,dv:ji,dq:Lc,since:n,tau:$i(0)};if(i===void 0||r.has(s)){this.drawn.set(s,a);continue}let c=[i.p[0]-o.p[0],i.p[1]-o.p[1],i.p[2]-o.p[2]],u=Math.hypot(c[0],c[1],c[2]);if(u>o.snap){this.drawn.set(s,a);continue}let l=jn(i.q,[-o.q[0],-o.q[1],-o.q[2],o.q[3]]),d=l[3]<0?[-l[0],-l[1],-l[2],-l[3]]:l;this.drawn.set(s,{...o,dp:c,dv:i.rate,dq:d,since:n,tau:$i(u/this.lengthUnit)})}}},Gh=t=>t===null?"":JSON.stringify(t);function uO(t,e,n,r){let s=r.presetBody?.half??[0,0,0],o=Math.hypot(s[0],s[1],s[2])+(t.desc===null?0:Bc(t.desc))+n;return Math.hypot(t.row[0]-e.x,t.row[1]-e.y,t.row[2]-(e.z+s[2]))<=o}function lO(t,e,n){let r=Math.hypot(e[0],e[1],e[2]);if(r===0||n===0)return t;let s=r*n/2,o=Math.sin(s)/r;return $r(jn([e[0]*o,e[1]*o,e[2]*o,Math.cos(s)],t))}function dO(t){let e=r=>-1+r/65534*2,n=$r([e(t[3]),e(t[4]),e(t[5]),e(t[6])]);return{p:[t[0],t[1],t[2]],q:[n[0],n[1],n[2],n[3]]}}var Yh={contract:"1.0",dt:1/60,substeps:1,gravity:[0,0,-9.81],upAxis:"z",lengthUnit:1},Kh=12;function fO(){let t=(e,n,r)=>({key:e,type:"dynamic",pose:{p:n,q:[0,0,0,1]},linvel:[1,0,0],colliders:[{key:"c",shape:{kind:"box",half:[r,r,r]}}]});return[t("a",[0,0,.5],.5),t("b",[0,0,1.6],.5),{key:"c",type:"dynamic",pose:{p:[2,0,1],q:[0,0,0,1]},angvel:[0,3,0],colliders:[{key:"c",shape:{kind:"sphere",radius:.4}}]}]}function Wx(t){let n=[t.World.create(Yh),t.World.create(Yh)].flatMap(r=>r.ok?[r.world]:[]);try{if(n.length!==2)return!1;let[r,s]=n,o={boxes:[[-20,-20,-1,20,20,0]],ramps:[]};if(!r.addStaticWorld(o).ok||!s.addStaticWorld(o).ok)return!1;for(let l of fO())if(!r.spawn(l).ok||!s.spawn(l).ok)return!1;for(let l=0;l<Kh;l++)r.step();s.canonicalize({});for(let l=0;l<Kh;l++)s.step();if(!r.canonicalize({quantize:!0}).ok)return!1;let{keys:i,data:a}=r.exportChanged(r.tick,{rest:!0}),c=[],u=jh(Yh);for(let l=0;l<i.length;l++)Wh(a,l*Ro,1,u,c,l*Ro);if(i.length!==3||!s.importWire(i,c).ok||!s.canonicalize({quantize:!0}).ok)return!1;for(let l=0;l<Kh;l++)if(r.step(),s.step(),r.stateHash()!==s.stateHash())return!1;return!0}finally{for(let r of n)r.free()}}var uV=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);var Eo=["x","y","z","vx","vy","vz","yaw","spin"],pO=(t,e)=>t.body.id<e.body.id?-1:t.body.id>e.body.id?1:0,Td=class{constructor(e,n){m(this,"pass",null);m(this,"rule");m(this,"others");this.rule=e,this.others=n}apply(e,n,r,s){(this.pass===null||this.pass.ack!==n||e<=this.pass.last)&&(this.pass={ack:n,last:n,others:this.others().map(u=>({body:{...u},from:0})).sort(pO)});let i=this.pass,a=e-n,c={...r};i.others=i.others.map(u=>{let l=(a-u.from)/s,d=u.body,f={...d,x:d.x+d.vx*l,y:d.y+d.vy*l,z:d.z+d.vz*l},h=JSON.stringify(f);return c.id<f.id?this.rule(c,f):this.rule(f,c),JSON.stringify(f)===h?u:{body:f,from:a}});for(let u of Eo){let l=c[u];typeof l=="number"&&l!==r[u]&&(r[u]=Math.fround(l))}i.last=e}seatAt(e,n,r,s){let o=this.pass!==null&&this.pass.ack===n?this.pass.others.find(l=>l.body.id===e):void 0,i=o===void 0?this.others().find(l=>l.id===e):void 0,a=o?.from??0,c=o?.body??i;if(c===void 0)return;let u=(r-a)/s;return{...c,x:c.x+c.vx*u,y:c.y+c.vy*u,z:c.z+c.vz*u}}};function ko(t,e,n){let r={x:n.x,y:n.y,z:n.z};for(let s=0;s<hO;s++){let o={...e,vx:0,vy:0,vz:0},i={...n,...r,vx:0,vy:0,vz:0};o.id<i.id?t(o,i):t(i,o);let a={x:r.x+(i.x-r.x)-(o.x-e.x),y:r.y+(i.y-r.y)-(o.y-e.y),z:r.z+(i.z-r.z)-(o.z-e.z)};if(s>0&&a.x===r.x&&a.y===r.y&&a.z===r.z||(r=a,s===0&&vd(t,e,n,r)<=mO))break}return vd(t,e,n,r)>Xx?wO(t,e,n,r):r}var hO=8,mO=.01,Xx=.001,yO=30,gO=8,bO=1;function wO(t,e,n,r){let s={x:n.x,y:n.y,z:n.z},o={x:r.x-s.x,y:r.y-s.y,z:r.z-s.z},i=Math.hypot(o.x,o.y,o.z)>0?o:Jx(t,e,n,s),a=Math.hypot(i.x,i.y,i.z);if(a===0)return r;let c={x:i.x/a,y:i.y/a,z:i.z/a},u=h=>({x:s.x+c.x*h,y:s.y+c.y*h,z:s.z+c.z*h}),l=h=>vd(t,e,n,u(h))>0,d=a,f=a+Math.max(bO,a);for(let h=0;h<gO&&l(f);h++)d=f,f=a+(f-a)*2;if(l(f))return r;for(let h=0;h<yO;h++){let p=(d+f)/2;l(p)?d=p:f=p}return u(f)}function Jx(t,e,n,r){let s={...e,vx:0,vy:0,vz:0},o={...n,...r,vx:0,vy:0,vz:0};return s.id<o.id?t(s,o):t(o,s),{x:o.x-r.x-(s.x-e.x),y:o.y-r.y-(s.y-e.y),z:o.z-r.z-(s.z-e.z)}}function vd(t,e,n,r){let s=Jx(t,e,n,r);return Math.hypot(s.x,s.y,s.z)}var SO=3*Math.PI,xO=Math.PI/2,_O=.05,RO=8,qx=16,EO=30,kO=8,Zx=(t,e,n)=>({...e,x:t.x+n.dx,y:t.y+n.dy,z:t.z+n.dz,vx:0,vy:0,vz:0});function Qh(t,e,n,r){let s=Zx(e,n,r),o=ko(t,e,s);return Math.hypot(o.x-s.x,o.y-s.y,o.z-s.z)}function Md(t,e,n,r,s){let o=Math.hypot(s.dx-r.dx,s.dy-r.dy,s.dz-r.dz),i=Math.min(o,Math.hypot(r.dx,r.dy,r.dz));if(i===0)return!1;for(let a=1;a<qx;a++){let c=a/qx,u={dx:r.dx+(s.dx-r.dx)*c,dy:r.dy+(s.dy-r.dy)*c,dz:r.dz+(s.dz-r.dz)*c};if(Qh(t,e,n,u)>Math.min(_O*i,RO))return!0}return!1}function Zh(t,e,n,r,s,o){let i=Math.cos(r),a=Math.sin(r),c=d=>Qh(t,e,n,{dx:d*i,dy:d*a,dz:s})>0;if(!c(0)||o<=0)return 0;let u=0,l=o;for(let d=0;d<kO&&c(l);d++)u=l,l*=2;for(let d=0;d<EO;d++){let f=(u+l)/2;c(f)?u=f:l=f}return l}var Gx=4,AO=20;function PO(t,e,n){let r=n.z>=e.z?1:-1,s=a=>Qh(t,e,n,{dx:n.x-e.x,dy:n.y-e.y,dz:n.z-e.z+r*a})>0;if(!s(0)||s(Gx))return n;let o=0,i=Gx;for(let a=0;a<AO;a++){let c=(o+i)/2;s(c)?o=c:i=c}return{...n,z:n.z+r*i}}var Yx=2*Math.PI,TO=t=>t-Yx*Math.floor((t+Math.PI)/Yx);function Kx(t,e,n,r,s,o=!1){let i=PO(t,e,n),a=ko(t,e,i),c={dx:a.x-e.x,dy:a.y-e.y,dz:a.z-e.z},u=a.x!==i.x||a.y!==i.y||a.z!==i.z,l=i.x-e.x,d=i.y-e.y,f=(j,L)=>({x:e.x+j.dx,y:e.y+j.dy,z:e.z+j.dz,side:{...j,held:L,bx:l,by:d,at:s}}),h=j=>f(vO(t,e,i,j),!0);if(r===void 0||!(o||Md(t,e,i,r,c)))return f(c,u);let p=Math.hypot(r.dx,r.dy),y=Math.hypot(c.dx,c.dy),S=Math.atan2(r.dy,r.dx);if(!r.held){if(r.dx*c.dx+r.dy*c.dy>=0)return f(c,u);let j=Zh(t,e,i,S,c.dz,Math.max(p,y));return h({dx:j*Math.cos(S),dy:j*Math.sin(S),dz:c.dz})}let b=TO(Math.atan2(c.dy,c.dx)-S),x=p>0?xO*Math.hypot(l-r.bx,d-r.by)/p:0,R=Math.max(x,SO*Math.max(0,s-r.at)/1e3),A=Math.min(Math.abs(b),R),E=b===0?1:A/Math.abs(b),P=S+Math.sign(b)*A,k=c.dz-r.dz,M=R*Math.max(p,y),B=Math.abs(k*E)>M?r.dz+Math.sign(k)*M:r.dz+k*E,K=Math.max(p+(y-p)*E,Zh(t,e,i,P,B,Math.max(p,y)));return h({dx:K*Math.cos(P),dy:K*Math.sin(P),dz:B})}function vO(t,e,n,r){let s=Zx(e,n,r);return vd(t,e,s,s)>Xx?qi(e,ko(t,e,s)):r}function MO(t,e,n,r,s,o,i){let a={dx:i.x-e.x,dy:i.y-e.y,dz:i.z-e.z};for(let c of r){let u=c===n?void 0:s.get(c.id);if(u===void 0)continue;let l={...c,x:e.x+u.dx,y:e.y+u.dy,z:e.z+u.dz,vx:0,vy:0,vz:0},d=f=>({dx:f.dx-u.dx,dy:f.dy-u.dy,dz:f.dz-u.dz});if(Md(t,l,n,d(o),d(a)))return!0}return!1}var Fc=(t,e)=>t<e?`${t}\0${e}`:`${e}\0${t}`,CO=12,Kr=(t,e)=>({...t,x:e.x,y:e.y,z:e.z,vx:0,vy:0,vz:0}),qi=(t,e)=>({dx:e.x-t.x,dy:e.y-t.y,dz:e.z-t.z}),Cd=(t,e)=>t.x===e.x&&t.y===e.y&&t.z===e.z,OO=720,IO=.1,DO=24,NO=8,BO=64;function em(t,e,n,r,s){return!Cd(ko(t,Kr(e,r),Kr(n,s)),s)}var Qx=(t,e,n,r)=>[{x:t.x-n.nx*r/2,y:t.y-n.ny*r/2,z:t.z},{x:e.x+n.nx*r/2,y:e.y+n.ny*r/2,z:e.z}];function LO(t,e,n,r,s,o,i){let a=l=>em(t,e,n,...Qx(r,s,o,l));if(!a(i))return i;let c=i,u=i+BO;for(let l=0;l<NO&&a(u);l++)c=u,u=i+(u-i)*2;for(let l=0;l<DO;l++){let d=(c+u)/2;a(d)?c=d:u=d}return u}function Jh(t,e){let n=Math.hypot(t,e);return n>0?{nx:t/n,ny:e/n}:null}function FO(t,e,n,r,s,o){let i=ko(t,Kr(e,r),Kr(n,s)),a=(o===void 0?null:Jh(o.dx,o.dy))??Jh(s.x-r.x,s.y-r.y),c=Jh(i.x-s.x,i.y-s.y),u=c!==null&&a!==null&&c.nx*a.nx+c.ny*a.ny<0?-1:1;return{...c===null?a??{nx:1,ny:0}:{nx:u*c.nx,ny:u*c.ny},push:0}}function zO(t,e,n,r){let s=r.get(e.id),o=r.get(n.id),i=ko(t,Kr(e,s),Kr(n,o));if(Cd(i,o))return!1;let a={x:(i.x-o.x)/2,y:(i.y-o.y)/2,z:(i.z-o.z)/2};return r.set(e.id,{x:s.x-a.x,y:s.y-a.y,z:s.z-a.z}),r.set(n.id,{x:o.x+a.x,y:o.y+a.y,z:o.z+a.z}),!0}function e_(t,e,n,r){return r.nx*(n.x-e.x)+r.ny*(n.y-e.y)<0&&!em(t,e,n,e,n)}var t_=(t,e,n,r,s)=>s.nx*(r.x-n.x-(e.x-t.x))+s.ny*(r.y-n.y-(e.y-t.y));function UO(t,e,n,r,s,o,i){let a=Fc(e.id,n.id),c=r.get(e.id),u=r.get(n.id),l=s.get(a),d=0;if(l===void 0){let y=o?.pair;if(y===void 0?!em(t,e,n,e,n):e_(t,e,n,y))return zO(t,e,n,r);l=y??FO(t,e,n,c,u,o),s.set(a,l);let S=y===void 0?0:y.push-OO*Math.min(i,IO);d=Math.max(0,S-t_(e,n,c,u,l))}let f=LO(t,e,n,c,u,l,d);if(f<=0)return!1;let[h,p]=Qx(c,u,l,f);return r.set(e.id,h),r.set(n.id,p),!0}function VO(t,e,n,r,s,o){if(s===void 0)return;let i=r.get(e.id),a=r.get(n.id),c=qi(i,a);if(s.dx*c.dx+s.dy*c.dy>=0)return;let u=Kr(e,i),l=Kr(n,a);if(!Md(t,u,l,s,c))return;let d=Math.atan2(s.dy,s.dx),f=Zh(t,u,l,d,s.dz,Math.hypot(s.dx,s.dy)),h={dx:f*Math.cos(d),dy:f*Math.sin(d),dz:s.dz};return o(n.id)>=o(e.id)?(r.set(n.id,{x:i.x+h.dx,y:i.y+h.dy,z:i.z+h.dz}),n.id):(r.set(e.id,{x:a.x-h.dx,y:a.y-h.dy,z:a.z-h.dz}),e.id)}function HO(t,e,n,r,s){let o=Kr(n,r),i=ko(t,e,o);return Cd(i,r)?r:Md(t,e,o,qi(e,s),qi(e,i))?s:i}function $O(t){return t.flatMap((e,n)=>t.slice(n+1).map(r=>[e,r]))}function n_(t,e,n,r,s){let o=[...n].sort((h,p)=>h.id<p.id?-1:h.id>p.id?1:0),i=new Map;for(let h of o){let p=r.get(h.id),y=Kx(t,e,h,p,s),b=p?.held===!0&&!y.side.held&&MO(t,e,h,o,r,p,y)?Kx(t,e,h,p,s,!0):y;i.set(h.id,{x:b.x,y:b.y,z:b.z})}let a=new Map(i),c=h=>{let p=r.get(h),y=a.get(h);return p===void 0?Number.POSITIVE_INFINITY:Math.hypot(y.x-e.x-p.dx,y.y-e.y-p.dy,y.z-e.z-p.dz)},u=$O(o),l=(h,p)=>r.get(Fc(h.id,p.id));for(let[h,p]of u){let y=l(h,p);(y?.pair===void 0||e_(t,h,p,y.pair))&&VO(t,h,p,i,y,c)}let d=new Map;for(let h=0;;h++){for(let y of o)i.set(y.id,HO(t,e,y,i.get(y.id),a.get(y.id)));if(h===CO)break;let p=!1;for(let[y,S]of u){let b=l(y,S);p=UO(t,y,S,i,d,b,b===void 0?0:Math.max(0,s-b.at)/1e3)||p}if(!p)break}let f=new Map;for(let h of o){let p=i.get(h.id);f.set(h.id,{...qi(e,p),held:!Cd(p,h),bx:h.x-e.x,by:h.y-e.y,at:s})}for(let[h,p]of u){let y=i.get(h.id),S=Fc(h.id,p.id),b=d.get(S),x=b===void 0?0:t_(h,p,y,i.get(p.id),b),R=b!==void 0&&x>0?{pair:{nx:b.nx,ny:b.ny,push:x}}:{};f.set(S,{...qi(y,i.get(p.id)),held:!1,bx:p.x-h.x,by:p.y-h.y,at:s,...R})}return{drawn:i,sides:f}}var Gi=(t,e,n)=>t+(n-e);var Yi=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function jO(t){if(!Yi(t)||typeof t.preset!="string"||!Object.hasOwn(vS,t.preset))return!1;let e=t.shape,n=t.hull;return!Yi(e)||e.kind!==qn.Box&&e.kind!==qn.Hull||!Yi(n)?!1:Yi(t.top)&&Yi(t.offWall)&&Array.isArray(t.pairs)&&typeof t.passes=="number"}function r_(t,e){if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}let r=Yi(n)?n.contacts:void 0;if(!jO(r))return null;let s={world:IS(e,r.hull.radius,r.hull.height,r.hull.skin)},o=new Map,i=a=>{let c=o.get(a);if(c!==void 0)return c;let u=Fh(r,{...s,fixed:a});return o.set(a,u),u};return{policy:r,rule:Fh(r,s),pass:ex(r,s),env:s,drawRule:i}}var Od=[.5,1,5,20],WO=new Set(["x","y","z"]),qO=new Set(["mstate","cap","spin","fuel"]),s_=2*Math.PI;function o_(t,e,n){let r=0,s=0;return t.forEach((o,i)=>{if(qO.has(o))return;let a=(n[i]??0)-(e[i]??0);WO.has(o)?r+=a*a:s=Math.max(s,Math.abs(o==="yaw"?a-s_*Math.floor((a+Math.PI)/s_):a))}),{place:Math.sqrt(r),state:s}}var i_=(t,e)=>t>.05*e;function a_(t,e){let n=Od.findIndex(r=>t<r*e);return n<0?Od.length:n}function c_(t){return Number.isSafeInteger(t)?(t%65536+65536)%65536:0}var m_=500;function GO(t,e,n,r){let s=t.poses.get(n)?.get(e);if(s===void 0)return;let o=t.poses.get(n-1)?.get(e),i=t.poses.get(n-2)?.get(e);if(o===void 0){let h=r/t.tickHz;return{...s,x:s.x+s.vx*h,y:s.y+s.vy*h,z:s.z+s.vz*h}}let a=Math.floor(r),c=h=>h*(h+1)/2,u=(h,p,y)=>{let S=h+p*a+y*c(a),b=h+p*(a+1)+y*c(a+1);return S+(b-S)*(r-a)},l=(h,p,y)=>y===void 0?0:h-2*p+y,d=vs(s.yaw-o.yaw),f=i===void 0?0:d-vs(o.yaw-i.yaw);return{...s,x:u(s.x,s.x-o.x,l(s.x,o.x,i?.x)),y:u(s.y,s.y-o.y,l(s.y,o.y,i?.y)),z:u(s.z,s.z-o.z,l(s.z,o.z,i?.z)),yaw:vs(u(s.yaw,d,f))}}function YO(t,e){let n=t.ack+t.ticks,r=Math.min(Math.max(e,t.ack+1),n),s=Math.floor(r),o=t.own.get(s);if(o===void 0)return;let i=t.own.get(s+1),a=r-s;return i===void 0||a===0?o:{...o,x:o.x+(i.x-o.x)*a,y:o.y+(i.y-o.y)*a,z:o.z+(i.z-o.z)*a,yaw:o.yaw+vs(i.yaw-o.yaw)*a}}var u_=8,KO=3,tm=.5,nm=(t,e)=>t.id<e.id?-1:t.id>e.id?1:0,ke=(t,e=0)=>typeof t=="number"&&Number.isFinite(t)?t:e,l_=2*Math.PI,vs=t=>t-l_*Math.floor((t+Math.PI)/l_),d_=t=>({x:ke(t.x),y:ke(t.y),z:ke(t.z),yaw:ke(t.yaw),vx:ke(t.vx),vy:ke(t.vy),vz:ke(t.vz)}),f_=(t,e)=>({id:t,x:ke(e.x),y:ke(e.y),z:ke(e.z),vx:ke(e.vx),vy:ke(e.vy),vz:ke(e.vz),yaw:ke(e.yaw),spin:ke(e.spin),...typeof e.flags=="number"?{flags:e.flags}:{}}),p_=(t,e)=>({id:t,x:ke(e.x),y:ke(e.y),z:ke(e.z),vx:ke(e.vx),vy:ke(e.vy),vz:ke(e.vz),yaw:ke(e.yaw),duck:ke(e.duck),flags:ke(e.flags)}),h_=(t,e)=>Eo.every(n=>t[n]===e[n]),Dd=class{constructor(e){m(this,"options");m(this,"serial",0);m(this,"current",null);m(this,"recent",[]);m(this,"applied",new Map);m(this,"missed",new Set);this.options=e}apply(e,n,r,s,o,i=null){let a=this.current,c=a===null||a.ack!==n||a.stateTick!==r||e<=a.last,u=a,l=c?this.start(n,r,o):a,d=e-n;for(let p=l.ticks+1;p<d;p++)this.tick(l,p,u?.ownIn.get(n+p),!1,u?.ownOn.get(n+p)??null),this.noteMissed(l,n+p);let f=d>l.ticks,h=f?this.tick(l,d,s,!0,i):null;f&&this.applied.set(e,l.touching.get(e)??new Set),l.last=e;for(let p of this.recent)this.extend(p,l,e);return h}takeMissed(){let e=[...this.missed].sort();return this.missed.clear(),e}noteMissed(e,n){let r=this.applied.get(n),s=e.touching.get(n);if(!(r===void 0||s===void 0))for(let o of s)r.has(o)||this.missed.add(o)}extend(e,n,r){let s=r-e.ack;for(let o=e.ticks+1;o<=s;o++)this.tick(e,o,n.ownIn.get(e.ack+o),!1,n.ownOn.get(e.ack+o)??null);e.last=Math.max(e.last,r)}poseAt(e,n,r=this.current){if(r===null)return;let s=Math.max(n,r.ack),o=r.ack+r.ticks,i=Math.min(Math.floor(s),o),a=r.poses.get(i)?.get(e);if(a===void 0)return;let c=i<o?r.poses.get(i+1)?.get(e):void 0,u=s-i;if(c===void 0){if(r===this.current){let l=Math.min(u,1)/r.tickHz;return{...a,x:a.x+a.vx*l,y:a.y+a.vy*l,z:a.z+a.vz*l}}return GO(r,e,i,u)??a}return{x:a.x+(c.x-a.x)*u,y:a.y+(c.y-a.y)*u,z:a.z+(c.z-a.z)*u,yaw:a.yaw+vs(c.yaw-a.yaw)*u,vx:a.vx+(c.vx-a.vx)*u,vy:a.vy+(c.vy-a.vy)*u,vz:a.vz+(c.vz-a.vz)*u}}motionAt(e,n,r=this.current){let s=this.poseAt(e,n,r),o=this.poseAt(e,n-tm,r),i=this.poseAt(e,n+tm,r);if(s===void 0||o===void 0||i===void 0||r===null)return;let a=r.tickHz/1e3/(2*tm);return{pose:s,rate:{vx:(i.x-o.x)*a,vy:(i.y-o.y)*a,vz:(i.z-o.z)*a,vyaw:vs(i.yaw-o.yaw)*a}}}changeAt(e,n,r){if(this.current===null||this.current===r)return;let s=Math.min(n,r.ack+r.ticks),o=this.motionAt(e,s,r),i=this.motionAt(e,s);return o===void 0||i===void 0?void 0:{before:o,after:i}}touchAheadMs(e,n){let r=this.current;if(r===null)return;let s=Math.floor(Math.max(n,r.ack));if(r.touching.get(s)?.has(e)===!0||r.touching.get(s+1)?.has(e)===!0)return 0;let o=r.seats.find(l=>l.id===e),i=this.poseAt(e,n,r),a=YO(r,n);if(o===void 0||i===void 0||a===void 0)return;let c={...f_(e,o.body),x:i.x,y:i.y,z:i.z,yaw:i.yaw,vx:i.vx,vy:i.vy,vz:i.vz},u={x:(i.vx-a.vx)/1e3,y:(i.vy-a.vy)/1e3,z:(i.vz-a.vz)/1e3};for(let l=0;l<=u_;l++){let d=l/u_*Rt.SEAT_CLOCK_TAU_MS;if(this.touches(a,{...c,x:c.x+u.x*d,y:c.y+u.y*d,z:c.z+u.z*d}))return d}}touchingAt(e,n){let r=this.current;return r===null?!1:r.touching.get(Math.round(Math.max(n,r.ack)))?.has(e)===!0}stateRate(e){let n=this.current,r=n?.poses.get(n.ack)?.get(e);if(r!==void 0)return{vx:r.vx/1e3,vy:r.vy/1e3,vz:r.vz/1e3,vyaw:0}}start(e,n,r){let s=this.options.others().map(a=>({id:a.id,epoch:a.epoch,body:{...a.body},input:a.input})).sort(nm),o=new Map([[e,new Map(s.map(a=>[a.id,d_(a.body)]))]]);this.serial+=1,this.current!==null&&(this.recent=[this.current,...this.recent].slice(0,KO));for(let a of this.applied.keys())a<=e&&this.applied.delete(a);let i={id:this.serial,ack:e,stateTick:n,tickHz:r,last:e,ticks:0,seats:s,poses:o,touching:new Map,own:new Map,ownIn:new Map,ownOn:new Map};return this.current=i,i}tick(e,n,r,s,o){let i=Math.ceil(this.options.maxAheadMs()*e.tickHz/1e3),a=n<=i?this.carry(e,n):null;if(n<=i)for(let p of e.seats)this.move(e,p,n,a===null?void 0:Mc(a.t,p.id));let c=r===void 0?void 0:{...r};r!==void 0&&(e.ownIn.set(e.ack+n,{...r}),e.ownOn.set(e.ack+n,o));let u=a===null?null:this.ride(e,a,c,o),l=e.seats.map(p=>f_(p.id,p.body)),d=new Set;if(c!==void 0)for(let p of l)this.touches(c,p)&&d.add(p.id);let f=c===void 0?l:[...l,c].sort(nm);if(this.contactPass(f),e.seats.forEach((p,y)=>{let S=l[y];for(let b of Eo)typeof S[b]=="number"&&(p.body[b]=S[b])}),a!==null&&this.impart(e,a,c),r!==void 0&&c!==void 0&&s)for(let p of Eo){let y=c[p];typeof y=="number"&&y!==r[p]&&(r[p]=Math.fround(y))}let h=e.ack+n;return e.poses.set(h,new Map(e.seats.map(p=>[p.id,d_(p.body)]))),e.touching.set(h,d),c!==void 0&&e.own.set(h,s&&r!==void 0?{...r}:c),e.ticks=n,u}ride(e,n,r,s){let o=n.t,i=new Map(e.seats.map(h=>[h.id,h.body])),a=h=>r!==void 0&&h===r.id?r:i.get(h);for(let h of o.seats){let p=a(h.id);p!==void 0&&(h.x=ke(p.x),h.y=ke(p.y))}Rx(n.l.lifts,o);for(let h of o.seats){let p=i.get(h.id);p!==void 0&&(p.x=h.x,p.y=h.y)}if(r===void 0||s===null)return null;let c=o.seats.find(h=>h.id===r.id),u=o.seats.findIndex(h=>h.id===s);if(c===void 0&&u<0)return null;let l=c===void 0?o.report.from[u]:[r.x,r.y],d=c??o.seats[u],f=[d.x-l[0],d.y-l[1]];return r.x=Math.fround(r.x+f[0]),r.y=Math.fround(r.y+f[1]),f}carry(e,n){let r=this.options.lifts?.()??null;if(r===null)return null;let s=e.own.get(e.ack+n-1),o=e.seats.map(c=>p_(c.id,c.body));s!==void 0&&o.push(p_(s.id,s)),o.sort(nm);let i=vc(r.lifts,o,e.stateTick+n,r.starts,1/e.tickHz,r.cache),a=new Map(i.seats.map(c=>[c.id,c]));for(let c of e.seats){let u=a.get(c.id);c.body.x=u.x,c.body.y=u.y,c.body.z=u.z,r.lifts.vehicle&&(c.body.yaw=u.yaw)}return{l:r,t:i}}impart(e,n,r){let s=new Map(e.seats.map(i=>[i.id,i.body]));r!==void 0&&s.set(r.id,r);for(let i of n.t.seats){let a=s.get(i.id);a!==void 0&&(i.x=ke(a.x),i.y=ke(a.y),i.z=ke(a.z),i.vx=ke(a.vx),i.vy=ke(a.vy),i.vz=ke(a.vz))}Cc(n.l.lifts,n.t,n.l.starts);let o=new Map(n.t.seats.map(i=>[i.id,i]));for(let i of e.seats){let a=o.get(i.id);i.body.vx=a.vx,i.body.vy=a.vy,i.body.vz=a.vz}}move(e,n,r,s){let o=1/e.tickHz,{predict:i,decayMs:a}=this.options.remote(),c=i===Zt.EXTRAPOLATE?void 0:this.options.step();if(c===void 0||n.input===void 0){let l=n.body;l.x=ke(l.x)+ke(l.vx)*o,l.y=ke(l.y)+ke(l.vy)*o,l.z=ke(l.z)+ke(l.vz)*o;return}this.options.seatRule?.(n.body,e.stateTick+r);let u=i===Zt.INPUT_DECAY?Rd(n.input,r,e.tickHz,a):n.input;c(n.body,u,o,s)}contactPass(e){if(this.options.pass!==void 0){this.options.pass(e);return}for(let n=0;n<e.length;n++)for(let r=n+1;r<e.length;r++)this.options.rule(e[n],e[r])}touches(e,n){let r={...e},s={...n};return r.id<s.id?this.options.rule(r,s):this.options.rule(s,r),!h_(r,e)||!h_(s,n)}};function y_(t,e,n,r){if(t===void 0||!Number.isFinite(t.seq))return{seq:e,at:n};let s=Math.max(0,n-t.at),o=t.seq+s*r/1e3,i=e-o;if(Math.abs(i)>Rt.SEAT_CLOCK_SNAP_INPUTS)return{seq:e,at:n};let a=o+i*(1-Math.exp(-s/Rt.SEAT_CLOCK_TAU_MS));return{seq:Math.max(t.seq,a),at:n}}function g_(t,e,n){if(t===void 0||!Number.isFinite(t))return e?1:0;let r=Math.max(0,n)/Rt.SEAT_CLOCK_TAU_MS;return e?Math.min(1,t+r):Math.max(0,t-r)}var XO=.01;function b_(t,e){let n=Math.exp(-e/Rt.SEAT_TAU_MS),r=Math.max(Math.abs(t.dx),Math.abs(t.dy),Math.abs(t.dz))*n<XO;return{dx:t.dx*n,dy:t.dy*n,dz:t.dz*n,done:r}}var JO=t=>t?Rt.SEAT_CONTACT_TAU_MS:Rt.SEAT_TAU_MS;function Id(t,e,n,r){let s=1/r,o=Math.exp(-s*n),i=e+s*t;return[(t+i*n)*o,(e-s*i*n)*o]}function w_(t,e,n,r,s,o,i,a,c){let u={ax:s.pose.x,ay:s.pose.y,az:s.pose.z},l={pass:e,epoch:n,dx:0,dy:0,dz:0,dyaw:0,vx:0,vy:0,vz:0,vyaw:0,...u,hx:0,hy:0,hz:0,stillMs:0,stopFound:!1};if(t===void 0||t.epoch!==n)return l;let d=JO(i),f=Math.max(0,o),[h,p]=Id(t.dx,t.vx,f,d),[y,S]=Id(t.dy,t.vy,f,d),[b,x]=Id(t.dz,t.vz,f,d),[R,A]=Id(t.dyaw,t.vyaw,f,d),E=t.pass!==e&&r!==void 0,P=E?r.before:s,k=E?r.after:s,M={x:P.pose.x-k.pose.x,y:P.pose.y-k.pose.y,z:P.pose.z-k.pose.z,yaw:vs(P.pose.yaw-k.pose.yaw)},B={vx:P.rate.vx-k.rate.vx,vy:P.rate.vy-k.rate.vy,vz:P.rate.vz-k.rate.vz,vyaw:P.rate.vyaw-k.rate.vyaw},K={pose:{...s.pose,x:s.pose.x+M.x,y:s.pose.y+M.y,z:s.pose.z+M.z},rate:{vx:s.rate.vx+B.vx,vy:s.rate.vy+B.vy,vz:s.rate.vz+B.vz,vyaw:s.rate.vyaw+B.vyaw}},j=E?ZO(t,B)||t.stopFound&&t.stillMs>0:t.stopFound,L=QO(t,{...t,pass:e,dx:h,dy:y,dz:b,dyaw:R,vx:p,vy:S,vz:x,vyaw:A,stopFound:j},K,s.rate,c),se={dx:L.dx+M.x,dy:L.dy+M.y,dz:L.dz+M.z,dyaw:vs(L.dyaw+M.yaw)};if(Math.hypot(se.dx,se.dy,se.dz)>a)return l;let v={vx:L.vx+B.vx,vy:L.vy+B.vy,vz:L.vz+B.vz,vyaw:L.vyaw+B.vyaw};return eI({...L,...se,...v,...u},s.rate,f)}function ZO(t,e){return e.vx*t.hx+e.vy*t.hy+e.vz*t.hz>Rt.SEAT_MOVING_UNITS_PER_MS}function QO(t,e,n,r,s){let o={x:t.hx,y:t.hy,z:t.hz},i=R=>R.x*o.x+R.y*o.y+R.z*o.z,a=i({x:n.rate.vx,y:n.rate.vy,z:n.rate.vz}),c=n.pose,l=i({x:c.x-t.ax,y:c.y-t.ay,z:c.z-t.az})+i({x:e.dx-t.dx,y:e.dy-t.dy,z:e.dz-t.dz}),d=i({x:r.vx,y:r.vy,z:r.vz})<0,f=s!==void 0&&i({x:s.vx,y:s.vy,z:s.vz})>Rt.SEAT_MOVING_UNITS_PER_MS,h=i({x:t.dx,y:t.dy,z:t.dz})>0,p=e.stopFound&&f&&h;if(t.stillMs>=Rt.SEAT_HOLD_MS||d&&!p)return e;let S=a+i({x:e.vx,y:e.vy,z:e.vz});if(l>=0&&S>=0)return e;let b=Math.max(0,-l),x=-S;return{...e,dx:e.dx+b*o.x,dy:e.dy+b*o.y,dz:e.dz+b*o.z,vx:e.vx+x*o.x,vy:e.vy+x*o.y,vz:e.vz+x*o.z}}function eI(t,e,n){let r=e.vx+t.vx,s=e.vy+t.vy,o=e.vz+t.vz,i=Math.hypot(r,s,o);return i>Rt.SEAT_MOVING_UNITS_PER_MS?{...t,hx:r/i,hy:s/i,hz:o/i,stillMs:0}:{...t,stillMs:t.stillMs+n}}function tI(t){if(!(t===void 0||typeof t.inMoveX!="number"))return{moveX:vt(t.inMoveX),moveY:vt(t.inMoveY),moveZ:vt(t.inMoveZ),yaw:vt(t.inYaw),pitch:vt(t.inPitch),buttons:vt(t.inButtons)}}var S_=1e3/60,nI=S_,rI=0,vt=t=>typeof t=="number"&&Number.isFinite(t)?t:rI;function x_(t){let e={status:t.enabled?We.LOADING:We.OFF,matched:0,replayed:0,peakResimMs:0,lastResimMs:0,slowResims:0,fallbacks:0,recoveries:0},n=null,r=null,s=0,o=0,i=new Map,a,c=t.state,u=new Map,l=x=>{e.status=x,n?.stop(x),n=null},d=()=>{if(r!==null||t.loadCore===void 0){t.loadCore===void 0&&(e.status=We.UNAVAILABLE);return}r=t.loadCore().then(x=>{if(e.status!==We.LOADING)return;if(!Wx(x))return l(We.SELF_TEST);let R=Nc(c.physDesc);if(R===null)return l(We.MISMATCH);let A=t.staticWorld();n=new Ad(x,{desc:R,staticWorld:{boxes:A.boxes.map(E=>[...E]),ramps:A.ramps.map(E=>[...E])},physicsHash:c.physics??"",tickHz:t.tickHz(),budgetMs:t.budgetMs,remoteStep:t.remoteStep?.(),bodyRule:t.bodyRule,...t.headSlide===void 0?{}:{headSlide:t.headSlide},kinematicRule:t.kinematicRule,...t.lifts===void 0?{}:{lifts:t.lifts},seatRule:t.seatRule,seatPose:t.seatPose,contactPass:t.contactPass,...t.clock===void 0?{}:{clock:t.clock}}),n.predicting||l(n.status)}).catch(()=>l(We.UNAVAILABLE))},f=()=>{let x=c.entities??new Map,R=j=>c.shapes?.get(j)?.data,A=[],E=[],P=j=>c.bodies?.has(j)===!0;for(let[j,L]of c.bodies??[]){let se=L.desc===void 0||L.desc===""?null:Bx(L.desc,R),v=x.get(j);if(v===void 0||t.motionKnown?.(j)===!1){let W=u.get(j)??(v===void 0?[0,0,0]:[v.x,v.y,v.z]);E.push({key:j,x:W[0],y:W[1],z:W[2],radius:se===null?0:Bc(se)});continue}u.set(j,[v.x,v.y,v.z]);let $=new Array(15),G={x:v.x,y:v.y,z:v.z,qx:vt(v.qx),qy:vt(v.qy),qz:vt(v.qz),qw:vt(v.qw),lvx:vt(v.lvx),lvy:vt(v.lvy),lvz:vt(v.lvz),avx:vt(v.avx),avy:vt(v.avy),avz:vt(v.avz),sleep:v.sleep===!0,rest:vt(v.rest)};Ix(G,$,0),A.push({key:j,desc:se,row:$,epoch:v.epoch})}for(let j of u.keys())c.bodies?.has(j)!==!0&&u.delete(j);let k=[];for(let[j,L]of c.joints??[])try{k.push({key:j,desc:JSON.parse(L.desc),motor:L.motor===""?null:JSON.parse(L.motor)})}catch{}let M=[],B=new Set,K=t.ownId();for(let[j,L]of x){if(L.owner===""||B.has(L.owner)||jr(L)||P(j)||c.players?.has(L.owner)!==!0)continue;B.add(L.owner);let se={...L};M.push({key:j,x:L.x,y:L.y,z:L.z,vx:L.vx,vy:L.vy,vz:L.vz,epoch:L.epoch,own:j===K,input:tI(c.players?.get(L.owner)),body:se})}return{tick:c.keyframe??0,ack:t.acked(),bodies:A,outside:E,joints:k,seats:M}},h=null,p=0,y=t.clock??(()=>performance.now()),S=()=>{let x=h;h=null,p=0,x!==null&&b(x)},b=x=>{if(n===null)return;for(let[A,E]of t.ownPath?.()??[])i.set(A,E);let R=n.adopt(x.keyframe,x.sent,A=>i.get(A)?.p,x.now,A=>i.get(A)?.v);R.kind==="match"&&e.matched++,R.kind==="replay"&&e.replayed++,R.kind==="replay"&&(e.lastResimMs=R.ms,R.ms>S_&&e.slowResims++),e.peakResimMs=Math.max(e.peakResimMs,R.ms),e.fallbacks=n.fallbacks,e.recoveries=n.recoveries,n.stopped?l(n.status):e.status=n.status,o=x.sent};return{status:e,onState(x){if(e.status===We.OFF)return;let R=c.keyframe??0;if(R===0||(c.physDesc??"")==="")return;if(n===null){d();return}if(R===s||c.tick!==R)return;s=R;let A={keyframe:f(),sent:t.sent(),now:x};if(p>=nI){h=A;return}let E=y();b(A),p+=y()-E},settle:S,afterSend(x,R){S();let A=t.sent(),E=a??x,P=A-o;for(let k=1;k<=P;k++){let M=k/P;if(x!==void 0&&E!==void 0){let B=[E.p[0]+(x.p[0]-E.p[0])*M,E.p[1]+(x.p[1]-E.p[1])*M,E.p[2]+(x.p[2]-E.p[2])*M];i.set(o+k,{p:B,v:x.v})}n?.advance(o+k,R)}o=A,a=x;for(let k of i.keys())k<A-256&&i.delete(k)},draw(x,R){return S(),n===null||!n.draws(x)?null:n.draw(x,R)},dispose(){n?.stop(We.OFF),n=null}}}Pt();var Nd={min:-1,max:1,bits:16,mode:"clamp"},Ki={min:-64,max:64,bits:16,mode:"clamp"},__=zt({moveX:Y.float32().default(0),moveY:Y.float32().default(0),moveZ:Y.float32().default(0),yaw:Y.float32().default(0),pitch:Y.float32().default(0),buttons:Y.number().default(0),tick:Y.number().default(0)},"AuthorityInput"),sI=1,R_=t=>({kind:Y.string().default(""),owner:Y.string().default(""),x:t(Y.float32().default(0)),y:t(Y.float32().default(0)),z:t(Y.float32().default(0)),vx:t(Y.float32().default(0)),vy:t(Y.float32().default(0)),vz:t(Y.float32().default(0)),yaw:t(Y.float32().default(0)),hp:Y.number().default(0),flags:Y.number().default(0),epoch:t(Y.number().default(0)),data:Y.string().default(""),t0:Y.number().default(0),g:Y.float32().default(0),src:Y.string().default(""),pitch:t(Y.float32().default(0)),duck:t(Y.float32().default(0)),mstate:t(Y.number().default(0)),cap:Y.float32().default(1),spin:t(Y.float32().default(0)),fuel:t(Y.float32().default(0)),qx:t(Y.quantized(Nd).optional()),qy:t(Y.quantized(Nd).optional()),qz:t(Y.quantized(Nd).optional()),qw:t(Y.quantized(Nd).optional()),lvx:t(Y.quantized(Ki).optional()),lvy:t(Y.quantized(Ki).optional()),lvz:t(Y.quantized(Ki).optional()),avx:t(Y.quantized(Ki).optional()),avy:t(Y.quantized(Ki).optional()),avz:t(Y.quantized(Ki).optional()),sleep:t(Y.boolean().optional()),rest:t(Y.number().optional())}),oI=zt(R_(t=>t),"AuthorityEntity"),iI=zt(R_(t=>t.view(sI)),"AuthorityEntity"),aI=zt({type:Y.string().default(""),kind:Y.string().default(""),colliders:Y.string().default(""),desc:Y.string().optional()},"AuthorityBody"),cI=zt({data:Y.string().default("")},"AuthorityShape"),uI=zt({desc:Y.string().default(""),motor:Y.string().default("")},"AuthorityJoint"),lI=zt({name:Y.string().default(""),uid:Y.string().default(""),team:Y.string().default(""),connected:Y.boolean().default(!0),avatarUrl:Y.string().default(""),seqBase:Y.number().default(0),inMoveX:Y.float32().optional(),inMoveY:Y.float32().optional(),inMoveZ:Y.float32().optional(),inYaw:Y.float32().optional(),inPitch:Y.float32().optional(),inButtons:Y.number().optional(),inRep:Y.number().optional(),inStarve:Y.number().optional(),inBuf:Y.number().optional()},"AuthorityPlayer"),E_={players:Y.map(lI),entities:Y.map(oI),tick:Y.number().default(0),clockOrigin:Y.float64().default(0),preset:Y.string().default(""),moduleSha:Y.string().default(""),tickOrigin:Y.float64().default(0),physics:Y.string().optional(),lengthUnit:Y.float32().optional(),bodies:Y.map(aI).optional(),physDesc:Y.string().optional(),keyframe:Y.number().optional(),shapes:Y.map(cI).optional(),joints:Y.map(uI).optional(),lifts:Y.string().optional(),matchKey:Y.string().optional()},CV=zt(E_,"AuthorityRoomState"),OV=zt({...E_,entities:Y.map(iI).view()},"AuthorityRoomState");var dI=(t,e)=>t+Math.atan2(Math.sin(e-t),Math.cos(e-t)),fI=(t,e,n)=>({x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n,z:t.z+(e.z-t.z)*n,yaw:t.yaw+(e.yaw-t.yaw)*n,pitch:t.pitch+(e.pitch-t.pitch)*n,duck:t.duck+(e.duck-t.duck)*n}),Bd=class{constructor(){m(this,"rings",new WeakMap)}push(e,n,r,s,o=0){let i=this.rings.get(e);i===void 0&&(i=[],this.rings.set(e,i));let a=i.at(-1);if(a!==void 0&&n<=a.t)return;let c=a!==void 0&&a.life===o,u=c?dI(a.pose.yaw,r.yaw):r.yaw;c&&n-a.t>s*1.5&&i.push({t:n-s,life:o,pose:a.pose}),i.push({t:n,life:o,pose:{...r,yaw:u}}),i.length>80&&i.splice(0,i.length-80)}at(e,n){let r=this.rings.get(e);if(r===void 0||r.length===0)return;let s=r[0],o=r.at(-1);if(n<=s.t)return s.pose;if(n>=o.t)return o.pose;let i=r.length-2;for(;i>0&&r[i].t>n;)i--;let a=r[i],c=r[i+1];return a.life!==c.life?a.pose:fI(a.pose,c.pose,(n-a.t)/(c.t-a.t))}forget(e){this.rings.delete(e)}};var gt={On:"on",Off:"off"};var LV={[Wn.Shooter]:{repeat:gt.On},[Wn.Platformer]:{repeat:gt.On},[Wn.VehicleArena]:{repeat:gt.Off},[Wn.PhysicsSandbox]:{repeat:gt.On},[Wn.Party]:{repeat:gt.On}},FV={repeat:gt.On};var k_=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);function A_(t){let e;try{e=JSON.parse(t)}catch{return gt.On}let n=k_(e)?e.inputs:void 0;return k_(n)&&n.repeat===gt.Off?gt.Off:gt.On}var P_={IDLE_SEAT_S:1800,IDLE_SEAT_MIN_S:30,IDLE_SEAT_MAX_S:86400,ROOM_AGE_S:86400,ROOM_AGE_MIN_S:60,ROOM_AGE_MAX_S:604800},VV={idleSeatS:P_.IDLE_SEAT_S,maxRoomAgeS:P_.ROOM_AGE_S};var f3={MAX_ENTITIES:256,MAX_HANDOFF_CHARS:256*1024,MAX_ROOM_ENTITIES:1024,MAX_OUTPUT_BYTES:32*1024,MAX_EVENTS_PER_TICK:64,MAX_ENTITY_DATA_BYTES:256,MAX_ENTITY_ID_CHARS:64,MAX_KIND_CHARS:64,MAX_SESSION_ID_CHARS:64,MAX_ABS:1e9,MASK_LIMIT:16777216,MAX_EPOCH:2**32-1,MAX_PROJECTILE_TICK:TS,MAX_PROJECTILE_G:wc,MAX_LAUNCH_UPDATES:224,MAX_LAUNCH_BYTES:28*1024,MAX_EVENT_TYPE_CHARS:Xt.MAX_EVENT_TYPE_CHARS,MAX_EVENT_BYTES:Xt.MAX_EVENT_BYTES,MAX_JSON_DEPTH:Xt.MAX_JSON_DEPTH,MAX_JSON_NODES:Xt.MAX_JSON_NODES,MAX_PLAYERS:Xt.ROOM_MAX_CLIENTS,MAX_PHYS_COMMANDS:256,MAX_PHYS_BYTES:32*1024,MAX_PHYSICS_OUTPUT_BYTES:64*1024,MAX_PHYSICS_WORLD_BOXES:32768,MAX_PHYSICS_WORLD_RAMPS:4096,MAX_WORLD_TEXT_CHARS:1245196};function Xi(t){return{moveX:Hn(t.moveX),moveY:Hn(t.moveY),moveZ:Hn(t.moveZ),yaw:Rs(t.yaw)??0,pitch:Rs(t.pitch)??0,buttons:fo(t.buttons)}}var p3=2**31-1;var S3=Ss.INPUT_REPEAT_MAX_MS,x3=Ss.INPUT_REPEAT_RUN_MS;function v_(t,e,n,r=gt.On){return r===gt.Off?t:Math.max(t,Math.min(t+C_(e),n))}function M_(t,e,n=gt.On){return n===gt.Off?t:t+C_(e)}var pI=(t,e,n)=>e<=n?e:Math.min(t,n),C_=t=>typeof t=="number"&&Number.isInteger(t)&&t>0?t:0;function O_(){return{shown:0,heldFrom:null}}function I_(t,e,n,r,s){let o=pI(t.shown,e,n);return o<=t.shown?(o<t.shown&&(t.heldFrom=null),t.shown=o,o):o===n||n-(o+1)<r||s?(t.heldFrom=null,t.shown=o,o):(t.heldFrom??(t.heldFrom=n),n-t.heldFrom<r?t.shown:(t.shown=o,o))}var hI=.03,mI=1,T_=.5;function D_(){return{seenRuns:null,owedMs:0,accMs:0,aheadMs:0}}function N_(t,e,n,r,s=gt.On){if(s===gt.Off||typeof e!="number"||!Number.isFinite(e))return;let o=t.seenRuns!==null&&e>t.seenRuns;if(t.seenRuns=e,!o||!(r>0))return;(typeof n=="number"&&Number.isFinite(n)?n:0)<=mI&&(t.owedMs=Math.max(t.owedMs,r))}function B_(t,e,n,r,s){let o=r>0?n.accMs/r:0;return{raw:t+e+T_*o,at:s+T_*n.aheadMs}}function L_(t,e,n){if(!(n>0)||!(e>0)||t.owedMs<=0)return 0;let r=Math.min(t.owedMs,e*hI);t.owedMs-=r,t.accMs+=r,t.aheadMs+=r;let s=Math.floor(t.accMs/n+.5);return t.accMs-=s*n,s}Pt();var V_=1,H_=1200,om=8,yI=170,gI=3,$_=32,im=8;var bI=5e3,wI=32,SI=32,xI=4,_I=1024,Po=1e3,j_=2e3,W_=250,Ld=50,q_=32,G_=20,Y_=65536,K_=250,Fd=2,X_=3,RI=1e3,EI=6e4,J_=3e4;function Z_(t,e){let n=Math.min(EI,RI*2**Math.min(t,16));return n/2+n/2*e}var To={Bind:"__fast",Off:"__fast:off",Again:"__fast:again",On:"__fast:on"},Q_={Uplink:1,Snapshot:2},Te={Oversized:"oversized",Truncated:"truncated",Trailing:"trailing",Version:"version",Kind:"kind",Session:"session",Key:"key",Count:"count",Fresh:"fresh",Actions:"actions",Flags:"flags",Order:"order",Field:"field",Ahead:"ahead",Fragment:"fragment",Mismatch:"mismatch",Duplicate:"duplicate",Keyframe:"keyframe",Body:"body",Base:"base",Stale:"stale"};var eR=29,F_=29,zd=24,am=1,cm=2,um=4,E3=am|cm|um,z_=255,tR=10,kI=4+zd,zc=4294967295,nR=65536,rm=1;var lm=t=>({ok:!0,value:t}),kn=t=>({ok:!1,fault:t}),rR=(t,e)=>Math.ceil(t*(Number.isFinite(e)&&e>0?e:0)/1e3),Ao=(t,e)=>typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=e;function Uc(t){return Math.min($_,Math.max(gI,rR(yI,t)))}function sR(t){return eR+im*(tR+zd)+Uc(t)*kI}var Vc=t=>rR(bI,t);function AI(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function dm(t){return/^(?:[0-9a-fA-F]{2})*$/.test(t)?Uint8Array.from(t.match(/../g)??[],e=>Number.parseInt(e,16)):new Uint8Array(0)}var PI=t=>typeof t=="string"&&t.length===2*om&&/^[0-9a-f]+$/.test(t),TI=(t,e)=>(e.buttons&~(t?.buttons??0))!==0,vI=t=>[t.moveX,t.moveY,t.moveZ,t.yaw,t.pitch].every(e=>typeof e=="number"&&Number.isFinite(Math.fround(e)))&&Ao(t.buttons,zc),MI=t=>Ao(t.seq,zc)&&t.seq>=1&&Ao(t.tick,nR-1)&&Ao(t.render,zc)&&vI(t.input),CI=t=>t.reduce((e,n)=>Math.max(e,n.render),0),OI=(t,e)=>e.render===0||t-e.render>=z_?z_:t-e.render;function II(t){let{window:e,actions:n}=t;if(!Ao(t.sid,zc)||!PI(t.key)||!Ao(t.ackSnap,zc))return!1;if(e.length===0)return t.fresh===0&&n.length===0;if(e.length>$_||n.length>im||!Ao(t.fresh,e.length)||t.fresh<1||![...n,...e].every(MI))return!1;let r=e.every((o,i)=>i===0||o.seq===e[i-1].seq+1),s=n.every((o,i)=>o.seq<(i+1<n.length?n[i+1].seq:e[0].seq));return r&&s}function sm(t,e,n){return t.setFloat32(e,n.moveX,!0),t.setFloat32(e+4,n.moveY,!0),t.setFloat32(e+8,n.moveZ,!0),t.setFloat32(e+12,n.yaw,!0),t.setFloat32(e+16,n.pitch,!0),t.setUint32(e+20,n.buttons,!0),e+zd}var U_=t=>{let e=new Uint8Array(zd);return sm(new DataView(e.buffer),0,t),AI(e)};function DI(t,e){if(t===null)return 0;let n=U_(t.input)===U_(e.input)?am:0;return e.tick===t.tick?n|=cm:e.tick===(t.tick+1)%nR&&(n|=um),n}function fm(t){if(!II(t))return kn(Te.Field);let e=new Uint8Array(H_),n=new DataView(e.buffer);e[0]=V_,e[1]=Q_.Uplink,n.setUint32(2,t.sid,!0),e.set(dm(t.key),6),n.setUint32(14,t.ackSnap,!0),n.setUint32(18,t.window.at(-1)?.seq??0,!0),e[22]=t.window.length,e[23]=t.fresh,e[24]=t.actions.length;let r=CI(t.window);n.setUint32(25,r,!0);let s=eR;for(let o of t.actions)n.setUint32(s,o.seq,!0),n.setUint16(s+4,o.tick,!0),n.setUint32(s+6,o.render,!0),s=sm(n,s+tR,o.input);return t.window.forEach((o,i)=>{let a=DI(i===0?null:t.window[i-1],o);e[s]=a,s+=1,(a&(cm|um))===0&&(n.setUint16(s,o.tick,!0),s+=2),e[s]=OI(r,o),s+=1,(a&am)===0&&(s=sm(n,s,o.input))}),lm(e.slice(0,s))}function NI(t,e,n){return t.length>H_?Te.Oversized:t.length<2?Te.Truncated:t[0]!==V_?Te.Version:t[1]!==e?Te.Kind:t.length<n?Te.Truncated:null}function oR(t,e){let n=t.slice(-Uc(e.tickHz)),r=n.length>0?n[0].seq:Number.POSITIVE_INFINITY,s=t.filter((o,i)=>o.seq>e.inputAck&&o.seq<r&&TI(i>0?t[i-1].input:null,o.input)).slice(0,im);return{sid:e.sid,key:e.key,ackSnap:e.ackSnap,fresh:Math.min(e.fresh,n.length),actions:s,window:n}}var BI=t=>[...t].sort((e,n)=>e.key-n.key);var k3=new Uint8Array(4096);function LI(t,e){let n=NI(t,Q_.Snapshot,F_);if(n!==null)return kn(n);let r=new DataView(t.buffer,t.byteOffset,t.byteLength);if(r.getUint32(2,!0)!==e)return kn(Te.Session);let s=r.getUint32(6,!0),o=r.getUint32(10,!0),i=t[22],a=t[23],c=t[24];if(c<1||c>SI||a>=c)return kn(Te.Fragment);if(!((i&~rm)===0&&i===rm==(o===0))||s<1||o>=s)return kn(Te.Keyframe);let l=t.slice(F_);return lm({snap:s,base:o,tick:r.getUint32(14,!0),inputAck:r.getUint32(18,!0),sent:r.getUint32(25,!0),keyframe:i===rm,frag:a,frags:c,chunk:l})}function FI(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.length<2)return kn(Te.Body);let n=e.getUint16(0,!0),r=2,s=[];for(let a=0;a<n;a+=1){if(r+2>t.length)return kn(Te.Body);let c=e.getUint16(r,!0);if(a>0&&c<=s[a-1])return kn(Te.Body);s.push(c),r+=2}if(r+2>t.length)return kn(Te.Body);let o=e.getUint16(r,!0);r+=2;let i=[];for(let a=0;a<o;a+=1){if(r+4>t.length)return kn(Te.Body);let c=e.getUint16(r,!0),u=e.getUint16(r+2,!0);if(u>_I||r+4+u>t.length||a>0&&c<=i[a-1].key)return kn(Te.Body);i.push({key:c,bytes:t.slice(r+4,r+4+u)}),r+=4+u}return r===t.length?lm({removed:s,records:i}):kn(Te.Body)}function zI(t,e){let n=new Set(e.removed),r=new Map(t.filter(s=>!n.has(s.key)).map(s=>[s.key,s]));for(let s of e.records)r.set(s.key,s);return BI([...r.values()])}var iR=()=>({partials:[],history:[],newest:0}),UI=(t,e)=>t.base===e.base&&t.tick===e.tick&&t.inputAck===e.inputAck&&t.sent===e.sent&&t.keyframe===e.keyframe&&t.frags===e.frags;function aR(t,e,n){let r=LI(e,n);if(!r.ok)return{rx:t,applied:null,fault:r.fault};let s=r.value;if(s.snap<=t.newest)return{rx:t,applied:null,fault:Te.Stale};let o=t.partials.find(u=>u.snap===s.snap);if(o!==void 0&&!UI(o,s))return{rx:t,applied:null,fault:Te.Mismatch};if(o?.chunks[s.frag])return{rx:t,applied:null,fault:Te.Duplicate};let i=o??{snap:s.snap,base:s.base,tick:s.tick,inputAck:s.inputAck,sent:s.sent,keyframe:s.keyframe,frags:s.frags,chunks:Array(s.frags).fill(null)},a={...i,chunks:i.chunks.map((u,l)=>l===s.frag?s.chunk:u)},c=t.partials.filter(u=>u.snap!==s.snap);if(a.chunks.some(u=>u===null)){let u=[...c,a].sort((l,d)=>l.snap-d.snap).slice(-xI);return{rx:{...t,partials:u},applied:null}}return VI({...t,partials:c},t,a)}function VI(t,e,n){let r=t.partials.length===e.partials.length?e:t,s=FI(HI(n.chunks));if(!s.ok)return{rx:r,applied:null,fault:Te.Body};let o=n.keyframe?null:e.history.find(u=>u.snap===n.base);if(o===void 0)return{rx:r,applied:null,fault:Te.Base};if(n.keyframe&&s.value.removed.length>0)return{rx:r,applied:null,fault:Te.Body};let i=zI(o?.records??[],s.value),a=[...e.history,{snap:n.snap,tick:n.tick,inputAck:n.inputAck,sent:n.sent,records:i}].slice(-wI);return{rx:{partials:t.partials.filter(u=>u.snap>n.snap),history:a,newest:n.snap},applied:n.snap}}function HI(t){let e=new Uint8Array(t.reduce((r,s)=>r+s.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}var Ht={Entity:1,Seat:2},_e={F32:"f32",U32:"u32",U16:"u16",Orientation:"q-orientation",Velocity:"q-velocity",Flag:"flag"},$I=[["x",_e.F32],["y",_e.F32],["z",_e.F32],["vx",_e.F32],["vy",_e.F32],["vz",_e.F32],["yaw",_e.F32],["pitch",_e.F32],["duck",_e.F32],["spin",_e.F32],["fuel",_e.F32],["epoch",_e.U32],["mstate",_e.U32],["qx",_e.Orientation],["qy",_e.Orientation],["qz",_e.Orientation],["qw",_e.Orientation],["lvx",_e.Velocity],["lvy",_e.Velocity],["lvz",_e.Velocity],["avx",_e.Velocity],["avy",_e.Velocity],["avz",_e.Velocity],["sleep",_e.Flag],["rest",_e.U16]],jI=[["inMoveX",_e.F32],["inMoveY",_e.F32],["inMoveZ",_e.F32],["inYaw",_e.F32],["inPitch",_e.F32],["inButtons",_e.U32],["inRep",_e.U32],["inStarve",_e.U32],["inBuf",_e.U32],["inAck",_e.U32]],WI=64,Ji=2,pm=4;var hm=65534,qI=hm/2,GI={[_e.Orientation]:1,[_e.Velocity]:64},Ud=()=>({x:0,y:0,z:0,vx:0,vy:0,vz:0,yaw:0,pitch:0,duck:0,spin:0,fuel:0,epoch:0,mstate:0,qx:0,qy:0,qz:0,qw:0,lvx:0,lvy:0,lvz:0,avx:0,avy:0,avz:0,sleep:!1,rest:0}),Vd=()=>({inMoveX:0,inMoveY:0,inMoveZ:0,inYaw:0,inPitch:0,inButtons:0,inRep:0,inStarve:0,inBuf:0,inAck:0});var YI=(t,e)=>-t+e/hm*(2*t),KI=t=>t===Ht.Entity?$I:t===Ht.Seat?jI:null;var uR={f32:4,u32:4,u16:2,"q-orientation":2,"q-velocity":2,flag:0},XI=255,JI=4,ZI=32,QI=new Uint8Array(Ji+XI+pm+ZI*JI),T3=new DataView(QI.buffer);var v3=new TextEncoder;function e1(t,e,n){if(e+uR[n]>t.byteLength)return{ok:!1,fault:Te.Truncated};switch(n){case _e.Flag:return{ok:!0,value:!0};case _e.F32:{let r=t.getFloat32(e,!0);return Number.isFinite(r)&&r!==0?{ok:!0,value:r}:{ok:!1,fault:Te.Field}}case _e.U32:{let r=t.getUint32(e,!0);return r!==0?{ok:!0,value:r}:{ok:!1,fault:Te.Field}}case _e.U16:{let r=t.getUint16(e,!0);return r!==0?{ok:!0,value:r}:{ok:!1,fault:Te.Field}}default:{let r=t.getUint16(e,!0);return r!==qI&&r<=hm?{ok:!0,value:YI(GI[n],r)}:{ok:!1,fault:Te.Field}}}}var t1=new TextDecoder("utf-8",{fatal:!0});function n1(t){let e=t[1];if(Ji+e>t.length)return{ok:!1,fault:Te.Truncated};if(e===0)return{ok:!1,fault:Te.Field};try{let n=t1.decode(t.subarray(Ji,Ji+e));return n.length<=WI?{ok:!0,value:n}:{ok:!1,fault:Te.Field}}catch{return{ok:!1,fault:Te.Field}}}function lR(t){if(t.length<Ji)return{ok:!1,fault:Te.Truncated};let e=KI(t[0]);if(e===null)return{ok:!1,fault:Te.Kind};let n=n1(t);if(!n.ok)return n;let r=new DataView(t.buffer,t.byteOffset,t.byteLength),s=Ji+t[1];if(s+pm>t.length)return{ok:!1,fault:Te.Truncated};let o=r.getUint32(s,!0);if(s+=pm,e.length<32&&o>>>e.length)return{ok:!1,fault:Te.Flags};if(t[0]===Ht.Entity){let a=cR(r,s,o,Ud(),e);return a.ok?{ok:!0,value:{kind:Ht.Entity,id:n.value,motion:a.value}}:a}let i=cR(r,s,o,Vd(),e);return i.ok?{ok:!0,value:{kind:Ht.Seat,id:n.value,motion:i.value}}:i}function cR(t,e,n,r,s){let o={},i=e;for(let[a,[c,u]]of s.entries()){if((n&1<<a)===0)continue;let l=e1(t,i,u);if(!l.ok)return l;o[c]=l.value,i+=uR[u]}return i!==t.byteLength?{ok:!1,fault:Te.Trailing}:{ok:!0,value:Object.assign(r,o)}}var r1=4294967295,s1=4,at={Unreachable:"unreachable",Handshake:"handshake",Stall:"stall",Server:"server",NoWebTransport:"no-webtransport",NoRelay:"no-relay",NotOffered:"not-offered"},o1=(t,e)=>typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=e;function mm(t){if(typeof t!="object"||t===null)return!1;let{sid:e,key:n,url:r}=t,s=typeof n=="string"&&n.length===2*om&&/^[0-9a-f]+$/.test(n);return o1(e,r1)&&s&&typeof r=="string"&&r.length>0}function i1(t,e,n){if(t.length===0)return[];let r=t[t.length-1].seq,s=Math.min(e,r-Uc(n)+1),o=Math.max(s,r-Vc(n)+1);return t.filter(i=>i.seq>=o)}var dR=(t,e)=>`${t}:${e}`;function ym(t){let e=iR(),n=[],r=new Map,s=0,o=!1,i=null,a=null,c=null,u=null,l=typeof t.bind.rev=="number"&&t.bind.rev>=Fd,d=null,f=new Map,h=new Map,p=()=>e.history.at(-1)?.inputAck??0,y=E=>{let P=new Map,k=new Map,M=[];for(let B of E){let K=f.get(B.key),j=K!==void 0&&(K.bytes===B.bytes||u1(K.bytes,B.bytes)),L=j?K.record:c1(B.bytes);P.set(B.key,{bytes:B.bytes,record:L}),L!==null&&(k.set(dR(L.kind,L.id),L),j||M.push(L))}return f=P,h=k,M};function S(E){if(o)return{applied:null};let P=aR(e,E,t.bind.sid);if(e=P.rx,P.fault!==void 0||P.applied===null)return{applied:null,fault:P.fault};let k=e.history.at(-1);if(k===void 0)return{applied:null};let M=x;x=k.snap,a=t.now(),n=i1(n,k.inputAck,t.tickHz);let B={snap:k.snap,tick:k.tick,inputAck:k.inputAck,sent:k.sent,changed:y(k.records)};t.onSnapshot?.(B);let K=B.changed.length>=q_&&(c===null||t.now()-c>=G_);return(k.snap-M>=Y_||K)&&b(),{applied:B}}function b(){if(o||!l||R===null)return;let E=fm({sid:t.bind.sid,key:t.bind.key,ackSnap:e.newest,fresh:0,actions:[],window:[]});if(!E.ok)return;let P=t.now();i??(i=P),c=P,R.send(E.value)}let x=0,R=t.open(t.bind.url,E=>{S(E)},t.bind);if(R===null)return null;let A=sR(t.tickHz);return{bind:t.bind,get rx(){return e},get lastQueued(){return n.at(-1)?.seq??0},get closed(){return o},opening:()=>R.opening?.()===!0,queue(E){o||(n.push({seq:E.seq,tick:E.tick,render:E.render,input:{...E.input}}),s+=1)},flush(){if(o||s===0)return;let E=t.now();for(let M of n.slice(-s))r.set(M.seq,E);a1(r,(n.at(-1)?.seq??0)-Vc(t.tickHz)+1);let P=Uc(t.tickHz),k=n.length-s;for(s=0;k<n.length;){let M=Math.min(k+P,n.length),B=oR(n.slice(0,M),{sid:t.bind.sid,key:t.bind.key,ackSnap:e.newest,inputAck:p(),fresh:M-k,tickHz:t.tickHz});k=M;let K=fm(B);K.ok&&(i??(i=E),c=E,R.send(K.value))}},framed(){let E=t.now(),P=u===null?0:E-u;u=E,!(P<=K_)&&(a!==null&&(a=Math.min(E,a+P)),i!==null&&(i=Math.min(E,i+P)))},keepalive(){if(o||!l)return;let E=a===null?Ld:W_;(c===null||t.now()-c>=E)&&b()},inputAt:E=>n.find(P=>P.seq===E),sentAt:E=>r.get(E),motionOf:(E,P)=>h.get(dR(E,P)),records:()=>[...h.values()],due(){if(o)return null;if(R.failed?.()===!0)return at.Unreachable;let E=R.maxDatagramBytes?.();if(E!==void 0&&E<A)return at.Unreachable;let P=t.now();if(a!==null)return P-a>j_?at.Stall:null;if(i===null)return null;let k=R.opening?.();if(k===!0){let B=Math.max(Po,s1*(t.roundTripMs?.()??0));return P-i>B?at.Handshake:null}k===!1&&(d??(d=P));let M=k===!1?Math.max(i,d??P):i;return P-M>Po?at.Handshake:null},receive:S,close(){o||(o=!0,R.close())}}}function a1(t,e){for(let n of t.keys()){if(n>=e)return;t.delete(n)}}function c1(t){let e=lR(t);return e.ok?e.value:null}var u1=(t,e)=>t.length===e.length&&t.every((n,r)=>n===e[r]);var Hc={Udp:"udp",WebSocket:"websocket"},Zi={Off:"off",NoUdp:"no_udp",NotOffered:"not_offered"},l1=Po,d1={[Zi.Off]:"the game turned the fast channel off",[Zi.NoUdp]:"this platform has no UDP",[Zi.NotOffered]:"the room does not offer the fast channel",unreachable:"fell back, the binding could not be used or its socket failed",handshake:"fell back, no UDP snapshot within 1 s of the first datagram (UDP blocked?)",stall:"fell back, no UDP snapshot for 2 s",server:"fell back, the room closed the channel","no-webtransport":"this browser has no WebTransport","no-relay":"the room has no WebTransport relay"},f1=t=>`genex transport: udp fast@1 ${t}`,Hd=t=>`genex transport: websocket, ${t}: ${d1[t]??"unknown"}`;function fR(){let t=new Set,e=n=>t.has(n)?null:(t.add(n),n);return{observe(n){return n.joinedMs===null?null:n.asked?n.udp?n.fallback!==null?e(Hd(n.fallback)):n.url!==null?n.snapshots>0?e(f1(n.url)):null:n.joinedMs>=l1?e(Hd(Zi.NotOffered)):null:e(Hd(Zi.NoUdp)):e(Hd(Zi.Off))},reset(){t.clear()}}}var p1=19,h1=3,m1=31,y1=Object.keys(Ud()),g1=Object.keys(Vd()).filter(t=>t!=="inAck"),b1=t=>t===Ht.Entity?y1:g1,w1=["tick","keyframe"],pR=64;function S1(){let t=[],e=0;return{snapshot(n,r){let s=t.at(-1)?.ack??e;r<=s||(t.push({tick:n,ack:r}),t.length>pR&&(t=t.slice(-pR)))},through(n){let r=0;for(;r<t.length&&t[r].tick<=n;)e=Math.max(e,t[r].ack),r+=1;return r>0&&(t=t.slice(r)),e},reset(n){t=[],e=n}}}function yR(t){let e=globalThis.process?.stderr;e?.write!==void 0?e.write(`${t}
15
+ `):console.info(t)}var x1=(t,e)=>{let n=setInterval(e,t);return n.unref?.(),()=>clearInterval(n)};function _1(t){if(typeof t!="object"||t===null)return null;let e=t,n=e._encoder;return typeof e._lastStamp!="number"||typeof n?.reset!="function"?null:t}function R1(t){let e=t;if(typeof e?._sampleStamp!="function")return()=>0;let n=e;return()=>{let r=n._sampleStamp().stamp;return typeof r=="number"&&Number.isInteger(r)&&r>=0&&r<=4294967295?r:0}}function gR(t){let{room:e,handle:n}=t,r={live:!1,snapshots:0,fallback:t.neverAsked,fallbacks:0,returns:0,transport:Hc.WebSocket,line:null},s=0,o=fR(),i=null,a=null,c=0,u=null,l=null,d=0,f=S1(),h=[],p=null,y=null,S=0,b=t.open===void 0?null:A1(e,()=>u?.client??null),x=t.open===void 0?null:(t.every??x1)(Ld,()=>{u?.client.keepalive(),A?.client.keepalive()}),R=t.random??Math.random,A=null,E=!1,P=0,k=null,M=null,B=_1(n),K=R1(n),j=()=>{if(u!==null)return Math.min(n.sentCount,d);if(l===null)return n.lastProcessed;let ee=n.lastProcessed-l.wsBefore;return ee>0?Math.max(l.ack,l.at+ee):l.ack},L=()=>e.state.players?.get(e.sessionId)?.seqBase??0,se=()=>{!E||t.open===void 0||(k=t.now()+Z_(P,R()),P+=1)},v=ee=>{if(l!==null)return;M!==null&&t.now()-M>=J_&&(P=0),ee===at.Server&&(P=Math.max(P,h1)),M=null,r.fallbacks+=1;let ue=u,Ae=u?.seqBase??L();l={at:n.sentCount,wsBefore:u?.wsBefore??n.sentCount,ack:j(),reason:ee},u?.client.close(),u=null,h=[],r.live=!1,r.fallback=ee,ue!==null&&B!==null&&(B._encoder.reset(),B._lastStamp=ue.stampAtBind);let pt={last:Ae+n.sentCount};e.send(To.Off,pt),b?.release(),se()},$=ee=>{r.fallback===null&&(r.fallbacks+=1),r.fallback=ee},G=ee=>{if(A===null)return;A.client.close(),A=null,$(ee);let ue={last:L()+n.sentCount};e.send(To.Off,ue),se()},W=ee=>{let ue=A;if(ue===null||l===null)return;A=null;let Ae=L(),pt=l.wsBefore+(n.sentCount-l.at);d=j(),f.reset(d),u={client:ue.client,seqBase:Ae,wsBefore:pt,stampAtBind:B?._lastStamp??0},l=null,k=null,M=t.now(),r.live=!0,r.fallback=null,r.fallbacks>0&&(r.returns+=1);let Bt={last:Ae+n.sentCount};e.send(To.On,Bt),ce({...ee,changed:ue.client.records()})},q=ee=>{ee.opening()&&e.ping(ue=>{S=ue})},ae=ee=>{if(t.open===void 0)return;if(P=Math.max(0,P-1),E=!0,A?.client.close(),A=null,l===null&&(r.fallback=null),l??(l={at:0,wsBefore:0,ack:0,reason:at.Unreachable}),h=[],!mm(ee))return $(at.Unreachable),se();a=ee.url;let ue={client:null,applied:0},Ae=ym({bind:ee,tickHz:t.tickHz(),open:t.open,now:t.now,roundTripMs:()=>S,onSnapshot:pt=>{if(u!==null&&u.client===ue.client)return ce(pt);ue.applied+=1,ue.applied>=X_&&W(pt)}});if(Ae===null)return $(t.open.whyNull?.(ee)??at.Unreachable),se();q(Ae),ue.client=Ae,A=ue,k=null,Ae.keepalive()},ce=ee=>{let ue=u;if(ue===null)return;r.snapshots+=1;let Ae=ue.client.motionOf(Ht.Seat,e.sessionId),pt=Ae?.kind===Ht.Seat?Ae.motion.inAck:0,Bt=Math.max(0,Math.min(n.sentCount,pt-ue.seqBase)),_r=-1;if(Bt>d){let Gn=ue.client.sentAt(ue.seqBase+Bt);Gn!==void 0&&(_r=t.now()-Gn),d=Bt}f.snapshot(ee.tick,d),e.clock.sample(ee.sent,_r),b?.write(ee)},ne=ee=>{let ue=ee?.probe===!0;if(t.open===void 0||u!==null||l!==null&&!ue)return;if(!t.stateCurrent()){p=ee;return}if(p=null,ue)return ae(ee);if(r.fallback=null,!mm(ee))return v(at.Unreachable);a=ee.url,E=typeof ee.rev=="number"&&ee.rev>=Fd;let Ae=ym({bind:ee,tickHz:t.tickHz(),open:t.open,now:t.now,roundTripMs:()=>S,onSnapshot:ce});if(Ae===null)return v(t.open.whyNull?.(ee)??at.Unreachable);q(Ae),u={client:Ae,seqBase:L(),wsBefore:n.sentCount,stampAtBind:B?._lastStamp??0},d=0,f.reset(0),r.live=!0,M=t.now();for(let pt of h)Ae.queue({...pt,seq:u.seqBase+pt.seq});h=[],Ae.flush(),Ae.keepalive()},Re=()=>{t.open!==void 0&&u===null&&l===null&&p===null&&t.stateCurrent()&&(y??(y=t.now()),t.now()-y>Po&&(r.fallback=at.NotOffered))},oe=()=>{i===null&&t.stateCurrent()&&e.state.players?.get(e.sessionId)!==void 0&&(i=t.now());let ee=r.snapshots-c;r.transport=r.live&&ee>0?Hc.Udp:Hc.WebSocket,r.returns!==s&&(s=r.returns,o.reset());let ue=r.fallback===at.NotOffered?null:r.fallback,Ae=o.observe({asked:!t.off,udp:t.open!==void 0,joinedMs:i===null?null:t.now()-i,url:a,snapshots:ee,fallback:ue});Ae!==null&&(r.line=Ae,t.log(Ae))};return t.open!==void 0&&(e.onMessage(To.Bind,ee=>ne(ee)),e.onMessage(To.Off,()=>v(at.Server)),e.onStateChange(()=>{p!==null&&t.stateCurrent()&&ne(p)}),B!==null&&E1(e,()=>u!==null)),{status:r,ack:j,settleAck(){return u===null?j():Math.min(j(),f.through(b?.webSocketTick()??Number(e.state.tick??0)))},sent(ee,ue,Ae){if(t.open===void 0||l!==null)return;let pt=K();if(u!==null){u.client.queue({seq:u.seqBase+ee,tick:ue,render:pt,input:Ae});return}h.push({seq:ee,tick:ue,render:pt,input:{...Ae}});let Bt=Vc(t.tickHz());h.length>Bt&&(h=h.slice(-Bt))},flush(){u?.client.flush()},poll(){u?.client.framed();let ee=u?.client.due()??null;ee!==null&&v(ee),u?.client.keepalive(),A?.client.framed();let ue=A?.client.due()??null;ue!==null&&G(ue),A?.client.keepalive(),k!==null&&t.now()>=k&&A===null&&l!==null&&(e.send(To.Again,{}),se()),Re(),oe()},motionKnown(ee){return u===null||u.client.motionOf(Ht.Entity,ee)!==void 0},inputAt(ee){if(u===null)return;let ue=u.client.inputAt(u.seqBase+ee);return ue===void 0?void 0:{...ue.input,tick:ue.tick}},dropped(){u?.client.close(),u=null,A?.client.close(),A=null,k=null,P=0,M=null,E=!1,b?.forget(),l=null,d=0,h=[],p=null,y=null,r.live=!1,r.fallback=t.neverAsked,r.transport=Hc.WebSocket,o.reset(),i=null,a=null,c=r.snapshots},dispose(){x?.(),A?.client.close(),A=null,u?.client.close(),u=null,r.live=!1,b?.dispose()}}}function E1(t,e){let n=t.connection;if(n===void 0)return;let r=n.send.bind(n);n.send=s=>{e()&&s.length>0&&(s[0]&m1)===p1||r(s)}}var k1={...Ud(),...Vd()};function A1(t,e){let n=t.serializer.decoder,r=t.state,s=new WeakMap,o=new Map,i=!1,a=n.triggerChanges,c=Object.getOwnPropertyDescriptor(n,"decode"),u=n.decode,l=x=>{let R=s.get(x),A=e();return R===void 0||A===null?void 0:A.motionOf(R.kind,R.id)},d=()=>{t.state.entities?.forEach((x,R)=>s.set(x,{kind:Ht.Entity,id:R})),t.state.players?.forEach((x,R)=>s.set(x,{kind:Ht.Seat,id:R}))},f=x=>{if(x===r)return!0;let R=s.get(x);return R===void 0?!1:(R.kind===Ht.Entity?t.state.entities?.get(R.id):t.state.players?.get(R.id))===x},h=(x,R,A,E)=>{let P=o.get(x);P===void 0&&(P=new Map,o.set(x,P));let k=P.get(R);k===void 0?P.set(R,{fast:A,ws:x[R]??k1[R]}):k.fast=A,mR(x,R,A,E)},p=()=>{d();for(let[x,R]of o){if(!f(x)){o.delete(x);continue}for(let[A,E]of R)E.ws!==E.fast&&(x[A]=E.ws)}i=!0},y=()=>{if(i){i=!1;for(let[x,R]of o)for(let[A,E]of R)E.ws!==E.fast&&(x[A]=E.fast)}},S=x=>{let R=x.field;if(R===void 0)return!1;let A=o.get(x.ref)?.get(R);return A===void 0?!1:(A.ws=x.value,!0)},b=x=>{if(e()===null)return a?.(x);d();for(let A of x){let E=A.value;if(A.field!==void 0||typeof E!="object"||E===null)continue;let P=l(E);P!==void 0&&hR(E,P,(k,M,B)=>h(k,M,B,null))}let R=x.filter(A=>!S(A));y(),a?.(R)};return Object.defineProperty(n,"triggerChanges",{configurable:!0,get:()=>b,set:x=>{a=x}}),Object.defineProperty(n,"decode",{configurable:!0,writable:!0,value:(...x)=>{e()!==null&&o.size>0&&p();try{return u.apply(n,x)}finally{y()}}}),{webSocketTick(){return Number(o.get(r)?.get("tick")?.ws??t.state.tick??0)},write(x){d();let R=[];for(let E of x.changed){let P=E.kind===Ht.Entity?t.state.entities?.get(E.id):t.state.players?.get(E.id);P!==void 0&&hR(P,E,(k,M,B)=>h(k,M,B,R))}let A=t.state.keyframe===void 0?["tick"]:w1;for(let E of A)h(r,E,x.tick,R);R.length>0&&a?.(R),t.onStateChange.invoke(t.state)},release(){d();let x=[],R=t.state.physics!==void 0;for(let[A,E]of o)if(!(!f(A)||R&&s.get(A)?.kind===Ht.Entity))for(let[P,k]of E)mR(A,P,k.ws,x);o.clear(),x.length!==0&&(a?.(x),t.onStateChange.invoke(t.state))},forget(){o.clear()},dispose(){o.clear(),Object.defineProperty(n,"triggerChanges",{configurable:!0,writable:!0,value:a}),c===void 0?Reflect.deleteProperty(n,"decode"):Object.defineProperty(n,"decode",c)}}}function hR(t,e,n){let r=e.motion;for(let s of b1(e.kind)){let o=r[s];(o===0||o===!1)&&t[s]===void 0||n(t,s,o)}}function mR(t,e,n,r){let s=t[e];s!==n&&(t[e]=n,r?.push({ref:t,refId:t[Q],op:N.REPLACE,field:e,value:n,previousValue:s}))}var bR=new Map,P1="udp:",T1=65535,v1=32,M1=["","/"],C1=t=>t.username===""&&t.password===""&&M1.includes(t.pathname)&&t.search===""&&t.hash==="";function O1(t){let e;try{e=new URL(t)}catch{return null}let n=Number(e.port),r=Number.isInteger(n)&&n>=1&&n<=T1;return e.protocol!==P1||!r||e.hostname===""||!C1(e)?null:{host:e.hostname.replace(/^\[(.*)\]$/,"$1"),port:n}}var wR=({createSocket:t,lookup:e,isIP:n})=>(r,s)=>{let o=O1(r);if(o===null)return null;let i=null,a=!1,c=!1,u=[],l=(h,p)=>{if(c)return;let y=t(p===6?"udp6":"udp4");i=y,y.on("message",S=>s(new Uint8Array(S.buffer,S.byteOffset,S.byteLength))),y.on("error",()=>{}),y.connect(o.port,h,()=>{if(a=!0,!c)for(let S of u)y.send(S);u=[]})},d=n(o.host);return d!==0?l(o.host,d):e(o.host,{all:!0,verbatim:!0},(h,p)=>{if(h!==null||p.length===0)return;let y=(bR.get(o.host)??0)%p.length;bR.set(o.host,y+1),l(p[y].address,p[y].family)}),{send(h){c||(a?i?.send(h):u=[...u,h].slice(-v1))},close(){c||(c=!0,i?.close())}}};function SR(){let t=globalThis.process?.getBuiltinModule,e=t?.("node:dgram"),n=t?.("node:dns"),r=t?.("node:net");if(!(e===void 0||n===void 0||r===void 0))return wR({createSocket:e.createSocket,lookup:n.lookup,isIP:r.isIP})}var I1=64,D1=4,N1="https:",B1=32,L1=/^[0-9a-f]+$/,F1="reliable-only";function xR(t){let e=t.wt;if(typeof e!="object"||e===null)return null;let{url:n,hashes:r}=e;if(typeof n!="string"||!Array.isArray(r)||r.length===0||r.length>D1)return null;let s=a=>typeof a=="string"&&a.length===I1&&L1.test(a);if(!r.every(s))return null;let o;try{o=new URL(n)}catch{return null}let i=o.username===""&&o.password===""&&o.search===""&&o.hash==="";return o.protocol!==N1||o.hostname===""||!i?null:{url:n,hashes:r.map(a=>dm(a))}}function z1(t){return{serverCertificateHashes:t.hashes.map(e=>({algorithm:"sha-256",value:e})),requireUnreliable:!0,allowPooling:!1,congestionControl:"low-latency"}}var U1=t=>t.reliability!==F1;function V1(t){return(t.datagrams.createWritable?.()??t.datagrams.writable)?.getWriter()??null}var $t={Connecting:"connecting",Open:"open",Failed:"failed",Closed:"closed"};function _R(t){let e=(n,r,s)=>{let o=s===void 0?null:xR(s);if(o===null||t===void 0)return null;let i;try{i=new t(o.url,z1(o))}catch{return null}let a=$t.Connecting,c=[],u=null,l=()=>{if(!(a===$t.Closed||a===$t.Failed)){a=$t.Failed,u=null,c=[];try{i.close()}catch{}}},d=(p,y)=>{p.write(y).catch(()=>{})},f=async p=>{for(;;){let y=await p.read();if(y.done)return;a===$t.Open&&r(y.value)}};return i.ready.then(()=>{if(a!==$t.Connecting)return;if(!U1(i))return l();let p=V1(i);if(p===null)return l();a=$t.Open,u=p;for(let y of c)d(p,y);c=[],f(i.datagrams.readable.getReader()).then(l,l)},()=>l()),i.closed.then(l,l),{send(p){a===$t.Open&&u!==null?d(u,p):a===$t.Connecting&&(c=[...c,p].slice(-B1))},close(){if(a===$t.Closed)return;let p=a;if(a=$t.Closed,u=null,c=[],p!==$t.Failed)try{i.close()}catch{}},failed:()=>a===$t.Failed,opening:()=>a===$t.Connecting,maxDatagramBytes(){let p=a===$t.Open?i.datagrams.maxDatagramSize:void 0;return typeof p=="number"?p:void 0}}};return e.whyNull=n=>t===void 0?at.NoWebTransport:xR(n)===null?at.NoRelay:at.Unreachable,e}var gm=t=>typeof t.WebTransport=="function"?t.WebTransport:void 0,RR=(t,e,n)=>_R(gm(globalThis))(t,e,n);RR.whyNull=t=>_R(gm(globalThis)).whyNull?.(t)??at.Unreachable;function ER(t,e=globalThis){return t===!1?{open:void 0,fallback:null}:t!==void 0?{open:t,fallback:null}:gm(e)!==void 0?{open:RR,fallback:null}:{open:void 0,fallback:e.document!==void 0||typeof e.importScripts=="function"?at.NoWebTransport:null}}var kR=100,$d=["x","y","z","yaw"],H1=.001;function AR(t,e,n,r){if(t===void 0)return[0,0,0,0];let s=t.err.map(o=>o*r);return t.k===e?s:t.shift.map((o,i)=>o+s[i]-n[i])}var $1=[1e3,2e3,4e3],PR=8,j1=250,TR=600,W1=["x","y","z","vx","vy","vz","yaw"],jd={Reconnecting:"reconnecting",Reconnected:"reconnected",Disconnect:"disconnect",...Es},q1=new Set(Object.values(jd)),bm={protocol:`[multiplayer] the authority server refused protocol ${4} (code 426) \u2014 this game was built with a @genex-ai/multiplayer that the server no longer serves. Update the package and republish.`,notEntitled:"[multiplayer] server-authoritative rooms are not available for this game (code 402): its owner is not entitled to them. This is final; the session does not retry.",freeQuota:"[multiplayer] no new server-authoritative room for this game (code 429): its owner is on Genex's free tier and has used the free included room time for this period. Rooms already running are not affected; new rooms open again next period, or with Genex Pro."},Wd=t=>t&&typeof t=="object"?t.code:void 0,G1=t=>t&&typeof t=="object"?t.message:void 0,Y1=t=>Wd(t)===fn.ROOM_QUOTA&&G1(t)===A0;function vR(t){throw fc(t)?console.error(bm.protocol):Wd(t)===fn.NOT_ENTITLED?console.error(bm.notEntitled):Y1(t)&&console.error(bm.freeQuota),t}var IR=t=>t.physicsCore!==void 0&&t.predictPhysics!==!1;function K1(){let t=typeof navigator>"u"?"":String(navigator.userAgent??"");return/Mobi|Android|iPhone|iPad/i.test(t)?Pd.mobile:Pd.desktop}async function X1(t){if(t.url)return[t.url];let e=tS(t.regions,t.urls);if(e.length===0)throw new Error("genex multiplayer: `urls` must contain at least one authority server URL");return(await oS(e,t.probe===void 0?{}:{probe:t.probe})).map(r=>r.url)}async function J1(t,e){let n=uS(e);if("refused"in n)throw new TypeError(`genex multiplayer: this room cannot be asked for (${n.refused})`);let r=await X1(t),s=t.capacityRetryMs??$1,o={region:0,refused:0,step:0};for(;;){let i=r[o.region];try{return{room:await NR(new Br(i),t,n),url:i,targets:r}}catch(a){if(n.method===Sr.JoinById){let d=lS(Wd(a),o.region,r.length);d===null&&vR(a),o={region:d,refused:0,step:0};continue}let c=rS(Wd(a));if(c===Ni.NextRegion&&o.region+1<r.length){o={region:o.region+1,refused:0,step:o.step};continue}let u=c===Ni.Capacity?sS(o,r.length,s):null;u===null&&vR(a);let l=u.attempt.waitMs;l>0&&await new Promise(d=>setTimeout(d,l)),o=u.state}}}var DR=t=>ER(t.fast??SR());function NR(t,e,n){let r=DR(e).open===void 0?[]:[dn.FAST,dn.FAST_RETURN],s={...dc(e.room,e.name,e.auth),...n.options,[Wp.CAPS]:IR(e)?[dn.PHYSICS,dn.PHYSICS_PREDICT,dn.INPUT_REPEAT,dn.LIFTS,dn.INPUT_TICK,...r]:[dn.PHYSICS,dn.INPUT_REPEAT,dn.LIFTS,dn.INPUT_TICK,...r],[Wp.SDK]:k0,protocol:4};return n.method===Sr.JoinById?t.joinById(n.roomId,s):n.method===Sr.Create?t.create(co.AUTHORITY,s):t.joinOrCreate(co.AUTHORITY,s)}function Qi(t){if(!t)return null;let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n=e.name,r=bc(n);if(r===void 0)return null;let s=Di(n,e.params);return{name:n,definition:r,params:s}}function wm(t,e){let{definition:n,params:r}=t,s=[...n.fields,...n.reads],o=n.fields;return{fields:s,step:(i,a,c,u)=>{let l=n.step(i,a,c,r,e,u);for(let d of o)i[d]=l[d]}}}var Sm=t=>t!==null&&t.definition.world?t.params.world??null:null,fe=(t,e)=>typeof t=="number"&&Number.isFinite(t)?t:e;function Z1(t){if(typeof t.inMoveX=="number")return{moveX:fe(t.inMoveX,0),moveY:fe(t.inMoveY,0),moveZ:fe(t.inMoveZ,0),yaw:fe(t.inYaw,0),pitch:fe(t.inPitch,0),buttons:fe(t.inButtons,0)}}var xm={body:!1,qx:0,qy:0,qz:0,qw:1,sleep:!1},MR=new Map,CR=2*Math.PI,vo=t=>t-CR*Math.floor((t+Math.PI)/CR),CH=[gn.Predicted,gn.Separate,gn.Timeline],Q1=gn.Predicted,ea=t=>{let e=t;return typeof e.local=="object"&&typeof e.error=="object"&&typeof e.prev=="object"&&typeof e.renderAlpha=="function"?e:null};async function BR(t){let e=await J1(t,t.matchKey===void 0?{}:{matchKey:t.matchKey});return eD(LR(xs(e.room),t,e.url),t,e,!1)}function eD(t,e,n,r){if(e.rejoin===!1)return t;let s=n.targets.filter(o=>o!==n.url);return mS(t,{closed:r,targets:[n.url,...s],join:async(o,i,a)=>{let c=await NR(new Br(o),e,tD(i,a)),u=LR(xs(c),e,o);return await pc(c,hn.firstStateTimeoutMs),u}})}function tD(t,e){return t===Li.Room?{method:Sr.JoinById,roomId:e.roomId,options:{}}:t===Li.Successor?{method:Sr.JoinOrCreate,options:hS({lostRoomId:e.roomId,matchKey:e.matchKey,closed:e.closed})}:{method:Sr.JoinOrCreate,options:e.matchKey===""?{}:{matchKey:e.matchKey}}}function LR(t,e,n){let r=t.state,s=()=>r.entities??MR,o=()=>r.players??MR,i=e.renderDelayMs??Ss.RENDER_DELAY_MS,a=t.input({type:__,mode:"reliable",renderDelay:i}),c=DR(e),u=gR({room:t,handle:a,open:c.open,neverAsked:c.fallback,off:e.fast===!1,log:e.fastLog??yR,now:e.fastClock??(()=>performance.now()),tickHz:()=>X(),stateCurrent:()=>!Jn}),l=null,d=gt.On,f=()=>{let g=r.preset??"";return g!==l&&(l=g,d=A_(g)),d},h=()=>v_(u.ack(),o().get(t.sessionId)?.inRep,a.sentCount,f()),p=g=>a.at(g)??u.inputAt(g),y=O_(),S=()=>{let g=M_(u.ack(),o().get(t.sessionId)?.inRep,f()),_=a.sentCount,T=g<_&&u.inputAt(g+1)!==void 0;return I_(y,g,_,a.replayBufferSize,T)},b=new Map,x=new Proxy(a,{get(g,_){if(_==="lastProcessed")return S();if(_==="pendingCount")return a.sentCount-u.ack();if(_==="at")return p;let T=Reflect.get(g,_,g);if(typeof T!="function")return T;let z=b.get(_);return z===void 0&&(z=T.bind(g),b.set(_,z)),z}}),R=ao.get(t,{mode:"lerp",delay:i}),A={mode:"lerp",fields:["x","y","z"]},E={mode:"lerp",fields:["yaw"],angle:!0};R.attachAll("entities",A),R.attachAll("entities",E),R.attachAll("entities",{mode:"lerp",fields:["pitch"]}),R.attachAll("entities",{mode:"lerp",fields:["duck"]});let P={moveX:0,moveY:0,moveZ:0,yaw:0,pitch:0,buttons:0},k={inputsSent:0,inputsDropped:0,reconciles:0,visibleCorrections:0,correctionBuckets:Od.map(()=>0).concat(0),peakCorrection:0,lastCorrection:0,peakStateCorrection:0,reseeds:0,bodyStates:0,bodySnaps:0,peakBodyCorrection:0,projectilesPredicted:0,projectilesConfirmed:0,projectilesRejected:0,lastProjectileLeadMs:0},M=new Map,B=(g,..._)=>{for(let T of M.get(g)??[])T(..._)},K=!0,j=!1,L=null,se=!0,v=()=>{L?.predicted?.reconciler.dispose(),L=null},$=e.world===void 0?yc:mo(e.world),G="no_entity",W="",q=typeof e.physics=="string"?e.physics:"",ae="",ce=()=>{if(e.predict===!1)return{prediction:null,reason:"off"};if(e.predict)return{prediction:e.predict,reason:""};let g=Qi(r.preset);if(g===null)return{prediction:null,reason:"no_preset"};let _=Sm(g);if(_!==null&&_!==$.hash){let T=`${_}/${$.hash}`;return W!==T&&(W=T,console.warn(`[multiplayer] the room's ${g.name} world (hash ${_}) is not this client's (hash ${$.hash}): your own entity is drawn from the server without prediction. Pass the room module's world to session.setWorld().`)),{prediction:null,reason:"world_mismatch"}}return{prediction:wm(g,$),reason:""}},ne=()=>{let g=[];for(let[_,T]of s())_===L?.id||T.owner===""||jr(T)||r.bodies?.has(_)===!0||!o().has(T.owner)||g.push({id:_,x:T.x,y:T.y,z:T.z,vx:T.vx,vy:T.vy,vz:T.vz,yaw:T.yaw,spin:fe(T.spin,0)});return g},Re=null,oe=()=>{if(e.contacts!==void 0)return null;let g=r.preset??"";return(Re===null||Re.text!==g||Re.hash!==$.hash)&&(Re={text:g,hash:$.hash,contacts:r_(g,$)}),Re.contacts},ee=()=>e.contacts!==void 0||oe()!==null,ue=e.contacts??((g,_)=>oe()?.rule(g,_)),Ae=e.contactPass??(e.contacts===void 0?g=>oe()?.pass(g):void 0),pt=new Td(ue,()=>Ms(ne())),Bt=()=>e.seatDrawing??oe()?.policy.drawing??Q1,_r=e.seatDrawing===void 0||e.seatDrawing===gn.Predicted?qd(ue):null,Gn=()=>ee()?_r:null,Co=()=>Bt()===gn.Predicted?Gn():null;function Ms(g){return oe()===null?g:g.map(_=>({..._,flags:fe(s().get(_.id)?.flags,0)}))}let na=(g,_,T=null)=>{if(L===null||!ee())return null;let z={..._,id:L.id,...oe()===null?{}:{flags:fe(L.entity.flags,0)}},H=Gn(),U=null;H!==null?U=H.apply(g,h(),r.tick??0,z,X(),T):pt.apply(g,h(),z,X());for(let re of Eo)typeof z[re]=="number"&&(_[re]=z[re]);return U};function qd(g){let _=null,T=()=>{let H=r.preset??"";if(_!==null&&_.text===H&&_.hash===$.hash)return _;let U=Qi(H),re=Sm(U),J=U!==null&&(re===null||re===$.hash)?wm(U,$):null;return _={text:H,hash:$.hash,fields:U===null?[]:[...U.definition.fields,...U.definition.reads],step:J===null?void 0:(ge,le,me,wt)=>J.step(ge,Xi({...le}),me,wt)},_},z=()=>{let{fields:H}=T(),U=[];for(let[re,te]of s()){if(re===L?.id||te.owner===""||jr(te)||r.bodies?.has(re)===!0)continue;let J=o().get(te.owner);if(J===void 0)continue;let ge=te,le={x:te.x,y:te.y,z:te.z,vx:te.vx,vy:te.vy,vz:te.vz,yaw:te.yaw,spin:fe(te.spin,0)};for(let me of H)le[me]=fe(ge[me],me==="cap"?1:0);oe()!==null&&(le.flags=fe(te.flags,0)),U.push({id:re,epoch:te.epoch,body:le,input:Z1(J)})}return U};return new Dd({rule:g,pass:Ae,others:z,step:()=>T().step,seatRule:e.seatRule,lifts:()=>{let H=bn();return H===null?null:{lifts:H,starts:ct(),cache:Gd}},remote:()=>{let H=Ls();return{predict:H?.remotePredict??Zt.HOLD,decayMs:H?.remoteDecayMs??xr.DEFAULT_REMOTE_DECAY_MS}},maxAheadMs:()=>(Ls()?.leadMs??xr.DEFAULT_LEAD_MS)+m_})}let An=null,bn=()=>{let g=r.preset??"",_=oe();if(An===null||An.text!==g||An.hash!==$.hash||An.heads!==_){let T=_!==null&&tx(_.policy)?{policy:_.policy,env:_.env}:void 0;An={text:g,hash:$.hash,heads:_,lifts:xx(g,$,T,X())}}return An.lifts},Yn={text:void 0,starts:void 0},ct=()=>{let g=r.lifts;return Yn.text!==g&&(Yn={text:g,starts:_x(g)}),Yn.starts},Kn=new Vi,Gd=new Vi,Wc=g=>{let _=Gn();return ne().map(T=>{let z=_?.poseAt(T.id,g-1),H=fe(s().get(T.id)?.flags,0),U=fe(s().get(T.id)?.duck,0);return z===void 0?{...T,duck:U,flags:H}:{id:T.id,x:z.x,y:z.y,z:z.z,vx:z.vx,vy:z.vy,vz:z.vz,yaw:z.yaw,duck:U,flags:H}})},qc=["x","y","z"],en=["vx","vy","vz"],Pn=(g,_,T,z,H)=>{if(L===null)return null;let U=z,re={id:L.id,x:U.x??0,y:U.y??0,z:U.z??0,vx:U.vx??0,vy:U.vy??0,vz:U.vz??0,yaw:U.yaw??0,duck:U.duck??0,flags:fe(L.entity.flags,0)},J=[...g.heads===void 0?[]:Wc(_),re].sort((le,me)=>le.id<me.id?-1:le.id>me.id?1:0),ge=vc(g,J,T,ct(),H,Kn);for(let le of qc)U[le]=re[le];return g.vehicle&&(U.yaw=re.yaw),{t:ge,mine:re}},bt=Number.NaN,Xr=null,ra=null,Jr=(g,_,T,z,H,U)=>{let re=Gi(r.tick??0,h(),_),te=bn(),J=te===null?null:Pn(te,_,U??re,T,H);e.seatRule?.(T,re,_),g(T,Xi(z),H,J===null?void 0:Mc(J.t,J.mine.id));let ge=J===null?-1:J.t.seats.indexOf(J.mine),le=J===null?null:J.t.report.on[ge]??null,me=na(_,T,le);if(te===null||J===null)return;me!==null&&Ex(te,J.t,ge,me);let wt=T;Xr=le;for(let nn of[...qc,...en])J.mine[nn]=wt[nn]??0;Cc(te,J.t,ct());for(let nn of en)wt[nn]=J.mine[nn]},sa=new Vi,oa=(g,_,T,z,H)=>{let U=bn();U===null||U.policy.platforms.length===0?g(_,T,z):Ax(U,ct(),sa,(re,te)=>g(re,T,z,te),_,H,z)},Cs=g=>{let{prediction:_,reason:T}=ce();if(G=T,!_)return null;let z=_.fields??W1;return{reconciler:R.reconciler(g,{input:x,fields:z,step:(U,re,te)=>{(U.isReplay||Number.isNaN(bt))&&(bt=Gi(r.tick??0,h(),U.tick)-U.tick),Xr=null,Jr(_.step,U.tick,re,te,U.dt,U.tick+bt),ra=Xr}}),fields:z,step:_.step}},Os=()=>{let g=L?.predicted;if(!L||!g)return null;let _=L.entity,T={};for(let U of g.fields)T[U]=fe(_[U],0);let z=a.stepSeconds??g.reconciler.stepMs/1e3,H=new Map;for(let U=h()+1;U<=a.sentCount;U++){let re=p(U);re!==void 0&&(Jr(g.step,U,T,re,z),H.set(U,{p:[T.x??0,T.y??0,T.z??0],v:[T.vx??0,T.vy??0,T.vz??0]}))}return H},Is=g=>{g.predicted&&(k.reseeds++,Oo(g))},Oo=g=>{g.predicted?.reconciler.dispose();let _=Cs(g.entity);if(g.predicted=_,!_)return;let T=_.reconciler.state,z=a.stepSeconds??_.reconciler.stepMs/1e3;bt=Gi(r.tick??0,h(),0);for(let H=h()+1;H<=a.sentCount;H++){let U=p(H);U!==void 0&&Jr(_.step,H,T,U,z)}g.reseeded=!0},ia=(g,_)=>_.owner===t.sessionId&&!jr(_)&&r.bodies?.has(g)!==!0,Zr=g=>s().get(g.id)===g.entity&&ia(g.id,g.entity),Qr=()=>{if(L&&Zr(L)){L.entity.epoch!==L.epoch&&(L.epoch=L.entity.epoch,Is(L));return}if(!(!L&&!se)){v(),se=!1,G="no_entity";for(let[g,_]of s())if(ia(g,_)){L={id:g,entity:_,epoch:_.epoch,predicted:Cs(_),reseeded:!1};return}}},tt=g=>{let _=g.reconciler.state;return g.fields.map(T=>_[T]??0)},Io=(g,_,T)=>{if(g.reconciler.reconcileSeq===T)return;let{place:z,state:H}=o_(g.fields,_,tt(g));k.reconciles++,k.lastCorrection=z,k.peakCorrection=Math.max(k.peakCorrection,z),k.peakStateCorrection=Math.max(k.peakStateCorrection,H);let U=Im();i_(z,U)&&(k.visibleCorrections++,k.correctionBuckets[a_(z,U)]+=1)},Gc=g=>{if(!g.fields.includes("yaw"))return null;let _=ea(g.reconciler),T=_?.local.yaw;return _&&typeof T=="number"?{local:T,error:_.error.yaw??0}:null},Yc=(g,_,T)=>{if(T===null||g.reconciler.reconcileSeq===_)return;let z=ea(g.reconciler),H=z?.local.yaw,U=z?.error.yaw;if(!z||typeof H!="number"||typeof U!="number")return;let re=T.local+T.error-H;(re<-Math.PI||re>=Math.PI)&&(z.error.yaw=vo(re)*(U/re))},Kc=g=>{let _=ea(g.reconciler);if(_===null||Number.isNaN(bt))return null;let T=z=>Object.fromEntries($d.map(H=>[H,fe(z[H],0)]));return{offset:bt,local:T(_.local),error:T(_.error),prev:T(_.prev)}},Xc=(g,_,T,z)=>{if(z===null||g.reconciler.reconcileSeq===_||z.offset===bt)return T;let H=bn(),U=ea(g.reconciler);if(H===null||H.policy.platforms.length===0||U===null)return T;let re=ct(),te=a.sentCount+z.offset+1,J=a.sentCount+bt+1,ge=qe=>({x:qe.x??0,y:qe.y??0,z:qe.z??0,yaw:qe.yaw??0,duck:fe(U.local.duck,0)}),le=Oc(H,ge(z.local),te,re);if(le<0||Oc(H,ge(U.local),J,re)!==le)return T;let me=(qe,wn,er)=>{let Tn=Vh(H.policy,le,ge(qe),wn,er,re);return{...Tn,yaw:H.vehicle?Tn.yaw:qe.yaw??0}},wt=Object.fromEntries($d.map(qe=>[qe,(z.local[qe]??0)+(z.error[qe]??0)])),nn=me(wt,te,J),kt=me(z.prev,te-1,J-1),zo=me(z.local,te,J);for(let qe of $d){if(typeof U.local[qe]!="number")continue;let wn=fe(U.local[qe],0),er=(wt[qe]??0)-wn,Tn=er===0?0:(U.error[qe]??0)/er;U.error[qe]=(nn[qe]-wn)*Tn,U.prev[qe]!==void 0&&(U.prev[qe]=kt[qe])}return g.fields.map((qe,wn)=>$d.includes(qe)?zo[qe]:T[wn]??0)},Ve=g=>{let _=L?.entity===g?L.predicted:null;if(!_||!_.fields.includes("yaw"))return;let T=ea(_.reconciler),z=T?.local.yaw;if(!T||typeof z!="number")return;let H=z+(T.error.yaw??0),U=T.prev.yaw??H;return U+vo(H-U)*T.renderAlpha()},es=D_(),Ds=Number.NaN,Do=g=>{let _=a.stepMs??0,T=o().get(t.sessionId);N_(es,T?.inStarve,T?.inBuf,_,f());let z=Number.isNaN(Ds)?0:g-Ds;return Ds=g,L_(es,z,_)},Xn,Rr=g=>{let _=a.stepMs;if(!_)return 0;if(Xn===void 0)return Xn=g,0;let T=Math.floor((g-Xn)/_);return T>PR?(Xn=g,PR):(Xn+=T*_,T)},No=()=>Gi(r.tick??0,h(),0),Ns=null,Bs=g=>{if(!K)return k.inputsDropped+=g,0;let _=0,T=c_((Ns??No())+a.sentCount+1);for(let z=0;z<g;z++){let H=Xi({...P});Object.assign(a.data,H),a.data.tick=T;let U=a.send();if(U===0){k.inputsDropped++;continue}_++,u.sent(U,T,H)}return u.flush(),k.inputsSent+=_,_},Lt=t.clock,Jc=()=>Lt.lastServerTime()>0?Lt.lastServerTime():performance.now(),Et=()=>Lt.lastServerTime()>0?Lt.serverNow()-i-Lt.smoothedRtt()/2:performance.now()-i,Bo=new WeakMap,Lo=g=>({x:g.x,y:g.y,z:g.z,yaw:g.yaw,pitch:fe(g.pitch,0),duck:fe(g.duck,0)}),Zc=g=>{let _=Jc(),T=Bo.get(g);if(T===void 0){Bo.set(g,{at:_,epoch:g.epoch,pose:Lo(g),respawns:[]});return}T.epoch!==g.epoch&&g.owner!==t.sessionId&&T.respawns.push({from:T.at,at:_,epoch:T.epoch,pose:T.pose}),T.at=_,T.epoch=g.epoch,T.pose=Lo(g)},Qc=g=>{let _=Bo.get(g)?.respawns;if(_===void 0||_.length===0)return;let T=Et();for(;_.length>0&&T>=_[0].at;)_.shift();return _[0]},ts=new Bd,ns=new Set,aa={text:"",k:1},eu=g=>(aa.text!==g&&(aa={text:g,k:Nc(g)?.keyframeTicks??1}),aa.k),Fo={text:"\0",desc:null},Ls=()=>{let g=r.physDesc??"";return Fo.text!==g&&(Fo={text:g,desc:Nc(g)}),Fo.desc},w=()=>e.remoteSamples!=="patch"&&(r.physDesc??"")!=="",C=()=>{if(ns.size===0)return;let g=r.tick??0;if(w()&&g===(r.keyframe??-1)){let T=ad(g,we(),X()),z=1e3/X()*eu(r.physDesc??"");for(let H of ns)ts.push(H,T,Lo(H),z,H.epoch)}ns.clear()},V=Ja(t);V(r).entities.onAdd(g=>{se=!0,Zc(g),ns.add(g),V(g).onChange(()=>{Zc(g),ns.add(g)})}),t.onStateChange(C),V(r).entities.onRemove(()=>{se=!0});let X=()=>a.stepMs?Math.round(1e3/a.stepMs):Ss.TICK_HZ,we=()=>r.tickOrigin??0,pe=()=>vh(Lt.serverNow(),we(),X()),Me=g=>({x:g.x,y:g.y,z:g.z,vx:g.vx,vy:g.vy,vz:g.vz,g:g.g??0,t0:g.t0??0}),ie=g=>ad(g.t0??0,we(),X()),Ne=R.spawns("entities",{owned:g=>jr(g)&&g.src===t.sessionId,correlate:(g,_)=>s().get(g.id)!==_?!1:(ut.delete(g),k.projectilesConfirmed++,k.lastProjectileLeadMs=ie(_)-g.at,!0),spawnTime:ie,ttl:g=>{let _=Math.max(2*g,TR);if(!K)return _;let T=performance.now(),z=T-nt.endedAt<_+nt.ms?nt.ms:0;return _+Math.max(T-ze,z)},onReject:g=>{ut.delete(g),k.projectilesRejected++}}),ze=performance.now(),nt={ms:0,endedAt:0},ut=new Map,Qe=()=>{if(ut.size===0)return;let g=u.settleAck();for(let[_,T]of ut)_.epoch!==a.epoch||_.seq>g||s().has(_.id)||(ut.delete(_),T(),k.projectilesRejected++)},Jn=!1,Zn=()=>{Jn=!1;for(let[g,_]of ut)g.epoch!==a.epoch&&(ut.delete(g),_(),k.projectilesRejected++)};t.onStateChange(()=>{let g=performance.now();(g-ze>nt.ms||g-nt.endedAt>TR+nt.ms)&&(nt={ms:g-ze,endedAt:g}),ze=g,Jn&&Zn(),Qe()});let rt=new Map,Er=()=>{let g=fe(r.lengthUnit,0);return{tickHz:X(),tickOrigin:we(),lengthUnit:g>0?g:1}},Yd=g=>({x:g.x,y:g.y,z:g.z,qx:fe(g.qx,0),qy:fe(g.qy,0),qz:fe(g.qz,0),qw:fe(g.qw,0),lvx:fe(g.lvx,0),lvy:fe(g.lvy,0),lvz:fe(g.lvz,0),avx:fe(g.avx,0),avy:fe(g.avy,0),avz:fe(g.avz,0),sleep:g.sleep===!0,epoch:g.epoch}),tu=()=>{let g=r.bodies;for(let[H,U]of rt)g?.get(H)!==U.descriptor&&rt.delete(H);if(g===void 0||g.size===0)return;let _=Lt.serverNow(),T=Er(),z=r.tick??0;for(let[H,U]of g){let re=s().get(H);if(re===void 0)continue;let te=rt.get(H),J=ES(Yd(re),z);if(te!==void 0&&PS(te.last,J)){te.entity=re;continue}let{drawing:ge,snap:le}=AS(te?.drawing??null,J,_,T);k.bodyStates++,le!==null?k.bodySnaps++:k.peakBodyCorrection=Math.max(k.peakBodyCorrection,Math.hypot(...ge.dp)),rt.set(H,{descriptor:U,entity:re,last:J,drawing:ge,handoff:te?.handoff??new _d})}};t.onStateChange(tu);let Qn=x_({enabled:IR(e),loadCore:e.physicsCore,state:r,sessionId:t.sessionId,staticWorld:()=>$,tickHz:X,sent:()=>a.sentCount,acked:()=>h(),ownId:()=>L?.id,ownPath:Os,bodyRule:e.bodyRule,headSlide:()=>{let g=oe()?.policy;return g?.headFriction===go.Slide?g.propSlide:null},kinematicRule:e.kinematicRule,lifts:()=>{let g=bn();return g===null||g.policy.platforms.length===0?null:{policy:g.policy,starts:ct()}},seatRule:e.seatRule,budgetMs:jx(e.physicsBudgetMs,K1()),contactPass:g=>oe()?.pass(g),motionKnown:g=>u.motionKnown(g),...typeof e.physicsClock=="function"?{clock:e.physicsClock}:{},..._r===null?{}:{seatPose:(g,_)=>{let T=Gn()?.poseAt(g,_);return T===void 0?void 0:{key:g,x:T.x,y:T.y,z:T.z,vx:T.vx,vy:T.vy,vz:T.vz}}},remoteStep:()=>{let g=Qi(r.preset??"");if(g===null)return;let{step:_}=wm(g,$);return(T,z,H,U)=>oa(_,T,Xi({...z}),H,U)}});t.onStateChange(()=>Qn.onState(Lt.serverNow()));let HR=()=>{let g=L?.predicted?.reconciler.state;return g===void 0?void 0:{p:[g.x??0,g.y??0,g.z??0],v:[g.vx??0,g.vy??0,g.vz??0]}},Pm=g=>(!rt.has(g)&&r.bodies?.has(g)===!0&&tu(),rt.get(g)),Kd=(g,_)=>{let T=Er(),z=Lt.serverNow(),H=Qn.draw(g,z),U=_.entity,re=_.descriptor?.kind,te=H===null&&e.kinematicRule!==void 0?$x(e.kinematicRule,g,z,T):null,J=_.handoff.draw(H??te??Ph(_.drawing,z,T),H!==null,U.epoch,z,kd(re),T.lengthUnit),[ge,le,me]=_.last.lv;return{id:g,kind:U.kind,owner:U.owner,x:J.p[0],y:J.p[1],z:J.p[2],yaw:vo(U.yaw),vx:ge*T.lengthUnit,vy:le*T.lengthUnit,vz:me*T.lengthUnit,hp:U.hp,flags:U.flags,epoch:U.epoch,data:U.data,t0:0,g:0,src:"",pitch:0,duck:0,mstate:0,cap:1,spin:0,fuel:0,body:!0,qx:J.q[0],qy:J.q[1],qz:J.q[2],qw:J.q[3],sleep:_.last.sleep,predicted:H!==null}},nu={epoch:-1,seq:0,n:0},Fs=g=>typeof g=="number"&&Number.isFinite(g)?Oe(Math.fround(g)):0,Tm=g=>{let _=Th(g.launch,pe(),X());return{id:g.id,kind:g.kind,owner:"",..._,yaw:0,hp:0,flags:0,epoch:0,data:"",t0:g.launch.t0,g:g.launch.g,src:t.sessionId,pitch:0,duck:0,mstate:0,cap:1,spin:0,fuel:0,...xm}},vm=()=>{let g=new Map;for(let _ of Ne.entries())_.state==="pending"&&_.local&&g.set(_.local.id,_.local);return g};t.onDrop(g=>{u.dropped(),K=!1,Jn=!0,B(jd.Reconnecting,{code:g})}),t.onReconnect(()=>{if(j){t.leave(!0).catch(()=>{});return}(async()=>(await pc(t,hn.firstStateTimeoutMs),!j&&(Jn&&Zn(),L?.predicted&&(L.predicted.reconciler.reset(),k.reseeds++),Xn=void 0,K=!0,B(jd.Reconnected))))()});let Mm=()=>{j=!0,K=!1,u.dispose(),v(),R.dispose(),Qn.dispose()};t.onLeave((g,_)=>{j||(Mm(),B(jd.Disconnect,g,P0(_)))}),t.onMessage("*",(g,_)=>{typeof g=="string"&&(e.onEvent?.(g,_),q1.has(g)||B(g,_))});let $R=g=>{if(!L?.reseeded||L.entity!==g||!L.predicted)return;let _=L.predicted.reconciler.state;return{x:_.x??g.x,y:_.y??g.y,z:_.z??g.z,yaw:_.yaw??g.yaw,pitch:_.pitch??fe(g.pitch,0),duck:_.duck??fe(g.duck,0),epoch:g.epoch}},jR=()=>{if(L===null||L.predicted===null)return null;let g=zm(L.entity);return{id:L.id,x:g.x,y:g.y,z:g.z,vx:0,vy:0,vz:0,yaw:g.yaw}},Cm=g=>{let T=L?.reseeded===!0&&L.predicted===g?1:ea(g.reconciler)?.renderAlpha()??1;return Math.max(0,a.sentCount-h()-1+T)},ru=new Map,tn=0,Om=()=>ee()&&Bt()!==gn.Timeline,Xd=g=>L?.entity!==g&&g.owner!==""&&!jr(g)&&o().has(g.owner),WR=(g,_)=>{let T=ru.get(g);return T!==void 0&&T.lives===_&&tn-T.at<=j1?T:void 0},su=new Map,Jd,ou=new Map,Zd=Number.NaN,ca={tick:Number.NaN,leadMs:Number.NaN},Im=()=>{let g=fe(r.lengthUnit,0);return g>0?g:yS[Qi(r.preset??"")?.name??""]??1},qR=()=>{let g=Co(),_=g?.current??null;if(g===null||_===null||L===null||L.predicted===null)return ca={tick:Number.NaN,leadMs:Number.NaN},null;let T=h(),z=Cm(L.predicted),H=B_(T,z,es,a.stepMs??0,tn);Jd=y_(Jd,H.raw,H.at,X());let U=Jd.seq,re=T+z,te=Number.isNaN(Zd)?0:tn-Zd;Zd=tn;let J=_.stateTick+(U-_.ack);ca={tick:J,leadMs:ad(J+1,we(),X())-Lt.serverNow()};let ge=Rt.SEAT_SNAP_METRES*Im(),le=new Map;for(let[me,wt]of s()){if(!Xd(wt))continue;let nn=g.motionAt(me,U);if(nn===void 0)continue;let kt=nn.pose,zo=su.get(me),qe=zo?.pass!=null&&zo.pass!==_?g.changeAt(me,U,zo.pass):void 0,wn=w_(zo,_,wt.epoch,qe,nn,te,g.touchingAt(me,U),ge,g.stateRate(me));su.set(me,wn);let er={x:kt.x+wn.dx,y:kt.y+wn.dy,z:kt.z+wn.dz,yaw:kt.yaw+wn.dyaw,pitch:fe(wt.pitch,0),duck:fe(wt.duck,0),epoch:wt.epoch},Tn=g_(ou.get(me),g.touchAheadMs(me,re)!==void 0,te);ou.set(me,Tn);let ua=Tn>0?g.motionAt(me,re)?.pose:void 0;ua!==void 0&&(er.x+=(ua.x-kt.x)*Tn,er.y+=(ua.y-kt.y)*Tn,er.z+=(ua.z-kt.z)*Tn,er.yaw+=vo(ua.yaw-kt.yaw)*Tn),le.set(me,{pose:er,at:kt})}for(let me of[...su.keys()])le.has(me)||su.delete(me);for(let me of[...ou.keys()])le.has(me)||ou.delete(me);return le},GR=g=>{if(!ee())return;let _=e.contacts===void 0?oe():null;return _===null||g===null?ue:_.drawRule(g.id)},YR=()=>{let g=new Map,_=Om()?jR():null,T=GR(_);if(T===void 0||_===null||L===null||L.predicted===null)return ru.clear(),ca={tick:Number.NaN,leadMs:Number.NaN},g;let z=Co()===null?null:qR(),H=[];for(let[J,ge]of s()){if(!Xd(ge))continue;let le=z?.get(J)?.pose??au(ge);g.set(J,le),H.push({id:J,x:le.x,y:le.y,z:le.z,vx:0,vy:0,vz:0,yaw:le.yaw,...oe()===null?{}:{flags:fe(ge.flags,0)}})}let U=new Map;for(let[J,ge]of g)U.set(J,`${L.entity.epoch}/${ge.epoch}`);for(let[J,ge]of g)for(let[le,me]of g)J<le&&U.set(Fc(J,le),`${ge.epoch}/${me.epoch}`);let re=new Map;for(let[J,ge]of U){let le=WR(J,ge);le!==void 0&&re.set(J,le)}let te=n_(T,_,H,re,tn);ru.clear();for(let[J,ge]of te.sides)ru.set(J,{...ge,lives:U.get(J)??""});for(let[J,ge]of te.drawn){let le=g.get(J);if(le===void 0)continue;let me=z?.get(J)?.at,wt=me===void 0?void 0:Math.hypot(ge.x-me.x,ge.y-me.y,ge.z-me.z);g.set(J,{...le,x:ge.x,y:ge.y,z:ge.z,...wt===void 0?{}:{correction:wt}})}return KR(g,_),g},iu=new Map,KR=(g,_)=>{let T=L?.entity;for(let[z,H]of g){let U=s().get(z),re=z===ra&&T!==void 0&&U!==void 0,te=re?[_.x-(T.x-U.x)-H.x,_.y-(T.y-U.y)-H.y,_.z-(T.z-U.z)-H.z,0]:[0,0,0,0],J=iu.get(z),ge=J===void 0?0:Math.exp(-Math.max(0,tn-J.at)/kR),le=AR(J,re?1:0,te,ge);iu.set(z,{k:re?1:0,shift:te,err:le,at:tn}),!(!re&&le.every(me=>Math.abs(me)<H1))&&g.set(z,{...H,x:H.x+te[0]+le[0],y:H.y+te[1]+le[1],z:H.z+te[2]+le[2]})}for(let z of[...iu.keys()])g.has(z)||iu.delete(z)},Qd=0;t.onStateChange(()=>{Qd++});let Dm,Nm=()=>{let g=Dm;if(g!==void 0&&g.at===tn&&g.states===Qd)return g.seats;let _=YR();return Dm={at:tn,states:Qd,seats:_},_},ef=null,Bm=()=>L?.predicted?(Number.isNaN(bt)?(r.tick??0)-h():bt)+h()+Cm(L.predicted)+1:Lm(),Lm=()=>(Et()-we())*X()/1e3,Fm=new WeakMap,XR=(g,_)=>{let T=bn();if(T===null||T.policy.platforms.length===0||!L?.predicted)return _;let z=Lm(),H=Bm(),U=ct(),re=(r.tick??0)+1,te=Oc(T,{x:g.x,y:g.y,z:g.z,duck:fe(g.duck,0)},re,U),J=te<0?_:{..._,...Vh(T.policy,te,_,z,H,U)};te>=0&&(J.z=Hh(T.policy,te,H,U)+(g.z-Hh(T.policy,te,re,U)));let ge=[J.x-_.x,J.y-_.y,J.z-_.z,J.yaw-_.yaw],le=Fm.get(g),me=tn,wt=le===void 0?0:Math.max(0,me-le.at),nn=Math.exp(-wt/kR),kt=AR(le,te,ge,nn);return Fm.set(g,{k:te,shift:ge,err:kt,at:me}),{..._,x:J.x+kt[0],y:J.y+kt[1],z:J.z+kt[2],yaw:J.yaw+kt[3]}},tf=null,JR=g=>{let _=au(g.entity);Oo(g);let T=au(g.entity);tf={dx:_.x-T.x,dy:_.y-T.y,dz:_.z-T.z,at:tn}},au=g=>{let _=ZR(g),T=L?.entity===g?tf:null;if(T===null)return _;let z=b_(T,tn-T.at);return z.done?(tf=null,_):{..._,x:_.x+z.dx,y:_.y+z.dy,z:_.z+z.dz}},ZR=g=>{let _=$R(g);if(_)return _;let T=Qc(g),z=R.value(g,"yaw"),U=(L?.entity!==g&&w()?ts.at(g,Et()):void 0)??{x:R.value(g,"x"),y:R.value(g,"y"),z:R.value(g,"z"),yaw:Ve(g)??z,pitch:fe(R.value(g,"pitch"),fe(g.pitch,0)),duck:fe(R.value(g,"duck"),fe(g.duck,0))};return T===void 0?{...L?.entity===g?U:XR(g,U),epoch:g.epoch}:{...Et()>T.from?T.pose:U,epoch:T.epoch}},zm=(g,_,T)=>(_!==void 0&&Om()&&Xd(g)?(T??Nm()).get(_):void 0)??au(g),QR=(g,_)=>{let T=Ne.entryFor(_),z=T?.local!==void 0&&_.src===t.sessionId?T.leadMs*X()/1e3:0,H=Th(Me(_),pe()+z,X());return{id:g,kind:_.kind,owner:_.owner,...H,yaw:vo(_.yaw),hp:_.hp,flags:_.flags,epoch:_.epoch,data:_.data,t0:_.t0,g:_.g,src:_.src,pitch:fe(_.pitch,0),duck:fe(_.duck,0),mstate:fe(_.mstate,0),cap:fe(_.cap,1),spin:fe(_.spin,0),fuel:fe(_.fuel,0),...xm}},nf={text:"",limit:Math.PI},eE=()=>{let g=r.preset??"";if(nf.text!==g){let _=Qi(g)?.params.pitchLimit;nf={text:g,limit:_===void 0?Math.PI:Math.fround(_)}}return nf.limit},tE=g=>{let _=eE(),T=vo(g);return T<-_?-_:T>_?_:T},rf=(g,_,T)=>L?.entity===g&&L.predicted?.fields.includes(_)?fe(L.predicted.reconciler.state[_],T):fe(g[_],T),sf=(g,_,T)=>{let z=Pm(g);if(z!==void 0)return Kd(g,z);if(jr(_))return QR(g,_);let H=zm(_,g,T);return{id:g,kind:_.kind,owner:_.owner,x:H.x,y:H.y,z:H.z,yaw:vo(H.yaw),vx:_.vx,vy:_.vy,vz:_.vz,hp:_.hp,flags:_.flags,epoch:H.epoch,data:_.data,t0:_.t0??0,g:_.g??0,src:_.src??"",pitch:tE(H.pitch),duck:H.duck<0?0:H.duck>1?1:H.duck,mstate:rf(_,"mstate",0),cap:fe(_.cap,1),spin:rf(_,"spin",0),fuel:rf(_,"fuel",0),...xm,...H.correction===void 0?{}:{predicted:!0,correction:H.correction}}};return{id:t.sessionId,url:n,input:P,frame(g=performance.now()){if(j)return 0;tn=g,u.poll(),Qn.settle(),Qr();let _=L?.predicted??null,T=_?tt(_):[],z=_?Gc(_):null,H=_?Kc(_):null,U=_?.reconciler.reconcileSeq??0,re=Do(g),te=R.tick(g)+re;if(!_){let ge=Bs(Rr(g)+re);return Qn.afterSend(void 0,Lt.serverNow()),Ns=No(),ge}Xn=void 0,Io(_,Xc(_,U,T,H),U),Yc(_,U,z);let J=Bs(te);return Qn.afterSend(HR(),Lt.serverNow()),Ns=No(),J>0&&L&&(L.reseeded=!1),(_r?.takeMissed()??[]).length>0&&L!==null&&JR(L),J},me(){return j||Qr(),L?sf(L.id,L.entity):void 0},code:t.roomId,get matchKey(){return r.matchKey??""},setWorld(g){let _=mo(g),T=_.hash!==$.hash;return $=_,T&&L&&!j&&Oo(L),$.hash},setPhysics(g){if(typeof g!="string")throw new TypeError("setPhysics: the hash is a string (the world's physicsHash)");return q=g,q},get physics(){let g=r.physics??"",_=g!==""&&g!==q;return _&&ae!==`${g}/${q}`&&(ae=`${g}/${q}`,console.warn(`[multiplayer] the room's physics world (hash ${g}) is not this client's (hash ${q||"none"}): your copy is never stepped from the room's state. Pass your world's physicsHash to session.setPhysics().`)),{reason:_?"physics_mismatch":"",physics:q,roomPhysics:g}},get physicsPrediction(){return Qn.status},drawTick(){return ca.tick},drawLead(){return ca.leadMs},liftPose(g){let _=bn();return _===null?void 0:kx(_.policy,g,Bm(),ct())},viewCarry(){let g=bn(),_=L?.predicted?L.predicted.reconciler.state:void 0;if(g===null||_===void 0)return ef=null,0;let T=Gi(r.tick??0,h(),a.sentCount)+1,z=Oc(g,{x:_.x??0,y:_.y??0,z:_.z??0,duck:_.duck??0},T,ct()),H=g.policy.platforms[z],U=ef;return ef=H===void 0?null:{k:z,tick:T},H===void 0||U===null||U.k!==z?0:Uh(H)*(T-U.tick)},get prediction(){j||Qr();let g=L?.predicted!=null,_=g?"":L?G:e.predict===!1?"off":"no_entity";return{predicting:g,reason:_,world:$.hash,roomWorld:Sm(Qi(r.preset??""))}},predictProjectile(g){if(!K)return"";let _=a.sentCount+1;(nu.epoch!==a.epoch||nu.seq!==_)&&(nu={epoch:a.epoch,seq:_,n:0});let T=o().get(t.sessionId)?.seqBase??0,z=`${t.sessionId}.${T+_}.${nu.n++}`,H=Lt.serverNow(),U=Fs(g.g),re={x:Fs(g.x),y:Fs(g.y),z:Fs(g.z),vx:Fs(g.vx),vy:Fs(g.vy),vz:Fs(g.vz),g:U<0?0:U>wc?wc:U,t0:vh(H,we(),X())},te={id:z,kind:String(g.kind),launch:re,at:H,seq:_,epoch:a.epoch},J=Ne.spawn(te);return ut.set(te,()=>J.cancel()),k.projectilesPredicted++,z},entity(g){let _=s().get(g);if(_)return sf(g,_);let T=Pm(g);if(T!==void 0)return Kd(g,T);let z=vm().get(g);return z?Tm(z):void 0},entities(){let g=new Map,_=Nm();for(let[T,z]of s())g.set(T,sf(T,z,_));for(let[T,z]of rt)g.has(T)||g.set(T,Kd(T,z));for(let[T,z]of vm())g.has(T)||g.set(T,Tm(z));return g},players(){let g=new Map;for(let[_,T]of o())g.set(_,{id:_,name:T.name,uid:T.uid,team:T.team,connected:T.connected,avatarUrl:T.avatarUrl});return g},get tick(){return r.tick??0},get connected(){return K},telemetry:k,fast:u.status,on(g,_){let T=M.get(g)??new Set;M.set(g,T);let z=_;return T.add(z),()=>{T.delete(z)}},async leave(){j||(Mm(),t.reconnection.enabled=!1,await t.leave(!0))}}}var nD=3,FR={ready:t=>ga.ready(t),auth:()=>Au(),urls:()=>Py(),regions:()=>Ty()},$c=FR;function rD(t){$c=t??FR}var zR;function sD(t){zR=t??void 0}var oD=Ss.MAX_REWIND_MS,iD=5,aD=3e4,cD=["moveX","moveY","moveZ","yaw","pitch","buttons"],ta=t=>typeof t=="number"&&Number.isFinite(t);function uD(t){return!Array.isArray(t)||t.length>iD?void 0:t.every(n=>ta(n)&&n>=0&&n<=aD)?t:void 0}function lD(t){let e=nr(t,"options"),n=typeof e.gameId=="string"?e.gameId:"";if(!n)throw new TypeError("genex bridge: `gameId` (the game slug) is required");let r=e.renderDelayMs,s=ta(r)&&r>=0&&r<=oD;return{gameId:n,name:typeof e.name=="string"&&e.name?e.name:void 0,urls:Array.isArray(e.urls)?e.urls.filter(o=>typeof o=="string"&&o!==""):[],predict:e.predict!==!1,predictPhysics:e.predictPhysics!==!1,renderDelayMs:s?r:void 0,capacityRetryMs:uD(e.capacityRetryMs),fast:e.fast===!1?!1:void 0}}var Em=new Map,dD=2**30,fD=dD,jc=t=>typeof t=="number"?Em.get(t):void 0,Mo=t=>{let e=jc(t);return e&&!e.closed?e.session:null};function km(t){t.closed=!0;for(let e of t.unwire.splice(0))e();t.session=null}function pD(t,e,n){ws(e)?e===xe.SERVER_RESTART&&ye(t,{type:"serverRestart"}):ye(t,{type:"message",kind:e,data:n??null})}async function hD(t){let e=t.opts;if(await $c.ready(e.gameId),t.closed)return;let n=e.urls.length?e.urls:$c.urls(),r=e.urls.length?[]:$c.regions?.()??[];if(!n.length&&!r.length)throw Object.assign(new Error("genex bridge: no authority server URL (pass urls, or run on a Genex page that serves authority rooms)"),{code:0});let s=await BR({urls:n,regions:r,room:e.gameId,name:e.name,auth:()=>$c.auth(),predict:e.predict?void 0:!1,physicsCore:zR,predictPhysics:e.predictPhysics,renderDelayMs:e.renderDelayMs,capacityRetryMs:e.capacityRetryMs,fast:e.fast,onEvent:(o,i)=>{t.closed||pD(t,o,i)}});if(t.closed){await s.leave();return}t.session=s,t.sessionId=s.id,t.world&&s.setWorld(t.world),t.unwire.push(s.on("reconnecting",({code:o})=>ye(t,{type:"reconnecting",code:o})),s.on("reconnected",()=>ye(t,{type:"reconnected"})),s.on("disconnect",o=>{km(t),ye(t,{type:"disconnected",code:o,reason:""})})),ye(t,{type:"joined",sessionId:s.id})}function mD(t){let e=lD(t),n=++fD,r={opts:e,q:[],overflowed:!1,session:null,unwire:[],roster:new Set,sessionId:"",closed:!1,world:null};return Em.set(n,r),hD(r).catch(s=>{r.closed||(km(r),ye(r,{type:"joinFailed",code:Jo(s),message:tr(s)}))}),n}function yD(t,e){let n=nr(e,"input"),r=Mo(t);if(!r)return!1;for(let s of cD){let o=n[s];ta(o)&&(r.input[s]=o)}return!0}function gD(t,e){let n=nr(e,"projectile"),r=Mo(t);if(!r)return"";let s=o=>ta(o)?o:0;return r.predictProjectile({kind:typeof n.kind=="string"?n.kind:"",x:s(n.x),y:s(n.y),z:s(n.z),vx:s(n.vx),vy:s(n.vy),vz:s(n.vz),...ta(n.g)?{g:n.g}:{}})}function bD(t,e){let n=nr(e,"world"),r=jc(t);if(!r||r.closed)return!1;let s;try{s=mo(n)}catch(o){return ye(r,Xo(tr(o))),!1}return r.world=s,r.session?.setWorld(s),!0}var wD=JSON.stringify({tick:0,sent:0,connected:!1,me:null,entities:[]});function SD(t,e){let n=Mo(t);if(!n)return wD;let r=n.frame(ta(e)?e:performance.now());return JSON.stringify({tick:n.tick,sent:r,connected:n.connected,me:n.me()??null,entities:[...n.entities().values()]})}var _m=8,Rm={PREDICTED:1,ASLEEP:2},xD=new Float32Array(0);function UR(t){return[...t.entities().values()].filter(e=>e.body).sort((e,n)=>e.id<n.id?-1:e.id>n.id?1:0)}function _D(t){let e=Mo(t);if(!e)return xD;let n=UR(e),r=new Float32Array(n.length*_m);return n.forEach((s,o)=>{let i=o*_m;r.set([s.x,s.y,s.z,s.qx,s.qy,s.qz,s.qw],i),r[i+7]=(s.predicted?Rm.PREDICTED:0)|(s.sleep?Rm.ASLEEP:0)}),r}function RD(t){let e=Mo(t);return JSON.stringify(e?UR(e).map(n=>n.id):[])}function ED(t){let e=jc(t),n=Mo(t);return JSON.stringify({sessionId:e?.sessionId??"",connected:!!n&&n.connected,closed:!e||e.closed,tick:n?.tick??0,queued:e?.q.length??0,players:n?[...n.players().values()]:[],telemetry:n?{...n.telemetry}:null,prediction:n?n.prediction:null,fast:n?n.fast:null,physicsPrediction:n?n.physicsPrediction:null})}function kD(t,e){let n=new Set(e.players().keys());for(let r of n)t.roster.has(r)||ye(t,{type:"playerJoined",id:r});for(let r of t.roster)n.has(r)||ye(t,{type:"playerLeft",id:r});t.roster=n}function AD(t){let e=jc(t);if(!e)return"[]";try{let n=Mo(t);n&&kD(e,n)}catch(n){ye(e,Xo(tr(n)))}return Mu(e)}function VR(t){let e=jc(t);if(!e||e.closed)return;let n=e.session;km(e),n?.leave().catch(()=>{}),ye(e,{type:"disconnected",code:pn.CONSENTED,reason:"left"})}function PD(t){VR(t),typeof t=="number"&&Em.delete(t)}var TD=Object.freeze({...rh,...Am,initEmbed:ku});globalThis.GenexMultiplayerBridge=TD;})();