@usions/sdk 2.29.0 → 2.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -254,10 +254,24 @@ encode, decode }`.
254
254
  ```javascript
255
255
  Usion.requestPayment(amount, reason)
256
256
  Usion.share('image', { imageUrl, text })
257
+ await Usion.shareFile(reportUrl, {
258
+ filename: 'report.pdf',
259
+ mimeType: 'application/pdf',
260
+ title: 'Share report'
261
+ })
262
+ await Usion.download(reportUrl, 'report.pdf', {
263
+ destination: 'files', // 'auto' sends images/videos to the gallery
264
+ mimeType: 'application/pdf'
265
+ })
257
266
  Usion.exit() // Close the mini-app
258
267
  Usion.log(message) // Debug log
259
268
  ```
260
269
 
270
+ `shareFile` and `download` accept public HTTP(S) URLs and base64 data URLs
271
+ (inline data is capped at 10 MB; remote files at 100 MB). Call them from a user
272
+ gesture. Mobile WebViews cannot export iframe-local `blob:` URLs; convert small
273
+ blobs to data URLs or upload them first.
274
+
261
275
  ### Leaderboard (opt-in per game)
262
276
 
263
277
  Enable on the service (`leaderboard: { enabled: true, order: 'desc' }`), then:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usions/sdk",
3
- "version": "2.29.0",
3
+ "version": "2.31.0",
4
4
  "description": "Usion Mini App SDK for iframe games and services",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
package/src/browser.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! @usions/sdk v2.29.0 — minified build; source: packages/sdk/src/modules (github.com/ugshanyu/usionthemobile) */
2
- var Usion=function(){"use strict";const e={NOT_CONNECTED:"NOT_CONNECTED",NO_ROOM:"NO_ROOM",ROOM_NOT_FOUND:"ROOM_NOT_FOUND",NOT_PARTICIPANT:"NOT_PARTICIPANT",NOT_IN_ROOM:"NOT_IN_ROOM",NOT_AUTHORITY:"NOT_AUTHORITY",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",JOIN_TIMEOUT:"JOIN_TIMEOUT",CONNECT_TIMEOUT:"CONNECT_TIMEOUT",INIT_TIMEOUT:"INIT_TIMEOUT",MATCH_TIMEOUT:"MATCH_TIMEOUT",STATE_TOO_LARGE:"STATE_TOO_LARGE",INVALID_STATE:"INVALID_STATE",STALE_STATE:"STALE_STATE",INVALID_NEXT_TURN:"INVALID_NEXT_TURN",INVALID_INPUT:"INVALID_INPUT",NOT_FOUND:"NOT_FOUND",QUOTA_EXCEEDED:"QUOTA_EXCEEDED",VALUE_TOO_LARGE:"VALUE_TOO_LARGE",LOBBY_FULL:"LOBBY_FULL",LOBBY_CLOSED:"LOBBY_CLOSED",WORLD_FULL:"WORLD_FULL",CONFLICT:"CONFLICT",RATE_LIMITED:"RATE_LIMITED",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",QUEUE_FULL:"QUEUE_FULL",CANCELLED:"CANCELLED",SUPERSEDED:"SUPERSEDED",UNSUPPORTED:"UNSUPPORTED",UNKNOWN:"UNKNOWN"};class t extends Error{constructor(t,n){super(n||t),this.name="UsionError",this.code=e[t]?t:e.UNKNOWN,this.retryAfter=void 0}}const n=[[/not authenticated/i,e.NOT_AUTHENTICATED],[/room_id required|no room id/i,e.NO_ROOM],[/room not found/i,e.ROOM_NOT_FOUND],[/not in room/i,e.NOT_IN_ROOM],[/not a participant/i,e.NOT_PARTICIPANT],[/room authority/i,e.NOT_AUTHORITY],[/exceeds .*limit/i,e.STATE_TOO_LARGE],[/stale checkpoint|stale state/i,e.STALE_STATE],[/state must be/i,e.INVALID_STATE],[/next_turn must be/i,e.INVALID_NEXT_TURN],[/rate limit|too many/i,e.RATE_LIMITED],[/join timeout/i,e.JOIN_TIMEOUT],[/connection timeout|connect timeout/i,e.CONNECT_TIMEOUT],[/request timeout/i,e.REQUEST_TIMEOUT],[/not connected/i,e.NOT_CONNECTED],[/quota exceeded/i,e.QUOTA_EXCEEDED],[/value too large/i,e.VALUE_TOO_LARGE],[/lobby is full/i,e.LOBBY_FULL],[/lobby is not open/i,e.LOBBY_CLOSED],[/world room is full/i,e.WORLD_FULL],[/not found|unknown service/i,e.NOT_FOUND],[/conflict/i,e.CONFLICT],[/cancelled/i,e.CANCELLED],[/superseded/i,e.SUPERSEDED]];function r(r,i){if(r instanceof t)return r;if(r&&"object"==typeof r){const n="string"==typeof r.code&&e[r.code]?r.code:null,i=r.message||r.error;if(n){const e=new t(n,"string"==typeof i?i:n),o=null!=r.retry_after?r.retry_after:r.retryAfter;return"number"==typeof o&&isFinite(o)&&(e.retryAfter=o),e}r instanceof Error||"string"!=typeof i||(r=i)}const o=r&&r.message?r.message:String(r||"Unknown error");for(let e=0;e<n.length;e++)if(n[e][0].test(o))return new t(n[e][1],o);return new t(i||e.UNKNOWN,o)}let i=0;const o={};function s(){return++i}let c=null;function a(e){return"undefined"==typeof window||(!!window.ReactNativeWebView||(window.parent===window||(!e||!e.source||e.source===window.parent)&&(null===c&&(c=function(){try{if(window.location.ancestorOrigins&&window.location.ancestorOrigins.length)return window.location.ancestorOrigins[0]}catch(e){}try{if("undefined"!=typeof document&&document.referrer)return new URL(document.referrer).origin}catch(e){}return null}()),!(c&&e&&e.origin&&e.origin!==c))))}const u={version:"2.29.0",config:{},_initialized:!1,_initCallback:null,_messageHandlerRegistered:!1,_results:[],_backButtonCallback:null,init:function(n,i){const s=this;return n&&"object"==typeof n&&(i=n,n=null),i=i||{},s._initialized?(n&&n(s.config),Promise.resolve(s.config)):(n&&(s._initCallback=n),s._initPromise||(s._initPromise=new Promise(function(e,t){s._initResolve=e,s._initReject=t}),s._initPromise.catch(function(){})),i.timeout>0&&!s._initTimer&&(s._initTimer=setTimeout(function(){s._initTimer=null,!s._initialized&&s._initReject&&s._initReject(new t(e.INIT_TIMEOUT,"No INIT from host within "+i.timeout+"ms — host silent or running standalone"))},i.timeout)),s._messageHandlerRegistered||(s._messageHandlerRegistered=!0,window.addEventListener("message",function(e){if(!a(e))return;let t;try{t="string"==typeof e.data?JSON.parse(e.data):e.data}catch(e){return}if("INIT"===t.type&&t.config){if(s._initialized)return t.config.authToken&&(s.config.authToken=t.config.authToken,s.user&&(s.user._token=t.config.authToken)),void 0!==t.config.balance&&s.wallet&&(s.wallet._balance=t.config.balance),void(!0!==t.config.userIsAdult&&!1!==t.config.userIsAdult||!s.user||(s.config.userIsAdult=t.config.userIsAdult,s.user._isAdult=t.config.userIsAdult));s.config=t.config,s._initialized=!0,s._isEmbedded=!0,t.config.userId&&(s.user._id=t.config.userId,s.user._name=t.config.userName,s.user._avatar=t.config.userAvatar,s.user._token=t.config.authToken,s.user._isAdult=!0===t.config.userIsAdult||!1===t.config.userIsAdult?t.config.userIsAdult:null),t.config.sessionId&&(s.session._id=t.config.sessionId,s.session._data=t.config.sessionData||{}),void 0!==t.config.balance&&(s.wallet._balance=t.config.balance),t.config.results&&(s._results=t.config.results),s._initCallback&&s._initCallback(t.config),s._initTimer&&(clearTimeout(s._initTimer),s._initTimer=null),s._initResolve&&s._initResolve(t.config)}if(t._requestId&&o[t._requestId]){const{resolve:e,reject:n}=o[t._requestId];delete o[t._requestId],t.error?n(r(t)):e(t)}if("BALANCE_UPDATE"===t.type&&(s.wallet._balance=t.balance,s.wallet._balanceChangeHandler&&s.wallet._balanceChangeHandler(t.balance)),"BACK_BUTTON_PRESSED"===t.type&&s._backButtonCallback){var n=s._backButtonCallback;s._backButtonCallback=null,n()}if("BOT_MESSAGE"===t.type&&s.bot&&s.bot._messageHandler&&s.bot._messageHandler(t.message),"HOST_NAVIGATE"===t.type&&"string"==typeof t.path&&(s.config&&(s.config.launchPath=t.path),s._hostNavigateCallback&&s._hostNavigateCallback({path:t.path,tab:t.tab||null})),"BACKEND_EVENT"===t.type&&t.event&&s._backendHandlers){const e=s._backendHandlers[t.event];e&&e(t.data)}if("GAME_ROOM_ASSIGNED"===t.type&&t.roomId&&s.game){var i=t.roomId;s.config.roomId=i,s.config.mode="multiplayer",s.game._dispatch("roomAssigned",{roomId:i}),Promise.resolve().then(function(){return s.game.connect()}).then(function(){return s.game.join(i)}).catch(function(){})}}),this._setupInteractionBeacon(),this._post({type:"READY"})),s._initPromise)},_setupInteractionBeacon:function(){const e=this;if(e._interactionBeaconSetup)return;if(e._interactionBeaconSetup=!0,"undefined"==typeof window||!window.addEventListener)return;const t=["pointerdown","mousedown","touchstart","keydown"];function n(r){if(!(r&&!1===r.isTrusted||e._interactionReported)){e._interactionReported=!0;for(let e=0;e<t.length;e++)try{window.removeEventListener(t[e],n,!0)}catch(e){}e._post({type:"USER_INTERACTION"})}}for(let e=0;e<t.length;e++)try{window.addEventListener(t[e],n,{capture:!0,passive:!0})}catch(r){try{window.addEventListener(t[e],n,!0)}catch(e){}}},getTheme:function(){return this.config.theme||"light"},getLanguage:function(){return this.config.language||"en"},getLaunchParams:function(){var e=this.config||{},t="single"===e.mode||"multiplayer"===e.mode?e.mode:e.roomId?"multiplayer":"single";return{path:e.launchPath||null,ref:e.ref||e.launchRef||null,roomId:e.roomId||null,mode:t}},_post:function(e){const t=JSON.stringify(e);window.ReactNativeWebView?window.ReactNativeWebView.postMessage(t):window.parent!==window&&window.parent.postMessage(e,"*")},_request:function(n,r,i){const c=this;return i=i||5e3,new Promise(function(a,u){const l=s(),d=setTimeout(function(){delete o[l],u(new t(e.REQUEST_TIMEOUT,"Request timeout"))},i);o[l]={resolve:function(e){clearTimeout(d),a(e)},reject:function(e){clearTimeout(d),u(e)}},c._post({type:n,_requestId:l,...r})})}};var l="_d:",d="_migrated_v2";function f(e){return l+e}function _(e,t,n){return e._backendEmit(t,Object.assign({service_id:e.config&&e.config.serviceId,scope:"storage"},n))}function h(e,t){return e._request("STORAGE_GET",{key:t}).then(function(e){return e?e.value:null})}function p(e,t,n){return e._request("STORAGE_SET",{key:t,value:n})}function m(e,t){return e._request("STORAGE_REMOVE",{key:t})}function y(e){return e._request("STORAGE_KEYS",{}).then(function(e){return e&&e.keys||[]})}function g(e){return e.catch(function(){})}const v={setLoading:function(e,t){const n="string"==typeof e?document.querySelector(e):e;n&&(t?(n.classList.add("usion-btn-loading"),n.disabled=!0,n.dataset.originalText=n.textContent):(n.classList.remove("usion-btn-loading"),n.disabled=!1,n.dataset.originalText&&(n.textContent=n.dataset.originalText)))},toggle:function(e,t){const n="string"==typeof e?document.querySelector(e):e;n&&(t?(n.classList.remove("usion-hidden","hidden"),n.classList.add("usion-visible")):(n.classList.add("usion-hidden"),n.classList.remove("usion-visible")))},charCount:function(e,t,n){const r="string"==typeof e?document.querySelector(e):e,i="string"==typeof t?document.querySelector(t):t;function o(){const e=r.value.length;i.textContent=e+" / "+n,i.classList.remove("warning","error"),e>.9*n?i.classList.add("error"):e>.7*n&&i.classList.add("warning")}r&&i&&(r.addEventListener("input",o),o())},selectionGrid:function(e,t,n){const r=document.querySelector(e);if(!r)return;let i=null;return r.querySelectorAll(t).forEach(function(e){e.addEventListener("click",function(){r.querySelectorAll(t).forEach(function(e){e.classList.remove("selected")}),e.classList.add("selected"),i=e.dataset.value||e.dataset.id,n&&n(i,e)})}),{getSelected:function(){return i},clear:function(){r.querySelectorAll(t).forEach(function(e){e.classList.remove("selected")}),i=null}}}},b={requestPayment:function(e,t,n){return this.wallet.requestPayment(e,t,n)},diagnostics:function(){const e=this.game||{};return{version:this.version,transport:e.directMode?"direct":e._useProxy?"proxy":e.socket?"socket":"none",connected:!!e.connected,joined:!!e._joined,roomId:e.roomId||null,playerId:e.playerId||null,lastSequence:e._lastSequence||0,lastActionApplied:e._lastActionApplied||0,rejoining:!!e._rejoinPromise}},submit:function(e){this._post({type:"SUBMIT",data:e})},error:function(e){this._post({type:"ERROR",message:e})},exit:function(e){var t={type:"EXIT"};e&&"number"==typeof e.backCount&&e.backCount>1&&(t.backCount=e.backCount),this._post(t)},share:function(e,t){var n=Object.assign({},t,{contentType:e,serviceId:this.config.serviceId,serviceName:this.config.serviceName});this._post({type:"SHARE",contentType:e,data:n})},download:function(e,t){return this._request("DOWNLOAD_FILE",{url:e,filename:t||"download.mp4"},12e4)},log:function(e){this._post({type:"LOG",msg:e}),console.log("[Usion]",e)},on:function(e,t){function n(n){if(!a(n))return;let r;try{r="string"==typeof n.data?JSON.parse(n.data):n.data}catch(e){return}r.type===e&&t(r)}return window.addEventListener("message",n),function(){window.removeEventListener("message",n)}}};function E(e,t){var n={liveness:{probeAfterMs:4e3,deadAfterMs:12e3},backpressureBytes:8192,lastInboundAt:0,lastProbeAt:0,lastWatchdogAt:0,livenessGraceUntil:0,lastCloseCode:null,declaredDead:!1,watchdogTimer:null,drainTimer:null,pendingInput:null,visHandler:null,lastVisResyncAt:0,wrappedDisconnect:!1,rtt:null,jitter:0,quality:"dead"};function r(){if(null!=n.rtt)return{rtt:n.rtt,jitter:n.jitter};var t=e._pingMeter;return t&&null!=t.rtt?{rtt:t.rtt,jitter:t.jitter}:{rtt:null,jitter:null}}function i(){var t=function(){var t=e.getConnectionState?e.getConnectionState():e.connected?"connected":"disconnected";if(n.declaredDead||"disconnected"===t)return"dead";if(e.directMode&&(!e.directSocket||1!==e.directSocket.readyState))return"dead";var i=r().rtt||0,o=e.directMode&&n.lastInboundAt?Date.now()-n.lastInboundAt:0;return i<150&&o<2e3?"good":i<400&&o<5e3?"fair":"poor"}();if(t!==n.quality){var i=n.quality;n.quality=t,e._dispatch("networkQuality",{quality:t,prev:i,stats:e.getNetworkStats()})}}function o(){n.watchdogTimer&&(clearInterval(n.watchdogTimer),n.watchdogTimer=null)}function s(){var t=e.directSocket;if(t&&1===t.readyState){var r=Date.now(),i=function(){};i.sentAt=r,i.statsOnly=!0,e._pongWaiters.push(i),n.lastProbeAt=r,e._sendDirect("ping",{t:r})}}function c(){var r=e.directSocket;if(e.directMode&&r&&1===r.readyState){if(n.liveness){var c=Date.now(),a=n.lastWatchdogAt&&c-n.lastWatchdogAt>2e3;if(n.lastWatchdogAt=c,"undefined"!=typeof document&&"hidden"===document.visibilityState)return void(n.livenessGraceUntil=c+n.liveness.deadAfterMs);if(a)return n.livenessGraceUntil=c+n.liveness.deadAfterMs,s(),void i();var u=c-n.lastInboundAt;if(u>=n.liveness.deadAfterMs&&c>=n.livenessGraceUntil){n.declaredDead=!0,o(),t.log("Direct socket liveness timeout - declaring dead"),i(),e._dispatch("disconnect","liveness_timeout");try{r.close()}catch(e){}return}u>=n.liveness.probeAfterMs&&c-n.lastProbeAt>=n.liveness.probeAfterMs&&s()}i()}else o()}function a(){n.drainTimer=null;var t=e.directSocket;if(t&&1===t.readyState){if(null!=n.pendingInput)if(t.bufferedAmount>n.backpressureBytes)n.drainTimer=setTimeout(a,50);else{var r=n.pendingInput;n.pendingInput=null,e._sendDirect("input",r)}}else n.pendingInput=null}function u(){o(),n.drainTimer&&(clearTimeout(n.drainTimer),n.drainTimer=null),n.pendingInput=null,function(){n.visHandler&&"undefined"!=typeof document&&document.removeEventListener&&document.removeEventListener("visibilitychange",n.visHandler);n.visHandler=null}(),e._pongWaiters&&e._pongWaiters.length&&(e._pongWaiters=e._pongWaiters.filter(function(e){return!e.statsOnly}))}e._res=n,e.getNetworkStats=function(){var t=!!e.directMode,i=t?e.directSocket:null,o=r();return{transport:t?"direct":"relay",connectionState:e.getConnectionState?e.getConnectionState():"disconnected",quality:n.quality,rtt:o.rtt,jitter:o.jitter,lastInboundAgeMs:t&&n.lastInboundAt?Math.max(0,Date.now()-n.lastInboundAt):null,bufferedAmount:i?i.bufferedAmount||0:null}},e.onNetworkQuality=function(t){return e._setHandler("networkQuality",t)},e._resConfigure=function(e){if(!1===e.liveness)n.liveness=null;else{var t=e.liveness&&"object"==typeof e.liveness?e.liveness:{},r=isFinite(t.probeAfterMs)?Math.max(1e3,t.probeAfterMs):4e3,i=isFinite(t.deadAfterMs)?t.deadAfterMs:12e3;n.liveness={probeAfterMs:r,deadAfterMs:Math.max(i,r+2e3)}}!1===e.backpressureBytes||0===e.backpressureBytes?n.backpressureBytes=0:"number"==typeof e.backpressureBytes&&e.backpressureBytes>0&&(n.backpressureBytes=e.backpressureBytes)},e._resOnOpen=function(){if(n.declaredDead=!1,n.lastCloseCode=null,n.lastInboundAt=Date.now(),n.lastProbeAt=0,n.lastWatchdogAt=Date.now(),n.livenessGraceUntil=0,o(),n.watchdogTimer=setInterval(c,1e3),function(){if("undefined"==typeof document||!document.addEventListener||n.visHandler)return;n.visHandler=function(){if("visible"===document.visibilityState&&e.directMode&&e._joined){var t=Date.now();if(n.liveness&&(n.livenessGraceUntil=t+n.liveness.deadAfterMs),n.lastWatchdogAt=t,n.lastProbeAt=0,s(),t-n.lastVisResyncAt>=2e3){n.lastVisResyncAt=t;try{e.requestSync(e._lastSequence||0)}catch(e){}}}},document.addEventListener("visibilitychange",n.visHandler)}(),!n.wrappedDisconnect){n.wrappedDisconnect=!0;var t=e.disconnect;e.disconnect=function(){return u(),t.apply(e,arguments)}}i()},e._resOnClose=function(e){n.lastCloseCode=e&&"number"==typeof e.code?e.code:null,u(),i()},e._resOnPong=function(e){e&&"number"==typeof e.sentAt&&function(e){if(e>=0){if(null==n.rtt)return n.rtt=e,void(n.jitter=0);n.jitter+=.3*(Math.abs(e-n.rtt)-n.jitter),n.rtt+=.3*(e-n.rtt)}}(Date.now()-e.sentAt),i()},e._resCanReuseToken=function(){if(4401===n.lastCloseCode)return!1;var t=e.directConfig;if(!t||!t.ws_url||!t.access_token)return!1;var r=function(e){if("number"==typeof e&&isFinite(e))return e>1e12?e:1e3*e;if("string"==typeof e&&e){var t=Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(e)?e:e+"Z");return isNaN(t)?null:t}return null}(t.expires_at);return null!=r&&r-Date.now()>3e4},e._resHoldInput=function(t){if(!n.backpressureBytes)return!1;var r=e.directSocket;return!(!r||!(null!=n.pendingInput||r.bufferedAmount>n.backpressureBytes))&&(n.pendingInput=t,n.drainTimer||(n.drainTimer=setTimeout(a,50)),!0)},e.on("disconnect",i),e.on("connectionState",i)}function w(n,r,i,o,s){return o=o||1e4,s=s||e.REQUEST_TIMEOUT,new Promise(function(c,a){let u=!1;const l=setTimeout(function(){u||(u=!0,a(new t(s,s===e.JOIN_TIMEOUT?"Join timeout":"Game request timeout")))},o);try{n.emit(r,i,function(e){u||(u=!0,clearTimeout(l),c(e||{}))})}catch(e){if(u)return;u=!0,clearTimeout(l),a(e)}})}function T(e,t){return e._joinPromise=t,t.catch(function(){e._joined=!1,e._joinPromise===t&&(e._joinPromise=null)}),t}function S(e,t,n){let r=(t-e)%n;const i=n/2;return r>i&&(r-=n),r<-i&&(r+=n),r}function I(e,t,n,r){return"deg"===r?e+S(e,t,360)*n:"rad"===r?e+S(e,t,2*Math.PI)*n:e+(t-e)*n}class A{constructor(e=120){this._items=[],this._maxSize=e}add(e){this._items.push(e),this._items.length>this._maxSize&&this._items.shift()}get size(){return this._items.length}setMaxSize(e){this._maxSize=Math.max(2,0|e)}latest(){return this._items.length?this._items[this._items.length-1]:null}prevLatest(){return this._items.length>=2?this._items[this._items.length-2]:null}clear(){this._items=[]}straddle(e){const t=this._items;if(0===t.length)return[null,null];if(1===t.length)return[t[0],t[0]];if(e<=t[0].time)return[t[0],t[0]];const n=t[t.length-1];if(e>=n.time)return[n,n];for(let n=t.length-1;n>0;n--)if(t[n-1].time<=e&&e<=t[n].time)return[t[n-1],t[n]];return[n,n]}}function O(e,t){return t?Array.isArray(e[t])?e[t]:[]:Array.isArray(e)?e:[]}class k{constructor(e={}){const t=e.serverFps||20;this._frameMs=1e3/t,this.vault=new A(e.maxSize||120),this._fixedBuffer=null!=e.bufferMs?e.bufferMs:Math.ceil(3*this._frameMs),this._bufferMs=this._fixedBuffer,this._adaptive=!!e.adaptive,this._minBuffer=null!=e.minBufferMs?e.minBufferMs:Math.ceil(2*this._frameMs),this._maxBuffer=null!=e.maxBufferMs?e.maxBufferMs:Math.ceil(8*this._frameMs),this._extrapolationMs=e.extrapolationMs||0,this._useServerTime=!!e.serverTime,this._now=e.now||(()=>Date.now()),this._lastArrival=null,this._avgInterval=this._frameMs,this._jitter=0,this._offset=null}getBufferMs(){return this._bufferMs}setBufferMs(e){this._fixedBuffer=Math.max(0,0|e),this._bufferMs=this._fixedBuffer}getJitter(){return this._jitter}add(e){if(!e)return;const t=this._now(),n=void 0!==e.state?e.state:e,r=e.time;if(null!=this._lastArrival){const e=t-this._lastArrival;if(this._avgInterval+=.1*(e-this._avgInterval),this._jitter+=.1*(Math.abs(e-this._avgInterval)-this._jitter),this._adaptive){const e=this._avgInterval+2*this._jitter;this._bufferMs=Math.max(this._minBuffer,Math.min(this._maxBuffer,e))}}if(this._lastArrival=t,this._useServerTime&&"number"==typeof r){const e=t-r;this._offset=null==this._offset?e:this._offset+.05*(e-this._offset)}const i=this._useServerTime&&"number"==typeof r?r:t;this.vault.add({time:i,state:n})}_renderTime(){return this._useServerTime&&null!=this._offset?this._now()-this._offset-this._bufferMs:this._now()-this._bufferMs}calc(e,t){const n=this._renderTime(),r=this.vault.latest();if(!r)return null;const i=String(e||"").trim().split(/\s+/).filter(Boolean).map(e=>{const t=e.match(/^(.+?)\((deg|rad)\)$/);return t?{key:t[1],type:t[2]}:{key:e,type:"linear"}});if(n>r.time)return this._extrapolationMs>0?this._extrapolate(n,i,t):O(r.state,t).map(e=>Object.assign({},e));const[o,s]=this.vault.straddle(n);if(!o||!s)return null;let c=0;return s.time!==o.time&&(c=(n-o.time)/(s.time-o.time),c=c<0?0:c>1?1:c),this._blend(O(o.state,t),O(s.state,t),c,i)}_blend(e,t,n,r){const i={};for(let t=0;t<e.length;t++)i[e[t].id]=e[t];return t.map(e=>{const t=i[e.id],o=Object.assign({},e);if(t)for(let i=0;i<r.length;i++){const{key:s,type:c}=r[i],a=t[s],u=e[s];"number"==typeof a&&"number"==typeof u&&(o[s]=I(a,u,n,c))}return o})}_extrapolate(e,t,n){const r=this.vault.latest(),i=this.vault.prevLatest(),o=O(r.state,n);if(!i||r.time<=i.time)return o.map(e=>Object.assign({},e));const s=Math.min(e-r.time,this._extrapolationMs),c=r.time-i.time,a={},u=O(i.state,n);for(let e=0;e<u.length;e++)a[u[e].id]=u[e];return o.map(e=>{const n=a[e.id],r=Object.assign({},e);if(n)for(let i=0;i<t.length;i++){const{key:o}=t[i],a=n[o],u=e[o];if("number"==typeof a&&"number"==typeof u){const e=(u-a)/c;r[o]=u+e*s}}return r})}}class M{constructor(e={}){if("function"!=typeof e.apply)throw new Error("Predictor requires an apply(state, input) function");this._apply=e.apply,this._state=void 0!==e.initialState?e.initialState:null,this._seq=0,this._pending=[],this._smoothKeys=function(e){if(!e)return null;let t=null!=e.keys?e.keys:e;return"string"==typeof t&&(t=t.trim().split(/\s+/).filter(Boolean)),Array.isArray(t)&&t.length?t:null}(e.smooth),this._smoothRate=e.smooth&&null!=e.smooth.rate?e.smooth.rate:.2,this._snapTo=e.smooth&&null!=e.smooth.snapTo?e.smooth.snapTo:.001,this._error={}}get state(){return this._state}get pending(){return this._pending.slice()}get lastSeq(){return this._seq}predict(e){this._seq+=1;const t=this._seq;return this._pending.push({seq:t,input:e}),this._state=this._apply(this._state,e),{seq:t,state:this._state}}reconcile(e,t){const n=this._state,r=null==t?-1:t;this._pending=this._pending.filter(e=>e.seq>r);let i=e;for(let e=0;e<this._pending.length;e++)i=this._apply(i,this._pending[e].input);if(this._smoothKeys&&n&&i)for(let e=0;e<this._smoothKeys.length;e++){const t=this._smoothKeys[e];"number"==typeof n[t]&&"number"==typeof i[t]&&(this._error[t]=(this._error[t]||0)+(n[t]-i[t]))}return this._state=i,this._state}view(e){if(!this._smoothKeys||!this._state||"object"!=typeof this._state)return this._state;const t=null!=e?e:this._smoothRate,n=Array.isArray(this._state)?this._state.slice():Object.assign({},this._state);for(let e=0;e<this._smoothKeys.length;e++){const r=this._smoothKeys[e];let i=this._error[r]||0;"number"==typeof n[r]&&0!==i&&(n[r]=n[r]+i),i*=1-t,Math.abs(i)<this._snapTo&&(i=0),this._error[r]=i}return n}reset(e){this._state=void 0!==e?e:null,this._seq=0,this._pending=[],this._error={}}}class C{constructor(e={}){if("function"!=typeof e.onFlush)throw new Error("Coalescer requires an onFlush(entries) callback");this._onFlush=e.onFlush,this._hz=e.hz||20,this._setInterval=e.setInterval||("undefined"!=typeof setInterval?setInterval:null),this._clearInterval=e.clearInterval||("undefined"!=typeof clearInterval?clearInterval:null),this._order=[],this._slots={},this._timer=null,!1!==e.autoStart&&this.start()}get running(){return null!==this._timer}_ensure(e,t){let n=this._slots[e];return n||(n={mode:t,value:void 0,list:[]},this._slots[e]=n,this._order.push(e)),n}queue(e,t){const n=this._ensure(e,"latest");n.mode="latest",n.value=t}append(e,t){const n=this._ensure(e,"list");n.mode="list",n.list.push(t)}drain(){const e=[];for(let t=0;t<this._order.length;t++){const n=this._order[t],r=this._slots[n];if("latest"===r.mode)void 0!==r.value&&e.push({type:n,data:r.value});else for(let t=0;t<r.list.length;t++)e.push({type:n,data:r.list[t]})}return this._order=[],this._slots={},e}flush(){if(0===this._order.length)return;const e=this.drain();e.length&&this._onFlush(e)}start(){!this._timer&&this._setInterval&&(this._timer=this._setInterval(()=>this.flush(),Math.max(1,Math.round(1e3/this._hz))))}stop(){this._timer&&this._clearInterval&&this._clearInterval(this._timer),this._timer=null}}class N{constructor(e={}){this._alpha=null!=e.alpha?e.alpha:.2,this._now=e.now||(()=>Date.now()),this._rtt=null,this._jitter=0,this._last=null,this._id=0,this._outstanding={}}get rtt(){return this._rtt}get latency(){return null==this._rtt?null:this._rtt/2}get jitter(){return this._jitter}get last(){return this._last}begin(){const e=++this._id;return this._outstanding[e]=this._now(),e}end(e){const t=this._outstanding[e];return null==t?null:(delete this._outstanding[e],this.sample(this._now()-t))}sample(e){return e>=0?(null==this._rtt?this._rtt=e:(this._jitter+=this._alpha*(Math.abs(e-this._rtt)-this._jitter),this._rtt+=this._alpha*(e-this._rtt)),this._last=e,e):null}reset(){this._rtt=null,this._jitter=0,this._last=null,this._outstanding={}}}const R=[{urls:"stun:stun.l.google.com:19302"}];function P(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}class q{constructor(e={}){if("host"!==e.role&&"guest"!==e.role)throw new Error("MeshConnection requires role 'host' or 'guest'");if("function"!=typeof e.sendSignal)throw new Error("MeshConnection requires a sendSignal(payload) function");this.role=e.role,this._sendSignal=e.sendSignal,this._iceServers=e.iceServers||R,this._sequenced=!1!==e.sequenced,this._autoReconnect=!1!==e.autoReconnect,this._maxRestarts=null!=e.maxRestarts?e.maxRestarts:5,this._RTCPeerConnection=e.RTCPeerConnection||("undefined"!=typeof RTCPeerConnection?RTCPeerConnection:null),this._setTimeout=e.setTimeout||("undefined"!=typeof setTimeout?setTimeout:null),this.connected=!1,this._pc=null,this._unreliable=null,this._reliable=null,this._sendSeq=0,this._recvSeq=0,this._restarts=0,this.onOpen=null,this.onMessage=null,this.onClose=null,this.onError=null,this.onStateChange=null}static iceServers(e={}){const t=[{urls:e.stun||"stun:stun.l.google.com:19302"}];if(e.turn){const n={urls:e.turn};e.turnUsername&&(n.username=e.turnUsername),e.turnCredential&&(n.credential=e.turnCredential),t.push(n)}return t}async start(){if(!this._RTCPeerConnection)throw new Error("RTCPeerConnection unavailable");const e=new this._RTCPeerConnection({iceServers:this._iceServers});this._pc=e,e.onicecandidate=e=>{e&&e.candidate&&this._sendSignal({type:"ice",candidate:e.candidate})};const t=()=>this._handleStateChange(e.connectionState||e.iceConnectionState);e.onconnectionstatechange=t,e.oniceconnectionstatechange=t,"host"===this.role?(this._bindChannel(this._unreliable=e.createDataChannel("unreliable",{ordered:!1,maxRetransmits:0}),"unreliable"),this._bindChannel(this._reliable=e.createDataChannel("reliable",{ordered:!0}),"reliable"),await this._makeOffer(!1)):e.ondatachannel=e=>{const t=e.channel;"unreliable"===t.label?this._bindChannel(this._unreliable=t,"unreliable"):"reliable"===t.label&&this._bindChannel(this._reliable=t,"reliable")}}async _makeOffer(e){const t=this._pc,n=await t.createOffer(e?{iceRestart:!0}:void 0);await t.setLocalDescription(n),this._sendSignal({type:"offer",sdp:t.localDescription,restart:!!e})}_handleStateChange(e){if(this.onStateChange&&this.onStateChange(e),"connected"!==e){if(("failed"===e||"disconnected"===e||"closed"===e)&&(this.connected&&(this.connected=!1,this.onClose&&this.onClose()),this._autoReconnect&&"host"===this.role&&"closed"!==e&&this._restarts<this._maxRestarts)){this._restarts+=1;const e=Math.min(1e3*this._restarts,5e3);this._setTimeout&&this._setTimeout(()=>{this._makeOffer(!0).catch(e=>{this.onError&&this.onError(e)})},e)}}else this._restarts=0}async handleSignal(e){const t=this._pc;if(t&&e&&e.type)try{if("offer"===e.type){await t.setRemoteDescription(e.sdp);const n=await t.createAnswer();await t.setLocalDescription(n),this._sendSignal({type:"answer",sdp:t.localDescription})}else"answer"===e.type?await t.setRemoteDescription(e.sdp):"ice"===e.type&&e.candidate&&await t.addIceCandidate(e.candidate)}catch(e){this.onError&&this.onError(e)}}_bindChannel(e,t){e.binaryType="arraybuffer",e.onopen=()=>{"unreliable"!==t||this.connected||(this.connected=!0,this.onOpen&&this.onOpen())},e.onmessage=e=>{if(!this.onMessage)return;let n=e.data;if(P(n))this.onMessage(n,t);else{try{n="string"==typeof n?JSON.parse(n):n}catch(n){return void this.onMessage(e.data,t)}if("unreliable"===t&&this._sequenced&&n&&"number"==typeof n.__s){if(n.__s<=this._recvSeq)return;return this._recvSeq=n.__s,void this.onMessage(n.m,t)}this.onMessage(n,t)}},e.onclose=()=>{this.connected&&(this.connected=!1,this.onClose&&this.onClose())},e.onerror=e=>{this.onError&&this.onError(e)}}send(e){const t=this._unreliable;return!(!t||"open"!==t.readyState)&&(P(e)?(t.send(e),!0):(this._sequenced?(this._sendSeq+=1,t.send(JSON.stringify({__s:this._sendSeq,m:e}))):t.send("string"==typeof e?e:JSON.stringify(e)),!0))}sendReliable(e){const t=this._reliable;return!(!t||"open"!==t.readyState)&&(P(e)?t.send(e):t.send("string"==typeof e?e:JSON.stringify(e)),!0)}close(){try{this._unreliable&&this._unreliable.close()}catch(e){}try{this._reliable&&this._reliable.close()}catch(e){}try{this._pc&&this._pc.close()}catch(e){}this._unreliable=this._reliable=this._pc=null,this.connected=!1}}class j{constructor(e={}){if(!e.selfId)throw new Error("MeshNetwork requires a selfId");if("function"!=typeof e.sendSignal)throw new Error("MeshNetwork requires sendSignal(toPeerId, payload)");this.selfId=e.selfId,this._sendSignal=e.sendSignal,this._opts=e,this._peers={},this.onPeerOpen=null,this.onPeerClose=null,this.onMessage=null,this.onError=null}get peerIds(){return Object.keys(this._peers)}get connectedCount(){let e=0;for(const t in this._peers)this._peers[t].connected&&(e+=1);return e}peer(e){return this._peers[e]||null}_roleFor(e){return this.selfId<e?"host":"guest"}_ensurePeer(e){if(this._peers[e])return this._peers[e];const t=this,n=new q({role:this._roleFor(e),iceServers:this._opts.iceServers,RTCPeerConnection:this._opts.RTCPeerConnection,setTimeout:this._opts.setTimeout,sequenced:this._opts.sequenced,autoReconnect:this._opts.autoReconnect,sendSignal:n=>t._sendSignal(e,n)});return n.onOpen=()=>{t.onPeerOpen&&t.onPeerOpen(e)},n.onClose=()=>{t.onPeerClose&&t.onPeerClose(e)},n.onMessage=(n,r)=>{t.onMessage&&t.onMessage(e,n,r)},n.onError=n=>{t.onError&&t.onError(e,n)},this._peers[e]=n,n}async addPeer(e){if(e===this.selfId)return null;const t=this._ensurePeer(e);return await t.start(),t}async setRoster(e){const t={};for(let n=0;n<e.length;n++)e[n]!==this.selfId&&(t[e[n]]=!0);for(const e in t)this._peers[e]||await this.addPeer(e);for(const e in this._peers)t[e]||this.removePeer(e)}removePeer(e){const t=this._peers[e];if(t){try{t.close()}catch(e){}delete this._peers[e]}}async handleSignal(e,t){if(!e||e===this.selfId)return;const n=this._ensurePeer(e);n._pc||await n.start(),await n.handleSignal(t)}send(e,t){const n=this._peers[e];return!!n&&n.send(t)}sendReliable(e,t){const n=this._peers[e];return!!n&&n.sendReliable(t)}broadcast(e){for(const t in this._peers)this._peers[t].send(e)}broadcastReliable(e){for(const t in this._peers)this._peers[t].sendReliable(e)}close(){for(const e in this._peers)try{this._peers[e].close()}catch(e){}this._peers={}}}const D="undefined"!=typeof TextEncoder?new TextEncoder:null,U="undefined"!=typeof TextDecoder?new TextDecoder:null;function L(e){return(t=e)instanceof ArrayBuffer||ArrayBuffer.isView(t)?{type:0,bytes:e instanceof Uint8Array?e:new Uint8Array(e.buffer||e)}:{type:1,bytes:(n=JSON.stringify(e),D?D.encode(n):Uint8Array.from(Buffer.from(n,"utf8")))};var t,n}function x(e,t){if(1===e)try{return JSON.parse((n=t,U?U.decode(n):Buffer.from(n).toString("utf8")))}catch(e){return null}var n;return t}class B{constructor(){this._buf=new Uint8Array(0)}push(e){const t=e instanceof Uint8Array?e:new Uint8Array(e),n=new Uint8Array(this._buf.length+t.length);n.set(this._buf,0),n.set(t,this._buf.length),this._buf=n;const r=[];for(;this._buf.length>=4;){const e=new DataView(this._buf.buffer,this._buf.byteOffset,4).getUint32(0,!1);if(this._buf.length<4+e)break;const t=this._buf[4],n=this._buf.subarray(5,4+e);r.push(x(t,n.slice())),this._buf=this._buf.subarray(4+e)}return r}}class H{constructor(e={}){if(!e.url)throw new Error("WebTransportConnection requires a url");this._url=e.url,this._opts=e,this._sequenced=!1!==e.sequenced,this._WT=e.WebTransport||("undefined"!=typeof WebTransport?WebTransport:null),this.connected=!1,this._t=null,this._dgWriter=null,this._streamWriter=null,this._deframer=new B,this._sendSeq=0,this._recvSeq=0,this.onOpen=null,this.onMessage=null,this.onClose=null,this.onError=null}async connect(){if(!this._WT)throw new Error("WebTransport unavailable in this environment");const e={};this._opts.serverCertificateHashes&&(e.serverCertificateHashes=this._opts.serverCertificateHashes);const t=new this._WT(this._url,e);if(this._t=t,t.ready&&"function"==typeof t.ready.then&&await t.ready,t.datagrams&&t.datagrams.writable&&(this._dgWriter=t.datagrams.writable.getWriter()),"function"==typeof t.createBidirectionalStream)try{const e=await t.createBidirectionalStream();this._streamWriter=e.writable.getWriter(),this._pumpReadable(e.readable,"reliable")}catch(e){}t.datagrams&&t.datagrams.readable&&this._pumpDatagrams(t.datagrams.readable),t.closed&&"function"==typeof t.closed.then&&t.closed.then(()=>this._onClosed(),()=>this._onClosed()),this.connected=!0,this.onOpen&&this.onOpen()}async _pumpDatagrams(e){try{const t=e.getReader();for(;;){const{value:e,done:n}=await t.read();if(n)break;e&&this._onDatagramBytes(e)}}catch(e){this.onError&&this.onError(e)}}async _pumpReadable(e,t){try{const n=e.getReader();for(;;){const{value:e,done:r}=await n.read();if(r)break;if(e){const n=this._deframer.push(e);for(let e=0;e<n.length;e++)this.onMessage&&this.onMessage(n[e],t)}}}catch(e){this.onError&&this.onError(e)}}_onDatagramBytes(e){const t=function(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);return t.length<5?null:{seq:new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(0,!1),value:x(t[4],t.subarray(5))}}(e);if(t){if(this._sequenced){if(t.seq<=this._recvSeq)return;this._recvSeq=t.seq}this.onMessage&&this.onMessage(t.value,"datagram")}}send(e){if(!this._dgWriter)return!1;this._sendSeq+=1;try{return this._dgWriter.write(function(e,t){const{type:n,bytes:r}=L(t),i=new Uint8Array(5+r.length);return new DataView(i.buffer).setUint32(0,e>>>0,!1),i[4]=n,i.set(r,5),i}(this._sendSeq,e)),!0}catch(e){return!1}}sendReliable(e){if(!this._streamWriter)return!1;try{return this._streamWriter.write(function(e){const{type:t,bytes:n}=L(e),r=new Uint8Array(5+n.length);return new DataView(r.buffer).setUint32(0,1+n.length,!1),r[4]=t,r.set(n,5),r}(e)),!0}catch(e){return!1}}_onClosed(){this.connected&&(this.connected=!1,this.onClose&&this.onClose())}close(){try{this._dgWriter&&this._dgWriter.releaseLock&&this._dgWriter.releaseLock()}catch(e){}try{this._t&&this._t.close()}catch(e){}this._t=this._dgWriter=this._streamWriter=null,this.connected=!1}}class G{constructor(e={}){this._set=e.setTimeout||("undefined"!=typeof setTimeout?setTimeout:null),this._clear=e.clearTimeout||("undefined"!=typeof clearTimeout?clearTimeout:null),this._rand=e.random||Math.random,this._timers=new Set,this.set(e)}set(e={}){return null!=e.latencyMs?this.latencyMs=Math.max(0,e.latencyMs):null==this.latencyMs&&(this.latencyMs=0),null!=e.jitterMs?this.jitterMs=Math.max(0,e.jitterMs):null==this.jitterMs&&(this.jitterMs=0),null!=e.lossPct?this.lossPct=Math.max(0,Math.min(100,e.lossPct)):null==this.lossPct&&(this.lossPct=0),null!=e.dupPct?this.dupPct=Math.max(0,Math.min(100,e.dupPct)):null==this.dupPct&&(this.dupPct=0),this}_delay(){const e=this.jitterMs?(2*this._rand()-1)*this.jitterMs:0,t=this.latencyMs+e;return t>0?t:0}_schedule(e,t){if(!this._set)return void e();const n=this._set(()=>{this._timers.delete(n),e()},t);this._timers.add(n)}wrap(e){const t=this;return function(...n){if(!(t.latencyMs||t.jitterMs||t.lossPct||t.dupPct))return e.apply(this,n);if(t.lossPct&&100*t._rand()<t.lossPct)return;const r=this;t._schedule(()=>e.apply(r,n),t._delay()),t.dupPct&&100*t._rand()<t.dupPct&&t._schedule(()=>e.apply(r,n),t._delay())}}flush(){if(this._clear)for(const e of this._timers)this._clear(e);this._timers.clear()}}class W{constructor(e={}){if(!e.playerId)throw new Error("Lockstep requires playerId");if(!Array.isArray(e.players)||0===e.players.length)throw new Error("Lockstep requires players[]");if("function"!=typeof e.step)throw new Error("Lockstep requires a step(frame, inputs) function");this.playerId=e.playerId,this._players=e.players.slice(),this._step=e.step,this._send=e.send||function(){},this._inputDelay=null!=e.inputDelay?e.inputDelay:2,this._idle=null!=e.idleInput?e.idleInput:null,this._inputs={},this._frame=0,this._submitFrame=this._inputDelay,this._replay=[];for(let e=0;e<this._inputDelay;e++){this._inputs[e]={};for(let t=0;t<this._players.length;t++)this._inputs[e][this._players[t]]=this._idle}}get frame(){return this._frame}get players(){return this._players.slice()}submit(e){const t=this._submitFrame++;return this._inputs[t]||(this._inputs[t]={}),this._inputs[t][this.playerId]=e,this._send({frame:t,playerId:this.playerId,input:e}),t}receive(e){e&&null!=e.frame&&e.playerId&&(this._inputs[e.frame]||(this._inputs[e.frame]={}),this._inputs[e.frame][e.playerId]=e.input)}_ready(e){const t=this._inputs[e];if(!t)return!1;for(let e=0;e<this._players.length;e++)if(!(this._players[e]in t))return!1;return!0}tick(){let e=0;for(;this._ready(this._frame);){const t=this._inputs[this._frame];this._step(this._frame,t),this._replay.push({frame:this._frame,inputs:t}),delete this._inputs[this._frame],this._frame+=1,e+=1}return e}isStalled(){return!this._ready(this._frame)}getReplay(){return this._replay.slice()}static replay(e,t){for(let n=0;n<e.length;n++)t(e[n].frame,e[n].inputs)}}function F(e,t,n){return e+(t-e)*n}class J{constructor(e={}){this._historyMs=e.historyMs||1e3,this._maxSize=e.maxSize||256,this._now=e.now||(()=>Date.now()),this._history=[]}record(e,t){const n=null!=t?t:this._now();this._history.push({time:n,entities:e.map(e=>Object.assign({},e))});const r=n-this._historyMs;for(;this._history.length>this._maxSize||this._history.length>2&&this._history[0].time<r;)this._history.shift()}get size(){return this._history.length}clear(){this._history=[]}rewind(e,t){const n=this._history;if(0===n.length)return{};if(e<=n[0].time)return V(n[0].entities);if(e>=n[n.length-1].time)return V(n[n.length-1].entities);let r=n[0],i=n[n.length-1];for(let t=n.length-1;t>0;t--)if(n[t-1].time<=e&&e<=n[t].time){r=n[t-1],i=n[t];break}const o=i.time-r.time,s=o>0?(e-r.time)/o:0,c=V(r.entities),a={},u=V(i.entities);for(const e in u){const n=u[e],r=c[e],i=Object.assign({},n);if(r){const e=t||Object.keys(n);for(let t=0;t<e.length;t++){const o=e[t];"number"==typeof r[o]&&"number"==typeof n[o]&&(i[o]=F(r[o],n[o],s))}}a[e]=i}return a}rewindForClient(e,t,n){const r=null!=(n=n||{}).maxRewindMs?n.maxRewindMs:250;let i=(e||0)/2+(t||0);return i>r&&(i=r),this.rewind(this._now()-i,n.keys)}}function V(e){const t={};for(let n=0;n<e.length;n++)t[e[n].id]=e[n];return t}const Q="_s",z="_d",Y="_a",K="_n",X="_ka",$="_add",Z="_del",ee="_ord";function te(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function ne(e){if(!Array.isArray(e)||0===e.length)return!1;for(let t=0;t<e.length;t++){const n=e[t];if(!te(n)||"string"!=typeof n.id&&"number"!=typeof n.id)return!1}return!0}function re(e,t){if(e===t)return;const n=Array.isArray(e),r=Array.isArray(t);return n!==r||te(e)!==te(t)?{[Q]:t}:r?ne(e)&&ne(t)?function(e,t){const n={},r=[];for(let t=0;t<e.length;t++)n[e[t].id]=e[t],r.push(e[t].id);const i=[],o={};let s=!1;for(let e=0;e<t.length;e++){const r=t[e];if(i.push(r.id),Object.prototype.hasOwnProperty.call(n,r.id)){const e=re(n[r.id],r);void 0!==e&&(o[X]||(o[X]={}),o[X][r.id]=e,s=!0)}else o[$]||(o[$]=[]),o[$].push(r),s=!0}const c={};for(let e=0;e<i.length;e++)c[i[e]]=!0;for(let e=0;e<r.length;e++)c[r[e]]||(o[Z]||(o[Z]=[]),o[Z].push(r[e]),s=!0);(function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0})(r,i)||(o[ee]=i,s=!0);return s?o:void 0}(e,t):function(e,t){const n={[Y]:{}};let r=!1;for(let i=0;i<t.length;i++){const o=i<e.length?re(e[i],t[i]):{[Q]:t[i]};void 0!==o&&(n[Y][i]=o,r=!0)}t.length!==e.length&&(n[K]=t.length,r=!0);return r?n:void 0}(e,t):te(t)?function(e,t){const n={};let r=!1;for(const i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;const o=re(e[i],t[i]);void 0!==o&&(n[i]=o,r=!0)}const i=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(Object.prototype.hasOwnProperty.call(t,n)||i.push(n));i.length&&(n[z]=i,r=!0);return r?n:void 0}(e,t):{[Q]:t}}function ie(e,t){if(null==t)return e;if(Object.prototype.hasOwnProperty.call(t,Q))return t[Q];if(t[X]||t[$]||t[Z]||t[ee])return function(e,t){const n=Array.isArray(e)?e:[],r={},i=[];for(let e=0;e<n.length;e++){const t=n[e];!t||"string"!=typeof t.id&&"number"!=typeof t.id||(r[t.id]=t,i.push(t.id))}if(t[X])for(const e in t[X])Object.prototype.hasOwnProperty.call(t[X],e)&&void 0!==r[e]&&(r[e]=ie(r[e],t[X][e]));if(t[$])for(let e=0;e<t[$].length;e++){const n=t[$][e];r[n.id]=n}const o={};if(t[Z])for(let e=0;e<t[Z].length;e++)o[t[Z][e]]=!0;if(t[ee]){const e=[];for(let n=0;n<t[ee].length;n++){const i=t[ee][n];void 0!==r[i]&&e.push(r[i])}return e}const s=[];for(let e=0;e<i.length;e++){const t=i[e];o[t]||s.push(r[t])}return s}(e,t);if(Object.prototype.hasOwnProperty.call(t,Y)||Object.prototype.hasOwnProperty.call(t,K)){const n=Array.isArray(e)?e:[],r=Object.prototype.hasOwnProperty.call(t,K)?t[K]:n.length,i=n.slice(0,r),o=t[Y]||{};for(const e in o)Object.prototype.hasOwnProperty.call(o,e)&&(i[e]=ie(i[e],o[e]));return i}const n=te(e)?Object.assign({},e):{},r=t[z];for(const e in t)e!==z&&Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=ie(n[e],t[e]));if(Array.isArray(r))for(let e=0;e<r.length;e++)delete n[r[e]];return n}function oe(e,t=2){const n=Math.pow(10,t);return function e(t){if("number"==typeof t)return Number.isFinite(t)?Math.round(t*n)/n:t;if(Array.isArray(t))return t.map(e);if(te(t)){const n={};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=e(t[r]));return n}return t}(e)}const se="undefined"!=typeof TextEncoder?new TextEncoder:null,ce="undefined"!=typeof TextDecoder?new TextDecoder:null;function ae(e,t){for(t>>>=0;t>127;)e.push(127&t|128),t>>>=7;e.push(t)}function ue(e,t){if(null==t)return void e.push(192);const n=typeof t;if("boolean"!==n)if("number"!==n){var r;if("string"===n){e.push(198);const n=se?se.encode(t):Buffer.from(t,"utf8");ae(e,n.length);for(let t=0;t<n.length;t++)e.push(n[t]);return}if(Array.isArray(t)){e.push(199),ae(e,t.length);for(let n=0;n<t.length;n++)ue(e,t[n])}else{if("object"===n){const n=Object.keys(t);e.push(200),ae(e,n.length);for(let r=0;r<n.length;r++){const i=n[r],o=se?se.encode(i):Buffer.from(i,"utf8");ae(e,o.length);for(let t=0;t<o.length;t++)e.push(o[t]);ue(e,t[i])}return}e.push(192)}}else if(Number.isInteger(t)&&t>=-2147483648&&t<=2147483647)e.push(196),ae(e,((r=t)<<1^r>>31)>>>0);else{e.push(197);const n=new Uint8Array(8);new DataView(n.buffer).setFloat64(0,t,!0);for(let t=0;t<8;t++)e.push(n[t])}else e.push(t?195:194)}function le(e){const t=[];return ue(t,e),Uint8Array.from(t)}function de(e){return function(e){let t=0;const n=new DataView(e.buffer,e.byteOffset,e.byteLength);function r(){let n,r=0,i=0;do{n=e[t++],i|=(127&n)<<r,r+=7}while(128&n);return i>>>0}function i(){const n=r(),i=e.subarray(t,t+n);return t+=n,ce?ce.decode(i):Buffer.from(i).toString("utf8")}return function o(){switch(e[t++]){case 192:default:return null;case 195:return!0;case 194:return!1;case 196:return(s=r())>>>1^-(1&s);case 197:{const e=n.getFloat64(t,!0);return t+=8,e}case 198:return i();case 199:{const e=r(),t=new Array(e);for(let n=0;n<e;n++)t[n]=o();return t}case 200:{const e=r(),t={};for(let n=0;n<e;n++)t[i()]=o();return t}}var s}}(e instanceof Uint8Array?e:new Uint8Array(e))()}function fe(e,t){if(!("string"==typeof e&&e.length>0||"number"==typeof e&&isFinite(e)))throw new Error("interestGrid."+t+": id must be a non-empty string or a finite number");return e}function _e(e,t,n){if("number"!=typeof e||!isFinite(e))throw new Error("interestGrid."+n+": "+t+" must be a finite number");return e}function he(e,t){if(_e(e,"radius",t),e<0)throw new Error("interestGrid."+t+": radius must be >= 0");return e}function pe(e){const t=null!=(e=e||{}).cellSize?e.cellSize:256;if("number"!=typeof t||!isFinite(t)||t<=0)throw new Error("createInterestGrid: cellSize must be a finite number > 0");const n=new Map,r=new Map,i=new Map;function o(e,t){let n=r.get(e);n||(n=new Set,r.set(e,n)),n.add(t)}function s(e,t){const n=r.get(e);n&&(n.delete(t),0===n.size&&r.delete(e))}function c(e,i,o,s){const c=o*o,a=Math.floor((e-o)/t),u=Math.floor((e+o)/t),l=Math.floor((i-o)/t),d=Math.floor((i+o)/t);for(let t=a;t<=u;t++)for(let o=l;o<=d;o++){const a=r.get(t+","+o);if(a)for(const t of a){const r=n.get(t);if(!r)continue;const o=r.x-e,a=r.y-i;o*o+a*a<=c&&s(t)}}}return{upsert:function(e,r,i){fe(e,"upsert"),_e(r,"x","upsert"),_e(i,"y","upsert");const c=Math.floor(r/t)+","+Math.floor(i/t),a=n.get(e);if(a)return a.x=r,a.y=i,void(a.key!==c&&(s(a.key,e),o(c,e),a.key=c));n.set(e,{x:r,y:i,key:c}),o(c,e)},remove:function(e){fe(e,"remove");const t=n.get(e);t&&(n.delete(e),s(t.key,e))},query:function(e,t,n){_e(e,"x","query"),_e(t,"y","query"),he(n,"query");const r=[];return c(e,t,n,function(e){r.push(e)}),r},observe:function(e,t,n,r){fe(e,"observe"),_e(t,"x","observe"),_e(n,"y","observe"),he(r,"observe");let o=i.get(e);o||(o={prev:new Set,next:new Set},i.set(e,o));const s=o.prev,a=o.next;a.clear();const u=[],l=[],d=[];c(t,n,r,function(e){a.add(e),d.push(e),s.has(e)||u.push(e)});for(const e of s)a.has(e)||l.push(e);return o.prev=a,o.next=s,{entered:u,left:l,visible:d}},dropObserver:function(e){fe(e,"dropObserver"),i.delete(e)},size:function(){return n.size}}}function me(e,t){e.diff=re,e.patch=ie,e.quantize=oe,e.encode=le,e.decode=de,e.createInterpolation=function(e){return new k(e||{})},e.createPredictor=function(e){return new M(e||{})},e.createLagCompensator=function(e){return new J(e||{})},e.createLockstep=function(e){return new W(e||{})},e.createInterestGrid=function(e){return pe(e||{})},e._channels=e._channels||{},e._userRealtime=e._userRealtime||null,e._inboundDispatch=null,e._dispatchRealtime=function(t){const n=t&&t.action_type;n&&e._channels[n]?e._channels[n](t&&(void 0!==t.action_data?t.action_data:t),t):e._userRealtime&&e._userRealtime(t)},e._installRealtimeRouter=function(){e._routerInstalled||(e._eventHandlers.realtime&&e._eventHandlers.realtime!==e._router&&(e._userRealtime=e._eventHandlers.realtime),e._router=function(t){(e._inboundDispatch||e._dispatchRealtime)(t)},e._eventHandlers.realtime=e._router,e._routerInstalled=!0)},e._onChannel=function(t,n){return e._channels[t]=n,e._installRealtimeRouter(),function(){delete e._channels[t]}},e.onRealtime=function(t){e._userRealtime=t,e._installRealtimeRouter()},e.createSender=function(e){const t=this,n=(e=e||{}).send||function(e,n){t.realtime(e,n)};return new C({hz:e.hz||20,autoStart:!1!==e.autoStart,onFlush:function(e){for(let t=0;t<e.length;t++)n(e[t].type,e[t].data)}})},e.createSnapshotSender=function(e){const t=this,n=(e=e||{}).channel||"state",r=!1!==e.delta,i=null!=e.keyframeEvery?e.keyframeEvery:30,o=e.precision,s=!0===e.encode?le:"function"==typeof e.encode?e.encode:null,c=e.send||function(e,n){t.realtime(e,n)},a="function"==typeof e.source?e.source:null;let u=null,l=0,d=0,f=0;function _(e){if(null==e)return;const t=null!=o?oe(e,o):e;let a;if(!r||null===u||f>=i)d+=1,u=null==(_=t)?_:JSON.parse(JSON.stringify(_)),l=d,f=0,a={s:d,f:t};else{const e=re(u,t);if(void 0===e)return;d+=1,f+=1,a={s:d,b:l,d:e}}var _;c(n,s?s(a):a)}const h=e.hz||20;let p;const m=a?null:new C({hz:h,autoStart:!1!==e.autoStart,onFlush:function(e){for(let t=0;t<e.length;t++)"__snap"===e[t].type&&(p=e[t].data);_(p)}});let y=null;function g(){m?m.start():y||"undefined"==typeof setInterval||(y=setInterval(function(){_(a())},Math.max(1,Math.round(1e3/h))))}return a&&!1!==e.autoStart&&g(),{send:function(e){m?m.queue("__snap",e):_(e)},flush:function(){m?m.flush():a&&_(a())},start:g,stop:function(){m&&m.stop(),y&&(clearInterval(y),y=null)},reset:function(){u=null,l=0,d=0,f=0}}},e.createSnapshotReceiver=function(e){const t=!0===(e=e||{}).decode?de:"function"==typeof e.decode?e.decode:null;let n=null,r=-1,i=null,o=-1,s=0;return{receive:function(e){return t&&(e instanceof ArrayBuffer||ArrayBuffer.isView(e))&&(e=t(e)),e?void 0!==e.f?void 0!==e.s&&e.s<=o?(s+=1,i):(n=e.f,r=void 0!==e.s?e.s:0,i=e.f,o=r,i):void 0!==e.d?void 0!==e.b&&e.b!==r||void 0!==e.s&&e.s<=o?(s+=1,i):(i=ie(n,e.d),void 0!==e.s&&(o=e.s),i):i:i},get state(){return i},get stats(){return{appliedSeq:o,baseSeq:r,dropped:s}},reset:function(){n=null,r=-1,i=null,o=-1,s=0}}},e.replicate=function(e,t){t=t||{};let n=null!=e?e:{};const r=this.createSnapshotSender(Object.assign({},t,{source:function(){return n}}));return{get state(){return n},set state(e){n=e},flush:function(){r.flush()},start:function(){r.start()},stop:function(){r.stop()}}},e.replica=function(e){const t=(e=e||{}).channel||"state",n=this.createSnapshotReceiver({decode:e.decode}),r=e.interpolate?this.createInterpolation("object"==typeof e.interpolate?e.interpolate:{}):null,i="string"==typeof e.interpolate?e.interpolate:e.keys||e.interpolate&&e.interpolate.keys,o=e.group||e.interpolate&&e.interpolate.group;let s=null;const c=this._onChannel(t,function(e){const t=n.receive(e);r&&null!=t&&r.add(t),s&&s(t)});return{get state(){return n.state},view:function(){return r?r.calc(i||"x y",o):n.state},onChange:function(e){s=e},stop:function(){c()}}},e.createMesh=function(e){const t=this,n=(e=e||{}).signalChannel||"signal",r=new q(Object.assign({},e,{sendSignal:function(e){t.realtime(n,e)}}));return this._onChannel(n,function(e){e&&e.type&&r.handleSignal(e)}),r},e.createMeshNetwork=function(e){const n=this,r=(e=e||{}).signalChannel||"mesh",i=e.selfId||t.user&&t.user.getId&&t.user.getId(),o=new j(Object.assign({},e,{selfId:i,sendSignal:function(e,t){n.realtime(r,{to:e,from:i,payload:t})}}));return this._onChannel(r,function(e){e&&e.to===i&&e.from&&o.handleSignal(e.from,e.payload)}),o},e.simulateNetwork=function(e){const t=this;return t._installRealtimeRouter(),t._realtimeRaw||"function"!=typeof t.realtime||(t._realtimeRaw=t.realtime.bind(t)),e?(t._sim?t._sim.set(e):t._sim=new G(e),t._realtimeRaw&&(t.realtime=t._sim.wrap(t._realtimeRaw)),t._inboundDispatch=t._sim.wrap(t._dispatchRealtime),t._sim):(t._realtimeRaw&&(t.realtime=t._realtimeRaw),t._inboundDispatch=null,t._sim&&t._sim.flush(),void(t._sim=null))},e.createWebTransport=function(e){const n=(e=e||{}).url||t.config&&(t.config.webTransportUrl||t.config.wtUrl);return new H(Object.assign({},e,{url:n}))},e.ping=function(){const e=this;if(e._pingMeter||(e._pingMeter=new N),e._pingInFlight)return e._pingInFlight;let t;if(e.directMode){if(!e.directSocket||1!==e.directSocket.readyState)return Promise.resolve(null);t=new Promise(function(t){const n=e._pingMeter.begin();let r=!1;const i=function(){r||(r=!0,t(e._pingMeter.end(n)))};i.sentAt=Date.now(),e._pongWaiters.push(i),e._sendDirect("ping",{t:Date.now()}),setTimeout(function(){if(r)return;r=!0;const o=e._pongWaiters.indexOf(i);o>=0&&e._pongWaiters.splice(o,1),delete e._pingMeter._outstanding[n],t(null)},3e3)})}else{if(!e.socket||!e.connected||e._useProxy)return Promise.resolve(null);t=new Promise(function(t){const n=Date.now();let r=!1;try{e.socket.emit("game:ping",{t:n},function(){r||(r=!0,t(e._pingMeter.sample(Date.now()-n)))})}catch(e){return void t(null)}setTimeout(function(){r||(r=!0,t(null))},3e3)})}return e._pingInFlight=t,t.then(function(){e._pingInFlight=null},function(){e._pingInFlight=null}),t},e.getRtt=function(){return this._pingMeter?this._pingMeter.rtt:null}}function ye(e,t){function n(t){var n=e[t];"function"==typeof n&&(e[t]=function(){var e=this;return n.apply(e,arguments).then(function(t){return e._awaitResync||e._setConnState("connected"),t})})}function r(t){t&&(t.host_id?e._hostId=t.host_id:t.player_ids&&t.player_ids.length&&(e._hostId=t.player_ids[0]))}e.getLastSequence=function(){return this._lastSequence||0},e.getLastAppliedSequence=function(){return this._lastActionApplied||0},e._connState="disconnected",e._awaitResync=!1,e._setConnState=function(e){this._connState!==e&&(this._connState=e,this._dispatch("connectionState",e))},e.getConnectionState=function(){return this._connState},e.onConnectionState=function(e){return this._setHandler("connectionState",e)},e.onReconnected=function(e){return this._setHandler("reconnected",e)},e.on("disconnect",function(){e._awaitResync=!1,e._setConnState("disconnected")}),e.on("reconnect",function(){e.roomId?(e._awaitResync=!0,e._setConnState("rejoining")):e._setConnState("connected")}),e.on("sync",function(t){e._awaitResync&&(e._awaitResync=!1,e._dispatch("reconnected",{state:t&&t.game_state||null,lastSequence:e._lastSequence||0,viaSync:!0}),e._setConnState("reconnected"),e._setConnState("connected"))}),n("connect"),n("connectDirect"),e._hostId=null,e.on("joined",r),e.on("playerJoined",r),e.syncedState=function(e,n){var r=this,i="function"==typeof(n=n||{}).reduce?n.reduce:function(e,t){return Object.assign({},e,t.data)},o=null!=n.checkpointEvery?n.checkpointEvery:1,s="all"===n.authority?"all":"host",c=n.type||"update",a=void 0===e?{}:e,u=0,l=0,d=-1,f=[],_=[];function h(e){for(var n=f.slice(),r=0;r<n.length;r++)try{n[r](a,e)}catch(e){t.log("syncedState onChange error: "+e.message)}}function p(){if("all"===s)return!0;var e=r.playerId||t.user&&t.user.getId&&t.user.getId();return!(!e||!r._hostId||e!==r._hostId)}function m(){return r.directMode?Promise.resolve({success:!1,error:"not_supported_in_direct_mode"}):r.setState({__usionSyncedState:1,seq:u,state:a})}function y(e,n,r,o){if(void 0!==o&&o<=u)return!1;var s;try{s=i(a,{playerId:e,type:n,data:r,sequence:o})}catch(e){return t.log("syncedState reduce error: "+e.message),!1}return void 0!==s&&(a=s),void 0!==o&&(u=o),!0}function g(e){if(e){var t=!1,n=e.game_state;n&&n.__usionSyncedState&&"number"==typeof n.seq&&n.seq>=u&&void 0!==n.state&&(a=n.state,u=n.seq,t=!0);var i=e.actions;if(i&&i.length)for(var o=i.slice().sort(function(e,t){return(e.sequence||0)-(t.sequence||0)}),s=0;s<o.length;s++){var c=o[s];c&&y(c.player_id,c.action_type,c.action_data,c.sequence)&&(t=!0)}if(t&&h("recover"),void 0!==e.sequence&&e.sequence>u&&d!==u){d=u;try{r.requestSync(u)}catch(e){}}}}return _.push(r.on("action",function(e){e&&y(e.player_id,e.action_type,e.action_data,e.sequence)&&(h("action"),o>0&&p()&&(l+=1)>=o&&(l=0,m()))})),_.push(r.on("sync",g)),_.push(r.on("joined",g)),{get:function(){return a},commit:function(e,t,n){var i,o,s;return"string"==typeof e?(i=e,o=t,s=n):(i=c,o=e,s=t),r.directMode?(y(r.playerId,i,o,void 0)&&h("action"),r.action(i,o,s)):r.action(i,o,s)},onChange:function(e){return f.push(e),function(){var t=f.indexOf(e);t>=0&&f.splice(t,1)}},isAuthority:p,checkpoint:function(){return m()},getSequence:function(){return u},destroy:function(){for(var e=0;e<_.length;e++)try{_[e]()}catch(e){}_.length=0,f.length=0}}}}const ge={joined:"joined",player_joined:"playerJoined",player_left:"playerLeft",player_connection:"playerConnection",state:"stateUpdate",state_update:"stateUpdate",sync:"sync",action:"action",realtime:"realtime",finished:"finished",restarted:"restarted",error:"error",rematch_request:"rematchRequest",disconnect:"disconnect",reconnect:"reconnect",connection_error:"connectionError",room_assigned:"roomAssigned",connection_state:"connectionState",reconnected:"reconnected",network_quality:"networkQuality"};const ve={SnapshotInterpolation:k,Vault:A,Predictor:M,Coalescer:C,PingMeter:N,MeshConnection:q,MeshNetwork:j,WebTransportConnection:H,NetworkSim:G,Lockstep:W,LagCompensator:J,diff:re,patch:ie,quantize:oe,encode:le,decode:de,createInterestGrid:pe},be=Object.assign({},u);var Ee;return be.user=function(e){return{_id:null,_name:null,_avatar:null,_token:null,_isAdult:null,getId:function(){return this._id||e.config.userId||null},getName:function(){return this._name||e.config.userName||null},getAvatar:function(){return this._avatar||e.config.userAvatar||null},isAdult:function(){if(!0===this._isAdult||!1===this._isAdult)return this._isAdult;var t=e.config&&e.config.userIsAdult;return!0===t||!1===t?t:null},getToken:function(){return this._token||e.config.authToken||null},getProfile:function(){return e._request("GET_USER_PROFILE",{}).then(function(t){return t.profile||{id:e.user.getId(),name:e.user.getName(),avatar:e.user.getAvatar(),isAdult:e.user.isAdult()}})}}}(be),be.storage=function(e){var t=null;function n(){return t||(t=_(e,"kv:get",{key:d}).then(function(t){if(!t||!t.exists||!0!==t.value)return Promise.all([_(e,"kv:keys",{}),y(e)]).then(function(t){var n=new Set(t[0]&&t[0].keys||[]);return Promise.all(t[1].map(function(t){var r=f(t);if(!n.has(r))return h(e,t).then(function(t){if(null!=t)return _(e,"kv:set",{key:r,value:t})})}))}).then(function(){return _(e,"kv:set",{key:d,value:!0})})}).catch(function(e){throw t=null,e}))}return{get:function(t){return n().then(function(){return _(e,"kv:get",{key:f(t)})}).then(function(n){return n&&n.exists?g(p(e,t,n.value)).then(function(){return n.value}):g(m(e,t)).then(function(){return null})}).catch(function(n){return h(e,t).then(function(e){if(null!=e)return e;throw n},function(){throw n})})},set:function(t,r){return n().then(function(){return _(e,"kv:set",{key:f(t),value:r})}).then(function(){return g(p(e,t,r))})},remove:function(t){return n().then(function(){return _(e,"kv:remove",{key:f(t)})}).then(function(){return g(m(e,t))})},clear:function(){return n().then(function(){return _(e,"kv:clear",{prefix:l})}).then(function(){return g(e._request("STORAGE_CLEAR",{}))})},keys:function(){return n().then(function(){return _(e,"kv:keys",{})}).then(function(e){return(e&&e.keys||[]).filter(function(e){return 0===e.indexOf(l)}).map(function(e){return e.slice(3)})}).catch(function(t){return y(e).catch(function(){throw t})})}}}(be),be.wallet=function(e){return{_balance:null,_balanceChangeHandler:null,_paymentTimeoutMs:6e4,_recoveryPollMs:2e3,_recoveryMaxPolls:10,_recoveryQueryTimeoutMs:8e3,getBalance:function(t){const n=this;return!(!t||!t.fresh)||null===n._balance?e._request("GET_BALANCE",{}).then(function(e){return n._balance=e.balance,e.balance}):Promise.resolve(n._balance)},hasCredits:function(e){return this.getBalance().then(function(t){return t>=e})},requestPayment:function(t,n,r){const i=this,o=r&&"object"==typeof r?r:null,c=o&&"string"==typeof o.idempotencyKey&&o.idempotencyKey?o.idempotencyKey:null;return new Promise(function(o,u){const l=s(),d=i._paymentTimeoutMs||6e4;let f=!1,_=null;function h(){clearTimeout(g),_&&clearTimeout(_),window.removeEventListener("message",y)}function p(e){f||(f=!0,h(),e&&void 0!==e.newBalance?i._balance=e.newBalance:(null!==i._balance&&(i._balance-=t),i.getBalance({fresh:!0}).catch(function(){})),o(e))}function m(e){f||(f=!0,h(),u(e))}function y(e){if(!a(e))return;let t;try{t="string"==typeof e.data?JSON.parse(e.data):e.data}catch(e){return}t&&t._requestId===l&&("PAYMENT_SUCCESS"===t.type?p(t):"PAYMENT_FAILED"===t.type&&m(new Error(t.reason||"Payment failed")))}window.addEventListener("message",y);const g=setTimeout(function(){const t=i._recoveryPollMs||2e3,n=i._recoveryMaxPolls||10,r=i._recoveryQueryTimeoutMs||8e3;let o=0,s=0;!function i(){f||e._request("PAYMENT_RESULT_QUERY",{paymentRequestId:l,idempotencyKey:c||void 0},r).then(function(e){if(f)return;const n=e&&e.status;if("succeeded"!==n)if("failed"!==n){if("pending"===n)return o=0,s=0,void(_=setTimeout(i,t));s=0,o+=1,o>=2?m(new Error("Payment confirmation timeout")):_=setTimeout(i,t)}else m(new Error(e.reason||"Payment failed"));else p({type:"PAYMENT_SUCCESS",_requestId:l,newBalance:e.newBalance,transactionId:e.transactionId,receiptToken:e.receiptToken})}).catch(function(){f||(s+=1,s>=n?m(new Error("Payment confirmation timeout")):_=setTimeout(i,t))})}()},d);e._post({type:"PAYMENT_REQUEST",_requestId:l,amount:t,reason:n,data:r,idempotencyKey:c||void 0})})},onBalanceChange:function(e){const t=this;return t._balanceChangeHandler=e,function(){t._balanceChangeHandler===e&&(t._balanceChangeHandler=null)}}}}(be),be.session=function(e){return{_id:null,_data:{},getId:function(){return this._id||e.config.sessionId||null},getData:function(e){return e?this._data[e]:this._data},setData:function(t,n){"object"==typeof t?Object.assign(this._data,t):this._data[t]=n,e._post({type:"SESSION_DATA_UPDATE",data:this._data})},clear:function(){this._data={},e._post({type:"SESSION_DATA_CLEAR"})}}}(be),be.chat=function(e){return{sendMessage:function(t,n){return e._request("SEND_MESSAGE_REQUEST",{recipientId:t,message:n})},createPersonalChat:function(t){return e._request("CREATE_PERSONAL_CHAT",{peerUserId:t})}}}(be),be.bot=function(e){return{_messageHandler:null,callAction:function(t,n){return e._request("CALL_BOT",{action:t,data:n||{}},3e4)},sendMessage:function(t){e._post({type:"SEND_USER_MESSAGE",text:t})},updateContext:function(t){e._post({type:"UPDATE_CONTEXT",context:t})},close:function(t){e._post({type:"CLOSE",result:t})},onMessage:function(e){this._messageHandler=e}}}(be),be.fileStorage=(Ee=be,{set:function(e,t,n){return Ee._request("FILE_STORAGE_SET",{key:e,base64Data:t,mimeType:n||"application/octet-stream"},3e4).then(function(){})},get:function(e){return Ee._request("FILE_STORAGE_GET",{key:e},3e4).then(function(e){return e&&e.base64Data?{base64Data:e.base64Data,mimeType:e.mimeType}:null})},remove:function(e){return Ee._request("FILE_STORAGE_REMOVE",{key:e}).then(function(){})}}),be.game=function(n){const i={socket:null,directSocket:null,roomId:null,playerId:null,connected:!1,directMode:!1,directConfig:null,_directSeq:0,_eventHandlers:{},_lastSequence:0,_connecting:!1,_connectPromise:null,_joined:!1,_joinPromise:null,_useProxy:!1,_proxyListenerSetup:!1,_heartbeatInterval:null,_pingMeter:null,_pongWaiters:[],_lastActionApplied:0,_rejoinPromise:null,connect:function(e,t){const r=this;return"direct"===(n.config&&n.config.connectionMode||"platform")?r.connectDirect():r._useProxy&&r.connected||r.socket&&r.connected?Promise.resolve():r._connecting&&r._connectPromise?r._connectPromise:window.__USION_PROXY__||window.parent!==window||window.ReactNativeWebView||n._isEmbedded?(n.log("Running in iframe – using parent app as socket proxy"),r._connectViaProxy()):(e=e||n.config.socketUrl,t=t||n.user.getToken(),e?t?(r._connecting=!0,r._connectPromise=new Promise(function(n,i){if("undefined"==typeof io){var o=["/socket.io.min.js","https://usions.com/socket.io.min.js","https://cdn.socket.io/4.7.2/socket.io.min.js"];!function s(c){if(c>=o.length)return r._connecting=!1,void i(new Error("Failed to load Socket.IO client"));var a=document.createElement("script");a.src=o[c],a.onload=function(){r._initSocket(e,t,n,i)},a.onerror=function(){s(c+1)},document.head.appendChild(a)}(0)}else r._initSocket(e,t,n,i)}),r._connectPromise):Promise.reject(new Error("No auth token available")):Promise.reject(new Error("No socket URL provided")))},onJoined:function(e){return this._setHandler("joined",e)},onPlayerJoined:function(e){return this._setHandler("playerJoined",e)},onPlayerLeft:function(e){return this._setHandler("playerLeft",e)},onStateUpdate:function(e){return this._setHandler("stateUpdate",e)},onSync:function(e){return this._setHandler("sync",e)},onAction:function(e){return this._setHandler("action",e)},onRealtime:function(e){return this._setHandler("realtime",e)},onGameFinished:function(e){return this._setHandler("finished",e)},onGameRestarted:function(e){return this._setHandler("restarted",e)},onError:function(e){return this._setHandler("error",e)},onRematchRequest:function(e){return this._setHandler("rematchRequest",e)},onDisconnect:function(e){return this._setHandler("disconnect",e)},onReconnect:function(e){return this._setHandler("reconnect",e)},onConnectionError:function(e){return this._setHandler("connectionError",e)},onPlayerConnection:function(e){return this._setHandler("playerConnection",e)},onRoomAssigned:function(e){return this._setHandler("roomAssigned",e)},_setHandler:function(e,t){const n=this;return n._eventHandlers[e]=t,function(){n._eventHandlers[e]===t&&(n._eventHandlers[e]=null)}},_dispatch:function(e){const t=Array.prototype.slice.call(arguments,1),r=this._eventHandlers[e];if(r)try{r.apply(null,t)}catch(t){n.log("game handler error ("+e+"): "+t.message)}const i=this._listeners[e];if(i&&i.length){const r=i.slice();for(let i=0;i<r.length;i++)try{r[i].apply(null,t)}catch(t){n.log("game listener error ("+e+"): "+t.message)}}},on:function(e,t){const n=this,r=function(e){let t=String(e||"");if(0===t.indexOf("game:")&&(t=t.slice(5)),ge[t])return ge[t];const n=t.replace(/([A-Z])/g,function(e){return"_"+e.toLowerCase()});return ge[n]||t}(e);return n._listeners[r]||(n._listeners[r]=[]),n._listeners[r].push(t),function(){const e=n._listeners[r];if(!e)return;const i=e.indexOf(t);i>=0&&e.splice(i,1)}},_listeners:{}};return function(e,t){e.connectDirect=function(e){var n=this;return e=e||{},n.directMode&&n.directSocket&&n.connected?Promise.resolve():(n._connecting&&n._connectPromise||(n._resConfigure&&n._resConfigure(e),n._connecting=!0,n.directMode=!0,n._autoReconnect=void 0!==e.autoReconnect?e.autoReconnect:!(t.config&&!1===t.config.autoReconnect),n._connectPromise=n._fetchDirectAccess(e).then(function(e){return n.directConfig=e,n._initDirectSocket(e)}).then(function(){n.connected=!0,n._connecting=!1,t.log("Direct game socket connected")}).catch(function(e){throw n._connecting=!1,n.connected=!1,n.directMode=!1,n._dispatch("connectionError",e),e})),n._connectPromise)},e._fetchDirectAccess=function(e){var n=e.roomId||this.roomId||t.config.roomId,r=e.serviceId||t.config.serviceId,i=e.apiUrl||t.config.apiUrl||"",o=e.token||t.user.getToken();if(!n)return Promise.reject(new Error("No room ID provided"));if(!r)return Promise.reject(new Error("No service ID provided"));if(this.roomId=n,this.playerId=t.user.getId(),t._isEmbedded)return t._request("GAME_ACCESS_REQUEST",{room_id:n,service_id:r,protocol_version:e.protocolVersion||t.config.protocolVersion||t.config.protocol_version||"2"},1e4);if(!i)return Promise.reject(new Error("No API URL provided"));if(!o)return Promise.reject(new Error("No auth token available"));var s=String(i).replace(/\/$/,"")+"/games/rooms/"+encodeURIComponent(n)+"/access";return fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o},body:JSON.stringify({service_id:r,client_type:"iframe",protocol_version:e.protocolVersion||t.config.protocolVersion||t.config.protocol_version||"2"})}).then(function(e){return e.ok?e.json():e.text().then(function(t){throw new Error(t||"Direct access failed: HTTP "+e.status)})})},e._initDirectSocket=function(e){var t=this;return new Promise(function(n,r){if(e&&e.ws_url&&e.access_token){var i=e.ws_url,o=-1===i.indexOf("?")?"?":"&",s=i+o+"token="+encodeURIComponent(e.access_token),c=new WebSocket(s);t.directSocket=c;var a=!1,u=!1,l=setTimeout(function(){if(!a){try{c.close()}catch(e){}r(new Error("Direct WebSocket connection timeout"))}},1e4);c.onopen=function(){a=!0,clearTimeout(l),u||(u=!0,t._sendDirect("join",{})),t._heartbeatInterval&&clearInterval(t._heartbeatInterval),t._heartbeatInterval=setInterval(function(){t.directSocket&&t.directSocket.readyState===WebSocket.OPEN&&t._sendDirect("heartbeat",{})},25e3),t._resOnOpen&&t._resOnOpen(),n()},c.onerror=function(){a||(clearTimeout(l),r(new Error("Direct WebSocket connection error")))},c.onclose=function(e){t._resOnClose&&t._resOnClose(e),t.connected=!1,t._joined=!1,t._joinPromise=null,t._heartbeatInterval&&(clearInterval(t._heartbeatInterval),t._heartbeatInterval=null),t._dispatch("disconnect",e&&e.reason?e.reason:"direct socket closed"),t.directMode&&!1!==t._autoReconnect&&t._scheduleDirectReconnect()},c.onmessage=function(e){t._res&&(t._res.lastInboundAt=Date.now()),t._handleDirectMessage(e&&e.data)}}else r(new Error("Invalid direct access payload"))})},e._scheduleDirectReconnect=function(){var e=this;if(!e._reconnecting){e._reconnecting=!0;var t=e._reconnectAttempt||0,n=function(){e.directMode?(t+=1,e._reconnectAttempt=t,(e._resCanReuseToken&&e._resCanReuseToken()?Promise.resolve(e.directConfig):e._fetchDirectAccess({})).then(function(t){return e.directConfig=t,e._initDirectSocket(t)}).then(function(){e.connected=!0,e._reconnecting=!1,e._reconnectAttempt=0,e._dispatch("reconnect",t),e.roomId&&e.requestSync(e._lastSequence||0)}).catch(function(){if(e.directMode){var r=Math.min(1e3*Math.pow(2,t-1),15e3);setTimeout(n,r)}else e._reconnecting=!1})):e._reconnecting=!1};setTimeout(n,100)}},e._sendDirect=function(e,t){this.directSocket&&this.directSocket.readyState===WebSocket.OPEN&&("input"===e&&this._resHoldInput&&this._resHoldInput(t)||(this._directSeq=this._directSeq+1,this.directSocket.send(JSON.stringify({type:e,room_id:this.roomId,ts:Date.now(),seq:this._directSeq,session_id:this.directConfig&&this.directConfig.session_id?this.directConfig.session_id:null,protocol_version:this.directConfig&&this.directConfig.protocol_version?this.directConfig.protocol_version:"2",payload:t||{}}))))},e._handleDirectMessage=function(e){var t;try{t="string"==typeof e?JSON.parse(e):e}catch(e){return}if(t&&t.type){var n=t.payload||{};if("joined"===t.type)return this._joined=!0,void this._dispatch("joined",n);if("player_joined"!==t.type)if("player_left"!==t.type){if("state_snapshot"===t.type||"state_delta"===t.type)return this._dispatch("realtime",n),void this._dispatch("stateUpdate",n);if("pong"===t.type){var r=this._pongWaiters&&this._pongWaiters.length?this._pongWaiters.shift():null;return this._resOnPong&&this._resOnPong(r),r&&r(),void this._dispatch("sync",n)}"match_end"!==t.type?"error"===t.type&&this._dispatch("error",n):this._dispatch("finished",n)}else this._dispatch("playerLeft",n);else this._dispatch("playerJoined",n)}}}(i,n),E(i,n),function(e,t){e._initSocket=function(e,n,r,i){const o=this;if(o.socket&&o.socket.connected)return o._connecting=!1,void r();o.socket&&(o.socket.disconnect(),o.socket=null);try{o.socket=io(e,{path:"/socket.io",transports:["websocket","polling"],auth:{token:n},autoConnect:!0,reconnection:!0,reconnectionAttempts:50,reconnectionDelay:1e3,reconnectionDelayMax:1e4}),t._bindBackendSocket&&t._bindBackendSocket(o.socket);var s=!1;o.socket.io&&"function"==typeof o.socket.io.on&&o.socket.io.on("reconnect_attempt",function(e){o._reconnAttempts=e}),o.socket.on("connect",function(){var e=s;if(s=!0,o.connected=!0,o._connecting=!1,t.log("Game socket connected"),o._heartbeatInterval&&clearInterval(o._heartbeatInterval),o._heartbeatInterval=setInterval(function(){o.socket&&o.connected&&o.roomId&&o.socket.emit("game:heartbeat",{room_id:o.roomId})},25e3),o.roomId){var n=o._lastSequence||0;o._joined=!1,o._joinPromise=null,o._rejoinPromise=o.join(o.roomId).then(function(){t.log("Reconnected - joined room "+o.roomId),o.requestSync(n)}).catch(function(e){t.log("Rejoin failed: "+(e&&e.message?e.message:String(e)))}).then(function(){o._rejoinPromise=null,o._flushOfflineQueue&&o._flushOfflineQueue()})}e&&(t.log("Game socket reconnected"),o._dispatch("reconnect",o._reconnAttempts||1),o._reconnAttempts=0),r()}),o.socket.on("connect_error",function(e){o._connecting=!1,t.log("Game socket error: "+e.message),o._dispatch("connectionError",e),i(e)}),o.socket.on("disconnect",function(e){o.connected=!1,o._joined=!1,o._joinPromise=null,o._heartbeatInterval&&(clearInterval(o._heartbeatInterval),o._heartbeatInterval=null),t.log("Game socket disconnected: "+e),o._dispatch("disconnect",e)}),o.socket.on("game:joined",function(e){void 0!==e.sequence&&(o._lastSequence=e.sequence,o._lastActionApplied=Math.max(o._lastActionApplied,e.sequence)),o._dispatch("joined",e)}),o.socket.on("game:player_joined",function(e){o._dispatch("playerJoined",e)}),o.socket.on("game:player_left",function(e){o._dispatch("playerLeft",e)}),o.socket.on("game:state",function(e){void 0!==e.sequence&&(o._lastSequence=Math.max(o._lastSequence,e.sequence)),o._dispatch("stateUpdate",e)}),o.socket.on("game:sync",function(e){void 0!==e.sequence&&(o._lastSequence=e.sequence,o._lastActionApplied=Math.max(o._lastActionApplied,e.sequence)),o._dispatch("sync",e),o._dispatch("stateUpdate",e)}),o.socket.on("game:action",function(e){if(void 0!==e.sequence){if(e.sequence<=o._lastActionApplied)return;o._lastActionApplied=e.sequence,o._lastSequence=Math.max(o._lastSequence,e.sequence)}o._dispatch("action",e)}),o.socket.on("game:player_connection",function(e){o._dispatch("playerConnection",e)}),o.socket.on("game:realtime",function(e){o._dispatch("realtime",e)}),o.socket.on("game:finished",function(e){void 0!==e.sequence&&(o._lastSequence=e.sequence),o._dispatch("finished",e)}),o.socket.on("game:error",function(e){t.log("Game error: "+(e.message||e.code)),o._dispatch("error",e)}),o.socket.on("game:rematch_request",function(e){o._dispatch("rematchRequest",e)}),o.socket.on("game:restarted",function(e){o._lastSequence=0,o._lastActionApplied=0,o._dispatch("restarted",e)})}catch(e){i(e)}}}(i,n),function(n,i){n._connectViaProxy=function(){var n=this;return n._useProxy&&n.connected?Promise.resolve():(n._useProxy=!0,n._connecting=!0,n._setupProxyListener(),n._connectPromise=new Promise(function(r,o){n._proxyConnectResolve=function(){n.connected=!0,n._connecting=!1,i.log("Game socket connected via parent proxy"),r()},i._post({type:"GAME_CONNECT"}),setTimeout(function(){n.connected||(n._connecting=!1,o(new t(e.CONNECT_TIMEOUT,"Proxy connection timeout")))},1e4)}),n._connectPromise)},n._setupProxyListener=function(){var e=this;e._proxyListenerSetup||(e._proxyListenerSetup=!0,window.addEventListener("message",function(t){if(a(t)){var n;try{n="string"==typeof t.data?JSON.parse(t.data):t.data}catch(e){return}if(n&&"object"==typeof n&&e._useProxy)switch(n.type){case"GAME_CONNECTED":e._proxyConnectResolve&&(e._proxyConnectResolve(),e._proxyConnectResolve=null);break;case"GAME_CONNECT_ERROR":e.connected=!1,e._connecting=!1;break;case"GAME_DISCONNECTED":e.connected=!1,e._dispatch("disconnect",n.reason||"transport");break;case"GAME_RECONNECTED":e.connected=!0,e._dispatch("reconnect",n.attempts||1);break;case"GAME_PLAYER_CONNECTION":e._dispatch("playerConnection",n);break;case"GAME_JOINED":e._joined=!0,void 0!==n.sequence&&(e._lastSequence=n.sequence,e._lastActionApplied=Math.max(e._lastActionApplied,n.sequence)),e._proxyJoinResolve&&(e._proxyJoinResolve(n),e._proxyJoinResolve=null),e._proxyJoinReject=null,e._dispatch("joined",n);break;case"GAME_JOIN_ERROR":e._joined=!1,e._proxyJoinReject&&(e._proxyJoinReject(r(n.message||"Join failed")),e._proxyJoinReject=null),e._proxyJoinResolve=null;break;case"GAME_PLAYER_JOINED":e._dispatch("playerJoined",n);break;case"GAME_PLAYER_LEFT":e._dispatch("playerLeft",n);break;case"GAME_STATE":void 0!==n.sequence&&(e._lastSequence=Math.max(e._lastSequence,n.sequence)),e._dispatch("stateUpdate",n);break;case"GAME_ACTION_DATA":if(void 0!==n.sequence){if(n.sequence<=e._lastActionApplied)break;e._lastActionApplied=n.sequence,e._lastSequence=Math.max(e._lastSequence,n.sequence)}e._dispatch("action",n);break;case"GAME_REALTIME_DATA":e._dispatch("realtime",n);break;case"GAME_FINISHED":void 0!==n.sequence&&(e._lastSequence=n.sequence),e._dispatch("finished",n);break;case"GAME_ERROR":i.log("Game error via proxy: "+(n.message||n.code)),e._dispatch("error",n);break;case"GAME_RESTARTED":e._lastSequence=0,e._lastActionApplied=0,e._dispatch("restarted",n);break;case"GAME_REMATCH_REQUEST":e._dispatch("rematchRequest",n);break;case"GAME_SYNC":void 0!==n.sequence&&(e._lastSequence=n.sequence,e._lastActionApplied=Math.max(e._lastActionApplied,n.sequence)),e._dispatch("sync",n),e._dispatch("stateUpdate",n)}}}))}}(i,n),function(n,i){function o(e){const t=e.roomId||i.config&&i.config.roomId,n=e.playerId||i.user&&"function"==typeof i.user.getId&&i.user.getId()||i.config&&i.config.userId;return t&&n?"_usion_game_state:"+n+":"+t:null}n.join=function(n){const o=this;if(n=n||i.config.roomId,o.roomId===n&&o._joinPromise)return o._joinPromise;if(o.roomId=n,o.playerId=i.user.getId(),o.directMode)return o._joined=!0,o._joinPromise=Promise.resolve({room_id:n,player_id:o.playerId}),o._joinPromise;if(o._useProxy){const r=new Promise(function(r,s){const c=function(e){s(e)};o._proxyJoinResolve=r,o._proxyJoinReject=c,i._post({type:"GAME_JOIN",room_id:n}),setTimeout(function(){o._proxyJoinReject===c&&(o._proxyJoinResolve=null,o._proxyJoinReject=null,s(new t(e.JOIN_TIMEOUT,"Join timeout")))},15e3)});return T(o,r)}let s;return s=o.socket&&o.connected?n?w(o.socket,"game:join",{room_id:n},15e3,e.JOIN_TIMEOUT).then(function(e){if(e.error)throw o._joined=!1,r(e);return o._joined=!0,void 0!==e.sequence&&(o._lastSequence=e.sequence,o._lastActionApplied=Math.max(o._lastActionApplied,e.sequence)),o._dispatch("joined",e),e}):Promise.reject(new t(e.NO_ROOM,"No room ID provided")):Promise.reject(new t(e.NOT_CONNECTED,"Not connected")),T(o,s)},n.joinWorld=function(e){const t=this;return e=e||{},i.matchmaking._joinWorld(e.serviceId).then(function(e){return t.roomId=e.roomId,{roomId:e.roomId,playerIds:e.players||[]}})},n.leave=function(){const e=this;return e.directMode?(e.roomId&&e._sendDirect("leave",{}),e.roomId=null,e._lastSequence=0,e._joined=!1,void(e._joinPromise=null)):e._useProxy?(e.roomId&&i._post({type:"GAME_LEAVE",room_id:e.roomId}),e.roomId=null,e._lastSequence=0,e._joined=!1,void(e._joinPromise=null)):void(e.socket&&e.connected&&e.roomId&&(e.socket.emit("game:leave",{room_id:e.roomId}),e.roomId=null,e._lastSequence=0,e._joined=!1,e._joinPromise=null))},n.action=function(n,r,o){const s=this,c=o&&o.nextTurn,a=!(!o||!o.queueOffline);if(s.directMode)return s._sendDirect("action",{action_type:n||"default",action_data:r||{}}),Promise.resolve({success:!0});if(a&&!s.connected)return s._queueOfflineAction(n,r,o);if(s._useProxy){if(!s.connected)return Promise.reject(new t(e.NOT_CONNECTED,"Not connected"));const o={type:"GAME_ACTION",room_id:s.roomId,action_type:n,action_data:r};return c&&(o.next_turn=c),i._post(o),Promise.resolve({success:!0,acknowledged:!1})}return(s._rejoinPromise||Promise.resolve()).then(function(){if(!s.socket||!s.connected){if(a)return s._queueOfflineAction(n,r,o);throw new t(e.NOT_CONNECTED,"Not connected")}const i={room_id:s.roomId,action_type:n,action_data:r};return c&&(i.next_turn=c),s._emitAction(i,!0)})},n._emitAction=function(n,i){const o=this;return o.socket&&o.connected?w(o.socket,"game:action",n).then(function(t){if(t.error){const s=r(t);if(i&&s.code===e.NOT_IN_ROOM)return o._autoRejoin().then(function(){return o._emitAction(n,!1)});throw s}return void 0!==t.sequence&&(o._lastSequence=t.sequence),t}):Promise.reject(new t(e.NOT_CONNECTED,"Not connected"))},n._autoRejoin=function(){const e=this;if(e._rejoinPromise)return e._rejoinPromise;if(!e.roomId||!e.socket||!e.connected)return Promise.resolve();i.log("Server reports socket not in room - auto-rejoining "+e.roomId);const t=e._lastSequence||0;return e._joined=!1,e._joinPromise=null,e._rejoinPromise=e.join(e.roomId).then(function(){e.requestSync(t)}).catch(function(e){i.log("Auto-rejoin failed: "+(e&&e.message?e.message:String(e)))}).then(function(){e._rejoinPromise=null,e._flushOfflineQueue&&e._flushOfflineQueue()}),e._rejoinPromise},n._queueOfflineAction=function(n,r,o){const s=this;return s._offlineQueue||(s._offlineQueue=[]),s._offlineQueue.length>=20?Promise.reject(new t(e.QUEUE_FULL,"Offline action queue is full (20)")):(i.log("Queued action while offline: "+n),new Promise(function(e,t){s._offlineQueue.push({actionType:n,actionData:r,opts:Object.assign({},o,{queueOffline:!1}),resolve:e,reject:t}),s._ensureOfflineFlushHook()}))},n._ensureOfflineFlushHook=function(){const e=this;e._offlineFlushHooked||(e._offlineFlushHooked=!0,e.on("reconnect",function(){e._flushOfflineQueue()}))},n._flushOfflineQueue=function(){const t=this,n=t._offlineQueue;if(!n||!n.length)return Promise.resolve();if(t._offlineFlushPromise)return t._offlineFlushPromise;if(!t.connected||!t._useProxy&&!t.directMode&&!t._joined)return Promise.resolve();i.log("Flushing "+n.length+" queued action(s) after reconnect");const o=Promise.resolve().then(function i(){if(!n.length)return Promise.resolve();if(!t.connected||!t._useProxy&&!t.directMode&&!t._joined)return Promise.resolve();const o=n[0];return t.action(o.actionType,o.actionData,o.opts).then(function(e){return n[0]===o&&n.shift(),o.resolve(e),i()},function(t){const s=r(t);if(s.code!==e.NOT_CONNECTED&&s.code!==e.NOT_IN_ROOM)return n[0]===o&&n.shift(),o.reject(t),i()})});function s(){t._offlineFlushPromise===o&&(t._offlineFlushPromise=null)}return t._offlineFlushPromise=o,o.then(s,s),o},n.setState=function(n){const o=this;if(o.directMode)return Promise.resolve({success:!1,error:"not_supported_in_direct_mode",code:e.UNSUPPORTED});const s=o._lastSequence||0;return o._useProxy?i._request("GAME_SET_STATE",{room_id:o.roomId,state:n||{},sequence:s}).then(function(e){if(e&&e.error){const t=r(e);return{success:!1,error:t.message,code:t.code}}return e||{success:!0}}).catch(function(t){const n=r(t,e.REQUEST_TIMEOUT);return{success:!1,error:n.message,code:n.code}}):o.socket&&o.connected?w(o.socket,"game:set_state",{room_id:o.roomId,state:n||{},sequence:s}).then(function(e){if(e.error){const t=r(e);return{success:!1,error:t.message,code:t.code}}return Object.keys(e).length?e:{success:!0}}):Promise.reject(new t(e.NOT_CONNECTED,"Not connected"))},n.realtime=function(t,n){const o=this;o.directMode?o._sendDirect("input",{action_type:t,action_data:n||{}}):o._useProxy?i._post({type:"GAME_REALTIME",room_id:o.roomId,action_type:t,action_data:n}):o.socket&&o.connected&&o.socket.emit("game:realtime",{room_id:o.roomId,action_type:t,action_data:n},function(t){if(!t||!t.error)return;const n=r(t);o._dispatch("error",{code:n.code,message:n.message,source:"realtime"}),n.code===e.NOT_IN_ROOM&&o._autoRejoin()})},n.requestSync=function(e){const t=this;e=void 0!==e?e:t._lastSequence,t.directMode?t._sendDirect("ping",{last_sequence:e||0}):t._useProxy&&t.roomId?i._post({type:"GAME_SYNC_REQUEST",room_id:t.roomId,last_sequence:e||0}):t.socket&&t.connected&&t.roomId&&t.socket.emit("game:sync_request",{room_id:t.roomId,last_sequence:e||0})},n.requestRematch=function(){const e=this;e.directMode?e._sendDirect("rematch",{}):e._useProxy&&e.roomId?i._post({type:"GAME_REMATCH",room_id:e.roomId}):e.socket&&e.connected&&e.roomId&&e.socket.emit("game:rematch",{room_id:e.roomId})},n.forfeit=function(){const n=this;return n.directMode?(n._sendDirect("forfeit",{}),Promise.resolve({success:!0})):n._useProxy?(i._post({type:"GAME_FORFEIT",room_id:n.roomId}),Promise.resolve({success:!0})):n.socket&&n.connected?w(n.socket,"game:forfeit",{room_id:n.roomId}).then(function(e){if(e.error)throw r(e);return e}):Promise.reject(new t(e.NOT_CONNECTED,"Not connected"))},n.reportResult=function(n,r){if(r=r||{},!((n=n||{}).draw||"string"==typeof n.winnerId&&n.winnerId))return Promise.reject(new t(e.INVALID_INPUT,"reportResult needs a winnerId (or draw: true)"));const o=n.roomId||this.roomId||i.config&&i.config.roomId||null;if(!o)return Promise.reject(new t(e.NO_ROOM,"reportResult needs a room — join a game first"));let s=null;return Array.isArray(n.standings)&&(s=n.standings.map(function(e){return"string"==typeof e?e:e&&(e.userId||e.user_id)||null}).filter(function(e){return"string"==typeof e&&e}),s.length||(s=null)),i._backendEmit("gc:match_result",{service_id:r.serviceId||i.config&&i.config.serviceId,room_id:o,winner_id:n.draw?null:n.winnerId,draw:!!n.draw,standings:s,scores:n.scores&&"object"==typeof n.scores?n.scores:null,display_score:null!=n.displayScore?String(n.displayScore):null,metric:null!=n.metric?String(n.metric):null,match_id:null!=n.matchId?String(n.matchId):null})},n.invite=function(e){const t=this;e=e||{};const n="undefined"!=typeof window&&(!!window.ReactNativeWebView||!!window.parent&&window.parent!==window),r=t.roomId||i.config&&i.config.roomId||null;if(!n){try{console.warn("[Usion] game.invite needs the Usion app; resolving as not sent.")}catch(e){}return Promise.resolve({success:!1,roomId:r,invited:[]})}const o={roomId:r};return"number"==typeof e.maxPlayers&&e.maxPlayers>0&&(o.maxPlayers=e.maxPlayers),i._request("GAME_INVITE_REQUEST",o,e.timeout||12e4).then(function(e){const n=(e=e||{}).roomId||r||null,i={success:!!e.success,roomId:n,invited:Array.isArray(e.invited)?e.invited:[]};return i.success&&n?Promise.resolve().then(function(){return t.connect()}).then(function(){return t.join(n)}).then(function(){return i}).catch(function(){return i}):i}).catch(function(){return{success:!1,roomId:r,invited:[]}})},n.disconnect=function(){const e=this;if(e._heartbeatInterval&&(clearInterval(e._heartbeatInterval),e._heartbeatInterval=null),e.directMode){if(e.directSocket)try{e.directSocket.close()}catch(e){}return e.directSocket=null,e.connected=!1,e.roomId=null,e._lastSequence=0,e._connecting=!1,e._connectPromise=null,e._joined=!1,e._joinPromise=null,e.directMode=!1,e.directConfig=null,void(e._directSeq=0)}if(e._useProxy)return i._post({type:"GAME_DISCONNECT"}),e.connected=!1,e.roomId=null,e._lastSequence=0,e._connecting=!1,e._connectPromise=null,e._joined=!1,e._joinPromise=null,void(e._useProxy=!1);e.socket&&(e.socket.disconnect(),e.socket=null,e.connected=!1,e.roomId=null,e._lastSequence=0,e._connecting=!1,e._connectPromise=null,e._joined=!1,e._joinPromise=null)},n.saveState=function(e){const t=o(this);if(!t)return!1;try{return localStorage.setItem(t,JSON.stringify({state:e,savedAt:Date.now()})),!0}catch(e){return!1}},n.loadState=function(){const e=o(this);if(!e)return null;try{const t=localStorage.getItem(e);if(!t)return null;const n=JSON.parse(t);return n&&void 0!==n.state?n.state:null}catch(e){return null}},n.clearState=function(){const e=o(this);if(e)try{localStorage.removeItem(e)}catch(e){}},n.debug=function(e){try{var t=window.parent&&window.parent!==window,n=!!window.ReactNativeWebView;if(t||n){var r=Object.assign({},e||{});r._diag=i.diagnostics?i.diagnostics():void 0,i._post({type:"GAME_DEBUG",payload:r})}}catch(e){}},n.isMultiplayer=function(){return"multiplayer"===i.getLaunchParams().mode},n.isConnected=function(){return this.directMode?!(!this.connected||!this.directSocket||this.directSocket.readyState!==WebSocket.OPEN):this._useProxy?!!this.connected:!!(this.connected&&this.socket&&this.socket.connected)}}(i,n),me(i,n),ye(i,n),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("visibilitychange",function(){if("visible"===document.visibilityState&&i.roomId)try{i.requestSync()}catch(e){}}),i}(be),be.UsionError=t,be.ERROR_CODES=e,function(n){n._backendHandlers={},n._boundSockets="undefined"!=typeof WeakSet?new WeakSet:null,n._bindBackendSocket=function(e){if(!e||"function"!=typeof e.onAny)return;if(this._boundSockets){if(this._boundSockets.has(e))return;this._boundSockets.add(e)}const t=this;e.onAny(function(e,n){const r=t._backendHandlers[e];r&&r(n)})},n._backendOn=function(e,t){this._backendHandlers[e]=t;const n=this.game&&this.game.socket;n&&("function"==typeof n.onAny?this._bindBackendSocket(n):"function"==typeof n.on&&n.on(e,t))},n._backendEmit=function(n,i,o){const s=this;function c(s){return new Promise(function(c,a){let u=!1;const l=setTimeout(function(){u||(u=!0,a(new t(e.REQUEST_TIMEOUT,"Backend request timeout")))},o);try{s.emit(n,i||{},function(e){u||(u=!0,clearTimeout(l),e&&e.error?a(r(e)):c(e))})}catch(e){clearTimeout(l),a(r(e))}})}o=o||8e3;const a=s.game&&s.game.socket;if(a&&a.connected)return c(a);if(s._isEmbedded)return s._request("BACKEND_EMIT",{event:n,data:i||{}},o).catch(function(e){throw r(e)});const u=s.config&&s.config.connectionMode||"platform";return!a&&"direct"!==u&&s.game&&"function"==typeof s.game.connect?s.game.connect().then(function(){const n=s.game.socket;if(n&&n.connected)return c(n);throw new t(e.NOT_CONNECTED,"No backend connection")}).catch(function(n){if(n instanceof t)throw n;throw new t(e.NOT_CONNECTED,"Backend connect failed: "+(n&&n.message?n.message:String(n)))}):Promise.reject(new t(e.NOT_CONNECTED,"No backend connection — socket is offline or reconnecting"))}}(be),be.lobby=function(e){const t={code:null,host:null,status:null,members:[]},n={};let r=!1;function i(){r||(r=!0,e._backendOn("lobby:update",function(e){t.code=e.code,t.host=e.host,t.status=e.status,t.members=e.members||[],n.update&&n.update(e)}),e._backendOn("lobby:started",function(e){t.status="started",n.started&&n.started(e)}))}function o(t,n){return i(),e._backendEmit(t,n)}return{get state(){return t},onUpdate:function(e){n.update=e,i()},onStarted:function(e){n.started=e,i()},create:async function(e){e=e||{};const n=await o("lobby:create",{max_players:e.maxPlayers||8,public:!!e.public});return n&&n.code&&(t.code=n.code),n},join:async function(e){const n=await o("lobby:join",{code:String(e||"").toUpperCase()});return n&&n.code&&(t.code=n.code),n},leave:function(){return t.code=null,o("lobby:leave",{}).catch(function(){})},setReady:function(e){return o("lobby:ready",{ready:!1!==e})},allReady:function(){return t.members.length>0&&t.members.every(function(e){return e.ready})},isHost:function(){const n=e.user&&e.user.getId&&e.user.getId();return!(!t.host||!n||t.host!==n)},start:function(e){return o("lobby:start",{room_id:e})},queue:async function(t,n){n=n||{};const r=e.config&&e.config.apiUrl||"",i=e.user&&e.user.getToken&&e.user.getToken();if(!r)throw new Error("No apiUrl configured");const o=await fetch(r.replace(/\/$/,"")+"/games/matchmake",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+i},body:JSON.stringify({service_id:t,conversation_id:n.conversationId||"standalone_"+t})});if(!o.ok)throw new Error("Matchmake failed: HTTP "+o.status);return o.json()}}}(be),be.leaderboard=function(e){function t(t){return t&&t.serviceId||e.config&&e.config.serviceId}return{submit:function(n,r,i){return e._backendEmit("lb:submit",{service_id:t(i),score:n,metadata:null!=r?r:null})},scores:function(n,r){var i=Array.isArray(n)?n:[n];return e._backendEmit("lb:scores",{service_id:t(r),user_ids:i}).then(function(e){return e&&e.scores||{}})},friends:function(n){return n=n||{},e._backendEmit("lb:friends",{service_id:t(n),limit:n.limit||50}).then(function(e){return e&&e.entries||[]})},top:function(n){return n=n||{},e._backendEmit("lb:top",{service_id:t(n),limit:n.limit||20}).then(function(e){return e&&e.entries||[]})},me:function(n){return e._backendEmit("lb:me",{service_id:t(n)})}}}(be),be.cloud=function(e){function t(t){return t&&t.serviceId||e.config&&e.config.serviceId}function n(n,r,i,o){var s=Object.assign({service_id:t(o),scope:r},i);return e._backendEmit(n,s)}function r(e){return{get:function(t,r){return n("kv:get",e,{key:t},r).then(function(e){return e&&e.exists?e.value:null})},set:function(t,r,i){return n("kv:set",e,{key:t,value:r},i)},remove:function(t,r){return n("kv:remove",e,{key:t},r)},keys:function(t){return n("kv:keys",e,{},t).then(function(e){return e&&e.keys||[]})}}}var i=r("user");return i.shared=r("shared"),i.shared.incr=function(e,t,r){return n("kv:incr","shared",{key:e,delta:null==t?1:t},r).then(function(e){return e&&e.value})},i}(be),be.matchmaking=function(n){let i=null,o=null,s=!1;function c(e){return{roomId:e&&e.room_id,players:e&&e.player_ids||[],serviceId:e&&e.service_id}}function a(){s||(s=!0,n._backendOn("mm:matched",function(e){const t=c(e);if(o&&o(t),i){const e=i;i=null,e.resolve(t)}}))}function u(o,s,u){if(a(),i){const n=i;i=null,n.reject(new t(e.SUPERSEDED,"Superseded by a newer find()"))}let l=null;const d={},f=new Promise(function(e,t){d.resolve=function(t){l&&clearTimeout(l),e(t)},d.reject=function(e){l&&clearTimeout(l),i===d&&(i=null),t(e)}});return i=d,s>0&&(l=setTimeout(function(){l=null,n._backendEmit("mm:cancel",{}).catch(function(){}),d.reject(new t(e.MATCH_TIMEOUT,u+s+"ms"))},s)),n._backendEmit("mm:join",o).then(function(e){e&&e.matched&&e.room_id&&i===d&&(i=null,d.resolve(c(e)))}).catch(function(e){i===d&&d.reject(r(e))}),f}return{onMatch:function(e){o=e,a()},find:function(e,t){t=t||{};return u({service_id:e||n.config&&n.config.serviceId,size:t.size||2},t.timeout,"No match within ")},_joinWorld:function(e){return u({service_id:e||n.config&&n.config.serviceId,mode:"world"},15e3,"No world placement within ")},cancel:function(){if(i){const n=i;i=null,n.reject(new t(e.CANCELLED,"cancelled"))}return n._backendEmit("mm:cancel",{})}}}(be),be.notify=function(e){function t(t){return t&&t.serviceId||e.config&&e.config.serviceId}return{send:function(n){return n=n||{},e._backendEmit("notify:send",{service_id:t(n),title:n.title,body:n.body,path:n.path})},setMuted:function(n,r){return e._backendEmit("notify:set_pref",{service_id:t(r),muted:!!n})},isMuted:function(n){return e._backendEmit("notify:get_pref",{service_id:t(n)}).then(function(e){return!(!e||!e.muted)})}}}(be),be.permissions=function(e){function t(e){return"string"==typeof e?e?[e]:[]:Array.isArray(e)?e.filter(function(e){return"string"==typeof e&&e}):[]}function n(){return"undefined"!=typeof window&&(!!window.ReactNativeWebView||!!window.parent&&window.parent!==window)}function r(e){const t={};return e.forEach(function(e){t[e]=!1}),t}function i(e,t){const n=t||{};return{granted:e.length>0&&e.every(function(e){return!!n[e]}),permissions:n}}const o={_requestTimeoutMs:12e4,request:function(c,u){const l=t(c),d=u&&"string"==typeof u.reason?u.reason:void 0;if(!n()){try{console.warn("[Usion] permissions.request needs the Usion app; resolving as not granted.")}catch(e){}return Promise.resolve(i(l,r(l)))}return new Promise(function(t){const n=s();let c=!1,u=null;function f(e){c||(c=!0,u&&clearTimeout(u),window.removeEventListener("message",_),t(e))}function _(e){if(!a(e))return;let t;try{t="string"==typeof e.data?JSON.parse(e.data):e.data}catch(e){return}t&&t._requestId===n&&"PERMISSION_RESULT"===t.type&&f(i(l,t.permissions))}window.addEventListener("message",_),u=setTimeout(function(){c||o.query(l).then(function(e){f(i(l,e))}).catch(function(){f(i(l,r(l)))})},o._requestTimeoutMs||12e4),e._post({type:"PERMISSION_REQUEST",_requestId:n,permissions:l,reason:d})})},query:function(i){const o=t(i);return n()?e._request("PERMISSION_QUERY",{permissions:o},8e3).then(function(e){return e&&e.permissions||{}}):Promise.resolve(r(o))},has:function(e){return o.query([e]).then(function(t){return!(!t||!t[e])})}};return o}(be),be.netcode=ve,Object.assign(be,function(e){return{saveResult:function(t,n){return e._request("SAVE_RESULT",{data:t,metadata:n||{}},15e3)},deleteResult:function(t){return e._request("DELETE_RESULT",{resultId:t})},getResults:function(){return e._results||[]}}}(be)),Object.assign(be,function(e){return{claimBackButton:function(t){e._backButtonCallback=t,e._post({type:"CLAIM_BACK_BUTTON"})},releaseBackButton:function(){e._backButtonCallback=null,e._post({type:"RELEASE_BACK_BUTTON"})}}}(be)),Object.assign(be,function(e){return{onHostNavigate:function(t){e._hostNavigateCallback=t,e._post({type:"HOST_NAVIGATE_SUBSCRIBED"})},offHostNavigate:function(){e._hostNavigateCallback=null,e._post({type:"HOST_NAVIGATE_UNSUBSCRIBED"})},openChat:function(t){t=t||{},e._post({type:"OPEN_CHAT_TAB",prefill:"string"==typeof t.prefill?t.prefill:void 0})},reportPath:function(t){"string"==typeof t&&t&&e._post({type:"TAB_CHANGED",path:t})}}}(be)),Object.assign(be,v),Object.assign(be,b),be}();"undefined"!=typeof window?window.Usion=Usion:"undefined"!=typeof globalThis&&(globalThis.Usion=Usion);
1
+ /*! @usions/sdk v2.31.0 — minified build; source: packages/sdk/src/modules (github.com/ugshanyu/usionthemobile) */
2
+ var Usion=function(){"use strict";const e={NOT_CONNECTED:"NOT_CONNECTED",NO_ROOM:"NO_ROOM",ROOM_NOT_FOUND:"ROOM_NOT_FOUND",NOT_PARTICIPANT:"NOT_PARTICIPANT",NOT_IN_ROOM:"NOT_IN_ROOM",NOT_AUTHORITY:"NOT_AUTHORITY",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",JOIN_TIMEOUT:"JOIN_TIMEOUT",CONNECT_TIMEOUT:"CONNECT_TIMEOUT",INIT_TIMEOUT:"INIT_TIMEOUT",MATCH_TIMEOUT:"MATCH_TIMEOUT",STATE_TOO_LARGE:"STATE_TOO_LARGE",INVALID_STATE:"INVALID_STATE",STALE_STATE:"STALE_STATE",INVALID_NEXT_TURN:"INVALID_NEXT_TURN",INVALID_INPUT:"INVALID_INPUT",NOT_FOUND:"NOT_FOUND",QUOTA_EXCEEDED:"QUOTA_EXCEEDED",VALUE_TOO_LARGE:"VALUE_TOO_LARGE",LOBBY_FULL:"LOBBY_FULL",LOBBY_CLOSED:"LOBBY_CLOSED",WORLD_FULL:"WORLD_FULL",CONFLICT:"CONFLICT",RATE_LIMITED:"RATE_LIMITED",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",QUEUE_FULL:"QUEUE_FULL",CANCELLED:"CANCELLED",SUPERSEDED:"SUPERSEDED",UNSUPPORTED:"UNSUPPORTED",UNKNOWN:"UNKNOWN"};class t extends Error{constructor(t,n){super(n||t),this.name="UsionError",this.code=e[t]?t:e.UNKNOWN,this.retryAfter=void 0}}const n=[[/not authenticated/i,e.NOT_AUTHENTICATED],[/room_id required|no room id/i,e.NO_ROOM],[/room not found/i,e.ROOM_NOT_FOUND],[/not in room/i,e.NOT_IN_ROOM],[/not a participant/i,e.NOT_PARTICIPANT],[/room authority/i,e.NOT_AUTHORITY],[/exceeds .*limit/i,e.STATE_TOO_LARGE],[/stale checkpoint|stale state/i,e.STALE_STATE],[/state must be/i,e.INVALID_STATE],[/next_turn must be/i,e.INVALID_NEXT_TURN],[/rate limit|too many/i,e.RATE_LIMITED],[/join timeout/i,e.JOIN_TIMEOUT],[/connection timeout|connect timeout/i,e.CONNECT_TIMEOUT],[/request timeout/i,e.REQUEST_TIMEOUT],[/not connected/i,e.NOT_CONNECTED],[/quota exceeded/i,e.QUOTA_EXCEEDED],[/value too large/i,e.VALUE_TOO_LARGE],[/lobby is full/i,e.LOBBY_FULL],[/lobby is not open/i,e.LOBBY_CLOSED],[/world room is full/i,e.WORLD_FULL],[/not found|unknown service/i,e.NOT_FOUND],[/conflict/i,e.CONFLICT],[/cancelled/i,e.CANCELLED],[/superseded/i,e.SUPERSEDED]];function r(r,i){if(r instanceof t)return r;if(r&&"object"==typeof r){const n="string"==typeof r.code&&e[r.code]?r.code:null,i=r.message||r.error;if(n){const e=new t(n,"string"==typeof i?i:n),o=null!=r.retry_after?r.retry_after:r.retryAfter;return"number"==typeof o&&isFinite(o)&&(e.retryAfter=o),e}r instanceof Error||"string"!=typeof i||(r=i)}const o=r&&r.message?r.message:String(r||"Unknown error");for(let e=0;e<n.length;e++)if(n[e][0].test(o))return new t(n[e][1],o);return new t(i||e.UNKNOWN,o)}let i=0;const o={};function s(){return++i}let c=null;function a(e){return"undefined"==typeof window||(!!window.ReactNativeWebView||(window.parent===window||(!e||!e.source||e.source===window.parent)&&(null===c&&(c=function(){try{if(window.location.ancestorOrigins&&window.location.ancestorOrigins.length)return window.location.ancestorOrigins[0]}catch(e){}try{if("undefined"!=typeof document&&document.referrer)return new URL(document.referrer).origin}catch(e){}return null}()),!(c&&e&&e.origin&&e.origin!==c))))}const u={version:"2.31.0",config:{},_initialized:!1,_initCallback:null,_messageHandlerRegistered:!1,_results:[],_backButtonCallback:null,init:function(n,i){const s=this;return n&&"object"==typeof n&&(i=n,n=null),i=i||{},s._initialized?(n&&n(s.config),Promise.resolve(s.config)):(n&&(s._initCallback=n),s._initPromise||(s._initPromise=new Promise(function(e,t){s._initResolve=e,s._initReject=t}),s._initPromise.catch(function(){})),i.timeout>0&&!s._initTimer&&(s._initTimer=setTimeout(function(){s._initTimer=null,!s._initialized&&s._initReject&&s._initReject(new t(e.INIT_TIMEOUT,"No INIT from host within "+i.timeout+"ms — host silent or running standalone"))},i.timeout)),s._messageHandlerRegistered||(s._messageHandlerRegistered=!0,window.addEventListener("message",function(e){if(!a(e))return;let t;try{t="string"==typeof e.data?JSON.parse(e.data):e.data}catch(e){return}if("INIT"===t.type&&t.config){if(s._initialized)return t.config.authToken&&(s.config.authToken=t.config.authToken,s.user&&(s.user._token=t.config.authToken)),void 0!==t.config.balance&&s.wallet&&(s.wallet._balance=t.config.balance),void(!0!==t.config.userIsAdult&&!1!==t.config.userIsAdult||!s.user||(s.config.userIsAdult=t.config.userIsAdult,s.user._isAdult=t.config.userIsAdult));s.config=t.config,s._initialized=!0,s._isEmbedded=!0,t.config.userId&&(s.user._id=t.config.userId,s.user._name=t.config.userName,s.user._avatar=t.config.userAvatar,s.user._token=t.config.authToken,s.user._isAdult=!0===t.config.userIsAdult||!1===t.config.userIsAdult?t.config.userIsAdult:null),t.config.sessionId&&(s.session._id=t.config.sessionId,s.session._data=t.config.sessionData||{}),void 0!==t.config.balance&&(s.wallet._balance=t.config.balance),t.config.results&&(s._results=t.config.results),s._initCallback&&s._initCallback(t.config),s._initTimer&&(clearTimeout(s._initTimer),s._initTimer=null),s._initResolve&&s._initResolve(t.config)}if(t._requestId&&o[t._requestId]){const{resolve:e,reject:n}=o[t._requestId];delete o[t._requestId],t.error?n(r(t)):e(t)}if("BALANCE_UPDATE"===t.type&&(s.wallet._balance=t.balance,s.wallet._balanceChangeHandler&&s.wallet._balanceChangeHandler(t.balance)),"BACK_BUTTON_PRESSED"===t.type&&s._backButtonCallback){var n=s._backButtonCallback;s._backButtonCallback=null,n()}if("BOT_MESSAGE"===t.type&&s.bot&&s.bot._messageHandler&&s.bot._messageHandler(t.message),"HOST_NAVIGATE"===t.type&&"string"==typeof t.path&&(s.config&&(s.config.launchPath=t.path),s._hostNavigateCallback&&s._hostNavigateCallback({path:t.path,tab:t.tab||null})),"BACKEND_EVENT"===t.type&&t.event&&s._backendHandlers){const e=s._backendHandlers[t.event];e&&e(t.data)}if("GAME_ROOM_ASSIGNED"===t.type&&t.roomId&&s.game){var i=t.roomId;s.config.roomId=i,s.config.mode="multiplayer",s.game._dispatch("roomAssigned",{roomId:i}),Promise.resolve().then(function(){return s.game.connect()}).then(function(){return s.game.join(i)}).catch(function(){})}}),this._setupInteractionBeacon(),this._post({type:"READY"})),s._initPromise)},_setupInteractionBeacon:function(){const e=this;if(e._interactionBeaconSetup)return;if(e._interactionBeaconSetup=!0,"undefined"==typeof window||!window.addEventListener)return;const t=["pointerdown","mousedown","touchstart","keydown"];function n(r){if(!(r&&!1===r.isTrusted||e._interactionReported)){e._interactionReported=!0;for(let e=0;e<t.length;e++)try{window.removeEventListener(t[e],n,!0)}catch(e){}e._post({type:"USER_INTERACTION"})}}for(let e=0;e<t.length;e++)try{window.addEventListener(t[e],n,{capture:!0,passive:!0})}catch(r){try{window.addEventListener(t[e],n,!0)}catch(e){}}},getTheme:function(){return this.config.theme||"light"},getLanguage:function(){return this.config.language||"en"},getLaunchParams:function(){var e=this.config||{},t="single"===e.mode||"multiplayer"===e.mode?e.mode:e.roomId?"multiplayer":"single";return{path:e.launchPath||null,ref:e.ref||e.launchRef||null,roomId:e.roomId||null,mode:t}},_post:function(e){const t=JSON.stringify(e);window.ReactNativeWebView?window.ReactNativeWebView.postMessage(t):window.parent!==window&&window.parent.postMessage(e,"*")},_request:function(n,r,i){const c=this;return i=i||5e3,new Promise(function(a,u){const l=s(),d=setTimeout(function(){delete o[l],u(new t(e.REQUEST_TIMEOUT,"Request timeout"))},i);o[l]={resolve:function(e){clearTimeout(d),a(e)},reject:function(e){clearTimeout(d),u(e)}},c._post({type:n,_requestId:l,...r})})}};var l="_d:",d="_migrated_v2";function f(e){return l+e}function _(e,t,n){return e._backendEmit(t,Object.assign({service_id:e.config&&e.config.serviceId,scope:"storage"},n))}function h(e,t){return e._request("STORAGE_GET",{key:t}).then(function(e){return e?e.value:null})}function p(e,t,n){return e._request("STORAGE_SET",{key:t,value:n})}function m(e,t){return e._request("STORAGE_REMOVE",{key:t})}function y(e){return e._request("STORAGE_KEYS",{}).then(function(e){return e&&e.keys||[]})}function g(e){return e.catch(function(){})}const v={setLoading:function(e,t){const n="string"==typeof e?document.querySelector(e):e;n&&(t?(n.classList.add("usion-btn-loading"),n.disabled=!0,n.dataset.originalText=n.textContent):(n.classList.remove("usion-btn-loading"),n.disabled=!1,n.dataset.originalText&&(n.textContent=n.dataset.originalText)))},toggle:function(e,t){const n="string"==typeof e?document.querySelector(e):e;n&&(t?(n.classList.remove("usion-hidden","hidden"),n.classList.add("usion-visible")):(n.classList.add("usion-hidden"),n.classList.remove("usion-visible")))},charCount:function(e,t,n){const r="string"==typeof e?document.querySelector(e):e,i="string"==typeof t?document.querySelector(t):t;function o(){const e=r.value.length;i.textContent=e+" / "+n,i.classList.remove("warning","error"),e>.9*n?i.classList.add("error"):e>.7*n&&i.classList.add("warning")}r&&i&&(r.addEventListener("input",o),o())},selectionGrid:function(e,t,n){const r=document.querySelector(e);if(!r)return;let i=null;return r.querySelectorAll(t).forEach(function(e){e.addEventListener("click",function(){r.querySelectorAll(t).forEach(function(e){e.classList.remove("selected")}),e.classList.add("selected"),i=e.dataset.value||e.dataset.id,n&&n(i,e)})}),{getSelected:function(){return i},clear:function(){r.querySelectorAll(t).forEach(function(e){e.classList.remove("selected")}),i=null}}}},b={requestPayment:function(e,t,n){return this.wallet.requestPayment(e,t,n)},diagnostics:function(){const e=this.game||{};return{version:this.version,transport:e.directMode?"direct":e._useProxy?"proxy":e.socket?"socket":"none",connected:!!e.connected,joined:!!e._joined,roomId:e.roomId||null,playerId:e.playerId||null,lastSequence:e._lastSequence||0,lastActionApplied:e._lastActionApplied||0,rejoining:!!e._rejoinPromise}},submit:function(e){this._post({type:"SUBMIT",data:e})},error:function(e){this._post({type:"ERROR",message:e})},exit:function(e){var t={type:"EXIT"};e&&"number"==typeof e.backCount&&e.backCount>1&&(t.backCount=e.backCount),this._post(t)},share:function(e,t){var n=Object.assign({},t,{contentType:e,serviceId:this.config.serviceId,serviceName:this.config.serviceName});this._post({type:"SHARE",contentType:e,data:n})},shareFile:function(e,t){var n={url:e};return(t=t||{}).filename&&(n.filename=t.filename),t.mimeType&&(n.mimeType=t.mimeType),t.title&&(n.title=t.title),t.text&&(n.text=t.text),this._request("SHARE_FILE",n,12e4)},shareToFeed:function(e,t){var n=Object.assign({},t,{contentType:e,serviceId:this.config.serviceId,serviceName:this.config.serviceName});return this._request("SHARE_TO_FEED",n,3e4)},download:function(e,t,n){t&&"object"==typeof t&&(t=(n=t).filename),n=n||{};var r={url:e,filename:t||n.filename||"download.mp4"};return n.mimeType&&(r.mimeType=n.mimeType),n.destination&&(r.destination=n.destination),n.title&&(r.title=n.title),this._request("DOWNLOAD_FILE",r,12e4)},log:function(e){this._post({type:"LOG",msg:e}),console.log("[Usion]",e)},on:function(e,t){function n(n){if(!a(n))return;let r;try{r="string"==typeof n.data?JSON.parse(n.data):n.data}catch(e){return}r.type===e&&t(r)}return window.addEventListener("message",n),function(){window.removeEventListener("message",n)}}};function E(e,t){var n={liveness:{probeAfterMs:4e3,deadAfterMs:12e3},backpressureBytes:8192,lastInboundAt:0,lastProbeAt:0,lastWatchdogAt:0,livenessGraceUntil:0,lastCloseCode:null,declaredDead:!1,watchdogTimer:null,drainTimer:null,pendingInput:null,visHandler:null,lastVisResyncAt:0,wrappedDisconnect:!1,rtt:null,jitter:0,quality:"dead"};function r(){if(null!=n.rtt)return{rtt:n.rtt,jitter:n.jitter};var t=e._pingMeter;return t&&null!=t.rtt?{rtt:t.rtt,jitter:t.jitter}:{rtt:null,jitter:null}}function i(){var t=function(){var t=e.getConnectionState?e.getConnectionState():e.connected?"connected":"disconnected";if(n.declaredDead||"disconnected"===t)return"dead";if(e.directMode&&(!e.directSocket||1!==e.directSocket.readyState))return"dead";var i=r().rtt||0,o=e.directMode&&n.lastInboundAt?Date.now()-n.lastInboundAt:0;return i<150&&o<2e3?"good":i<400&&o<5e3?"fair":"poor"}();if(t!==n.quality){var i=n.quality;n.quality=t,e._dispatch("networkQuality",{quality:t,prev:i,stats:e.getNetworkStats()})}}function o(){n.watchdogTimer&&(clearInterval(n.watchdogTimer),n.watchdogTimer=null)}function s(){var t=e.directSocket;if(t&&1===t.readyState){var r=Date.now(),i=function(){};i.sentAt=r,i.statsOnly=!0,e._pongWaiters.push(i),n.lastProbeAt=r,e._sendDirect("ping",{t:r})}}function c(){var r=e.directSocket;if(e.directMode&&r&&1===r.readyState){if(n.liveness){var c=Date.now(),a=n.lastWatchdogAt&&c-n.lastWatchdogAt>2e3;if(n.lastWatchdogAt=c,"undefined"!=typeof document&&"hidden"===document.visibilityState)return void(n.livenessGraceUntil=c+n.liveness.deadAfterMs);if(a)return n.livenessGraceUntil=c+n.liveness.deadAfterMs,s(),void i();var u=c-n.lastInboundAt;if(u>=n.liveness.deadAfterMs&&c>=n.livenessGraceUntil){n.declaredDead=!0,o(),t.log("Direct socket liveness timeout - declaring dead"),i(),e._dispatch("disconnect","liveness_timeout");try{r.close()}catch(e){}return}u>=n.liveness.probeAfterMs&&c-n.lastProbeAt>=n.liveness.probeAfterMs&&s()}i()}else o()}function a(){n.drainTimer=null;var t=e.directSocket;if(t&&1===t.readyState){if(null!=n.pendingInput)if(t.bufferedAmount>n.backpressureBytes)n.drainTimer=setTimeout(a,50);else{var r=n.pendingInput;n.pendingInput=null,e._sendDirect("input",r)}}else n.pendingInput=null}function u(){o(),n.drainTimer&&(clearTimeout(n.drainTimer),n.drainTimer=null),n.pendingInput=null,function(){n.visHandler&&"undefined"!=typeof document&&document.removeEventListener&&document.removeEventListener("visibilitychange",n.visHandler);n.visHandler=null}(),e._pongWaiters&&e._pongWaiters.length&&(e._pongWaiters=e._pongWaiters.filter(function(e){return!e.statsOnly}))}e._res=n,e.getNetworkStats=function(){var t=!!e.directMode,i=t?e.directSocket:null,o=r();return{transport:t?"direct":"relay",connectionState:e.getConnectionState?e.getConnectionState():"disconnected",quality:n.quality,rtt:o.rtt,jitter:o.jitter,lastInboundAgeMs:t&&n.lastInboundAt?Math.max(0,Date.now()-n.lastInboundAt):null,bufferedAmount:i?i.bufferedAmount||0:null}},e.onNetworkQuality=function(t){return e._setHandler("networkQuality",t)},e._resConfigure=function(e){if(!1===e.liveness)n.liveness=null;else{var t=e.liveness&&"object"==typeof e.liveness?e.liveness:{},r=isFinite(t.probeAfterMs)?Math.max(1e3,t.probeAfterMs):4e3,i=isFinite(t.deadAfterMs)?t.deadAfterMs:12e3;n.liveness={probeAfterMs:r,deadAfterMs:Math.max(i,r+2e3)}}!1===e.backpressureBytes||0===e.backpressureBytes?n.backpressureBytes=0:"number"==typeof e.backpressureBytes&&e.backpressureBytes>0&&(n.backpressureBytes=e.backpressureBytes)},e._resOnOpen=function(){if(n.declaredDead=!1,n.lastCloseCode=null,n.lastInboundAt=Date.now(),n.lastProbeAt=0,n.lastWatchdogAt=Date.now(),n.livenessGraceUntil=0,o(),n.watchdogTimer=setInterval(c,1e3),function(){if("undefined"==typeof document||!document.addEventListener||n.visHandler)return;n.visHandler=function(){if("visible"===document.visibilityState&&e.directMode&&e._joined){var t=Date.now();if(n.liveness&&(n.livenessGraceUntil=t+n.liveness.deadAfterMs),n.lastWatchdogAt=t,n.lastProbeAt=0,s(),t-n.lastVisResyncAt>=2e3){n.lastVisResyncAt=t;try{e.requestSync(e._lastSequence||0)}catch(e){}}}},document.addEventListener("visibilitychange",n.visHandler)}(),!n.wrappedDisconnect){n.wrappedDisconnect=!0;var t=e.disconnect;e.disconnect=function(){return u(),t.apply(e,arguments)}}i()},e._resOnClose=function(e){n.lastCloseCode=e&&"number"==typeof e.code?e.code:null,u(),i()},e._resOnPong=function(e){e&&"number"==typeof e.sentAt&&function(e){if(e>=0){if(null==n.rtt)return n.rtt=e,void(n.jitter=0);n.jitter+=.3*(Math.abs(e-n.rtt)-n.jitter),n.rtt+=.3*(e-n.rtt)}}(Date.now()-e.sentAt),i()},e._resCanReuseToken=function(){if(4401===n.lastCloseCode)return!1;var t=e.directConfig;if(!t||!t.ws_url||!t.access_token)return!1;var r=function(e){if("number"==typeof e&&isFinite(e))return e>1e12?e:1e3*e;if("string"==typeof e&&e){var t=Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(e)?e:e+"Z");return isNaN(t)?null:t}return null}(t.expires_at);return null!=r&&r-Date.now()>3e4},e._resHoldInput=function(t){if(!n.backpressureBytes)return!1;var r=e.directSocket;return!(!r||!(null!=n.pendingInput||r.bufferedAmount>n.backpressureBytes))&&(n.pendingInput=t,n.drainTimer||(n.drainTimer=setTimeout(a,50)),!0)},e.on("disconnect",i),e.on("connectionState",i)}function T(n,r,i,o,s){return o=o||1e4,s=s||e.REQUEST_TIMEOUT,new Promise(function(c,a){let u=!1;const l=setTimeout(function(){u||(u=!0,a(new t(s,s===e.JOIN_TIMEOUT?"Join timeout":"Game request timeout")))},o);try{n.emit(r,i,function(e){u||(u=!0,clearTimeout(l),c(e||{}))})}catch(e){if(u)return;u=!0,clearTimeout(l),a(e)}})}function w(e,t){return e._joinPromise=t,t.catch(function(){e._joined=!1,e._joinPromise===t&&(e._joinPromise=null)}),t}function S(e,t,n){let r=(t-e)%n;const i=n/2;return r>i&&(r-=n),r<-i&&(r+=n),r}function I(e,t,n,r){return"deg"===r?e+S(e,t,360)*n:"rad"===r?e+S(e,t,2*Math.PI)*n:e+(t-e)*n}class A{constructor(e=120){this._items=[],this._maxSize=e}add(e){this._items.push(e),this._items.length>this._maxSize&&this._items.shift()}get size(){return this._items.length}setMaxSize(e){this._maxSize=Math.max(2,0|e)}latest(){return this._items.length?this._items[this._items.length-1]:null}prevLatest(){return this._items.length>=2?this._items[this._items.length-2]:null}clear(){this._items=[]}straddle(e){const t=this._items;if(0===t.length)return[null,null];if(1===t.length)return[t[0],t[0]];if(e<=t[0].time)return[t[0],t[0]];const n=t[t.length-1];if(e>=n.time)return[n,n];for(let n=t.length-1;n>0;n--)if(t[n-1].time<=e&&e<=t[n].time)return[t[n-1],t[n]];return[n,n]}}function O(e,t){return t?Array.isArray(e[t])?e[t]:[]:Array.isArray(e)?e:[]}class k{constructor(e={}){const t=e.serverFps||20;this._frameMs=1e3/t,this.vault=new A(e.maxSize||120),this._fixedBuffer=null!=e.bufferMs?e.bufferMs:Math.ceil(3*this._frameMs),this._bufferMs=this._fixedBuffer,this._adaptive=!!e.adaptive,this._minBuffer=null!=e.minBufferMs?e.minBufferMs:Math.ceil(2*this._frameMs),this._maxBuffer=null!=e.maxBufferMs?e.maxBufferMs:Math.ceil(8*this._frameMs),this._extrapolationMs=e.extrapolationMs||0,this._useServerTime=!!e.serverTime,this._now=e.now||(()=>Date.now()),this._lastArrival=null,this._avgInterval=this._frameMs,this._jitter=0,this._offset=null}getBufferMs(){return this._bufferMs}setBufferMs(e){this._fixedBuffer=Math.max(0,0|e),this._bufferMs=this._fixedBuffer}getJitter(){return this._jitter}add(e){if(!e)return;const t=this._now(),n=void 0!==e.state?e.state:e,r=e.time;if(null!=this._lastArrival){const e=t-this._lastArrival;if(this._avgInterval+=.1*(e-this._avgInterval),this._jitter+=.1*(Math.abs(e-this._avgInterval)-this._jitter),this._adaptive){const e=this._avgInterval+2*this._jitter;this._bufferMs=Math.max(this._minBuffer,Math.min(this._maxBuffer,e))}}if(this._lastArrival=t,this._useServerTime&&"number"==typeof r){const e=t-r;this._offset=null==this._offset?e:this._offset+.05*(e-this._offset)}const i=this._useServerTime&&"number"==typeof r?r:t;this.vault.add({time:i,state:n})}_renderTime(){return this._useServerTime&&null!=this._offset?this._now()-this._offset-this._bufferMs:this._now()-this._bufferMs}calc(e,t){const n=this._renderTime(),r=this.vault.latest();if(!r)return null;const i=String(e||"").trim().split(/\s+/).filter(Boolean).map(e=>{const t=e.match(/^(.+?)\((deg|rad)\)$/);return t?{key:t[1],type:t[2]}:{key:e,type:"linear"}});if(n>r.time)return this._extrapolationMs>0?this._extrapolate(n,i,t):O(r.state,t).map(e=>Object.assign({},e));const[o,s]=this.vault.straddle(n);if(!o||!s)return null;let c=0;return s.time!==o.time&&(c=(n-o.time)/(s.time-o.time),c=c<0?0:c>1?1:c),this._blend(O(o.state,t),O(s.state,t),c,i)}_blend(e,t,n,r){const i={};for(let t=0;t<e.length;t++)i[e[t].id]=e[t];return t.map(e=>{const t=i[e.id],o=Object.assign({},e);if(t)for(let i=0;i<r.length;i++){const{key:s,type:c}=r[i],a=t[s],u=e[s];"number"==typeof a&&"number"==typeof u&&(o[s]=I(a,u,n,c))}return o})}_extrapolate(e,t,n){const r=this.vault.latest(),i=this.vault.prevLatest(),o=O(r.state,n);if(!i||r.time<=i.time)return o.map(e=>Object.assign({},e));const s=Math.min(e-r.time,this._extrapolationMs),c=r.time-i.time,a={},u=O(i.state,n);for(let e=0;e<u.length;e++)a[u[e].id]=u[e];return o.map(e=>{const n=a[e.id],r=Object.assign({},e);if(n)for(let i=0;i<t.length;i++){const{key:o}=t[i],a=n[o],u=e[o];if("number"==typeof a&&"number"==typeof u){const e=(u-a)/c;r[o]=u+e*s}}return r})}}class M{constructor(e={}){if("function"!=typeof e.apply)throw new Error("Predictor requires an apply(state, input) function");this._apply=e.apply,this._state=void 0!==e.initialState?e.initialState:null,this._seq=0,this._pending=[],this._smoothKeys=function(e){if(!e)return null;let t=null!=e.keys?e.keys:e;return"string"==typeof t&&(t=t.trim().split(/\s+/).filter(Boolean)),Array.isArray(t)&&t.length?t:null}(e.smooth),this._smoothRate=e.smooth&&null!=e.smooth.rate?e.smooth.rate:.2,this._snapTo=e.smooth&&null!=e.smooth.snapTo?e.smooth.snapTo:.001,this._error={}}get state(){return this._state}get pending(){return this._pending.slice()}get lastSeq(){return this._seq}predict(e){this._seq+=1;const t=this._seq;return this._pending.push({seq:t,input:e}),this._state=this._apply(this._state,e),{seq:t,state:this._state}}reconcile(e,t){const n=this._state,r=null==t?-1:t;this._pending=this._pending.filter(e=>e.seq>r);let i=e;for(let e=0;e<this._pending.length;e++)i=this._apply(i,this._pending[e].input);if(this._smoothKeys&&n&&i)for(let e=0;e<this._smoothKeys.length;e++){const t=this._smoothKeys[e];"number"==typeof n[t]&&"number"==typeof i[t]&&(this._error[t]=(this._error[t]||0)+(n[t]-i[t]))}return this._state=i,this._state}view(e){if(!this._smoothKeys||!this._state||"object"!=typeof this._state)return this._state;const t=null!=e?e:this._smoothRate,n=Array.isArray(this._state)?this._state.slice():Object.assign({},this._state);for(let e=0;e<this._smoothKeys.length;e++){const r=this._smoothKeys[e];let i=this._error[r]||0;"number"==typeof n[r]&&0!==i&&(n[r]=n[r]+i),i*=1-t,Math.abs(i)<this._snapTo&&(i=0),this._error[r]=i}return n}reset(e){this._state=void 0!==e?e:null,this._seq=0,this._pending=[],this._error={}}}class C{constructor(e={}){if("function"!=typeof e.onFlush)throw new Error("Coalescer requires an onFlush(entries) callback");this._onFlush=e.onFlush,this._hz=e.hz||20,this._setInterval=e.setInterval||("undefined"!=typeof setInterval?setInterval:null),this._clearInterval=e.clearInterval||("undefined"!=typeof clearInterval?clearInterval:null),this._order=[],this._slots={},this._timer=null,!1!==e.autoStart&&this.start()}get running(){return null!==this._timer}_ensure(e,t){let n=this._slots[e];return n||(n={mode:t,value:void 0,list:[]},this._slots[e]=n,this._order.push(e)),n}queue(e,t){const n=this._ensure(e,"latest");n.mode="latest",n.value=t}append(e,t){const n=this._ensure(e,"list");n.mode="list",n.list.push(t)}drain(){const e=[];for(let t=0;t<this._order.length;t++){const n=this._order[t],r=this._slots[n];if("latest"===r.mode)void 0!==r.value&&e.push({type:n,data:r.value});else for(let t=0;t<r.list.length;t++)e.push({type:n,data:r.list[t]})}return this._order=[],this._slots={},e}flush(){if(0===this._order.length)return;const e=this.drain();e.length&&this._onFlush(e)}start(){!this._timer&&this._setInterval&&(this._timer=this._setInterval(()=>this.flush(),Math.max(1,Math.round(1e3/this._hz))))}stop(){this._timer&&this._clearInterval&&this._clearInterval(this._timer),this._timer=null}}class N{constructor(e={}){this._alpha=null!=e.alpha?e.alpha:.2,this._now=e.now||(()=>Date.now()),this._rtt=null,this._jitter=0,this._last=null,this._id=0,this._outstanding={}}get rtt(){return this._rtt}get latency(){return null==this._rtt?null:this._rtt/2}get jitter(){return this._jitter}get last(){return this._last}begin(){const e=++this._id;return this._outstanding[e]=this._now(),e}end(e){const t=this._outstanding[e];return null==t?null:(delete this._outstanding[e],this.sample(this._now()-t))}sample(e){return e>=0?(null==this._rtt?this._rtt=e:(this._jitter+=this._alpha*(Math.abs(e-this._rtt)-this._jitter),this._rtt+=this._alpha*(e-this._rtt)),this._last=e,e):null}reset(){this._rtt=null,this._jitter=0,this._last=null,this._outstanding={}}}const R=[{urls:"stun:stun.l.google.com:19302"}];function P(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}class q{constructor(e={}){if("host"!==e.role&&"guest"!==e.role)throw new Error("MeshConnection requires role 'host' or 'guest'");if("function"!=typeof e.sendSignal)throw new Error("MeshConnection requires a sendSignal(payload) function");this.role=e.role,this._sendSignal=e.sendSignal,this._iceServers=e.iceServers||R,this._sequenced=!1!==e.sequenced,this._autoReconnect=!1!==e.autoReconnect,this._maxRestarts=null!=e.maxRestarts?e.maxRestarts:5,this._RTCPeerConnection=e.RTCPeerConnection||("undefined"!=typeof RTCPeerConnection?RTCPeerConnection:null),this._setTimeout=e.setTimeout||("undefined"!=typeof setTimeout?setTimeout:null),this.connected=!1,this._pc=null,this._unreliable=null,this._reliable=null,this._sendSeq=0,this._recvSeq=0,this._restarts=0,this.onOpen=null,this.onMessage=null,this.onClose=null,this.onError=null,this.onStateChange=null}static iceServers(e={}){const t=[{urls:e.stun||"stun:stun.l.google.com:19302"}];if(e.turn){const n={urls:e.turn};e.turnUsername&&(n.username=e.turnUsername),e.turnCredential&&(n.credential=e.turnCredential),t.push(n)}return t}async start(){if(!this._RTCPeerConnection)throw new Error("RTCPeerConnection unavailable");const e=new this._RTCPeerConnection({iceServers:this._iceServers});this._pc=e,e.onicecandidate=e=>{e&&e.candidate&&this._sendSignal({type:"ice",candidate:e.candidate})};const t=()=>this._handleStateChange(e.connectionState||e.iceConnectionState);e.onconnectionstatechange=t,e.oniceconnectionstatechange=t,"host"===this.role?(this._bindChannel(this._unreliable=e.createDataChannel("unreliable",{ordered:!1,maxRetransmits:0}),"unreliable"),this._bindChannel(this._reliable=e.createDataChannel("reliable",{ordered:!0}),"reliable"),await this._makeOffer(!1)):e.ondatachannel=e=>{const t=e.channel;"unreliable"===t.label?this._bindChannel(this._unreliable=t,"unreliable"):"reliable"===t.label&&this._bindChannel(this._reliable=t,"reliable")}}async _makeOffer(e){const t=this._pc,n=await t.createOffer(e?{iceRestart:!0}:void 0);await t.setLocalDescription(n),this._sendSignal({type:"offer",sdp:t.localDescription,restart:!!e})}_handleStateChange(e){if(this.onStateChange&&this.onStateChange(e),"connected"!==e){if(("failed"===e||"disconnected"===e||"closed"===e)&&(this.connected&&(this.connected=!1,this.onClose&&this.onClose()),this._autoReconnect&&"host"===this.role&&"closed"!==e&&this._restarts<this._maxRestarts)){this._restarts+=1;const e=Math.min(1e3*this._restarts,5e3);this._setTimeout&&this._setTimeout(()=>{this._makeOffer(!0).catch(e=>{this.onError&&this.onError(e)})},e)}}else this._restarts=0}async handleSignal(e){const t=this._pc;if(t&&e&&e.type)try{if("offer"===e.type){await t.setRemoteDescription(e.sdp);const n=await t.createAnswer();await t.setLocalDescription(n),this._sendSignal({type:"answer",sdp:t.localDescription})}else"answer"===e.type?await t.setRemoteDescription(e.sdp):"ice"===e.type&&e.candidate&&await t.addIceCandidate(e.candidate)}catch(e){this.onError&&this.onError(e)}}_bindChannel(e,t){e.binaryType="arraybuffer",e.onopen=()=>{"unreliable"!==t||this.connected||(this.connected=!0,this.onOpen&&this.onOpen())},e.onmessage=e=>{if(!this.onMessage)return;let n=e.data;if(P(n))this.onMessage(n,t);else{try{n="string"==typeof n?JSON.parse(n):n}catch(n){return void this.onMessage(e.data,t)}if("unreliable"===t&&this._sequenced&&n&&"number"==typeof n.__s){if(n.__s<=this._recvSeq)return;return this._recvSeq=n.__s,void this.onMessage(n.m,t)}this.onMessage(n,t)}},e.onclose=()=>{this.connected&&(this.connected=!1,this.onClose&&this.onClose())},e.onerror=e=>{this.onError&&this.onError(e)}}send(e){const t=this._unreliable;return!(!t||"open"!==t.readyState)&&(P(e)?(t.send(e),!0):(this._sequenced?(this._sendSeq+=1,t.send(JSON.stringify({__s:this._sendSeq,m:e}))):t.send("string"==typeof e?e:JSON.stringify(e)),!0))}sendReliable(e){const t=this._reliable;return!(!t||"open"!==t.readyState)&&(P(e)?t.send(e):t.send("string"==typeof e?e:JSON.stringify(e)),!0)}close(){try{this._unreliable&&this._unreliable.close()}catch(e){}try{this._reliable&&this._reliable.close()}catch(e){}try{this._pc&&this._pc.close()}catch(e){}this._unreliable=this._reliable=this._pc=null,this.connected=!1}}class j{constructor(e={}){if(!e.selfId)throw new Error("MeshNetwork requires a selfId");if("function"!=typeof e.sendSignal)throw new Error("MeshNetwork requires sendSignal(toPeerId, payload)");this.selfId=e.selfId,this._sendSignal=e.sendSignal,this._opts=e,this._peers={},this.onPeerOpen=null,this.onPeerClose=null,this.onMessage=null,this.onError=null}get peerIds(){return Object.keys(this._peers)}get connectedCount(){let e=0;for(const t in this._peers)this._peers[t].connected&&(e+=1);return e}peer(e){return this._peers[e]||null}_roleFor(e){return this.selfId<e?"host":"guest"}_ensurePeer(e){if(this._peers[e])return this._peers[e];const t=this,n=new q({role:this._roleFor(e),iceServers:this._opts.iceServers,RTCPeerConnection:this._opts.RTCPeerConnection,setTimeout:this._opts.setTimeout,sequenced:this._opts.sequenced,autoReconnect:this._opts.autoReconnect,sendSignal:n=>t._sendSignal(e,n)});return n.onOpen=()=>{t.onPeerOpen&&t.onPeerOpen(e)},n.onClose=()=>{t.onPeerClose&&t.onPeerClose(e)},n.onMessage=(n,r)=>{t.onMessage&&t.onMessage(e,n,r)},n.onError=n=>{t.onError&&t.onError(e,n)},this._peers[e]=n,n}async addPeer(e){if(e===this.selfId)return null;const t=this._ensurePeer(e);return await t.start(),t}async setRoster(e){const t={};for(let n=0;n<e.length;n++)e[n]!==this.selfId&&(t[e[n]]=!0);for(const e in t)this._peers[e]||await this.addPeer(e);for(const e in this._peers)t[e]||this.removePeer(e)}removePeer(e){const t=this._peers[e];if(t){try{t.close()}catch(e){}delete this._peers[e]}}async handleSignal(e,t){if(!e||e===this.selfId)return;const n=this._ensurePeer(e);n._pc||await n.start(),await n.handleSignal(t)}send(e,t){const n=this._peers[e];return!!n&&n.send(t)}sendReliable(e,t){const n=this._peers[e];return!!n&&n.sendReliable(t)}broadcast(e){for(const t in this._peers)this._peers[t].send(e)}broadcastReliable(e){for(const t in this._peers)this._peers[t].sendReliable(e)}close(){for(const e in this._peers)try{this._peers[e].close()}catch(e){}this._peers={}}}const D="undefined"!=typeof TextEncoder?new TextEncoder:null,U="undefined"!=typeof TextDecoder?new TextDecoder:null;function L(e){return(t=e)instanceof ArrayBuffer||ArrayBuffer.isView(t)?{type:0,bytes:e instanceof Uint8Array?e:new Uint8Array(e.buffer||e)}:{type:1,bytes:(n=JSON.stringify(e),D?D.encode(n):Uint8Array.from(Buffer.from(n,"utf8")))};var t,n}function x(e,t){if(1===e)try{return JSON.parse((n=t,U?U.decode(n):Buffer.from(n).toString("utf8")))}catch(e){return null}var n;return t}class B{constructor(){this._buf=new Uint8Array(0)}push(e){const t=e instanceof Uint8Array?e:new Uint8Array(e),n=new Uint8Array(this._buf.length+t.length);n.set(this._buf,0),n.set(t,this._buf.length),this._buf=n;const r=[];for(;this._buf.length>=4;){const e=new DataView(this._buf.buffer,this._buf.byteOffset,4).getUint32(0,!1);if(this._buf.length<4+e)break;const t=this._buf[4],n=this._buf.subarray(5,4+e);r.push(x(t,n.slice())),this._buf=this._buf.subarray(4+e)}return r}}class H{constructor(e={}){if(!e.url)throw new Error("WebTransportConnection requires a url");this._url=e.url,this._opts=e,this._sequenced=!1!==e.sequenced,this._WT=e.WebTransport||("undefined"!=typeof WebTransport?WebTransport:null),this.connected=!1,this._t=null,this._dgWriter=null,this._streamWriter=null,this._deframer=new B,this._sendSeq=0,this._recvSeq=0,this.onOpen=null,this.onMessage=null,this.onClose=null,this.onError=null}async connect(){if(!this._WT)throw new Error("WebTransport unavailable in this environment");const e={};this._opts.serverCertificateHashes&&(e.serverCertificateHashes=this._opts.serverCertificateHashes);const t=new this._WT(this._url,e);if(this._t=t,t.ready&&"function"==typeof t.ready.then&&await t.ready,t.datagrams&&t.datagrams.writable&&(this._dgWriter=t.datagrams.writable.getWriter()),"function"==typeof t.createBidirectionalStream)try{const e=await t.createBidirectionalStream();this._streamWriter=e.writable.getWriter(),this._pumpReadable(e.readable,"reliable")}catch(e){}t.datagrams&&t.datagrams.readable&&this._pumpDatagrams(t.datagrams.readable),t.closed&&"function"==typeof t.closed.then&&t.closed.then(()=>this._onClosed(),()=>this._onClosed()),this.connected=!0,this.onOpen&&this.onOpen()}async _pumpDatagrams(e){try{const t=e.getReader();for(;;){const{value:e,done:n}=await t.read();if(n)break;e&&this._onDatagramBytes(e)}}catch(e){this.onError&&this.onError(e)}}async _pumpReadable(e,t){try{const n=e.getReader();for(;;){const{value:e,done:r}=await n.read();if(r)break;if(e){const n=this._deframer.push(e);for(let e=0;e<n.length;e++)this.onMessage&&this.onMessage(n[e],t)}}}catch(e){this.onError&&this.onError(e)}}_onDatagramBytes(e){const t=function(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);return t.length<5?null:{seq:new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(0,!1),value:x(t[4],t.subarray(5))}}(e);if(t){if(this._sequenced){if(t.seq<=this._recvSeq)return;this._recvSeq=t.seq}this.onMessage&&this.onMessage(t.value,"datagram")}}send(e){if(!this._dgWriter)return!1;this._sendSeq+=1;try{return this._dgWriter.write(function(e,t){const{type:n,bytes:r}=L(t),i=new Uint8Array(5+r.length);return new DataView(i.buffer).setUint32(0,e>>>0,!1),i[4]=n,i.set(r,5),i}(this._sendSeq,e)),!0}catch(e){return!1}}sendReliable(e){if(!this._streamWriter)return!1;try{return this._streamWriter.write(function(e){const{type:t,bytes:n}=L(e),r=new Uint8Array(5+n.length);return new DataView(r.buffer).setUint32(0,1+n.length,!1),r[4]=t,r.set(n,5),r}(e)),!0}catch(e){return!1}}_onClosed(){this.connected&&(this.connected=!1,this.onClose&&this.onClose())}close(){try{this._dgWriter&&this._dgWriter.releaseLock&&this._dgWriter.releaseLock()}catch(e){}try{this._t&&this._t.close()}catch(e){}this._t=this._dgWriter=this._streamWriter=null,this.connected=!1}}class G{constructor(e={}){this._set=e.setTimeout||("undefined"!=typeof setTimeout?setTimeout:null),this._clear=e.clearTimeout||("undefined"!=typeof clearTimeout?clearTimeout:null),this._rand=e.random||Math.random,this._timers=new Set,this.set(e)}set(e={}){return null!=e.latencyMs?this.latencyMs=Math.max(0,e.latencyMs):null==this.latencyMs&&(this.latencyMs=0),null!=e.jitterMs?this.jitterMs=Math.max(0,e.jitterMs):null==this.jitterMs&&(this.jitterMs=0),null!=e.lossPct?this.lossPct=Math.max(0,Math.min(100,e.lossPct)):null==this.lossPct&&(this.lossPct=0),null!=e.dupPct?this.dupPct=Math.max(0,Math.min(100,e.dupPct)):null==this.dupPct&&(this.dupPct=0),this}_delay(){const e=this.jitterMs?(2*this._rand()-1)*this.jitterMs:0,t=this.latencyMs+e;return t>0?t:0}_schedule(e,t){if(!this._set)return void e();const n=this._set(()=>{this._timers.delete(n),e()},t);this._timers.add(n)}wrap(e){const t=this;return function(...n){if(!(t.latencyMs||t.jitterMs||t.lossPct||t.dupPct))return e.apply(this,n);if(t.lossPct&&100*t._rand()<t.lossPct)return;const r=this;t._schedule(()=>e.apply(r,n),t._delay()),t.dupPct&&100*t._rand()<t.dupPct&&t._schedule(()=>e.apply(r,n),t._delay())}}flush(){if(this._clear)for(const e of this._timers)this._clear(e);this._timers.clear()}}class F{constructor(e={}){if(!e.playerId)throw new Error("Lockstep requires playerId");if(!Array.isArray(e.players)||0===e.players.length)throw new Error("Lockstep requires players[]");if("function"!=typeof e.step)throw new Error("Lockstep requires a step(frame, inputs) function");this.playerId=e.playerId,this._players=e.players.slice(),this._step=e.step,this._send=e.send||function(){},this._inputDelay=null!=e.inputDelay?e.inputDelay:2,this._idle=null!=e.idleInput?e.idleInput:null,this._inputs={},this._frame=0,this._submitFrame=this._inputDelay,this._replay=[];for(let e=0;e<this._inputDelay;e++){this._inputs[e]={};for(let t=0;t<this._players.length;t++)this._inputs[e][this._players[t]]=this._idle}}get frame(){return this._frame}get players(){return this._players.slice()}submit(e){const t=this._submitFrame++;return this._inputs[t]||(this._inputs[t]={}),this._inputs[t][this.playerId]=e,this._send({frame:t,playerId:this.playerId,input:e}),t}receive(e){e&&null!=e.frame&&e.playerId&&(this._inputs[e.frame]||(this._inputs[e.frame]={}),this._inputs[e.frame][e.playerId]=e.input)}_ready(e){const t=this._inputs[e];if(!t)return!1;for(let e=0;e<this._players.length;e++)if(!(this._players[e]in t))return!1;return!0}tick(){let e=0;for(;this._ready(this._frame);){const t=this._inputs[this._frame];this._step(this._frame,t),this._replay.push({frame:this._frame,inputs:t}),delete this._inputs[this._frame],this._frame+=1,e+=1}return e}isStalled(){return!this._ready(this._frame)}getReplay(){return this._replay.slice()}static replay(e,t){for(let n=0;n<e.length;n++)t(e[n].frame,e[n].inputs)}}function W(e,t,n){return e+(t-e)*n}class J{constructor(e={}){this._historyMs=e.historyMs||1e3,this._maxSize=e.maxSize||256,this._now=e.now||(()=>Date.now()),this._history=[]}record(e,t){const n=null!=t?t:this._now();this._history.push({time:n,entities:e.map(e=>Object.assign({},e))});const r=n-this._historyMs;for(;this._history.length>this._maxSize||this._history.length>2&&this._history[0].time<r;)this._history.shift()}get size(){return this._history.length}clear(){this._history=[]}rewind(e,t){const n=this._history;if(0===n.length)return{};if(e<=n[0].time)return V(n[0].entities);if(e>=n[n.length-1].time)return V(n[n.length-1].entities);let r=n[0],i=n[n.length-1];for(let t=n.length-1;t>0;t--)if(n[t-1].time<=e&&e<=n[t].time){r=n[t-1],i=n[t];break}const o=i.time-r.time,s=o>0?(e-r.time)/o:0,c=V(r.entities),a={},u=V(i.entities);for(const e in u){const n=u[e],r=c[e],i=Object.assign({},n);if(r){const e=t||Object.keys(n);for(let t=0;t<e.length;t++){const o=e[t];"number"==typeof r[o]&&"number"==typeof n[o]&&(i[o]=W(r[o],n[o],s))}}a[e]=i}return a}rewindForClient(e,t,n){const r=null!=(n=n||{}).maxRewindMs?n.maxRewindMs:250;let i=(e||0)/2+(t||0);return i>r&&(i=r),this.rewind(this._now()-i,n.keys)}}function V(e){const t={};for(let n=0;n<e.length;n++)t[e[n].id]=e[n];return t}const Q="_s",z="_d",Y="_a",K="_n",X="_ka",$="_add",Z="_del",ee="_ord";function te(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function ne(e){if(!Array.isArray(e)||0===e.length)return!1;for(let t=0;t<e.length;t++){const n=e[t];if(!te(n)||"string"!=typeof n.id&&"number"!=typeof n.id)return!1}return!0}function re(e,t){if(e===t)return;const n=Array.isArray(e),r=Array.isArray(t);return n!==r||te(e)!==te(t)?{[Q]:t}:r?ne(e)&&ne(t)?function(e,t){const n={},r=[];for(let t=0;t<e.length;t++)n[e[t].id]=e[t],r.push(e[t].id);const i=[],o={};let s=!1;for(let e=0;e<t.length;e++){const r=t[e];if(i.push(r.id),Object.prototype.hasOwnProperty.call(n,r.id)){const e=re(n[r.id],r);void 0!==e&&(o[X]||(o[X]={}),o[X][r.id]=e,s=!0)}else o[$]||(o[$]=[]),o[$].push(r),s=!0}const c={};for(let e=0;e<i.length;e++)c[i[e]]=!0;for(let e=0;e<r.length;e++)c[r[e]]||(o[Z]||(o[Z]=[]),o[Z].push(r[e]),s=!0);(function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0})(r,i)||(o[ee]=i,s=!0);return s?o:void 0}(e,t):function(e,t){const n={[Y]:{}};let r=!1;for(let i=0;i<t.length;i++){const o=i<e.length?re(e[i],t[i]):{[Q]:t[i]};void 0!==o&&(n[Y][i]=o,r=!0)}t.length!==e.length&&(n[K]=t.length,r=!0);return r?n:void 0}(e,t):te(t)?function(e,t){const n={};let r=!1;for(const i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;const o=re(e[i],t[i]);void 0!==o&&(n[i]=o,r=!0)}const i=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(Object.prototype.hasOwnProperty.call(t,n)||i.push(n));i.length&&(n[z]=i,r=!0);return r?n:void 0}(e,t):{[Q]:t}}function ie(e,t){if(null==t)return e;if(Object.prototype.hasOwnProperty.call(t,Q))return t[Q];if(t[X]||t[$]||t[Z]||t[ee])return function(e,t){const n=Array.isArray(e)?e:[],r={},i=[];for(let e=0;e<n.length;e++){const t=n[e];!t||"string"!=typeof t.id&&"number"!=typeof t.id||(r[t.id]=t,i.push(t.id))}if(t[X])for(const e in t[X])Object.prototype.hasOwnProperty.call(t[X],e)&&void 0!==r[e]&&(r[e]=ie(r[e],t[X][e]));if(t[$])for(let e=0;e<t[$].length;e++){const n=t[$][e];r[n.id]=n}const o={};if(t[Z])for(let e=0;e<t[Z].length;e++)o[t[Z][e]]=!0;if(t[ee]){const e=[];for(let n=0;n<t[ee].length;n++){const i=t[ee][n];void 0!==r[i]&&e.push(r[i])}return e}const s=[];for(let e=0;e<i.length;e++){const t=i[e];o[t]||s.push(r[t])}return s}(e,t);if(Object.prototype.hasOwnProperty.call(t,Y)||Object.prototype.hasOwnProperty.call(t,K)){const n=Array.isArray(e)?e:[],r=Object.prototype.hasOwnProperty.call(t,K)?t[K]:n.length,i=n.slice(0,r),o=t[Y]||{};for(const e in o)Object.prototype.hasOwnProperty.call(o,e)&&(i[e]=ie(i[e],o[e]));return i}const n=te(e)?Object.assign({},e):{},r=t[z];for(const e in t)e!==z&&Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=ie(n[e],t[e]));if(Array.isArray(r))for(let e=0;e<r.length;e++)delete n[r[e]];return n}function oe(e,t=2){const n=Math.pow(10,t);return function e(t){if("number"==typeof t)return Number.isFinite(t)?Math.round(t*n)/n:t;if(Array.isArray(t))return t.map(e);if(te(t)){const n={};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=e(t[r]));return n}return t}(e)}const se="undefined"!=typeof TextEncoder?new TextEncoder:null,ce="undefined"!=typeof TextDecoder?new TextDecoder:null;function ae(e,t){for(t>>>=0;t>127;)e.push(127&t|128),t>>>=7;e.push(t)}function ue(e,t){if(null==t)return void e.push(192);const n=typeof t;if("boolean"!==n)if("number"!==n){var r;if("string"===n){e.push(198);const n=se?se.encode(t):Buffer.from(t,"utf8");ae(e,n.length);for(let t=0;t<n.length;t++)e.push(n[t]);return}if(Array.isArray(t)){e.push(199),ae(e,t.length);for(let n=0;n<t.length;n++)ue(e,t[n])}else{if("object"===n){const n=Object.keys(t);e.push(200),ae(e,n.length);for(let r=0;r<n.length;r++){const i=n[r],o=se?se.encode(i):Buffer.from(i,"utf8");ae(e,o.length);for(let t=0;t<o.length;t++)e.push(o[t]);ue(e,t[i])}return}e.push(192)}}else if(Number.isInteger(t)&&t>=-2147483648&&t<=2147483647)e.push(196),ae(e,((r=t)<<1^r>>31)>>>0);else{e.push(197);const n=new Uint8Array(8);new DataView(n.buffer).setFloat64(0,t,!0);for(let t=0;t<8;t++)e.push(n[t])}else e.push(t?195:194)}function le(e){const t=[];return ue(t,e),Uint8Array.from(t)}function de(e){return function(e){let t=0;const n=new DataView(e.buffer,e.byteOffset,e.byteLength);function r(){let n,r=0,i=0;do{n=e[t++],i|=(127&n)<<r,r+=7}while(128&n);return i>>>0}function i(){const n=r(),i=e.subarray(t,t+n);return t+=n,ce?ce.decode(i):Buffer.from(i).toString("utf8")}return function o(){switch(e[t++]){case 192:default:return null;case 195:return!0;case 194:return!1;case 196:return(s=r())>>>1^-(1&s);case 197:{const e=n.getFloat64(t,!0);return t+=8,e}case 198:return i();case 199:{const e=r(),t=new Array(e);for(let n=0;n<e;n++)t[n]=o();return t}case 200:{const e=r(),t={};for(let n=0;n<e;n++)t[i()]=o();return t}}var s}}(e instanceof Uint8Array?e:new Uint8Array(e))()}function fe(e,t){if(!("string"==typeof e&&e.length>0||"number"==typeof e&&isFinite(e)))throw new Error("interestGrid."+t+": id must be a non-empty string or a finite number");return e}function _e(e,t,n){if("number"!=typeof e||!isFinite(e))throw new Error("interestGrid."+n+": "+t+" must be a finite number");return e}function he(e,t){if(_e(e,"radius",t),e<0)throw new Error("interestGrid."+t+": radius must be >= 0");return e}function pe(e){const t=null!=(e=e||{}).cellSize?e.cellSize:256;if("number"!=typeof t||!isFinite(t)||t<=0)throw new Error("createInterestGrid: cellSize must be a finite number > 0");const n=new Map,r=new Map,i=new Map;function o(e,t){let n=r.get(e);n||(n=new Set,r.set(e,n)),n.add(t)}function s(e,t){const n=r.get(e);n&&(n.delete(t),0===n.size&&r.delete(e))}function c(e,i,o,s){const c=o*o,a=Math.floor((e-o)/t),u=Math.floor((e+o)/t),l=Math.floor((i-o)/t),d=Math.floor((i+o)/t);for(let t=a;t<=u;t++)for(let o=l;o<=d;o++){const a=r.get(t+","+o);if(a)for(const t of a){const r=n.get(t);if(!r)continue;const o=r.x-e,a=r.y-i;o*o+a*a<=c&&s(t)}}}return{upsert:function(e,r,i){fe(e,"upsert"),_e(r,"x","upsert"),_e(i,"y","upsert");const c=Math.floor(r/t)+","+Math.floor(i/t),a=n.get(e);if(a)return a.x=r,a.y=i,void(a.key!==c&&(s(a.key,e),o(c,e),a.key=c));n.set(e,{x:r,y:i,key:c}),o(c,e)},remove:function(e){fe(e,"remove");const t=n.get(e);t&&(n.delete(e),s(t.key,e))},query:function(e,t,n){_e(e,"x","query"),_e(t,"y","query"),he(n,"query");const r=[];return c(e,t,n,function(e){r.push(e)}),r},observe:function(e,t,n,r){fe(e,"observe"),_e(t,"x","observe"),_e(n,"y","observe"),he(r,"observe");let o=i.get(e);o||(o={prev:new Set,next:new Set},i.set(e,o));const s=o.prev,a=o.next;a.clear();const u=[],l=[],d=[];c(t,n,r,function(e){a.add(e),d.push(e),s.has(e)||u.push(e)});for(const e of s)a.has(e)||l.push(e);return o.prev=a,o.next=s,{entered:u,left:l,visible:d}},dropObserver:function(e){fe(e,"dropObserver"),i.delete(e)},size:function(){return n.size}}}function me(e,t){e.diff=re,e.patch=ie,e.quantize=oe,e.encode=le,e.decode=de,e.createInterpolation=function(e){return new k(e||{})},e.createPredictor=function(e){return new M(e||{})},e.createLagCompensator=function(e){return new J(e||{})},e.createLockstep=function(e){return new F(e||{})},e.createInterestGrid=function(e){return pe(e||{})},e._channels=e._channels||{},e._userRealtime=e._userRealtime||null,e._inboundDispatch=null,e._dispatchRealtime=function(t){const n=t&&t.action_type;n&&e._channels[n]?e._channels[n](t&&(void 0!==t.action_data?t.action_data:t),t):e._userRealtime&&e._userRealtime(t)},e._installRealtimeRouter=function(){e._routerInstalled||(e._eventHandlers.realtime&&e._eventHandlers.realtime!==e._router&&(e._userRealtime=e._eventHandlers.realtime),e._router=function(t){(e._inboundDispatch||e._dispatchRealtime)(t)},e._eventHandlers.realtime=e._router,e._routerInstalled=!0)},e._onChannel=function(t,n){return e._channels[t]=n,e._installRealtimeRouter(),function(){delete e._channels[t]}},e.onRealtime=function(t){e._userRealtime=t,e._installRealtimeRouter()},e.createSender=function(e){const t=this,n=(e=e||{}).send||function(e,n){t.realtime(e,n)};return new C({hz:e.hz||20,autoStart:!1!==e.autoStart,onFlush:function(e){for(let t=0;t<e.length;t++)n(e[t].type,e[t].data)}})},e.createSnapshotSender=function(e){const t=this,n=(e=e||{}).channel||"state",r=!1!==e.delta,i=null!=e.keyframeEvery?e.keyframeEvery:30,o=e.precision,s=!0===e.encode?le:"function"==typeof e.encode?e.encode:null,c=e.send||function(e,n){t.realtime(e,n)},a="function"==typeof e.source?e.source:null;let u=null,l=0,d=0,f=0;function _(e){if(null==e)return;const t=null!=o?oe(e,o):e;let a;if(!r||null===u||f>=i)d+=1,u=null==(_=t)?_:JSON.parse(JSON.stringify(_)),l=d,f=0,a={s:d,f:t};else{const e=re(u,t);if(void 0===e)return;d+=1,f+=1,a={s:d,b:l,d:e}}var _;c(n,s?s(a):a)}const h=e.hz||20;let p;const m=a?null:new C({hz:h,autoStart:!1!==e.autoStart,onFlush:function(e){for(let t=0;t<e.length;t++)"__snap"===e[t].type&&(p=e[t].data);_(p)}});let y=null;function g(){m?m.start():y||"undefined"==typeof setInterval||(y=setInterval(function(){_(a())},Math.max(1,Math.round(1e3/h))))}return a&&!1!==e.autoStart&&g(),{send:function(e){m?m.queue("__snap",e):_(e)},flush:function(){m?m.flush():a&&_(a())},start:g,stop:function(){m&&m.stop(),y&&(clearInterval(y),y=null)},reset:function(){u=null,l=0,d=0,f=0}}},e.createSnapshotReceiver=function(e){const t=!0===(e=e||{}).decode?de:"function"==typeof e.decode?e.decode:null;let n=null,r=-1,i=null,o=-1,s=0;return{receive:function(e){return t&&(e instanceof ArrayBuffer||ArrayBuffer.isView(e))&&(e=t(e)),e?void 0!==e.f?void 0!==e.s&&e.s<=o?(s+=1,i):(n=e.f,r=void 0!==e.s?e.s:0,i=e.f,o=r,i):void 0!==e.d?void 0!==e.b&&e.b!==r||void 0!==e.s&&e.s<=o?(s+=1,i):(i=ie(n,e.d),void 0!==e.s&&(o=e.s),i):i:i},get state(){return i},get stats(){return{appliedSeq:o,baseSeq:r,dropped:s}},reset:function(){n=null,r=-1,i=null,o=-1,s=0}}},e.replicate=function(e,t){t=t||{};let n=null!=e?e:{};const r=this.createSnapshotSender(Object.assign({},t,{source:function(){return n}}));return{get state(){return n},set state(e){n=e},flush:function(){r.flush()},start:function(){r.start()},stop:function(){r.stop()}}},e.replica=function(e){const t=(e=e||{}).channel||"state",n=this.createSnapshotReceiver({decode:e.decode}),r=e.interpolate?this.createInterpolation("object"==typeof e.interpolate?e.interpolate:{}):null,i="string"==typeof e.interpolate?e.interpolate:e.keys||e.interpolate&&e.interpolate.keys,o=e.group||e.interpolate&&e.interpolate.group;let s=null;const c=this._onChannel(t,function(e){const t=n.receive(e);r&&null!=t&&r.add(t),s&&s(t)});return{get state(){return n.state},view:function(){return r?r.calc(i||"x y",o):n.state},onChange:function(e){s=e},stop:function(){c()}}},e.createMesh=function(e){const t=this,n=(e=e||{}).signalChannel||"signal",r=new q(Object.assign({},e,{sendSignal:function(e){t.realtime(n,e)}}));return this._onChannel(n,function(e){e&&e.type&&r.handleSignal(e)}),r},e.createMeshNetwork=function(e){const n=this,r=(e=e||{}).signalChannel||"mesh",i=e.selfId||t.user&&t.user.getId&&t.user.getId(),o=new j(Object.assign({},e,{selfId:i,sendSignal:function(e,t){n.realtime(r,{to:e,from:i,payload:t})}}));return this._onChannel(r,function(e){e&&e.to===i&&e.from&&o.handleSignal(e.from,e.payload)}),o},e.simulateNetwork=function(e){const t=this;return t._installRealtimeRouter(),t._realtimeRaw||"function"!=typeof t.realtime||(t._realtimeRaw=t.realtime.bind(t)),e?(t._sim?t._sim.set(e):t._sim=new G(e),t._realtimeRaw&&(t.realtime=t._sim.wrap(t._realtimeRaw)),t._inboundDispatch=t._sim.wrap(t._dispatchRealtime),t._sim):(t._realtimeRaw&&(t.realtime=t._realtimeRaw),t._inboundDispatch=null,t._sim&&t._sim.flush(),void(t._sim=null))},e.createWebTransport=function(e){const n=(e=e||{}).url||t.config&&(t.config.webTransportUrl||t.config.wtUrl);return new H(Object.assign({},e,{url:n}))},e.ping=function(){const e=this;if(e._pingMeter||(e._pingMeter=new N),e._pingInFlight)return e._pingInFlight;let t;if(e.directMode){if(!e.directSocket||1!==e.directSocket.readyState)return Promise.resolve(null);t=new Promise(function(t){const n=e._pingMeter.begin();let r=!1;const i=function(){r||(r=!0,t(e._pingMeter.end(n)))};i.sentAt=Date.now(),e._pongWaiters.push(i),e._sendDirect("ping",{t:Date.now()}),setTimeout(function(){if(r)return;r=!0;const o=e._pongWaiters.indexOf(i);o>=0&&e._pongWaiters.splice(o,1),delete e._pingMeter._outstanding[n],t(null)},3e3)})}else{if(!e.socket||!e.connected||e._useProxy)return Promise.resolve(null);t=new Promise(function(t){const n=Date.now();let r=!1;try{e.socket.emit("game:ping",{t:n},function(){r||(r=!0,t(e._pingMeter.sample(Date.now()-n)))})}catch(e){return void t(null)}setTimeout(function(){r||(r=!0,t(null))},3e3)})}return e._pingInFlight=t,t.then(function(){e._pingInFlight=null},function(){e._pingInFlight=null}),t},e.getRtt=function(){return this._pingMeter?this._pingMeter.rtt:null}}function ye(e,t){function n(t){var n=e[t];"function"==typeof n&&(e[t]=function(){var e=this;return n.apply(e,arguments).then(function(t){return e._awaitResync||e._setConnState("connected"),t})})}function r(t){t&&(t.host_id?e._hostId=t.host_id:t.player_ids&&t.player_ids.length&&(e._hostId=t.player_ids[0]))}e.getLastSequence=function(){return this._lastSequence||0},e.getLastAppliedSequence=function(){return this._lastActionApplied||0},e._connState="disconnected",e._awaitResync=!1,e._setConnState=function(e){this._connState!==e&&(this._connState=e,this._dispatch("connectionState",e))},e.getConnectionState=function(){return this._connState},e.onConnectionState=function(e){return this._setHandler("connectionState",e)},e.onReconnected=function(e){return this._setHandler("reconnected",e)},e.on("disconnect",function(){e._awaitResync=!1,e._setConnState("disconnected")}),e.on("reconnect",function(){e.roomId?(e._awaitResync=!0,e._setConnState("rejoining")):e._setConnState("connected")}),e.on("sync",function(t){e._awaitResync&&(e._awaitResync=!1,e._dispatch("reconnected",{state:t&&t.game_state||null,lastSequence:e._lastSequence||0,viaSync:!0}),e._setConnState("reconnected"),e._setConnState("connected"))}),n("connect"),n("connectDirect"),e._hostId=null,e.on("joined",r),e.on("playerJoined",r),e.syncedState=function(e,n){var r=this,i="function"==typeof(n=n||{}).reduce?n.reduce:function(e,t){return Object.assign({},e,t.data)},o=null!=n.checkpointEvery?n.checkpointEvery:1,s="all"===n.authority?"all":"host",c=n.type||"update",a=void 0===e?{}:e,u=0,l=0,d=-1,f=[],_=[];function h(e){for(var n=f.slice(),r=0;r<n.length;r++)try{n[r](a,e)}catch(e){t.log("syncedState onChange error: "+e.message)}}function p(){if("all"===s)return!0;var e=r.playerId||t.user&&t.user.getId&&t.user.getId();return!(!e||!r._hostId||e!==r._hostId)}function m(){return r.directMode?Promise.resolve({success:!1,error:"not_supported_in_direct_mode"}):r.setState({__usionSyncedState:1,seq:u,state:a})}function y(e,n,r,o){if(void 0!==o&&o<=u)return!1;var s;try{s=i(a,{playerId:e,type:n,data:r,sequence:o})}catch(e){return t.log("syncedState reduce error: "+e.message),!1}return void 0!==s&&(a=s),void 0!==o&&(u=o),!0}function g(e){if(e){var t=!1,n=e.game_state;n&&n.__usionSyncedState&&"number"==typeof n.seq&&n.seq>=u&&void 0!==n.state&&(a=n.state,u=n.seq,t=!0);var i=e.actions;if(i&&i.length)for(var o=i.slice().sort(function(e,t){return(e.sequence||0)-(t.sequence||0)}),s=0;s<o.length;s++){var c=o[s];c&&y(c.player_id,c.action_type,c.action_data,c.sequence)&&(t=!0)}if(t&&h("recover"),void 0!==e.sequence&&e.sequence>u&&d!==u){d=u;try{r.requestSync(u)}catch(e){}}}}return _.push(r.on("action",function(e){e&&y(e.player_id,e.action_type,e.action_data,e.sequence)&&(h("action"),o>0&&p()&&(l+=1)>=o&&(l=0,m()))})),_.push(r.on("sync",g)),_.push(r.on("joined",g)),{get:function(){return a},commit:function(e,t,n){var i,o,s;return"string"==typeof e?(i=e,o=t,s=n):(i=c,o=e,s=t),r.directMode?(y(r.playerId,i,o,void 0)&&h("action"),r.action(i,o,s)):r.action(i,o,s)},onChange:function(e){return f.push(e),function(){var t=f.indexOf(e);t>=0&&f.splice(t,1)}},isAuthority:p,checkpoint:function(){return m()},getSequence:function(){return u},destroy:function(){for(var e=0;e<_.length;e++)try{_[e]()}catch(e){}_.length=0,f.length=0}}}}const ge={joined:"joined",player_joined:"playerJoined",player_left:"playerLeft",player_connection:"playerConnection",state:"stateUpdate",state_update:"stateUpdate",sync:"sync",action:"action",realtime:"realtime",finished:"finished",restarted:"restarted",error:"error",rematch_request:"rematchRequest",disconnect:"disconnect",reconnect:"reconnect",connection_error:"connectionError",room_assigned:"roomAssigned",connection_state:"connectionState",reconnected:"reconnected",network_quality:"networkQuality"};const ve={SnapshotInterpolation:k,Vault:A,Predictor:M,Coalescer:C,PingMeter:N,MeshConnection:q,MeshNetwork:j,WebTransportConnection:H,NetworkSim:G,Lockstep:F,LagCompensator:J,diff:re,patch:ie,quantize:oe,encode:le,decode:de,createInterestGrid:pe},be=Object.assign({},u);var Ee;return be.user=function(e){return{_id:null,_name:null,_avatar:null,_token:null,_isAdult:null,getId:function(){return this._id||e.config.userId||null},getName:function(){return this._name||e.config.userName||null},getAvatar:function(){return this._avatar||e.config.userAvatar||null},isAdult:function(){if(!0===this._isAdult||!1===this._isAdult)return this._isAdult;var t=e.config&&e.config.userIsAdult;return!0===t||!1===t?t:null},getToken:function(){return this._token||e.config.authToken||null},getProfile:function(){return e._request("GET_USER_PROFILE",{}).then(function(t){return t.profile||{id:e.user.getId(),name:e.user.getName(),avatar:e.user.getAvatar(),isAdult:e.user.isAdult()}})}}}(be),be.storage=function(e){var t=null;function n(){return t||(t=_(e,"kv:get",{key:d}).then(function(t){if(!t||!t.exists||!0!==t.value)return Promise.all([_(e,"kv:keys",{}),y(e)]).then(function(t){var n=new Set(t[0]&&t[0].keys||[]);return Promise.all(t[1].map(function(t){var r=f(t);if(!n.has(r))return h(e,t).then(function(t){if(null!=t)return _(e,"kv:set",{key:r,value:t})})}))}).then(function(){return _(e,"kv:set",{key:d,value:!0})})}).catch(function(e){throw t=null,e}))}return{get:function(t){return n().then(function(){return _(e,"kv:get",{key:f(t)})}).then(function(n){return n&&n.exists?g(p(e,t,n.value)).then(function(){return n.value}):g(m(e,t)).then(function(){return null})}).catch(function(n){return h(e,t).then(function(e){if(null!=e)return e;throw n},function(){throw n})})},set:function(t,r){return n().then(function(){return _(e,"kv:set",{key:f(t),value:r})}).then(function(){return g(p(e,t,r))})},remove:function(t){return n().then(function(){return _(e,"kv:remove",{key:f(t)})}).then(function(){return g(m(e,t))})},clear:function(){return n().then(function(){return _(e,"kv:clear",{prefix:l})}).then(function(){return g(e._request("STORAGE_CLEAR",{}))})},keys:function(){return n().then(function(){return _(e,"kv:keys",{})}).then(function(e){return(e&&e.keys||[]).filter(function(e){return 0===e.indexOf(l)}).map(function(e){return e.slice(3)})}).catch(function(t){return y(e).catch(function(){throw t})})}}}(be),be.wallet=function(e){return{_balance:null,_balanceChangeHandler:null,_paymentTimeoutMs:6e4,_recoveryPollMs:2e3,_recoveryMaxPolls:10,_recoveryQueryTimeoutMs:8e3,getBalance:function(t){const n=this;return!(!t||!t.fresh)||null===n._balance?e._request("GET_BALANCE",{}).then(function(e){return n._balance=e.balance,e.balance}):Promise.resolve(n._balance)},hasCredits:function(e){return this.getBalance().then(function(t){return t>=e})},requestPayment:function(t,n,r){const i=this,o=r&&"object"==typeof r?r:null,c=o&&"string"==typeof o.idempotencyKey&&o.idempotencyKey?o.idempotencyKey:null;return new Promise(function(o,u){const l=s(),d=i._paymentTimeoutMs||6e4;let f=!1,_=null;function h(){clearTimeout(g),_&&clearTimeout(_),window.removeEventListener("message",y)}function p(e){f||(f=!0,h(),e&&void 0!==e.newBalance?i._balance=e.newBalance:(null!==i._balance&&(i._balance-=t),i.getBalance({fresh:!0}).catch(function(){})),o(e))}function m(e){f||(f=!0,h(),u(e))}function y(e){if(!a(e))return;let t;try{t="string"==typeof e.data?JSON.parse(e.data):e.data}catch(e){return}t&&t._requestId===l&&("PAYMENT_SUCCESS"===t.type?p(t):"PAYMENT_FAILED"===t.type&&m(new Error(t.reason||"Payment failed")))}window.addEventListener("message",y);const g=setTimeout(function(){const t=i._recoveryPollMs||2e3,n=i._recoveryMaxPolls||10,r=i._recoveryQueryTimeoutMs||8e3;let o=0,s=0;!function i(){f||e._request("PAYMENT_RESULT_QUERY",{paymentRequestId:l,idempotencyKey:c||void 0},r).then(function(e){if(f)return;const n=e&&e.status;if("succeeded"!==n)if("failed"!==n){if("pending"===n)return o=0,s=0,void(_=setTimeout(i,t));s=0,o+=1,o>=2?m(new Error("Payment confirmation timeout")):_=setTimeout(i,t)}else m(new Error(e.reason||"Payment failed"));else p({type:"PAYMENT_SUCCESS",_requestId:l,newBalance:e.newBalance,transactionId:e.transactionId,receiptToken:e.receiptToken})}).catch(function(){f||(s+=1,s>=n?m(new Error("Payment confirmation timeout")):_=setTimeout(i,t))})}()},d);e._post({type:"PAYMENT_REQUEST",_requestId:l,amount:t,reason:n,data:r,idempotencyKey:c||void 0})})},onBalanceChange:function(e){const t=this;return t._balanceChangeHandler=e,function(){t._balanceChangeHandler===e&&(t._balanceChangeHandler=null)}}}}(be),be.session=function(e){return{_id:null,_data:{},getId:function(){return this._id||e.config.sessionId||null},getData:function(e){return e?this._data[e]:this._data},setData:function(t,n){"object"==typeof t?Object.assign(this._data,t):this._data[t]=n,e._post({type:"SESSION_DATA_UPDATE",data:this._data})},clear:function(){this._data={},e._post({type:"SESSION_DATA_CLEAR"})}}}(be),be.chat=function(e){return{sendMessage:function(t,n){return e._request("SEND_MESSAGE_REQUEST",{recipientId:t,message:n})},createPersonalChat:function(t){return e._request("CREATE_PERSONAL_CHAT",{peerUserId:t})}}}(be),be.bot=function(e){return{_messageHandler:null,callAction:function(t,n){return e._request("CALL_BOT",{action:t,data:n||{}},3e4)},sendMessage:function(t){e._post({type:"SEND_USER_MESSAGE",text:t})},updateContext:function(t){e._post({type:"UPDATE_CONTEXT",context:t})},close:function(t){e._post({type:"CLOSE",result:t})},onMessage:function(e){this._messageHandler=e}}}(be),be.fileStorage=(Ee=be,{set:function(e,t,n){return Ee._request("FILE_STORAGE_SET",{key:e,base64Data:t,mimeType:n||"application/octet-stream"},3e4).then(function(){})},get:function(e){return Ee._request("FILE_STORAGE_GET",{key:e},3e4).then(function(e){return e&&e.base64Data?{base64Data:e.base64Data,mimeType:e.mimeType}:null})},remove:function(e){return Ee._request("FILE_STORAGE_REMOVE",{key:e}).then(function(){})}}),be.game=function(n){const i={socket:null,directSocket:null,roomId:null,playerId:null,connected:!1,directMode:!1,directConfig:null,_directSeq:0,_eventHandlers:{},_lastSequence:0,_connecting:!1,_connectPromise:null,_joined:!1,_joinPromise:null,_useProxy:!1,_proxyListenerSetup:!1,_heartbeatInterval:null,_pingMeter:null,_pongWaiters:[],_lastActionApplied:0,_rejoinPromise:null,connect:function(e,t){const r=this;return"direct"===(n.config&&n.config.connectionMode||"platform")?r.connectDirect():r._useProxy&&r.connected||r.socket&&r.connected?Promise.resolve():r._connecting&&r._connectPromise?r._connectPromise:window.__USION_PROXY__||window.parent!==window||window.ReactNativeWebView||n._isEmbedded?(n.log("Running in iframe – using parent app as socket proxy"),r._connectViaProxy()):(e=e||n.config.socketUrl,t=t||n.user.getToken(),e?t?(r._connecting=!0,r._connectPromise=new Promise(function(n,i){if("undefined"==typeof io){var o=["/socket.io.min.js","https://usions.com/socket.io.min.js","https://cdn.socket.io/4.7.2/socket.io.min.js"];!function s(c){if(c>=o.length)return r._connecting=!1,void i(new Error("Failed to load Socket.IO client"));var a=document.createElement("script");a.src=o[c],a.onload=function(){r._initSocket(e,t,n,i)},a.onerror=function(){s(c+1)},document.head.appendChild(a)}(0)}else r._initSocket(e,t,n,i)}),r._connectPromise):Promise.reject(new Error("No auth token available")):Promise.reject(new Error("No socket URL provided")))},onJoined:function(e){return this._setHandler("joined",e)},onPlayerJoined:function(e){return this._setHandler("playerJoined",e)},onPlayerLeft:function(e){return this._setHandler("playerLeft",e)},onStateUpdate:function(e){return this._setHandler("stateUpdate",e)},onSync:function(e){return this._setHandler("sync",e)},onAction:function(e){return this._setHandler("action",e)},onRealtime:function(e){return this._setHandler("realtime",e)},onGameFinished:function(e){return this._setHandler("finished",e)},onGameRestarted:function(e){return this._setHandler("restarted",e)},onError:function(e){return this._setHandler("error",e)},onRematchRequest:function(e){return this._setHandler("rematchRequest",e)},onDisconnect:function(e){return this._setHandler("disconnect",e)},onReconnect:function(e){return this._setHandler("reconnect",e)},onConnectionError:function(e){return this._setHandler("connectionError",e)},onPlayerConnection:function(e){return this._setHandler("playerConnection",e)},onRoomAssigned:function(e){return this._setHandler("roomAssigned",e)},_setHandler:function(e,t){const n=this;return n._eventHandlers[e]=t,function(){n._eventHandlers[e]===t&&(n._eventHandlers[e]=null)}},_dispatch:function(e){const t=Array.prototype.slice.call(arguments,1),r=this._eventHandlers[e];if(r)try{r.apply(null,t)}catch(t){n.log("game handler error ("+e+"): "+t.message)}const i=this._listeners[e];if(i&&i.length){const r=i.slice();for(let i=0;i<r.length;i++)try{r[i].apply(null,t)}catch(t){n.log("game listener error ("+e+"): "+t.message)}}},on:function(e,t){const n=this,r=function(e){let t=String(e||"");if(0===t.indexOf("game:")&&(t=t.slice(5)),ge[t])return ge[t];const n=t.replace(/([A-Z])/g,function(e){return"_"+e.toLowerCase()});return ge[n]||t}(e);return n._listeners[r]||(n._listeners[r]=[]),n._listeners[r].push(t),function(){const e=n._listeners[r];if(!e)return;const i=e.indexOf(t);i>=0&&e.splice(i,1)}},_listeners:{}};return function(e,t){e.connectDirect=function(e){var n=this;return e=e||{},n.directMode&&n.directSocket&&n.connected?Promise.resolve():(n._connecting&&n._connectPromise||(n._resConfigure&&n._resConfigure(e),n._connecting=!0,n.directMode=!0,n._autoReconnect=void 0!==e.autoReconnect?e.autoReconnect:!(t.config&&!1===t.config.autoReconnect),n._connectPromise=n._fetchDirectAccess(e).then(function(e){return n.directConfig=e,n._initDirectSocket(e)}).then(function(){n.connected=!0,n._connecting=!1,t.log("Direct game socket connected")}).catch(function(e){throw n._connecting=!1,n.connected=!1,n.directMode=!1,n._dispatch("connectionError",e),e})),n._connectPromise)},e._fetchDirectAccess=function(e){var n=e.roomId||this.roomId||t.config.roomId,r=e.serviceId||t.config.serviceId,i=e.apiUrl||t.config.apiUrl||"",o=e.token||t.user.getToken();if(!n)return Promise.reject(new Error("No room ID provided"));if(!r)return Promise.reject(new Error("No service ID provided"));if(this.roomId=n,this.playerId=t.user.getId(),t._isEmbedded)return t._request("GAME_ACCESS_REQUEST",{room_id:n,service_id:r,protocol_version:e.protocolVersion||t.config.protocolVersion||t.config.protocol_version||"2"},1e4);if(!i)return Promise.reject(new Error("No API URL provided"));if(!o)return Promise.reject(new Error("No auth token available"));var s=String(i).replace(/\/$/,"")+"/games/rooms/"+encodeURIComponent(n)+"/access";return fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o},body:JSON.stringify({service_id:r,client_type:"iframe",protocol_version:e.protocolVersion||t.config.protocolVersion||t.config.protocol_version||"2"})}).then(function(e){return e.ok?e.json():e.text().then(function(t){throw new Error(t||"Direct access failed: HTTP "+e.status)})})},e._initDirectSocket=function(e){var t=this;return new Promise(function(n,r){if(e&&e.ws_url&&e.access_token){var i=e.ws_url,o=-1===i.indexOf("?")?"?":"&",s=i+o+"token="+encodeURIComponent(e.access_token),c=new WebSocket(s);t.directSocket=c;var a=!1,u=!1,l=setTimeout(function(){if(!a){try{c.close()}catch(e){}r(new Error("Direct WebSocket connection timeout"))}},1e4);c.onopen=function(){a=!0,clearTimeout(l),u||(u=!0,t._sendDirect("join",{})),t._heartbeatInterval&&clearInterval(t._heartbeatInterval),t._heartbeatInterval=setInterval(function(){t.directSocket&&t.directSocket.readyState===WebSocket.OPEN&&t._sendDirect("heartbeat",{})},25e3),t._resOnOpen&&t._resOnOpen(),n()},c.onerror=function(){a||(clearTimeout(l),r(new Error("Direct WebSocket connection error")))},c.onclose=function(e){t._resOnClose&&t._resOnClose(e),t.connected=!1,t._joined=!1,t._joinPromise=null,t._heartbeatInterval&&(clearInterval(t._heartbeatInterval),t._heartbeatInterval=null),t._dispatch("disconnect",e&&e.reason?e.reason:"direct socket closed"),t.directMode&&!1!==t._autoReconnect&&t._scheduleDirectReconnect()},c.onmessage=function(e){t._res&&(t._res.lastInboundAt=Date.now()),t._handleDirectMessage(e&&e.data)}}else r(new Error("Invalid direct access payload"))})},e._scheduleDirectReconnect=function(){var e=this;if(!e._reconnecting){e._reconnecting=!0;var t=e._reconnectAttempt||0,n=function(){e.directMode?(t+=1,e._reconnectAttempt=t,(e._resCanReuseToken&&e._resCanReuseToken()?Promise.resolve(e.directConfig):e._fetchDirectAccess({})).then(function(t){return e.directConfig=t,e._initDirectSocket(t)}).then(function(){e.connected=!0,e._reconnecting=!1,e._reconnectAttempt=0,e._dispatch("reconnect",t),e.roomId&&e.requestSync(e._lastSequence||0)}).catch(function(){if(e.directMode){var r=Math.min(1e3*Math.pow(2,t-1),15e3);setTimeout(n,r)}else e._reconnecting=!1})):e._reconnecting=!1};setTimeout(n,100)}},e._sendDirect=function(e,t){this.directSocket&&this.directSocket.readyState===WebSocket.OPEN&&("input"===e&&this._resHoldInput&&this._resHoldInput(t)||(this._directSeq=this._directSeq+1,this.directSocket.send(JSON.stringify({type:e,room_id:this.roomId,ts:Date.now(),seq:this._directSeq,session_id:this.directConfig&&this.directConfig.session_id?this.directConfig.session_id:null,protocol_version:this.directConfig&&this.directConfig.protocol_version?this.directConfig.protocol_version:"2",payload:t||{}}))))},e._handleDirectMessage=function(e){var t;try{t="string"==typeof e?JSON.parse(e):e}catch(e){return}if(t&&t.type){var n=t.payload||{};if("joined"===t.type)return this._joined=!0,void this._dispatch("joined",n);if("player_joined"!==t.type)if("player_left"!==t.type){if("state_snapshot"===t.type||"state_delta"===t.type)return this._dispatch("realtime",n),void this._dispatch("stateUpdate",n);if("pong"===t.type){var r=this._pongWaiters&&this._pongWaiters.length?this._pongWaiters.shift():null;return this._resOnPong&&this._resOnPong(r),r&&r(),void this._dispatch("sync",n)}"match_end"!==t.type?"error"===t.type&&this._dispatch("error",n):this._dispatch("finished",n)}else this._dispatch("playerLeft",n);else this._dispatch("playerJoined",n)}}}(i,n),E(i,n),function(e,t){e._initSocket=function(e,n,r,i){const o=this;if(o.socket&&o.socket.connected)return o._connecting=!1,void r();o.socket&&(o.socket.disconnect(),o.socket=null);try{o.socket=io(e,{path:"/socket.io",transports:["websocket","polling"],auth:{token:n},autoConnect:!0,reconnection:!0,reconnectionAttempts:50,reconnectionDelay:1e3,reconnectionDelayMax:1e4}),t._bindBackendSocket&&t._bindBackendSocket(o.socket);var s=!1;o.socket.io&&"function"==typeof o.socket.io.on&&o.socket.io.on("reconnect_attempt",function(e){o._reconnAttempts=e}),o.socket.on("connect",function(){var e=s;if(s=!0,o.connected=!0,o._connecting=!1,t.log("Game socket connected"),o._heartbeatInterval&&clearInterval(o._heartbeatInterval),o._heartbeatInterval=setInterval(function(){o.socket&&o.connected&&o.roomId&&o.socket.emit("game:heartbeat",{room_id:o.roomId})},25e3),o.roomId){var n=o._lastSequence||0;o._joined=!1,o._joinPromise=null,o._rejoinPromise=o.join(o.roomId).then(function(){t.log("Reconnected - joined room "+o.roomId),o.requestSync(n)}).catch(function(e){t.log("Rejoin failed: "+(e&&e.message?e.message:String(e)))}).then(function(){o._rejoinPromise=null,o._flushOfflineQueue&&o._flushOfflineQueue()})}e&&(t.log("Game socket reconnected"),o._dispatch("reconnect",o._reconnAttempts||1),o._reconnAttempts=0),r()}),o.socket.on("connect_error",function(e){o._connecting=!1,t.log("Game socket error: "+e.message),o._dispatch("connectionError",e),i(e)}),o.socket.on("disconnect",function(e){o.connected=!1,o._joined=!1,o._joinPromise=null,o._heartbeatInterval&&(clearInterval(o._heartbeatInterval),o._heartbeatInterval=null),t.log("Game socket disconnected: "+e),o._dispatch("disconnect",e)}),o.socket.on("game:joined",function(e){void 0!==e.sequence&&(o._lastSequence=e.sequence,o._lastActionApplied=Math.max(o._lastActionApplied,e.sequence)),o._dispatch("joined",e)}),o.socket.on("game:player_joined",function(e){o._dispatch("playerJoined",e)}),o.socket.on("game:player_left",function(e){o._dispatch("playerLeft",e)}),o.socket.on("game:state",function(e){void 0!==e.sequence&&(o._lastSequence=Math.max(o._lastSequence,e.sequence)),o._dispatch("stateUpdate",e)}),o.socket.on("game:sync",function(e){void 0!==e.sequence&&(o._lastSequence=e.sequence,o._lastActionApplied=Math.max(o._lastActionApplied,e.sequence)),o._dispatch("sync",e),o._dispatch("stateUpdate",e)}),o.socket.on("game:action",function(e){if(void 0!==e.sequence){if(e.sequence<=o._lastActionApplied)return;o._lastActionApplied=e.sequence,o._lastSequence=Math.max(o._lastSequence,e.sequence)}o._dispatch("action",e)}),o.socket.on("game:player_connection",function(e){o._dispatch("playerConnection",e)}),o.socket.on("game:realtime",function(e){o._dispatch("realtime",e)}),o.socket.on("game:finished",function(e){void 0!==e.sequence&&(o._lastSequence=e.sequence),o._dispatch("finished",e)}),o.socket.on("game:error",function(e){t.log("Game error: "+(e.message||e.code)),o._dispatch("error",e)}),o.socket.on("game:rematch_request",function(e){o._dispatch("rematchRequest",e)}),o.socket.on("game:restarted",function(e){o._lastSequence=0,o._lastActionApplied=0,o._dispatch("restarted",e)})}catch(e){i(e)}}}(i,n),function(n,i){n._connectViaProxy=function(){var n=this;return n._useProxy&&n.connected?Promise.resolve():(n._useProxy=!0,n._connecting=!0,n._setupProxyListener(),n._connectPromise=new Promise(function(r,o){n._proxyConnectResolve=function(){n.connected=!0,n._connecting=!1,i.log("Game socket connected via parent proxy"),r()},i._post({type:"GAME_CONNECT"}),setTimeout(function(){n.connected||(n._connecting=!1,o(new t(e.CONNECT_TIMEOUT,"Proxy connection timeout")))},1e4)}),n._connectPromise)},n._setupProxyListener=function(){var e=this;e._proxyListenerSetup||(e._proxyListenerSetup=!0,window.addEventListener("message",function(t){if(a(t)){var n;try{n="string"==typeof t.data?JSON.parse(t.data):t.data}catch(e){return}if(n&&"object"==typeof n&&e._useProxy)switch(n.type){case"GAME_CONNECTED":e._proxyConnectResolve&&(e._proxyConnectResolve(),e._proxyConnectResolve=null);break;case"GAME_CONNECT_ERROR":e.connected=!1,e._connecting=!1;break;case"GAME_DISCONNECTED":e.connected=!1,e._dispatch("disconnect",n.reason||"transport");break;case"GAME_RECONNECTED":e.connected=!0,e._dispatch("reconnect",n.attempts||1);break;case"GAME_PLAYER_CONNECTION":e._dispatch("playerConnection",n);break;case"GAME_JOINED":e._joined=!0,void 0!==n.sequence&&(e._lastSequence=n.sequence,e._lastActionApplied=Math.max(e._lastActionApplied,n.sequence)),e._proxyJoinResolve&&(e._proxyJoinResolve(n),e._proxyJoinResolve=null),e._proxyJoinReject=null,e._dispatch("joined",n);break;case"GAME_JOIN_ERROR":e._joined=!1,e._proxyJoinReject&&(e._proxyJoinReject(r(n.message||"Join failed")),e._proxyJoinReject=null),e._proxyJoinResolve=null;break;case"GAME_PLAYER_JOINED":e._dispatch("playerJoined",n);break;case"GAME_PLAYER_LEFT":e._dispatch("playerLeft",n);break;case"GAME_STATE":void 0!==n.sequence&&(e._lastSequence=Math.max(e._lastSequence,n.sequence)),e._dispatch("stateUpdate",n);break;case"GAME_ACTION_DATA":if(void 0!==n.sequence){if(n.sequence<=e._lastActionApplied)break;e._lastActionApplied=n.sequence,e._lastSequence=Math.max(e._lastSequence,n.sequence)}e._dispatch("action",n);break;case"GAME_REALTIME_DATA":e._dispatch("realtime",n);break;case"GAME_FINISHED":void 0!==n.sequence&&(e._lastSequence=n.sequence),e._dispatch("finished",n);break;case"GAME_ERROR":i.log("Game error via proxy: "+(n.message||n.code)),e._dispatch("error",n);break;case"GAME_RESTARTED":e._lastSequence=0,e._lastActionApplied=0,e._dispatch("restarted",n);break;case"GAME_REMATCH_REQUEST":e._dispatch("rematchRequest",n);break;case"GAME_SYNC":void 0!==n.sequence&&(e._lastSequence=n.sequence,e._lastActionApplied=Math.max(e._lastActionApplied,n.sequence)),e._dispatch("sync",n),e._dispatch("stateUpdate",n)}}}))}}(i,n),function(n,i){function o(e){const t=e.roomId||i.config&&i.config.roomId,n=e.playerId||i.user&&"function"==typeof i.user.getId&&i.user.getId()||i.config&&i.config.userId;return t&&n?"_usion_game_state:"+n+":"+t:null}n.join=function(n){const o=this;if(n=n||i.config.roomId,o.roomId===n&&o._joinPromise)return o._joinPromise;if(o.roomId=n,o.playerId=i.user.getId(),o.directMode)return o._joined=!0,o._joinPromise=Promise.resolve({room_id:n,player_id:o.playerId}),o._joinPromise;if(o._useProxy){const r=new Promise(function(r,s){const c=function(e){s(e)};o._proxyJoinResolve=r,o._proxyJoinReject=c,i._post({type:"GAME_JOIN",room_id:n}),setTimeout(function(){o._proxyJoinReject===c&&(o._proxyJoinResolve=null,o._proxyJoinReject=null,s(new t(e.JOIN_TIMEOUT,"Join timeout")))},15e3)});return w(o,r)}let s;return s=o.socket&&o.connected?n?T(o.socket,"game:join",{room_id:n},15e3,e.JOIN_TIMEOUT).then(function(e){if(e.error)throw o._joined=!1,r(e);return o._joined=!0,void 0!==e.sequence&&(o._lastSequence=e.sequence,o._lastActionApplied=Math.max(o._lastActionApplied,e.sequence)),o._dispatch("joined",e),e}):Promise.reject(new t(e.NO_ROOM,"No room ID provided")):Promise.reject(new t(e.NOT_CONNECTED,"Not connected")),w(o,s)},n.joinWorld=function(e){const t=this;return e=e||{},i.matchmaking._joinWorld(e.serviceId).then(function(e){return t.roomId=e.roomId,{roomId:e.roomId,playerIds:e.players||[]}})},n.leave=function(){const e=this;return e.directMode?(e.roomId&&e._sendDirect("leave",{}),e.roomId=null,e._lastSequence=0,e._joined=!1,void(e._joinPromise=null)):e._useProxy?(e.roomId&&i._post({type:"GAME_LEAVE",room_id:e.roomId}),e.roomId=null,e._lastSequence=0,e._joined=!1,void(e._joinPromise=null)):void(e.socket&&e.connected&&e.roomId&&(e.socket.emit("game:leave",{room_id:e.roomId}),e.roomId=null,e._lastSequence=0,e._joined=!1,e._joinPromise=null))},n.action=function(n,r,o){const s=this,c=o&&o.nextTurn,a=!(!o||!o.queueOffline);if(s.directMode)return s._sendDirect("action",{action_type:n||"default",action_data:r||{}}),Promise.resolve({success:!0});if(a&&!s.connected)return s._queueOfflineAction(n,r,o);if(s._useProxy){if(!s.connected)return Promise.reject(new t(e.NOT_CONNECTED,"Not connected"));const o={type:"GAME_ACTION",room_id:s.roomId,action_type:n,action_data:r};return c&&(o.next_turn=c),i._post(o),Promise.resolve({success:!0,acknowledged:!1})}return(s._rejoinPromise||Promise.resolve()).then(function(){if(!s.socket||!s.connected){if(a)return s._queueOfflineAction(n,r,o);throw new t(e.NOT_CONNECTED,"Not connected")}const i={room_id:s.roomId,action_type:n,action_data:r};return c&&(i.next_turn=c),s._emitAction(i,!0)})},n._emitAction=function(n,i){const o=this;return o.socket&&o.connected?T(o.socket,"game:action",n).then(function(t){if(t.error){const s=r(t);if(i&&s.code===e.NOT_IN_ROOM)return o._autoRejoin().then(function(){return o._emitAction(n,!1)});throw s}return void 0!==t.sequence&&(o._lastSequence=t.sequence),t}):Promise.reject(new t(e.NOT_CONNECTED,"Not connected"))},n._autoRejoin=function(){const e=this;if(e._rejoinPromise)return e._rejoinPromise;if(!e.roomId||!e.socket||!e.connected)return Promise.resolve();i.log("Server reports socket not in room - auto-rejoining "+e.roomId);const t=e._lastSequence||0;return e._joined=!1,e._joinPromise=null,e._rejoinPromise=e.join(e.roomId).then(function(){e.requestSync(t)}).catch(function(e){i.log("Auto-rejoin failed: "+(e&&e.message?e.message:String(e)))}).then(function(){e._rejoinPromise=null,e._flushOfflineQueue&&e._flushOfflineQueue()}),e._rejoinPromise},n._queueOfflineAction=function(n,r,o){const s=this;return s._offlineQueue||(s._offlineQueue=[]),s._offlineQueue.length>=20?Promise.reject(new t(e.QUEUE_FULL,"Offline action queue is full (20)")):(i.log("Queued action while offline: "+n),new Promise(function(e,t){s._offlineQueue.push({actionType:n,actionData:r,opts:Object.assign({},o,{queueOffline:!1}),resolve:e,reject:t}),s._ensureOfflineFlushHook()}))},n._ensureOfflineFlushHook=function(){const e=this;e._offlineFlushHooked||(e._offlineFlushHooked=!0,e.on("reconnect",function(){e._flushOfflineQueue()}))},n._flushOfflineQueue=function(){const t=this,n=t._offlineQueue;if(!n||!n.length)return Promise.resolve();if(t._offlineFlushPromise)return t._offlineFlushPromise;if(!t.connected||!t._useProxy&&!t.directMode&&!t._joined)return Promise.resolve();i.log("Flushing "+n.length+" queued action(s) after reconnect");const o=Promise.resolve().then(function i(){if(!n.length)return Promise.resolve();if(!t.connected||!t._useProxy&&!t.directMode&&!t._joined)return Promise.resolve();const o=n[0];return t.action(o.actionType,o.actionData,o.opts).then(function(e){return n[0]===o&&n.shift(),o.resolve(e),i()},function(t){const s=r(t);if(s.code!==e.NOT_CONNECTED&&s.code!==e.NOT_IN_ROOM)return n[0]===o&&n.shift(),o.reject(t),i()})});function s(){t._offlineFlushPromise===o&&(t._offlineFlushPromise=null)}return t._offlineFlushPromise=o,o.then(s,s),o},n.setState=function(n){const o=this;if(o.directMode)return Promise.resolve({success:!1,error:"not_supported_in_direct_mode",code:e.UNSUPPORTED});const s=o._lastSequence||0;return o._useProxy?i._request("GAME_SET_STATE",{room_id:o.roomId,state:n||{},sequence:s}).then(function(e){if(e&&e.error){const t=r(e);return{success:!1,error:t.message,code:t.code}}return e||{success:!0}}).catch(function(t){const n=r(t,e.REQUEST_TIMEOUT);return{success:!1,error:n.message,code:n.code}}):o.socket&&o.connected?T(o.socket,"game:set_state",{room_id:o.roomId,state:n||{},sequence:s}).then(function(e){if(e.error){const t=r(e);return{success:!1,error:t.message,code:t.code}}return Object.keys(e).length?e:{success:!0}}):Promise.reject(new t(e.NOT_CONNECTED,"Not connected"))},n.realtime=function(t,n){const o=this;o.directMode?o._sendDirect("input",{action_type:t,action_data:n||{}}):o._useProxy?i._post({type:"GAME_REALTIME",room_id:o.roomId,action_type:t,action_data:n}):o.socket&&o.connected&&o.socket.emit("game:realtime",{room_id:o.roomId,action_type:t,action_data:n},function(t){if(!t||!t.error)return;const n=r(t);o._dispatch("error",{code:n.code,message:n.message,source:"realtime"}),n.code===e.NOT_IN_ROOM&&o._autoRejoin()})},n.requestSync=function(e){const t=this;e=void 0!==e?e:t._lastSequence,t.directMode?t._sendDirect("ping",{last_sequence:e||0}):t._useProxy&&t.roomId?i._post({type:"GAME_SYNC_REQUEST",room_id:t.roomId,last_sequence:e||0}):t.socket&&t.connected&&t.roomId&&t.socket.emit("game:sync_request",{room_id:t.roomId,last_sequence:e||0})},n.requestRematch=function(){const e=this;e.directMode?e._sendDirect("rematch",{}):e._useProxy&&e.roomId?i._post({type:"GAME_REMATCH",room_id:e.roomId}):e.socket&&e.connected&&e.roomId&&e.socket.emit("game:rematch",{room_id:e.roomId})},n.forfeit=function(){const n=this;return n.directMode?(n._sendDirect("forfeit",{}),Promise.resolve({success:!0})):n._useProxy?(i._post({type:"GAME_FORFEIT",room_id:n.roomId}),Promise.resolve({success:!0})):n.socket&&n.connected?T(n.socket,"game:forfeit",{room_id:n.roomId}).then(function(e){if(e.error)throw r(e);return e}):Promise.reject(new t(e.NOT_CONNECTED,"Not connected"))},n.reportResult=function(n,r){if(r=r||{},!((n=n||{}).draw||"string"==typeof n.winnerId&&n.winnerId))return Promise.reject(new t(e.INVALID_INPUT,"reportResult needs a winnerId (or draw: true)"));const o=n.roomId||this.roomId||i.config&&i.config.roomId||null;if(!o)return Promise.reject(new t(e.NO_ROOM,"reportResult needs a room — join a game first"));let s=null;return Array.isArray(n.standings)&&(s=n.standings.map(function(e){return"string"==typeof e?e:e&&(e.userId||e.user_id)||null}).filter(function(e){return"string"==typeof e&&e}),s.length||(s=null)),i._backendEmit("gc:match_result",{service_id:r.serviceId||i.config&&i.config.serviceId,room_id:o,winner_id:n.draw?null:n.winnerId,draw:!!n.draw,standings:s,scores:n.scores&&"object"==typeof n.scores?n.scores:null,display_score:null!=n.displayScore?String(n.displayScore):null,metric:null!=n.metric?String(n.metric):null,match_id:null!=n.matchId?String(n.matchId):null})},n.invite=function(e){const t=this;e=e||{};const n="undefined"!=typeof window&&(!!window.ReactNativeWebView||!!window.parent&&window.parent!==window),r=t.roomId||i.config&&i.config.roomId||null;if(!n){try{console.warn("[Usion] game.invite needs the Usion app; resolving as not sent.")}catch(e){}return Promise.resolve({success:!1,roomId:r,invited:[]})}const o={roomId:r};return"number"==typeof e.maxPlayers&&e.maxPlayers>0&&(o.maxPlayers=e.maxPlayers),i._request("GAME_INVITE_REQUEST",o,e.timeout||12e4).then(function(e){const n=(e=e||{}).roomId||r||null,i={success:!!e.success,roomId:n,invited:Array.isArray(e.invited)?e.invited:[]};return i.success&&n?Promise.resolve().then(function(){return t.connect()}).then(function(){return t.join(n)}).then(function(){return i}).catch(function(){return i}):i}).catch(function(){return{success:!1,roomId:r,invited:[]}})},n.disconnect=function(){const e=this;if(e._heartbeatInterval&&(clearInterval(e._heartbeatInterval),e._heartbeatInterval=null),e.directMode){if(e.directSocket)try{e.directSocket.close()}catch(e){}return e.directSocket=null,e.connected=!1,e.roomId=null,e._lastSequence=0,e._connecting=!1,e._connectPromise=null,e._joined=!1,e._joinPromise=null,e.directMode=!1,e.directConfig=null,void(e._directSeq=0)}if(e._useProxy)return i._post({type:"GAME_DISCONNECT"}),e.connected=!1,e.roomId=null,e._lastSequence=0,e._connecting=!1,e._connectPromise=null,e._joined=!1,e._joinPromise=null,void(e._useProxy=!1);e.socket&&(e.socket.disconnect(),e.socket=null,e.connected=!1,e.roomId=null,e._lastSequence=0,e._connecting=!1,e._connectPromise=null,e._joined=!1,e._joinPromise=null)},n.saveState=function(e){const t=o(this);if(!t)return!1;try{return localStorage.setItem(t,JSON.stringify({state:e,savedAt:Date.now()})),!0}catch(e){return!1}},n.loadState=function(){const e=o(this);if(!e)return null;try{const t=localStorage.getItem(e);if(!t)return null;const n=JSON.parse(t);return n&&void 0!==n.state?n.state:null}catch(e){return null}},n.clearState=function(){const e=o(this);if(e)try{localStorage.removeItem(e)}catch(e){}},n.debug=function(e){try{var t=window.parent&&window.parent!==window,n=!!window.ReactNativeWebView;if(t||n){var r=Object.assign({},e||{});r._diag=i.diagnostics?i.diagnostics():void 0,i._post({type:"GAME_DEBUG",payload:r})}}catch(e){}},n.isMultiplayer=function(){return"multiplayer"===i.getLaunchParams().mode},n.isConnected=function(){return this.directMode?!(!this.connected||!this.directSocket||this.directSocket.readyState!==WebSocket.OPEN):this._useProxy?!!this.connected:!!(this.connected&&this.socket&&this.socket.connected)}}(i,n),me(i,n),ye(i,n),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("visibilitychange",function(){if("visible"===document.visibilityState&&i.roomId)try{i.requestSync()}catch(e){}}),i}(be),be.UsionError=t,be.ERROR_CODES=e,function(n){n._backendHandlers={},n._boundSockets="undefined"!=typeof WeakSet?new WeakSet:null,n._bindBackendSocket=function(e){if(!e||"function"!=typeof e.onAny)return;if(this._boundSockets){if(this._boundSockets.has(e))return;this._boundSockets.add(e)}const t=this;e.onAny(function(e,n){const r=t._backendHandlers[e];r&&r(n)})},n._backendOn=function(e,t){this._backendHandlers[e]=t;const n=this.game&&this.game.socket;n&&("function"==typeof n.onAny?this._bindBackendSocket(n):"function"==typeof n.on&&n.on(e,t))},n._backendEmit=function(n,i,o){const s=this;function c(s){return new Promise(function(c,a){let u=!1;const l=setTimeout(function(){u||(u=!0,a(new t(e.REQUEST_TIMEOUT,"Backend request timeout")))},o);try{s.emit(n,i||{},function(e){u||(u=!0,clearTimeout(l),e&&e.error?a(r(e)):c(e))})}catch(e){clearTimeout(l),a(r(e))}})}o=o||8e3;const a=s.game&&s.game.socket;if(a&&a.connected)return c(a);if(s._isEmbedded)return s._request("BACKEND_EMIT",{event:n,data:i||{}},o).catch(function(e){throw r(e)});const u=s.config&&s.config.connectionMode||"platform";return!a&&"direct"!==u&&s.game&&"function"==typeof s.game.connect?s.game.connect().then(function(){const n=s.game.socket;if(n&&n.connected)return c(n);throw new t(e.NOT_CONNECTED,"No backend connection")}).catch(function(n){if(n instanceof t)throw n;throw new t(e.NOT_CONNECTED,"Backend connect failed: "+(n&&n.message?n.message:String(n)))}):Promise.reject(new t(e.NOT_CONNECTED,"No backend connection — socket is offline or reconnecting"))}}(be),be.lobby=function(e){const t={code:null,host:null,status:null,members:[]},n={};let r=!1;function i(){r||(r=!0,e._backendOn("lobby:update",function(e){t.code=e.code,t.host=e.host,t.status=e.status,t.members=e.members||[],n.update&&n.update(e)}),e._backendOn("lobby:started",function(e){t.status="started",n.started&&n.started(e)}))}function o(t,n){return i(),e._backendEmit(t,n)}return{get state(){return t},onUpdate:function(e){n.update=e,i()},onStarted:function(e){n.started=e,i()},create:async function(e){e=e||{};const n=await o("lobby:create",{max_players:e.maxPlayers||8,public:!!e.public});return n&&n.code&&(t.code=n.code),n},join:async function(e){const n=await o("lobby:join",{code:String(e||"").toUpperCase()});return n&&n.code&&(t.code=n.code),n},leave:function(){return t.code=null,o("lobby:leave",{}).catch(function(){})},setReady:function(e){return o("lobby:ready",{ready:!1!==e})},allReady:function(){return t.members.length>0&&t.members.every(function(e){return e.ready})},isHost:function(){const n=e.user&&e.user.getId&&e.user.getId();return!(!t.host||!n||t.host!==n)},start:function(e){return o("lobby:start",{room_id:e})},queue:async function(t,n){n=n||{};const r=e.config&&e.config.apiUrl||"",i=e.user&&e.user.getToken&&e.user.getToken();if(!r)throw new Error("No apiUrl configured");const o=await fetch(r.replace(/\/$/,"")+"/games/matchmake",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+i},body:JSON.stringify({service_id:t,conversation_id:n.conversationId||"standalone_"+t})});if(!o.ok)throw new Error("Matchmake failed: HTTP "+o.status);return o.json()}}}(be),be.leaderboard=function(e){function t(t){return t&&t.serviceId||e.config&&e.config.serviceId}return{submit:function(n,r,i){return e._backendEmit("lb:submit",{service_id:t(i),score:n,metadata:null!=r?r:null})},scores:function(n,r){var i=Array.isArray(n)?n:[n];return e._backendEmit("lb:scores",{service_id:t(r),user_ids:i}).then(function(e){return e&&e.scores||{}})},friends:function(n){return n=n||{},e._backendEmit("lb:friends",{service_id:t(n),limit:n.limit||50}).then(function(e){return e&&e.entries||[]})},top:function(n){return n=n||{},e._backendEmit("lb:top",{service_id:t(n),limit:n.limit||20}).then(function(e){return e&&e.entries||[]})},me:function(n){return e._backendEmit("lb:me",{service_id:t(n)})}}}(be),be.cloud=function(e){function t(t){return t&&t.serviceId||e.config&&e.config.serviceId}function n(n,r,i,o){var s=Object.assign({service_id:t(o),scope:r},i);return e._backendEmit(n,s)}function r(e){return{get:function(t,r){return n("kv:get",e,{key:t},r).then(function(e){return e&&e.exists?e.value:null})},set:function(t,r,i){return n("kv:set",e,{key:t,value:r},i)},remove:function(t,r){return n("kv:remove",e,{key:t},r)},keys:function(t){return n("kv:keys",e,{},t).then(function(e){return e&&e.keys||[]})}}}var i=r("user");return i.shared=r("shared"),i.shared.incr=function(e,t,r){return n("kv:incr","shared",{key:e,delta:null==t?1:t},r).then(function(e){return e&&e.value})},i}(be),be.matchmaking=function(n){let i=null,o=null,s=!1;function c(e){return{roomId:e&&e.room_id,players:e&&e.player_ids||[],serviceId:e&&e.service_id}}function a(){s||(s=!0,n._backendOn("mm:matched",function(e){const t=c(e);if(o&&o(t),i){const e=i;i=null,e.resolve(t)}}))}function u(o,s,u){if(a(),i){const n=i;i=null,n.reject(new t(e.SUPERSEDED,"Superseded by a newer find()"))}let l=null;const d={},f=new Promise(function(e,t){d.resolve=function(t){l&&clearTimeout(l),e(t)},d.reject=function(e){l&&clearTimeout(l),i===d&&(i=null),t(e)}});return i=d,s>0&&(l=setTimeout(function(){l=null,n._backendEmit("mm:cancel",{}).catch(function(){}),d.reject(new t(e.MATCH_TIMEOUT,u+s+"ms"))},s)),n._backendEmit("mm:join",o).then(function(e){e&&e.matched&&e.room_id&&i===d&&(i=null,d.resolve(c(e)))}).catch(function(e){i===d&&d.reject(r(e))}),f}return{onMatch:function(e){o=e,a()},find:function(e,t){t=t||{};return u({service_id:e||n.config&&n.config.serviceId,size:t.size||2},t.timeout,"No match within ")},_joinWorld:function(e){return u({service_id:e||n.config&&n.config.serviceId,mode:"world"},15e3,"No world placement within ")},cancel:function(){if(i){const n=i;i=null,n.reject(new t(e.CANCELLED,"cancelled"))}return n._backendEmit("mm:cancel",{})}}}(be),be.notify=function(e){function t(t){return t&&t.serviceId||e.config&&e.config.serviceId}return{send:function(n){return n=n||{},e._backendEmit("notify:send",{service_id:t(n),title:n.title,body:n.body,path:n.path})},setMuted:function(n,r){return e._backendEmit("notify:set_pref",{service_id:t(r),muted:!!n})},isMuted:function(n){return e._backendEmit("notify:get_pref",{service_id:t(n)}).then(function(e){return!(!e||!e.muted)})}}}(be),be.permissions=function(e){function t(e){return"string"==typeof e?e?[e]:[]:Array.isArray(e)?e.filter(function(e){return"string"==typeof e&&e}):[]}function n(){return"undefined"!=typeof window&&(!!window.ReactNativeWebView||!!window.parent&&window.parent!==window)}function r(e){const t={};return e.forEach(function(e){t[e]=!1}),t}function i(e,t){const n=t||{};return{granted:e.length>0&&e.every(function(e){return!!n[e]}),permissions:n}}const o={_requestTimeoutMs:12e4,request:function(c,u){const l=t(c),d=u&&"string"==typeof u.reason?u.reason:void 0;if(!n()){try{console.warn("[Usion] permissions.request needs the Usion app; resolving as not granted.")}catch(e){}return Promise.resolve(i(l,r(l)))}return new Promise(function(t){const n=s();let c=!1,u=null;function f(e){c||(c=!0,u&&clearTimeout(u),window.removeEventListener("message",_),t(e))}function _(e){if(!a(e))return;let t;try{t="string"==typeof e.data?JSON.parse(e.data):e.data}catch(e){return}t&&t._requestId===n&&"PERMISSION_RESULT"===t.type&&f(i(l,t.permissions))}window.addEventListener("message",_),u=setTimeout(function(){c||o.query(l).then(function(e){f(i(l,e))}).catch(function(){f(i(l,r(l)))})},o._requestTimeoutMs||12e4),e._post({type:"PERMISSION_REQUEST",_requestId:n,permissions:l,reason:d})})},query:function(i){const o=t(i);return n()?e._request("PERMISSION_QUERY",{permissions:o},8e3).then(function(e){return e&&e.permissions||{}}):Promise.resolve(r(o))},has:function(e){return o.query([e]).then(function(t){return!(!t||!t[e])})}};return o}(be),be.screen=function(e){var t=[],n=!1;function r(e){if(a(e)){var n;try{n="string"==typeof e.data?JSON.parse(e.data):e.data}catch(e){return}if(n&&"SCREEN_CAPTURE"===n.type)for(var r="string"==typeof n.kind&&n.kind?n.kind:"screenshot",i=t.slice(),o=0;o<i.length;o++)try{i[o]({kind:r})}catch(e){}}}return{protect:function(t){try{e._post({type:"SCREEN_PROTECT",enabled:!!t})}catch(e){}},onCapture:function(e){if("function"!=typeof e)return function(){};t.push(e),n||"undefined"!=typeof window&&window.addEventListener&&(window.addEventListener("message",r),n=!0);var i=!1;return function(){if(!i){i=!0;var o=t.indexOf(e);o>=0&&t.splice(o,1),0===t.length&&function(){if(n){try{window.removeEventListener("message",r)}catch(e){}n=!1}}()}}},support:function(){var t=e.config&&e.config.screenCapture||null;return{block:!(!t||!t.block),detect:!(!t||!t.detect)}}}}(be),be.netcode=ve,Object.assign(be,function(e){return{saveResult:function(t,n){return e._request("SAVE_RESULT",{data:t,metadata:n||{}},15e3)},deleteResult:function(t){return e._request("DELETE_RESULT",{resultId:t})},getResults:function(){return e._results||[]}}}(be)),Object.assign(be,function(e){return{claimBackButton:function(t){e._backButtonCallback=t,e._post({type:"CLAIM_BACK_BUTTON"})},releaseBackButton:function(){e._backButtonCallback=null,e._post({type:"RELEASE_BACK_BUTTON"})}}}(be)),Object.assign(be,function(e){return{onHostNavigate:function(t){e._hostNavigateCallback=t,e._post({type:"HOST_NAVIGATE_SUBSCRIBED"})},offHostNavigate:function(){e._hostNavigateCallback=null,e._post({type:"HOST_NAVIGATE_UNSUBSCRIBED"})},openChat:function(t){t=t||{},e._post({type:"OPEN_CHAT_TAB",prefill:"string"==typeof t.prefill?t.prefill:void 0})},reportPath:function(t){"string"==typeof t&&t&&e._post({type:"TAB_CHANGED",path:t})}}}(be)),Object.assign(be,v),Object.assign(be,b),be}();"undefined"!=typeof window?window.Usion=Usion:"undefined"!=typeof globalThis&&(globalThis.Usion=Usion);
@@ -68,7 +68,7 @@ export function isTrustedMessageSource(event) {
68
68
  * Core Usion object with init, _post, _request
69
69
  */
70
70
  export const core = {
71
- version: '2.29.0', // synced from package.json by scripts/sync-version.mjs
71
+ version: '2.31.0', // synced from package.json by scripts/sync-version.mjs
72
72
  config: {},
73
73
  _initialized: false,
74
74
  _initCallback: null,
@@ -32,6 +32,7 @@ import { createCloudModule } from './cloud.js';
32
32
  import { createMatchmakingModule } from './matchmaking.js';
33
33
  import { createNotifyModule } from './notify.js';
34
34
  import { createPermissionsModule } from './permissions.js';
35
+ import { createScreenModule } from './screen.js';
35
36
  import { applyBackendChannel } from './backend-channel.js';
36
37
  import { netcode } from './netcode/index.js';
37
38
  import { UsionError, ERROR_CODES } from './errors.js';
@@ -60,6 +61,8 @@ Usion.matchmaking = createMatchmakingModule(Usion);
60
61
  Usion.notify = createNotifyModule(Usion);
61
62
  // Permission requests (host-mediated modal; embedded feature).
62
63
  Usion.permissions = createPermissionsModule(Usion);
64
+ // Screen-capture guard (host-mediated; honest per-platform capability).
65
+ Usion.screen = createScreenModule(Usion);
63
66
 
64
67
  // Netcode toolkit (transport-agnostic, zero-dependency).
65
68
  Usion.netcode = netcode;
@@ -99,16 +99,69 @@ export const miscMethods = {
99
99
  },
100
100
 
101
101
  /**
102
- * Download a file to the device's storage / gallery.
103
- * @param {string} url - URL of the file to download
104
- * @param {string} [filename] - Optional filename (default: 'download.mp4')
105
- * @returns {Promise<{success: boolean, error?: string}>}
102
+ * Share an actual file attachment through the operating system share sheet.
103
+ * Use an HTTPS URL or a base64 data URL; mobile blob: URLs belong to the
104
+ * WebView process and cannot be opened by the native host.
105
+ *
106
+ * @param {string} url - HTTPS/HTTP URL or base64 data URL
107
+ * @param {object} [options]
108
+ * @param {string} [options.filename] - Suggested attachment filename
109
+ * @param {string} [options.mimeType] - MIME type when the URL does not declare it
110
+ * @param {string} [options.title] - Native share dialog title
111
+ * @param {string} [options.text] - Optional caption (supported by compatible web targets)
112
+ * @returns {Promise<{success: boolean, destination?: string, cancelled?: boolean, fallback?: boolean}>}
113
+ */
114
+ shareFile: function(url, options) {
115
+ options = options || {};
116
+ var payload = { url: url };
117
+ if (options.filename) payload.filename = options.filename;
118
+ if (options.mimeType) payload.mimeType = options.mimeType;
119
+ if (options.title) payload.title = options.title;
120
+ if (options.text) payload.text = options.text;
121
+ return this._request('SHARE_FILE', payload, 120000);
122
+ },
123
+
124
+ /**
125
+ * Publish content to the signed-in user's Usions feed with service attribution.
126
+ * @param {'audio'|'image'|'video'|'text'|'mixed'} contentType
127
+ * @param {object} data
128
+ * @returns {Promise<{success: boolean, postId?: string, shareUrl?: string}>}
129
+ */
130
+ shareToFeed: function(contentType, data) {
131
+ var payload = Object.assign({}, data, {
132
+ contentType: contentType,
133
+ serviceId: this.config.serviceId,
134
+ serviceName: this.config.serviceName
135
+ });
136
+ return this._request('SHARE_TO_FEED', payload, 30000);
137
+ },
138
+
139
+ /**
140
+ * Download a file to the device's storage / gallery. In auto mode images
141
+ * and videos go to the gallery; other file types go to Files/Downloads.
142
+ *
143
+ * @param {string} url - HTTPS/HTTP URL or base64 data URL
144
+ * @param {string|object} [filename] - Filename, or the options object
145
+ * @param {object} [options]
146
+ * @param {'auto'|'gallery'|'files'} [options.destination]
147
+ * @param {string} [options.mimeType]
148
+ * @param {string} [options.title]
149
+ * @returns {Promise<{success: boolean, destination?: string, cancelled?: boolean}>}
106
150
  */
107
- download: function(url, filename) {
108
- return this._request('DOWNLOAD_FILE', {
151
+ download: function(url, filename, options) {
152
+ if (filename && typeof filename === 'object') {
153
+ options = filename;
154
+ filename = options.filename;
155
+ }
156
+ options = options || {};
157
+ var payload = {
109
158
  url: url,
110
- filename: filename || 'download.mp4'
111
- }, 120000);
159
+ filename: filename || options.filename || 'download.mp4'
160
+ };
161
+ if (options.mimeType) payload.mimeType = options.mimeType;
162
+ if (options.destination) payload.destination = options.destination;
163
+ if (options.title) payload.title = options.title;
164
+ return this._request('DOWNLOAD_FILE', payload, 120000);
112
165
  },
113
166
 
114
167
  /**
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Usion SDK Screen — mark a moment as secret, and know when it was captured.
3
+ *
4
+ * Some apps show something the user is not supposed to keep: the pattern a
5
+ * memory game flashes for two seconds, a one-time code, a card another player
6
+ * must not see. `Usion.screen.protect(true)` tells the host "this screen is
7
+ * secret"; `protect(false)` releases it the instant the moment is over.
8
+ *
9
+ * Usion.screen.protect(true); // preview starts — no souvenirs
10
+ * ...
11
+ * Usion.screen.protect(false); // preview over — back to normal
12
+ *
13
+ * const stop = Usion.screen.onCapture(function () {
14
+ * regenerateRound(); // neutralize, never punish
15
+ * });
16
+ *
17
+ * What the platform can actually do differs per OS, and the host declares it
18
+ * honestly — read it with `support()` and design for the weakest case:
19
+ *
20
+ * Android { block: true, detect: false } FLAG_SECURE blocks the capture,
21
+ * so `onCapture` never fires.
22
+ * iOS { block: false, detect: true } the OS cannot block it, so the
23
+ * host reports it after the fact.
24
+ * Web { block: false, detect: false } a browser can do neither.
25
+ * missing { block: false, detect: false } older app builds, standalone.
26
+ *
27
+ * This is a DETERRENT, never a security guarantee: a second phone pointed at
28
+ * the screen defeats every platform. Anything that must not leak belongs on
29
+ * your server, not behind this flag.
30
+ *
31
+ * Every method is safe outside the Usion host: `protect()` is a silent no-op,
32
+ * `onCapture()` simply never fires, and `support()` reports all-false.
33
+ */
34
+
35
+ import { isTrustedMessageSource } from './core.js';
36
+
37
+ export function createScreenModule(Usion) {
38
+ /** @type {Array<function>} */
39
+ var subscribers = [];
40
+ var listening = false;
41
+
42
+ function onMessage(event) {
43
+ // Only the real host shell may claim a capture happened — a sibling frame
44
+ // must not be able to fake one (it could grief a game into rerolling).
45
+ if (!isTrustedMessageSource(event)) return;
46
+
47
+ var data;
48
+ try {
49
+ data = typeof event.data === 'string' ? JSON.parse(event.data) : event.data;
50
+ } catch (e) {
51
+ return;
52
+ }
53
+ if (!data || data.type !== 'SCREEN_CAPTURE') return;
54
+
55
+ // 'screenshot' is the only kind hosts send today; 'recording' is reserved.
56
+ // An unknown kind is still a capture — pass it through rather than drop it.
57
+ var kind = (typeof data.kind === 'string' && data.kind) ? data.kind : 'screenshot';
58
+
59
+ // Snapshot: a callback may unsubscribe (or subscribe) while we fan out.
60
+ var current = subscribers.slice();
61
+ for (var i = 0; i < current.length; i++) {
62
+ // One broken subscriber must not silence the others.
63
+ try { current[i]({ kind: kind }); } catch (e) { /* subscriber's problem */ }
64
+ }
65
+ }
66
+
67
+ function startListening() {
68
+ if (listening) return;
69
+ if (typeof window === 'undefined' || !window.addEventListener) return;
70
+ window.addEventListener('message', onMessage);
71
+ listening = true;
72
+ }
73
+
74
+ function stopListening() {
75
+ if (!listening) return;
76
+ try { window.removeEventListener('message', onMessage); } catch (e) { /* noop */ }
77
+ listening = false;
78
+ }
79
+
80
+ return {
81
+ /**
82
+ * Mark the current screen secret (`true`) or release it (`false`).
83
+ *
84
+ * Fire-and-forget: there is no acknowledgement and nothing to await. Keep
85
+ * the protected window as short as the secret itself — on Android the
86
+ * whole app is unscreenshottable while it is on, and a leaked `true` would
87
+ * silently break the user's ability to capture anything else. Always pair
88
+ * it with `protect(false)`.
89
+ *
90
+ * Safe no-op when running standalone, or on a host that cannot protect.
91
+ * @param {boolean} enabled
92
+ */
93
+ protect: function (enabled) {
94
+ try {
95
+ Usion._post({ type: 'SCREEN_PROTECT', enabled: !!enabled });
96
+ } catch (e) {
97
+ // No host, no window, no postMessage — nothing to protect, nothing to
98
+ // report. A screen flag must never take the app down with it.
99
+ }
100
+ },
101
+
102
+ /**
103
+ * Called when the host observes the user capturing the screen — today only
104
+ * on platforms that report it (`support().detect`), i.e. iOS. On Android
105
+ * the capture is blocked instead, so this never fires; on web neither
106
+ * happens. React by neutralizing the value of the capture (reroll the
107
+ * round, invalidate the code), never by punishing the user: the same
108
+ * gesture may have been an accidental button combination.
109
+ *
110
+ * @param {function({ kind: string }): void} callback - `kind` is
111
+ * `'screenshot'` today (`'recording'` is reserved for a later release).
112
+ * @returns {function(): void} Unsubscribe function (safe to call twice).
113
+ */
114
+ onCapture: function (callback) {
115
+ if (typeof callback !== 'function') return function () {};
116
+
117
+ subscribers.push(callback);
118
+ startListening();
119
+
120
+ var done = false;
121
+ return function () {
122
+ if (done) return;
123
+ done = true;
124
+ var i = subscribers.indexOf(callback);
125
+ if (i >= 0) subscribers.splice(i, 1);
126
+ if (subscribers.length === 0) stopListening();
127
+ };
128
+ },
129
+
130
+ /**
131
+ * What this host can do about screen capture, declared by the host in its
132
+ * INIT config. Synchronous and always an object — an older app build or a
133
+ * standalone page reports `{ block: false, detect: false }`, so a plain
134
+ * `if (!Usion.screen.support().block)` covers every unsupported case.
135
+ *
136
+ * @returns {{ block: boolean, detect: boolean }} `block`: the OS prevents
137
+ * the capture. `detect`: the OS reports it, so `onCapture` can fire.
138
+ */
139
+ support: function () {
140
+ var cap = (Usion.config && Usion.config.screenCapture) || null;
141
+ return {
142
+ block: !!(cap && cap.block),
143
+ detect: !!(cap && cap.detect),
144
+ };
145
+ },
146
+ };
147
+ }
package/types/index.d.ts CHANGED
@@ -37,6 +37,12 @@ export interface UsionConfig {
37
37
  * `Usion.getLaunchParams().mode`. (SDK ≥ 2.18)
38
38
  */
39
39
  mode?: 'single' | 'multiplayer';
40
+ /**
41
+ * What this host can do about screen capture, declared honestly per
42
+ * platform. Absent on older app builds and standalone pages — read it with
43
+ * `Usion.screen.support()`, which treats absent as all-false. (SDK ≥ 2.31)
44
+ */
45
+ screenCapture?: ScreenCaptureSupport;
40
46
  }
41
47
 
42
48
  // ─── Payment ─────────────────────────────────────────────────────
@@ -159,9 +165,15 @@ export interface ShareMediaItem {
159
165
 
160
166
  export interface ShareData {
161
167
  text?: string;
168
+ message?: string;
169
+ title?: string;
162
170
  audioUrl?: string;
163
171
  imageUrl?: string;
164
172
  videoUrl?: string;
173
+ /** Generic attachment URL for the host's external share action. */
174
+ fileUrl?: string;
175
+ filename?: string;
176
+ mimeType?: string;
165
177
  thumbnailUrl?: string;
166
178
  width?: number;
167
179
  height?: number;
@@ -169,6 +181,30 @@ export interface ShareData {
169
181
  media?: ShareMediaItem[];
170
182
  }
171
183
 
184
+ export interface FileTransferOptions {
185
+ filename?: string;
186
+ mimeType?: string;
187
+ title?: string;
188
+ }
189
+
190
+ export interface ShareFileOptions extends FileTransferOptions {
191
+ /** Optional caption on web targets that accept a file and text together. */
192
+ text?: string;
193
+ }
194
+
195
+ export interface DownloadOptions extends FileTransferOptions {
196
+ /** `auto` saves images/videos to the gallery and other types to Files/Downloads. */
197
+ destination?: 'auto' | 'gallery' | 'files';
198
+ }
199
+
200
+ export interface FileTransferResult {
201
+ success: boolean;
202
+ destination?: 'gallery' | 'files' | 'share-sheet' | 'download';
203
+ cancelled?: boolean;
204
+ /** Web could not attach the binary and shared its URL or downloaded it instead. */
205
+ fallback?: boolean;
206
+ }
207
+
172
208
  // ─── Game ────────────────────────────────────────────────────────
173
209
 
174
210
  export interface GameJoinResult {
@@ -1167,10 +1203,12 @@ export interface UsionSDK {
1167
1203
  reportPath(path: string): void;
1168
1204
 
1169
1205
  // Download
1170
- download(url: string, filename?: string): Promise<{ success?: boolean; error?: string }>;
1206
+ download(url: string, filename?: string, options?: DownloadOptions): Promise<FileTransferResult>;
1207
+ download(url: string, options?: DownloadOptions): Promise<FileTransferResult>;
1171
1208
 
1172
1209
  // Sharing
1173
1210
  share(contentType: 'audio' | 'image' | 'video' | 'text' | 'mixed', data: ShareData): void;
1211
+ shareFile(url: string, options?: ShareFileOptions): Promise<FileTransferResult>;
1174
1212
  shareToFeed(contentType: 'text' | 'image' | 'video' | 'audio' | 'mixed', data: {
1175
1213
  text?: string;
1176
1214
  media?: Array<{ type: 'image' | 'video' | 'audio'; url: string; thumbnailUrl?: string; width?: number; height?: number; duration?: number }>;
@@ -1230,6 +1268,7 @@ export interface UsionSDK {
1230
1268
  cloud: CloudModule;
1231
1269
  notify: NotifyModule;
1232
1270
  permissions: PermissionsModule;
1271
+ screen: UsionScreen;
1233
1272
  netcode: NetcodeModule;
1234
1273
  }
1235
1274
 
@@ -1270,6 +1309,55 @@ export interface PermissionsModule {
1270
1309
  has(permission: string): Promise<boolean>;
1271
1310
  }
1272
1311
 
1312
+ /**
1313
+ * What the host can actually do about screen capture on this platform.
1314
+ * Android blocks it (`block`), iOS can only report it (`detect`), web can do
1315
+ * neither. Both false is the honest default for anything else.
1316
+ */
1317
+ export interface ScreenCaptureSupport {
1318
+ /** The OS prevents the capture outright (Android FLAG_SECURE). */
1319
+ block: boolean;
1320
+ /** The OS reports a capture after the fact (iOS), so `onCapture` can fire. */
1321
+ detect: boolean;
1322
+ }
1323
+
1324
+ /** The kinds of capture a host reports. `'recording'` is reserved for a later release. */
1325
+ export type ScreenCaptureKind = 'screenshot' | 'recording';
1326
+
1327
+ /** A capture the host observed. Treat an unrecognized `kind` as a capture too. */
1328
+ export interface ScreenCaptureEvent {
1329
+ kind: ScreenCaptureKind | (string & {});
1330
+ }
1331
+
1332
+ /**
1333
+ * Mark a moment as secret and learn when it was captured anyway (SDK ≥ 2.31).
1334
+ *
1335
+ * A deterrent, never a guarantee — a second phone pointed at the screen beats
1336
+ * every platform, so nothing that must not leak belongs behind this flag.
1337
+ * Capability differs per OS; read `support()` and design for the weakest case.
1338
+ * Safe everywhere: standalone, older hosts, and web all degrade to no-ops.
1339
+ */
1340
+ export interface UsionScreen {
1341
+ /**
1342
+ * Mark the current screen secret (`true`) or release it (`false`).
1343
+ * Fire-and-forget; always pair the `true` with a `false` — on Android the
1344
+ * app stays unscreenshottable until it is released.
1345
+ */
1346
+ protect(enabled: boolean): void;
1347
+ /**
1348
+ * Called when the host observes a capture — only where `support().detect`
1349
+ * is true (iOS). Android blocks the capture instead, so it never fires
1350
+ * there; web does neither. Neutralize the captured value, never punish.
1351
+ * Returns an unsubscribe function.
1352
+ */
1353
+ onCapture(callback: (event: ScreenCaptureEvent) => void): UnsubscribeFn;
1354
+ /**
1355
+ * What this host can do, from the INIT config. Synchronous, and always an
1356
+ * object — an older host or a standalone page reports all-false.
1357
+ */
1358
+ support(): ScreenCaptureSupport;
1359
+ }
1360
+
1273
1361
  /** Scoped server-persisted KV operations (per-user or shared). */
1274
1362
  export interface CloudScope {
1275
1363
  /** Get a value; resolves to null when the key doesn't exist. */