@usions/sdk 2.33.0 → 2.35.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
@@ -287,6 +287,64 @@ const me = await Usion.leaderboard.me(); // { score, rank, total }
287
287
  `friends()` is scoped to users you've chatted with (your conversations) plus
288
288
  yourself. Works in standalone *and* embedded games (rides the backend channel).
289
289
 
290
+ ### Tournament support registration
291
+
292
+ Declare tournament support in the game's service registration. This is
293
+ optional game metadata shared by SDK v2 and v3, separate from `sdk.capabilities`.
294
+ It makes the game eligible for tournament discovery; it does not create an
295
+ active tournament, a bracket, entry fees, prizes, or permission to trust scores.
296
+ Leaderboard or multiplayer support alone does not opt a game in.
297
+
298
+ From the creator's trusted server or development tooling, use the creator REST
299
+ API with the creator's bearer token. Keep that credential out of mini-app code.
300
+ For a new game:
301
+
302
+ ```http
303
+ POST /services
304
+ Authorization: Bearer <creator-token>
305
+ Content-Type: application/json
306
+
307
+ {
308
+ "name": "My Game",
309
+ "iframe_url": "https://game.example",
310
+ "tags": ["game"],
311
+ "is_published": true,
312
+ "tournament": { "enabled": true }
313
+ }
314
+ ```
315
+
316
+ Enable an existing registered game without changing its other settings:
317
+
318
+ ```http
319
+ PUT /services/<service-id>
320
+ Authorization: Bearer <creator-token>
321
+ Content-Type: application/json
322
+
323
+ { "tournament": { "enabled": true } }
324
+ ```
325
+
326
+ The service must have the `game` tag. Set `enabled` to `false` to disable;
327
+ omit `tournament` on unrelated updates to preserve the current setting. New
328
+ games default to disabled. Query discoverable, opted-in games with
329
+ `GET /registry/explore/items?section=games&tournament=true`; existing visibility
330
+ and access rules still apply.
331
+ Unpublished or otherwise inaccessible games are not made discoverable by this
332
+ marker; opt-in on an existing game preserves its publication status.
333
+
334
+ For an AI Creator build, put exactly one declaration in the entry HTML:
335
+
336
+ ```html
337
+ <meta name="usion:tournament" content="true">
338
+ ```
339
+
340
+ Use `content="false"` to disable. Only the exact values `true` and `false` are
341
+ accepted; duplicate declarations or attributes are rejected before publishing.
342
+ Comments, scripts, and other files do not declare support. Omitting the marker
343
+ on a later build preserves the registered value; remove support explicitly
344
+ before changing the service from a game into an app. Hand-built games use the
345
+ creator API above; loading the SDK or adding a marker to an external site does
346
+ not register or change its service.
347
+
290
348
  ### Matchmaking (play with online strangers)
291
349
 
292
350
  Pair players who don't know each other into a game:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usions/sdk",
3
- "version": "2.33.0",
3
+ "version": "2.35.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.33.0 — minified build; source: packages/sdk/src/modules (github.com/ugshanyu/usionthemobile) */
2
- var Usion=function(){"use strict";const e={PERMISSION_DENIED:"PERMISSION_DENIED",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 i(i,r){if(i instanceof t)return i;if(i&&"object"==typeof i){const n="string"==typeof i.code&&e[i.code]?i.code:null,r=i.message||i.error;if(n){const e=new t(n,"string"==typeof r?r:n),o=null!=i.retry_after?i.retry_after:i.retryAfter;return"number"==typeof o&&isFinite(o)&&(e.retryAfter=o),e}i instanceof Error||"string"!=typeof r||(i=r)}const o=i&&i.message?i.message:String(i||"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(r||e.UNKNOWN,o)}let r=0;const o={};function s(){return++r}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.33.0",config:{},_initialized:!1,_initCallback:null,_messageHandlerRegistered:!1,_results:[],_backButtonCallback:null,init:function(n,r){const s=this;return n&&"object"==typeof n&&(r=n,n=null),r=r||{},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(){})),r.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 "+r.timeout+"ms — host silent or running standalone"))},r.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),!0!==t.config.userIsAdult&&!1!==t.config.userIsAdult||!s.user||(s.config.userIsAdult=t.config.userIsAdult,s.user._isAdult=t.config.userIsAdult),void(t.config.hostFeatures&&"object"==typeof t.config.hostFeatures&&(s.config.hostFeatures=t.config.hostFeatures));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(i(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 r=t.roomId;s.config.roomId=r,s.config.mode="multiplayer",s.game._dispatch("roomAssigned",{roomId:r}),Promise.resolve().then(function(){return s.game.connect()}).then(function(){return s.game.join(r)}).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(i){if(!(i&&!1===i.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(i){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,i,r){const c=this;return r=r||5e3,new Promise(function(a,u){const l=s(),d=setTimeout(function(){delete o[l],u(new t(e.REQUEST_TIMEOUT,"Request timeout"))},r);o[l]={resolve:function(e){clearTimeout(d),a(e)},reject:function(e){clearTimeout(d),u(e)}},c._post({type:n,_requestId:l,...i})})}};var l="_d:",d="_migrated_v2";function f(e){return l+e}function h(e,t,n){return e._backendEmit(t,Object.assign({service_id:e.config&&e.config.serviceId,scope:"storage"},n))}function _(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 g(e){return e._request("STORAGE_KEYS",{}).then(function(e){return e&&e.keys||[]})}function y(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 i="string"==typeof e?document.querySelector(e):e,r="string"==typeof t?document.querySelector(t):t;function o(){const e=i.value.length;r.textContent=e+" / "+n,r.classList.remove("warning","error"),e>.9*n?r.classList.add("error"):e>.7*n&&r.classList.add("warning")}i&&r&&(i.addEventListener("input",o),o())},selectionGrid:function(e,t,n){const i=document.querySelector(e);if(!i)return;let r=null;return i.querySelectorAll(t).forEach(function(e){e.addEventListener("click",function(){i.querySelectorAll(t).forEach(function(e){e.classList.remove("selected")}),e.classList.add("selected"),r=e.dataset.value||e.dataset.id,n&&n(r,e)})}),{getSelected:function(){return r},clear:function(){i.querySelectorAll(t).forEach(function(e){e.classList.remove("selected")}),r=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)},shareToStory:function(e,t){var n={url:e};return(t=t||{}).filename&&(n.filename=t.filename),t.mimeType&&(n.mimeType=t.mimeType),t.stickerUrl&&(n.stickerUrl=t.stickerUrl),t.backgroundTopColor&&(n.backgroundTopColor=t.backgroundTopColor),t.backgroundBottomColor&&(n.backgroundBottomColor=t.backgroundBottomColor),t.title&&(n.title=t.title),t.text&&(n.text=t.text),this._request("SHARE_TO_STORY",n,12e4)},download:function(e,t,n){t&&"object"==typeof t&&(t=(n=t).filename),n=n||{};var i={url:e,filename:t||n.filename||"download.mp4"};return n.mimeType&&(i.mimeType=n.mimeType),n.destination&&(i.destination=n.destination),n.title&&(i.title=n.title),this._request("DOWNLOAD_FILE",i,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 i;try{i="string"==typeof n.data?JSON.parse(n.data):n.data}catch(e){return}i.type===e&&t(i)}return window.addEventListener("message",n),function(){window.removeEventListener("message",n)}}};var I=/[\x00-\x1f\x7f\s\\]/;function w(e){return"string"!=typeof e?"path must be a string":e.length>512?"path too long (max 512)":"/"!==e.charAt(0)||"/"===e.charAt(1)?"path must be a relative in-app path starting with a single '/'":-1!==e.indexOf("://")||I.test(e)?"path contains illegal characters":null}function T(e){return Array.from(e).length}var E=5242880,S=/^data:image\/(png|jpeg|webp);base64,/,A=/^[A-Za-z0-9+/]+={0,2}$/;function k(){var e="undefined"!=typeof globalThis?globalThis.crypto:void 0;if(e&&"function"==typeof e.randomUUID)return e.randomUUID();var t=new Array(16);if(e&&"function"==typeof e.getRandomValues){var n=new Uint8Array(16);e.getRandomValues(n);for(var i=0;i<16;i++)t[i]=n[i]}else for(var r=0;r<16;r++)t[r]=Math.floor(256*Math.random());t[6]=15&t[6]|64,t[8]=63&t[8]|128;var o=t.map(function(e){return(e+256).toString(16).slice(1)}).join("");return o.slice(0,8)+"-"+o.slice(8,12)+"-"+o.slice(12,16)+"-"+o.slice(16,20)+"-"+o.slice(20)}const O={canShareToFeed:function(e){var t=this.config&&this.config.hostFeatures;return!(!t||!0!==t.feedShare)&&("image"===e?!0===t.feedShareImage:"video"===e?!0===t.feedShareVideo:"videoUpload"===e?!0===t.feedShareVideoUpload:!e)},uploadFeedVideo:function(n){if(!this.canShareToFeed("videoUpload"))return Promise.reject(new t(e.UNSUPPORTED,"Video uploads require a newer host"));if(!n||"number"!=typeof n.size||n.size<=0||n.size>104857600||["video/mp4","video/quicktime","video/webm","video/x-matroska"].indexOf(n.type)<0)return Promise.reject(new t(e.INVALID_INPUT,"Choose a supported video of at most 100 MB"));var i=this.user&&this.user.getToken(),r=this.config||{};if(!i||!r.serviceId||!r.apiUrl)return Promise.reject(new t(e.NOT_AUTHENTICATED,"Sign in to upload"));var o=new FormData;return o.append("file",n,n.name||"video"),fetch(r.apiUrl.replace(/\/$/,"")+"/feed/video-uploads/"+encodeURIComponent(r.serviceId),{method:"POST",headers:{Authorization:"Bearer "+i},body:o}).then(function(n){if(!n.ok)throw new t(429===n.status?e.RATE_LIMITED:401===n.status?e.NOT_AUTHENTICATED:403===n.status?e.PERMISSION_DENIED:n.status<500?e.INVALID_INPUT:e.UNKNOWN,"Video upload failed");return n.json()}).then(function(n){if(!n||"string"!=typeof n.receipt)throw new t(e.UNKNOWN,"Invalid upload response");return{receipt:n.receipt}})},shareToFeed:function(n,i){if(i=i||{},"video"===n&&null==i.video&&null==i.videoReceipt)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: video is required"));var r="string"==typeof i.text?i.text.trim():"";if(!r)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: text is required"));var o={contentType:n||"text",text:r,requestId:"string"==typeof i.requestId&&i.requestId?i.requestId:k(),serviceId:this.config&&this.config.serviceId,serviceName:this.config&&this.config.serviceName};if(null!=i.path&&""!==i.path){var s=w(i.path);if(s)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: "+s));o.path=i.path}if(null!=i.card){var c=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return{error:"card must be an object"};var t="string"==typeof e.title?e.title.trim():"";if(!t)return{error:"card.title is required"};if(T(t)>200)return{error:"card.title too long (max 200)"};var n={title:t};if(null!=e.subtitle){if("string"!=typeof e.subtitle)return{error:"card.subtitle must be a string"};var i=e.subtitle.trim();if(T(i)>60)return{error:"card.subtitle too long (max 60)"};i&&(n.subtitle=i)}return{card:n}}(i.card);if("error"in c)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: "+c.error));o.card=c.card}if(null!=i.image){var a=function(e){var t="string"==typeof e&&S.exec(e);if(!t)return"image must be a data:image/(png|jpeg|webp);base64 URL";var n=e.slice(t[0].length),i="=="===n.slice(-2)?2:"="===n.slice(-1)?1:0;return Math.floor(3*n.length/4)-i>E?"image too large (max 5 MB)":n.length%4==0&&A.test(n)?null:"image is not valid base64"}(i.image);if(a)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: "+a));o.image=i.image}if(null!=i.video){if(null!=i.image||"string"!=typeof i.video||!/^data:video\/mp4;base64,/.test(i.video))return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: video must be an MP4 data URL without an image"));var u=i.video.slice(22),l="=="===u.slice(-2)?2:"="===u.slice(-1)?1:0;if(!u||u.length%4!=0||3*u.length/4-l>E||!A.test(u))return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: invalid video or video exceeds 5 MB"));if(!this.canShareToFeed("video"))return Promise.reject(new t(e.UNSUPPORTED,"shareToFeed: host does not support video"));o.video=i.video}if(null!=i.videoReceipt){if(null!=i.video||null!=i.image||"string"!=typeof i.videoReceipt||!i.videoReceipt||i.videoReceipt.length>8192)return Promise.reject(new t(e.INVALID_INPUT,"Invalid video receipt"));if(!this.canShareToFeed("videoUpload"))return Promise.reject(new t(e.UNSUPPORTED,"Video uploads require a newer host"));o.videoReceipt=i.videoReceipt}return this._request("SHARE_TO_FEED",o,6e5).then(function(e){return Object.assign({success:!0},e)})},openApp:function(n,i){if("string"!=typeof n||!n.trim())throw new t(e.INVALID_INPUT,"openApp: serviceId is required");var r={type:"OPEN_SERVICE",serviceId:n.trim()};if(null!=i&&""!==i){var o=w(i);if(o)throw new t(e.INVALID_INPUT,"openApp: "+o);r.path=i}this._post(r)}};function P(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 i(){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 r(){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 r=i().rtt||0,o=e.directMode&&n.lastInboundAt?Date.now()-n.lastInboundAt:0;return r<150&&o<2e3?"good":r<400&&o<5e3?"fair":"poor"}();if(t!==n.quality){var r=n.quality;n.quality=t,e._dispatch("networkQuality",{quality:t,prev:r,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 i=Date.now(),r=function(){};r.sentAt=i,r.statsOnly=!0,e._pongWaiters.push(r),n.lastProbeAt=i,e._sendDirect("ping",{t:i})}}function c(){var i=e.directSocket;if(e.directMode&&i&&1===i.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 r();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"),r(),e._dispatch("disconnect","liveness_timeout");try{i.close()}catch(e){}return}u>=n.liveness.probeAfterMs&&c-n.lastProbeAt>=n.liveness.probeAfterMs&&s()}r()}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 i=n.pendingInput;n.pendingInput=null,e._sendDirect("input",i)}}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,r=t?e.directSocket:null,o=i();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:r?r.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:{},i=isFinite(t.probeAfterMs)?Math.max(1e3,t.probeAfterMs):4e3,r=isFinite(t.deadAfterMs)?t.deadAfterMs:12e3;n.liveness={probeAfterMs:i,deadAfterMs:Math.max(r,i+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)}}r()},e._resOnClose=function(e){n.lastCloseCode=e&&"number"==typeof e.code?e.code:null,u(),r()},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),r()},e._resCanReuseToken=function(){if(4401===n.lastCloseCode)return!1;var t=e.directConfig;if(!t||!t.ws_url||!t.access_token)return!1;var i=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!=i&&i-Date.now()>3e4},e._resHoldInput=function(t){if(!n.backpressureBytes)return!1;var i=e.directSocket;return!(!i||!(null!=n.pendingInput||i.bufferedAmount>n.backpressureBytes))&&(n.pendingInput=t,n.drainTimer||(n.drainTimer=setTimeout(a,50)),!0)},e.on("disconnect",r),e.on("connectionState",r)}function N(n,i,r,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(i,r,function(e){u||(u=!0,clearTimeout(l),c(e||{}))})}catch(e){if(u)return;u=!0,clearTimeout(l),a(e)}})}function C(e,t){return e._joinPromise=t,t.catch(function(){e._joined=!1,e._joinPromise===t&&(e._joinPromise=null)}),t}function R(e,t,n){let i=(t-e)%n;const r=n/2;return i>r&&(i-=n),i<-r&&(i+=n),i}function M(e,t,n,i){return"deg"===i?e+R(e,t,360)*n:"rad"===i?e+R(e,t,2*Math.PI)*n:e+(t-e)*n}class q{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 j(e,t){return t?Array.isArray(e[t])?e[t]:[]:Array.isArray(e)?e:[]}class D{constructor(e={}){const t=e.serverFps||20;this._frameMs=1e3/t,this.vault=new q(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,i=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 i){const e=t-i;this._offset=null==this._offset?e:this._offset+.05*(e-this._offset)}const r=this._useServerTime&&"number"==typeof i?i:t;this.vault.add({time:r,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(),i=this.vault.latest();if(!i)return null;const r=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>i.time)return this._extrapolationMs>0?this._extrapolate(n,r,t):j(i.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(j(o.state,t),j(s.state,t),c,r)}_blend(e,t,n,i){const r={};for(let t=0;t<e.length;t++)r[e[t].id]=e[t];return t.map(e=>{const t=r[e.id],o=Object.assign({},e);if(t)for(let r=0;r<i.length;r++){const{key:s,type:c}=i[r],a=t[s],u=e[s];"number"==typeof a&&"number"==typeof u&&(o[s]=M(a,u,n,c))}return o})}_extrapolate(e,t,n){const i=this.vault.latest(),r=this.vault.prevLatest(),o=j(i.state,n);if(!r||i.time<=r.time)return o.map(e=>Object.assign({},e));const s=Math.min(e-i.time,this._extrapolationMs),c=i.time-r.time,a={},u=j(r.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],i=Object.assign({},e);if(n)for(let r=0;r<t.length;r++){const{key:o}=t[r],a=n[o],u=e[o];if("number"==typeof a&&"number"==typeof u){const e=(u-a)/c;i[o]=u+e*s}}return i})}}class U{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,i=null==t?-1:t;this._pending=this._pending.filter(e=>e.seq>i);let r=e;for(let e=0;e<this._pending.length;e++)r=this._apply(r,this._pending[e].input);if(this._smoothKeys&&n&&r)for(let e=0;e<this._smoothKeys.length;e++){const t=this._smoothKeys[e];"number"==typeof n[t]&&"number"==typeof r[t]&&(this._error[t]=(this._error[t]||0)+(n[t]-r[t]))}return this._state=r,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 i=this._smoothKeys[e];let r=this._error[i]||0;"number"==typeof n[i]&&0!==r&&(n[i]=n[i]+r),r*=1-t,Math.abs(r)<this._snapTo&&(r=0),this._error[i]=r}return n}reset(e){this._state=void 0!==e?e:null,this._seq=0,this._pending=[],this._error={}}}class L{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],i=this._slots[n];if("latest"===i.mode)void 0!==i.value&&e.push({type:n,data:i.value});else for(let t=0;t<i.list.length;t++)e.push({type:n,data:i.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 x{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 B=[{urls:"stun:stun.l.google.com:19302"}];function H(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}class F{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||B,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(H(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)&&(H(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)&&(H(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 G{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 F({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,i)=>{t.onMessage&&t.onMessage(e,n,i)},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 W="undefined"!=typeof TextEncoder?new TextEncoder:null,V="undefined"!=typeof TextDecoder?new TextDecoder:null;function J(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),W?W.encode(n):Uint8Array.from(Buffer.from(n,"utf8")))};var t,n}function z(e,t){if(1===e)try{return JSON.parse((n=t,V?V.decode(n):Buffer.from(n).toString("utf8")))}catch(e){return null}var n;return t}class Q{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 i=[];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);i.push(z(t,n.slice())),this._buf=this._buf.subarray(4+e)}return i}}class Y{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 Q,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:i}=await n.read();if(i)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:z(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:i}=J(t),r=new Uint8Array(5+i.length);return new DataView(r.buffer).setUint32(0,e>>>0,!1),r[4]=n,r.set(i,5),r}(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}=J(e),i=new Uint8Array(5+n.length);return new DataView(i.buffer).setUint32(0,1+n.length,!1),i[4]=t,i.set(n,5),i}(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 K{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 i=this;t._schedule(()=>e.apply(i,n),t._delay()),t.dupPct&&100*t._rand()<t.dupPct&&t._schedule(()=>e.apply(i,n),t._delay())}}flush(){if(this._clear)for(const e of this._timers)this._clear(e);this._timers.clear()}}class X{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 $(e,t,n){return e+(t-e)*n}class Z{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 i=n-this._historyMs;for(;this._history.length>this._maxSize||this._history.length>2&&this._history[0].time<i;)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 ee(n[0].entities);if(e>=n[n.length-1].time)return ee(n[n.length-1].entities);let i=n[0],r=n[n.length-1];for(let t=n.length-1;t>0;t--)if(n[t-1].time<=e&&e<=n[t].time){i=n[t-1],r=n[t];break}const o=r.time-i.time,s=o>0?(e-i.time)/o:0,c=ee(i.entities),a={},u=ee(r.entities);for(const e in u){const n=u[e],i=c[e],r=Object.assign({},n);if(i){const e=t||Object.keys(n);for(let t=0;t<e.length;t++){const o=e[t];"number"==typeof i[o]&&"number"==typeof n[o]&&(r[o]=$(i[o],n[o],s))}}a[e]=r}return a}rewindForClient(e,t,n){const i=null!=(n=n||{}).maxRewindMs?n.maxRewindMs:250;let r=(e||0)/2+(t||0);return r>i&&(r=i),this.rewind(this._now()-r,n.keys)}}function ee(e){const t={};for(let n=0;n<e.length;n++)t[e[n].id]=e[n];return t}const te="_s",ne="_d",ie="_a",re="_n",oe="_ka",se="_add",ce="_del",ae="_ord";function ue(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function le(e){if(!Array.isArray(e)||0===e.length)return!1;for(let t=0;t<e.length;t++){const n=e[t];if(!ue(n)||"string"!=typeof n.id&&"number"!=typeof n.id)return!1}return!0}function de(e,t){if(e===t)return;const n=Array.isArray(e),i=Array.isArray(t);return n!==i||ue(e)!==ue(t)?{[te]:t}:i?le(e)&&le(t)?function(e,t){const n={},i=[];for(let t=0;t<e.length;t++)n[e[t].id]=e[t],i.push(e[t].id);const r=[],o={};let s=!1;for(let e=0;e<t.length;e++){const i=t[e];if(r.push(i.id),Object.prototype.hasOwnProperty.call(n,i.id)){const e=de(n[i.id],i);void 0!==e&&(o[oe]||(o[oe]={}),o[oe][i.id]=e,s=!0)}else o[se]||(o[se]=[]),o[se].push(i),s=!0}const c={};for(let e=0;e<r.length;e++)c[r[e]]=!0;for(let e=0;e<i.length;e++)c[i[e]]||(o[ce]||(o[ce]=[]),o[ce].push(i[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})(i,r)||(o[ae]=r,s=!0);return s?o:void 0}(e,t):function(e,t){const n={[ie]:{}};let i=!1;for(let r=0;r<t.length;r++){const o=r<e.length?de(e[r],t[r]):{[te]:t[r]};void 0!==o&&(n[ie][r]=o,i=!0)}t.length!==e.length&&(n[re]=t.length,i=!0);return i?n:void 0}(e,t):ue(t)?function(e,t){const n={};let i=!1;for(const r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;const o=de(e[r],t[r]);void 0!==o&&(n[r]=o,i=!0)}const r=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(Object.prototype.hasOwnProperty.call(t,n)||r.push(n));r.length&&(n[ne]=r,i=!0);return i?n:void 0}(e,t):{[te]:t}}function fe(e,t){if(null==t)return e;if(Object.prototype.hasOwnProperty.call(t,te))return t[te];if(t[oe]||t[se]||t[ce]||t[ae])return function(e,t){const n=Array.isArray(e)?e:[],i={},r=[];for(let e=0;e<n.length;e++){const t=n[e];!t||"string"!=typeof t.id&&"number"!=typeof t.id||(i[t.id]=t,r.push(t.id))}if(t[oe])for(const e in t[oe])Object.prototype.hasOwnProperty.call(t[oe],e)&&void 0!==i[e]&&(i[e]=fe(i[e],t[oe][e]));if(t[se])for(let e=0;e<t[se].length;e++){const n=t[se][e];i[n.id]=n}const o={};if(t[ce])for(let e=0;e<t[ce].length;e++)o[t[ce][e]]=!0;if(t[ae]){const e=[];for(let n=0;n<t[ae].length;n++){const r=t[ae][n];void 0!==i[r]&&e.push(i[r])}return e}const s=[];for(let e=0;e<r.length;e++){const t=r[e];o[t]||s.push(i[t])}return s}(e,t);if(Object.prototype.hasOwnProperty.call(t,ie)||Object.prototype.hasOwnProperty.call(t,re)){const n=Array.isArray(e)?e:[],i=Object.prototype.hasOwnProperty.call(t,re)?t[re]:n.length,r=n.slice(0,i),o=t[ie]||{};for(const e in o)Object.prototype.hasOwnProperty.call(o,e)&&(r[e]=fe(r[e],o[e]));return r}const n=ue(e)?Object.assign({},e):{},i=t[ne];for(const e in t)e!==ne&&Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=fe(n[e],t[e]));if(Array.isArray(i))for(let e=0;e<i.length;e++)delete n[i[e]];return n}function he(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(ue(t)){const n={};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[i]=e(t[i]));return n}return t}(e)}const _e="undefined"!=typeof TextEncoder?new TextEncoder:null,pe="undefined"!=typeof TextDecoder?new TextDecoder:null;function me(e,t){for(t>>>=0;t>127;)e.push(127&t|128),t>>>=7;e.push(t)}function ge(e,t){if(null==t)return void e.push(192);const n=typeof t;if("boolean"!==n)if("number"!==n){var i;if("string"===n){e.push(198);const n=_e?_e.encode(t):Buffer.from(t,"utf8");me(e,n.length);for(let t=0;t<n.length;t++)e.push(n[t]);return}if(Array.isArray(t)){e.push(199),me(e,t.length);for(let n=0;n<t.length;n++)ge(e,t[n])}else{if("object"===n){const n=Object.keys(t);e.push(200),me(e,n.length);for(let i=0;i<n.length;i++){const r=n[i],o=_e?_e.encode(r):Buffer.from(r,"utf8");me(e,o.length);for(let t=0;t<o.length;t++)e.push(o[t]);ge(e,t[r])}return}e.push(192)}}else if(Number.isInteger(t)&&t>=-2147483648&&t<=2147483647)e.push(196),me(e,((i=t)<<1^i>>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 ye(e){const t=[];return ge(t,e),Uint8Array.from(t)}function ve(e){return function(e){let t=0;const n=new DataView(e.buffer,e.byteOffset,e.byteLength);function i(){let n,i=0,r=0;do{n=e[t++],r|=(127&n)<<i,i+=7}while(128&n);return r>>>0}function r(){const n=i(),r=e.subarray(t,t+n);return t+=n,pe?pe.decode(r):Buffer.from(r).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=i())>>>1^-(1&s);case 197:{const e=n.getFloat64(t,!0);return t+=8,e}case 198:return r();case 199:{const e=i(),t=new Array(e);for(let n=0;n<e;n++)t[n]=o();return t}case 200:{const e=i(),t={};for(let n=0;n<e;n++)t[r()]=o();return t}}var s}}(e instanceof Uint8Array?e:new Uint8Array(e))()}function be(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 Ie(e,t,n){if("number"!=typeof e||!isFinite(e))throw new Error("interestGrid."+n+": "+t+" must be a finite number");return e}function we(e,t){if(Ie(e,"radius",t),e<0)throw new Error("interestGrid."+t+": radius must be >= 0");return e}function Te(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,i=new Map,r=new Map;function o(e,t){let n=i.get(e);n||(n=new Set,i.set(e,n)),n.add(t)}function s(e,t){const n=i.get(e);n&&(n.delete(t),0===n.size&&i.delete(e))}function c(e,r,o,s){const c=o*o,a=Math.floor((e-o)/t),u=Math.floor((e+o)/t),l=Math.floor((r-o)/t),d=Math.floor((r+o)/t);for(let t=a;t<=u;t++)for(let o=l;o<=d;o++){const a=i.get(t+","+o);if(a)for(const t of a){const i=n.get(t);if(!i)continue;const o=i.x-e,a=i.y-r;o*o+a*a<=c&&s(t)}}}return{upsert:function(e,i,r){be(e,"upsert"),Ie(i,"x","upsert"),Ie(r,"y","upsert");const c=Math.floor(i/t)+","+Math.floor(r/t),a=n.get(e);if(a)return a.x=i,a.y=r,void(a.key!==c&&(s(a.key,e),o(c,e),a.key=c));n.set(e,{x:i,y:r,key:c}),o(c,e)},remove:function(e){be(e,"remove");const t=n.get(e);t&&(n.delete(e),s(t.key,e))},query:function(e,t,n){Ie(e,"x","query"),Ie(t,"y","query"),we(n,"query");const i=[];return c(e,t,n,function(e){i.push(e)}),i},observe:function(e,t,n,i){be(e,"observe"),Ie(t,"x","observe"),Ie(n,"y","observe"),we(i,"observe");let o=r.get(e);o||(o={prev:new Set,next:new Set},r.set(e,o));const s=o.prev,a=o.next;a.clear();const u=[],l=[],d=[];c(t,n,i,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){be(e,"dropObserver"),r.delete(e)},size:function(){return n.size}}}function Ee(e,t){e.diff=de,e.patch=fe,e.quantize=he,e.encode=ye,e.decode=ve,e.createInterpolation=function(e){return new D(e||{})},e.createPredictor=function(e){return new U(e||{})},e.createLagCompensator=function(e){return new Z(e||{})},e.createLockstep=function(e){return new X(e||{})},e.createInterestGrid=function(e){return Te(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 L({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",i=!1!==e.delta,r=null!=e.keyframeEvery?e.keyframeEvery:30,o=e.precision,s=!0===e.encode?ye:"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 h(e){if(null==e)return;const t=null!=o?he(e,o):e;let a;if(!i||null===u||f>=r)d+=1,u=null==(h=t)?h:JSON.parse(JSON.stringify(h)),l=d,f=0,a={s:d,f:t};else{const e=de(u,t);if(void 0===e)return;d+=1,f+=1,a={s:d,b:l,d:e}}var h;c(n,s?s(a):a)}const _=e.hz||20;let p;const m=a?null:new L({hz:_,autoStart:!1!==e.autoStart,onFlush:function(e){for(let t=0;t<e.length;t++)"__snap"===e[t].type&&(p=e[t].data);h(p)}});let g=null;function y(){m?m.start():g||"undefined"==typeof setInterval||(g=setInterval(function(){h(a())},Math.max(1,Math.round(1e3/_))))}return a&&!1!==e.autoStart&&y(),{send:function(e){m?m.queue("__snap",e):h(e)},flush:function(){m?m.flush():a&&h(a())},start:y,stop:function(){m&&m.stop(),g&&(clearInterval(g),g=null)},reset:function(){u=null,l=0,d=0,f=0}}},e.createSnapshotReceiver=function(e){const t=!0===(e=e||{}).decode?ve:"function"==typeof e.decode?e.decode:null;let n=null,i=-1,r=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,r):(n=e.f,i=void 0!==e.s?e.s:0,r=e.f,o=i,r):void 0!==e.d?void 0!==e.b&&e.b!==i||void 0!==e.s&&e.s<=o?(s+=1,r):(r=fe(n,e.d),void 0!==e.s&&(o=e.s),r):r:r},get state(){return r},get stats(){return{appliedSeq:o,baseSeq:i,dropped:s}},reset:function(){n=null,i=-1,r=null,o=-1,s=0}}},e.replicate=function(e,t){t=t||{};let n=null!=e?e:{};const i=this.createSnapshotSender(Object.assign({},t,{source:function(){return n}}));return{get state(){return n},set state(e){n=e},flush:function(){i.flush()},start:function(){i.start()},stop:function(){i.stop()}}},e.replica=function(e){const t=(e=e||{}).channel||"state",n=this.createSnapshotReceiver({decode:e.decode}),i=e.interpolate?this.createInterpolation("object"==typeof e.interpolate?e.interpolate:{}):null,r="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);i&&null!=t&&i.add(t),s&&s(t)});return{get state(){return n.state},view:function(){return i?i.calc(r||"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",i=new F(Object.assign({},e,{sendSignal:function(e){t.realtime(n,e)}}));return this._onChannel(n,function(e){e&&e.type&&i.handleSignal(e)}),i},e.createMeshNetwork=function(e){const n=this,i=(e=e||{}).signalChannel||"mesh",r=e.selfId||t.user&&t.user.getId&&t.user.getId(),o=new G(Object.assign({},e,{selfId:r,sendSignal:function(e,t){n.realtime(i,{to:e,from:r,payload:t})}}));return this._onChannel(i,function(e){e&&e.to===r&&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 K(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 Y(Object.assign({},e,{url:n}))},e.ping=function(){const e=this;if(e._pingMeter||(e._pingMeter=new x),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 i=!1;const r=function(){i||(i=!0,t(e._pingMeter.end(n)))};r.sentAt=Date.now(),e._pongWaiters.push(r),e._sendDirect("ping",{t:Date.now()}),setTimeout(function(){if(i)return;i=!0;const o=e._pongWaiters.indexOf(r);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 i=!1;try{e.socket.emit("game:ping",{t:n},function(){i||(i=!0,t(e._pingMeter.sample(Date.now()-n)))})}catch(e){return void t(null)}setTimeout(function(){i||(i=!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 Se(e,t){e.syncedState=function(e,n){var i=this,r="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=0,h=new Map,_=[],p=[];function m(e){for(var n=_.slice(),i=0;i<n.length;i++)try{n[i](a,e)}catch(e){t.log("syncedState onChange error: "+e.message)}}function g(){if("all"===s)return!0;var e=i.playerId||t.user&&t.user.getId&&t.user.getId();return!(!e||!i._hostId||e!==i._hostId)}function y(){return i.directMode?Promise.resolve({success:!1,error:"not_supported_in_direct_mode"}):i.setState({__usionSyncedState:1,seq:u,state:a})}function v(e,n,i,o){if(void 0!==o){if(!Number.isSafeInteger(o)||o<=u)return!1;if(f=Math.max(f,o),o!==u+1)return h.size<1e3&&h.set(o,{playerId:e,type:n,data:i,sequence:o}),!1}var s;try{s=r(a,{playerId:e,type:n,data:i,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 b(){var e=0;for(h.forEach(function(e,t){t<=u&&h.delete(t)});h.has(u+1);){var t=h.get(u+1);if(!v(t.playerId,t.type,t.data,t.sequence))break;h.delete(t.sequence),e+=1}return e}function I(){if(!(f<=u||d===u)){d=u;try{i.requestSync(u)}catch(e){d=-1}}}function w(e){if(e){var t=!1;Number.isSafeInteger(e.sequence)&&(f=Math.max(f,e.sequence));var 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 r=i.slice().sort(function(e,t){return(e.sequence||0)-(t.sequence||0)}),o=0;o<r.length;o++){var s=r[o];s&&v(s.player_id,s.action_type,s.action_data,s.sequence)&&(t=!0)}b()&&(t=!0),t&&m("recover"),I()}}return p.push(i.on("action",function(e){if(e){var t=v(e.player_id,e.action_type,e.action_data,e.sequence)?1:0;(t+=b())&&(m("action"),function(e){o>0&&g()&&(l+=e)>=o&&(l=0,y())}(t)),I()}})),p.push(i.on("sync",w)),p.push(i.on("joined",w)),{get:function(){return a},commit:function(e,t,n){var r,o,s;return"string"==typeof e?(r=e,o=t,s=n):(r=c,o=e,s=t),i.directMode?(v(i.playerId,r,o,void 0)&&m("action"),i.action(r,o,s)):i.action(r,o,s)},onChange:function(e){return _.push(e),function(){var t=_.indexOf(e);t>=0&&_.splice(t,1)}},isAuthority:g,checkpoint:function(){return y()},getSequence:function(){return u},destroy:function(){for(var e=0;e<p.length;e++)try{p[e]()}catch(e){}p.length=0,_.length=0,h.clear()}}}}const Ae="__usion_players_v1",ke=e=>["direct","turn","webrtc"].includes(e),Oe=()=>globalThis.crypto.randomUUID(),Pe=e=>"string"==typeof e&&e.length>0&&e.length<=128;class Ne{constructor(e,t,n={}){this.game=e,this.usion=t,this.options=n,this.selfId=t.user.getId(),this.roomId=null,this.closed=!1,this.online=!1,this.session=Oe(),this.peers=new Map,this.roster=new Set,this.listeners={message:new Set,status:new Set,log:new Set},this.logs=[],this.sequence=0,this.generation=0,this.lastHello=0,this.RTC=void 0===n.RTCPeerConnection?globalThis.RTCPeerConnection:n.RTCPeerConnection,this.iceServers=n.iceServers||[{urls:"stun:stun.l.google.com:19302"}],this.timeout=n.directTimeoutMs??6e3,this.unsubscribers=[e._onChannel(Ae,(e,t)=>this._incoming(e,t)),e.on("joined",e=>this._joined(e)),e.on("playerJoined",e=>this._roster(e)),e.on("playerLeft",e=>this._roster(e,!0)),e.on("sync",e=>this._roster(e)),e.on("roomAssigned",({roomId:e})=>{this._join(e).catch(()=>this._log("join_failed"))}),e.on("disconnect",()=>this._offline()),e.on("reconnect",()=>this._recover()),e.on("reconnected",()=>this._recover())],this.tick=setInterval(()=>this._tick(),1e3)}async start(){const e=this.options.roomId||this.game.roomId||this.usion.config.roomId;return e&&await this._join(e),this}_emit(e,t){for(const n of this.listeners[e])try{n(t)}catch{}}_listen(e,t){return this.listeners[e].add(t),()=>this.listeners[e].delete(t)}onMessage(e){return this._listen("message",e)}onStatusChange(e){return this._listen("status",e)}onLog(e){return this._listen("log",e)}getLogs(){return this.logs.map(e=>({...e}))}_log(e,t=void 0,n=void 0){const i={time:Date.now(),event:e,peerId:t,reason:n};this.logs.push(i),this.logs.length>100&&this.logs.shift(),this._emit("log",{...i})}getStatus(){return{roomId:this.roomId,state:this.closed?"closed":this.roomId?this.online?"connected":"offline":"waiting",peers:[...this.peers.values()].map(e=>({playerId:e.id,transport:this.online?e.mode:"offline",rttMs:e.rtt,sent:e.sent,received:e.received}))}}_status(){this._emit("status",this.getStatus())}_mode(e,t,n){e.mode=t,e.rtt=null,this._log("transport",e.id,n),this._status()}async _join(e){if(this.closed)return;const t=++this.generation;if(this.roomId!==e&&(this._clearPeers(),this.roster.clear(),this.session=Oe(),this.roomId=e),this.online=!1,await this.game.connect(),this.closed||t!==this.generation)return;const n=await this.game.join(e);this.closed||t!==this.generation||this._joined(n||{})}_joined(e){if(this.closed)return;(e.room_id||this.game.roomId)===this.roomId&&(this.online=!0,this._roster(e),this._hello(),this._status())}_recover(){this.closed||this.online||!this.roomId||this._join(this.roomId).catch(()=>this._log("rejoin_failed"))}_offline(){this.closed||(this.generation++,this.online=!1,this.session=Oe(),this._clearPeers(),this._log("offline"),this._status())}_roster(e,t=!1){if(!(this.closed||!e||e.room_id&&e.room_id!==this.roomId)){Array.isArray(e.player_ids)?this.roster=new Set(e.player_ids.filter(Pe)):Pe(e.player_id)&&(t?this.roster.delete(e.player_id):this.roster.add(e.player_id));for(const[n,i]of this.peers)(!this.roster.has(n)||t&&n===e.player_id)&&(this._closeRTC(i),this.peers.delete(n),this._log("peer_left",n));this._hello(),this._status()}}_relay(e,t){if(!this.online||this.closed)return!1;try{return this.game.realtime(Ae,{...e,v:1,room:this.roomId,session:this.session,to:t}),!0}catch{return this._log("relay_send_failed",t),!1}}_hello(e=void 0){this._relay({kind:"hello"},e)}_peer(e,t){let n=this.peers.get(e);if(n&&n.session!==t&&(this._closeRTC(n),this.peers.delete(e),n=null),!n){if(this.peers.size>=7)return this._log("peer_limit",e),null;n={id:e,session:t,mode:"relay",pc:null,dc:null,attempt:null,candidates:[],queue:Promise.resolve(),lastDirect:0,lastSequence:-1,rtt:null,sent:0,received:0,started:!1,pendingPing:null},this.peers.set(e,n),this._log("peer_joined",e),this._status()}return n}_incoming(e,t){const n=t?.player_id;if(this.closed||!this.online||!e||1!==e.v||e.room!==this.roomId||t.room_id!==this.roomId||!Pe(n)||n===this.selfId||!this.roster.has(n)||!Pe(e.session)||e.to&&e.to!==this.selfId)return;if("hello"===e.kind){const t=this.peers.get(n)?.session===e.session,i=this._peer(n,e.session);if(!i)return;return t||this._hello(n),void(this.selfId<n&&!i.started&&this._attempt(i))}const i=this.peers.get(n);if(i&&i.session===e.session&&e.target===this.session)if("offer"===e.kind&&this.selfId>n&&Pe(e.attempt)){if(i.attempt===e.attempt)return;this._setup(i,e.attempt),i.pc&&this._signal(i,e)}else["answer","ice"].includes(e.kind)&&e.attempt===i.attempt?this._signal(i,e):"fallback"===e.kind&&e.attempt===i.attempt?this._fallback(i,"peer_requested",!1):"retry"===e.kind&&this.selfId<n?this._attempt(i):"data"===e.kind&&this._receive(i,e,"relay")}_control(e,t){return this._relay({...t,target:e.session,attempt:e.attempt},e.id)}_setup(e,t){if(this._closeRTC(e),e.attempt=t,e.started=!0,this.RTC&&!1!==this.options.direct){this._mode(e,"connecting","direct_attempt");try{const t=e.pc=new this.RTC({iceServers:this.iceServers});e.localCandidates=[],e.descriptionSent=!1,t.onicecandidate=n=>{if(e.pc!==t||!n.candidate)return;const i=n.candidate.toJSON();e.descriptionSent?this._control(e,{kind:"ice",candidate:i}):e.localCandidates.length<64&&e.localCandidates.push(i)},t.ondatachannel=n=>{e.pc===t&&this._channel(e,t,n.channel)},t.onconnectionstatechange=()=>{e.pc===t&&["failed","disconnected","closed"].includes(t.connectionState)&&this._fallback(e,t.connectionState)},e.timer=setTimeout(()=>{e.pc===t&&this._fallback(e,"direct_timeout")},this.timeout)}catch{this._fallback(e,"rtc_setup_failed")}}else this._fallback(e,"direct_unavailable")}_attempt(e){this._setup(e,Oe());const t=e.pc;if(t){try{this._channel(e,t,t.createDataChannel("usion-game",{ordered:!1,maxRetransmits:0}))}catch{return void this._fallback(e,"channel_failed")}e.queue=(async()=>{const n=await t.createOffer();e.pc===t&&(await t.setLocalDescription(n),e.pc===t&&this._description(e,"offer"))})().catch(()=>{e.pc===t&&this._fallback(e,"offer_failed")})}}_signal(e,t){const n=e.pc;n&&(e.queue=e.queue.then(async()=>{if(e.pc===n)if("ice"===t.kind)n.remoteDescription?await n.addIceCandidate(t.candidate):e.candidates.length<64&&e.candidates.push(t.candidate);else{if(await n.setRemoteDescription(t.description),e.pc!==n)return;const i=e.candidates;e.candidates=[];for(const e of i)await n.addIceCandidate(e);"offer"===t.kind&&(await n.setLocalDescription(await n.createAnswer()),e.pc===n&&this._description(e,"answer"))}}).catch(()=>{e.pc===n&&this._fallback(e,"negotiation_failed")}))}_description(e,t){this._control(e,{kind:t,description:e.pc.localDescription.toJSON()}),e.descriptionSent=!0;for(const t of e.localCandidates)this._control(e,{kind:"ice",candidate:t});e.localCandidates=[]}_channel(e,t,n){e.dc=n,n.onopen=()=>{e.pc===t&&(clearTimeout(e.timer),e.lastDirect=Date.now(),this._mode(e,"webrtc","channel_open"),this._inspectRoute(e,t))},n.onmessage=n=>{if(!(e.pc!==t||"string"!=typeof n.data||n.data.length>16384))try{this._receive(e,JSON.parse(n.data),"direct")}catch{}},n.onerror=n.onclose=()=>{e.pc===t&&this._fallback(e,"channel_closed")}}async _inspectRoute(e,t){if(t?.getStats)try{const n=await t.getStats();if(e.pc!==t||!ke(e.mode))return;let i;if(n.forEach(e=>{"transport"===e.type&&e.selectedCandidatePairId&&(i=n.get(e.selectedCandidatePairId))}),i||n.forEach(e=>{"candidate-pair"===e.type&&e.nominated&&"succeeded"===e.state&&(i=e)}),!i)return;const r=n.get(i.localCandidateId),o=n.get(i.remoteCandidateId);if(!r?.candidateType||!o?.candidateType)return;const s="relay"===r.candidateType||"relay"===o.candidateType?"turn":"direct";s!==e.mode&&this._mode(e,s,"ice_route_selected")}catch{}}_closeRTC(e){clearTimeout(e.timer);const t=e.pc,n=e.dc;e.pc=e.dc=null,e.candidates=[],e.queue=Promise.resolve(),n&&(n.onopen=n.onmessage=n.onerror=n.onclose=null,n.close()),t&&(t.onicecandidate=t.ondatachannel=t.onconnectionstatechange=null,t.close())}_fallback(e,t,n=!0){n&&this._control(e,{kind:"fallback"}),this._closeRTC(e),this._mode(e,"relay",t)}_packet(e,t){const n={...t,kind:"data",room:this.roomId,session:this.session,target:e.session};if(ke(e.mode)&&"open"===e.dc?.readyState)try{if(e.dc.bufferedAmount>65536)throw Error("backpressure");return e.dc.send(JSON.stringify(n)),!0}catch{this._fallback(e,"send_failed")}return this._control(e,n)}_receive(e,t,n){t.room===this.roomId&&t.session===e.session&&t.target===this.session&&("direct"===n&&(e.lastDirect=Date.now()),Number.isSafeInteger(t.ping)&&t.ping>0?this._packet(e,{pong:t.ping}):Number.isSafeInteger(t.pong)&&t.pong>0?t.pong===e.pendingPing&&(e.rtt=Date.now()-t.pong,e.pendingPing=null,this._status()):!Number.isSafeInteger(t.seq)||t.seq<=e.lastSequence||(e.lastSequence=t.seq,e.received++,this._emit("message",{data:t.data,playerId:e.id,transport:"direct"===n?ke(e.mode)?e.mode:"webrtc":n})))}send(e,t){if(this.closed||!this.online)return!1;const n=JSON.stringify(e);if(void 0===n||(new TextEncoder).encode(n).length>4096)throw new Error("connectPlayers messages must be JSON, at most 4096 bytes");const i=JSON.parse(n),r=++this.sequence,o=t?[this.peers.get(t)].filter(Boolean):[...this.peers.values()];let s=o.length>0;for(const e of o){const t=this._packet(e,{data:i,seq:r});t&&e.sent++,s=s&&t}return s}forceRelay(e){for(const t of this.peers.values())e&&t.id!==e||this._fallback(t,"forced")}retryDirect(e){if(this.online&&!this.closed)for(const t of this.peers.values())e&&t.id!==e||(this.selfId<t.id?this._attempt(t):this._control(t,{kind:"retry"}))}async invite(){return this.game.invite()}_tick(){if(!this.online||this.closed)return;const e=Date.now();e-this.lastHello>=3e3&&(this.lastHello=e,this._hello());for(const t of this.peers.values())ke(t.mode)&&e-(t.lastStats||0)>1e4&&(t.lastStats=e,this._inspectRoute(t,t.pc)),ke(t.mode)&&e-t.lastDirect>3e3&&this._fallback(t,"direct_unresponsive"),t.pendingPing=e,this._packet(t,{ping:e})}_clearPeers(){for(const e of this.peers.values())this._closeRTC(e);this.peers.clear()}close(){if(!this.closed){this.closed=!0,this.generation++,clearInterval(this.tick),this._clearPeers(),this.unsubscribers.forEach(e=>e()),this._status();for(const e of Object.values(this.listeners))e.clear()}}}const Ce={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 Re={SnapshotInterpolation:D,Vault:q,Predictor:U,Coalescer:L,PingMeter:x,MeshConnection:F,MeshNetwork:G,WebTransportConnection:Y,NetworkSim:K,Lockstep:X,LagCompensator:Z,diff:de,patch:fe,quantize:he,encode:ye,decode:ve,createInterestGrid:Te},Me=Object.assign({},u);var qe;return Me.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()}})},openProfile:function(t){"string"==typeof t&&t&&0!==t.indexOf("guest_")&&e._post({type:"OPEN_USER_PROFILE",userId:t})}}}(Me),Me.storage=function(e){var t=null;function n(){return t||(t=h(e,"kv:get",{key:d}).then(function(t){if(!t||!t.exists||!0!==t.value)return Promise.all([h(e,"kv:keys",{}),g(e)]).then(function(t){var n=new Set(t[0]&&t[0].keys||[]);return Promise.all(t[1].map(function(t){var i=f(t);if(!n.has(i))return _(e,t).then(function(t){if(null!=t)return h(e,"kv:set",{key:i,value:t})})}))}).then(function(){return h(e,"kv:set",{key:d,value:!0})})}).catch(function(e){throw t=null,e}))}return{get:function(t){return n().then(function(){return h(e,"kv:get",{key:f(t)})}).then(function(n){return n&&n.exists?y(p(e,t,n.value)).then(function(){return n.value}):y(m(e,t)).then(function(){return null})}).catch(function(n){return _(e,t).then(function(e){if(null!=e)return e;throw n},function(){throw n})})},set:function(t,i){return n().then(function(){return h(e,"kv:set",{key:f(t),value:i})}).then(function(){return y(p(e,t,i))})},remove:function(t){return n().then(function(){return h(e,"kv:remove",{key:f(t)})}).then(function(){return y(m(e,t))})},clear:function(){return n().then(function(){return h(e,"kv:clear",{prefix:l})}).then(function(){return y(e._request("STORAGE_CLEAR",{}))})},keys:function(){return n().then(function(){return h(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 g(e).catch(function(){throw t})})}}}(Me),Me.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,i){const r=this,o=i&&"object"==typeof i?i:null,c=o&&"string"==typeof o.idempotencyKey&&o.idempotencyKey?o.idempotencyKey:null;return new Promise(function(o,u){const l=s(),d=r._paymentTimeoutMs||6e4;let f=!1,h=null;function _(){clearTimeout(y),h&&clearTimeout(h),window.removeEventListener("message",g)}function p(e){f||(f=!0,_(),e&&void 0!==e.newBalance?r._balance=e.newBalance:(null!==r._balance&&(r._balance-=t),r.getBalance({fresh:!0}).catch(function(){})),o(e))}function m(e){f||(f=!0,_(),u(e))}function g(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",g);const y=setTimeout(function(){const t=r._recoveryPollMs||2e3,n=r._recoveryMaxPolls||10,i=r._recoveryQueryTimeoutMs||8e3;let o=0,s=0;!function r(){f||e._request("PAYMENT_RESULT_QUERY",{paymentRequestId:l,idempotencyKey:c||void 0},i).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(h=setTimeout(r,t));s=0,o+=1,o>=2?m(new Error("Payment confirmation timeout")):h=setTimeout(r,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")):h=setTimeout(r,t))})}()},d);e._post({type:"PAYMENT_REQUEST",_requestId:l,amount:t,reason:n,data:i,idempotencyKey:c||void 0})})},onBalanceChange:function(e){const t=this;return t._balanceChangeHandler=e,function(){t._balanceChangeHandler===e&&(t._balanceChangeHandler=null)}}}}(Me),Me.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"})}}}(Me),Me.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})}}}(Me),Me.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}}}(Me),Me.fileStorage=(qe=Me,{set:function(e,t,n){return qe._request("FILE_STORAGE_SET",{key:e,base64Data:t,mimeType:n||"application/octet-stream"},3e4).then(function(){})},get:function(e){return qe._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 qe._request("FILE_STORAGE_REMOVE",{key:e}).then(function(){})}}),Me.game=function(n){const r={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 i=this;return"direct"===(n.config&&n.config.connectionMode||"platform")?i.connectDirect():i._useProxy&&i.connected||i.socket&&i.connected?Promise.resolve():i._connecting&&i._connectPromise?i._connectPromise:window.__USION_PROXY__||window.parent!==window||window.ReactNativeWebView||n._isEmbedded?(n.log("Running in iframe – using parent app as socket proxy"),i._connectViaProxy()):(e=e||n.config.socketUrl,t=t||n.user.getToken(),e?t?(i._connecting=!0,i._connectPromise=new Promise(function(n,r){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 i._connecting=!1,void r(new Error("Failed to load Socket.IO client"));var a=document.createElement("script");a.src=o[c],a.onload=function(){i._initSocket(e,t,n,r)},a.onerror=function(){s(c+1)},document.head.appendChild(a)}(0)}else i._initSocket(e,t,n,r)}),i._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),i=this._eventHandlers[e];if(i)try{i.apply(null,t)}catch(t){n.log("game handler error ("+e+"): "+t.message)}const r=this._listeners[e];if(r&&r.length){const i=r.slice();for(let r=0;r<i.length;r++)try{i[r].apply(null,t)}catch(t){n.log("game listener error ("+e+"): "+t.message)}}},on:function(e,t){const n=this,i=function(e){let t=String(e||"");if(0===t.indexOf("game:")&&(t=t.slice(5)),Ce[t])return Ce[t];const n=t.replace(/([A-Z])/g,function(e){return"_"+e.toLowerCase()});return Ce[n]||t}(e);return n._listeners[i]||(n._listeners[i]=[]),n._listeners[i].push(t),function(){const e=n._listeners[i];if(!e)return;const r=e.indexOf(t);r>=0&&e.splice(r,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,i=e.serviceId||t.config.serviceId,r=e.apiUrl||t.config.apiUrl||"",o=e.token||t.user.getToken();if(!n)return Promise.reject(new Error("No room ID provided"));if(!i)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:i,protocol_version:e.protocolVersion||t.config.protocolVersion||t.config.protocol_version||"2"},1e4);if(!r)return Promise.reject(new Error("No API URL provided"));if(!o)return Promise.reject(new Error("No auth token available"));var s=String(r).replace(/\/$/,"")+"/games/rooms/"+encodeURIComponent(n)+"/access";return fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o},body:JSON.stringify({service_id:i,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,i){if(e&&e.ws_url&&e.access_token){var r=e.ws_url,o=-1===r.indexOf("?")?"?":"&",s=r+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){}i(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),i(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 i(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 i=Math.min(1e3*Math.pow(2,t-1),15e3);setTimeout(n,i)}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 i=this._pongWaiters&&this._pongWaiters.length?this._pongWaiters.shift():null;return this._resOnPong&&this._resOnPong(i),i&&i(),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)}}}(r,n),P(r,n),function(e,t){e._initSocket=function(e,n,i,r){const o=this;if(o.socket&&o.socket.connected)return o._connecting=!1,void i();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),i()}),o.socket.on("connect_error",function(e){o._connecting=!1,t.log("Game socket error: "+e.message),o._dispatch("connectionError",e),r(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){r(e)}}}(r,n),function(n,r){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(i,o){n._proxyConnectResolve=function(){n.connected=!0,n._connecting=!1,r.log("Game socket connected via parent proxy"),i()},r._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(i(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":r.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)}}}))}}(r,n),function(n,r){function o(e){const t=e.roomId||r.config&&r.config.roomId,n=e.playerId||r.user&&"function"==typeof r.user.getId&&r.user.getId()||r.config&&r.config.userId;return t&&n?"_usion_game_state:"+n+":"+t:null}n.join=function(n){const o=this;if(n=n||r.config.roomId,o.roomId===n&&o._joinPromise)return o._joinPromise;if(o.roomId=n,o.playerId=r.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 i=new Promise(function(i,s){const c=function(e){s(e)};o._proxyJoinResolve=i,o._proxyJoinReject=c,r._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 C(o,i)}let s;return s=o.socket&&o.connected?n?N(o.socket,"game:join",{room_id:n},15e3,e.JOIN_TIMEOUT).then(function(e){if(e.error)throw o._joined=!1,i(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")),C(o,s)},n.joinWorld=function(e){const t=this;return e=e||{},r.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._playersConnection&&e._playersConnection.close(),e.directMode?(e.roomId&&e._sendDirect("leave",{}),e.roomId=null,e._lastSequence=0,e._joined=!1,void(e._joinPromise=null)):e._useProxy?(e.roomId&&r._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,i,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:i||{}}),Promise.resolve({success:!0});if(a&&!s.connected)return s._queueOfflineAction(n,i,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:i};return c&&(o.next_turn=c),r._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,i,o);throw new t(e.NOT_CONNECTED,"Not connected")}const r={room_id:s.roomId,action_type:n,action_data:i};return c&&(r.next_turn=c),s._emitAction(r,!0)})},n._emitAction=function(n,r){const o=this;return o.socket&&o.connected?N(o.socket,"game:action",n).then(function(t){if(t.error){const s=i(t);if(r&&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();r.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){r.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,i,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)")):(r.log("Queued action while offline: "+n),new Promise(function(e,t){s._offlineQueue.push({actionType:n,actionData:i,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();r.log("Flushing "+n.length+" queued action(s) after reconnect");const o=Promise.resolve().then(function r(){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),r()},function(t){const s=i(t);if(s.code!==e.NOT_CONNECTED&&s.code!==e.NOT_IN_ROOM)return n[0]===o&&n.shift(),o.reject(t),r()})});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,c=n&&1===n.__usionSyncedState&&Number.isSafeInteger(n.seq)&&n.seq>=0&&n.seq<=s?n.seq:s;return o._useProxy?r._request("GAME_SET_STATE",{room_id:o.roomId,state:n||{},sequence:c}).then(function(e){if(e&&e.error){const t=i(e);return{success:!1,error:t.message,code:t.code}}return e||{success:!0}}).catch(function(t){const n=i(t,e.REQUEST_TIMEOUT);return{success:!1,error:n.message,code:n.code}}):o.socket&&o.connected?N(o.socket,"game:set_state",{room_id:o.roomId,state:n||{},sequence:c}).then(function(e){if(e.error){const t=i(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?r._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=i(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?r._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?r._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?(r._post({type:"GAME_FORFEIT",room_id:n.roomId}),Promise.resolve({success:!0})):n.socket&&n.connected?N(n.socket,"game:forfeit",{room_id:n.roomId}).then(function(e){if(e.error)throw i(e);return e}):Promise.reject(new t(e.NOT_CONNECTED,"Not connected"))},n.reportResult=function(n,i){if(i=i||{},!((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||r.config&&r.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)),r._backendEmit("gc:match_result",{service_id:i.serviceId||r.config&&r.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),i=t.roomId||r.config&&r.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:i,invited:[]})}const o={roomId:i};return"number"==typeof e.maxPlayers&&e.maxPlayers>0&&(o.maxPlayers=e.maxPlayers),r._request("GAME_INVITE_REQUEST",o,e.timeout||12e4).then(function(e){const n=(e=e||{}).roomId||i||null,r={success:!!e.success,roomId:n,invited:Array.isArray(e.invited)?e.invited:[]};return r.success&&n?Promise.resolve().then(function(){return t.connect()}).then(function(){return t.join(n)}).then(function(){return r}).catch(function(){return r}):r}).catch(function(){return{success:!1,roomId:i,invited:[]}})},n.disconnect=function(){const e=this;if(e._playersConnection&&e._playersConnection.close(),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 r._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 i=Object.assign({},e||{});i._diag=r.diagnostics?r.diagnostics():void 0,r._post({type:"GAME_DEBUG",payload:i})}}catch(e){}},n.isMultiplayer=function(){return"multiplayer"===r.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)}}(r,n),Ee(r,n),function(e,t){e.connectPlayers=function(n={}){if(e._playersConnection&&!e._playersConnection.closed)return e._playersPromise;if(e.directMode||"direct"===t.config.connectionMode)return Promise.reject(new Error("connectPlayers requires platform room signaling"));if(!Pe(t.user.getId()))return Promise.reject(new Error("Initialize Usion before connectPlayers"));if(void 0!==n.directTimeoutMs&&(!Number.isFinite(n.directTimeoutMs)||n.directTimeoutMs<1e3||n.directTimeoutMs>3e4))return Promise.reject(new Error("directTimeoutMs must be 1000–30000"));const i=e._playersConnection=new Ne(e,t,n);return e._playersPromise=i.start().catch(e=>{throw i.close(),e}),e._playersPromise}}(r,n),function(e,t){e.getParticipants=async function(){const e=this.roomId;if(!e)throw new Error("Join a room before reading participants");for(let n=0;n<5;n++){const i=t.user.getToken();if(!i){if(n<4){await new Promise(e=>setTimeout(e,500));continue}throw new Error("Participant access needs an authenticated Usions session")}const r=String(t.config.apiUrl||"").replace(/\/$/,"");if(!r)throw new Error("No API URL provided");const o=await fetch(r+"/games/rooms/"+encodeURIComponent(e)+"/participants",{headers:{Authorization:"Bearer "+i},cache:"no-store"});if(401===o.status&&n<4){await new Promise(e=>setTimeout(e,500));continue}if(!o.ok)throw new Error("Participant access failed: HTTP "+o.status);const s=await o.json();if(this.roomId!==e)throw new Error("Room changed while loading participants");return s}}}(r,n),function(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 i(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",i),e.on("playerJoined",i),Se(e,t)}(r,n),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("visibilitychange",function(){if("visible"===document.visibilityState&&r.roomId)try{r.requestSync()}catch(e){}}),r}(Me),Me.UsionError=t,Me.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 i=t._backendHandlers[e];i&&i(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,r,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,r||{},function(e){u||(u=!0,clearTimeout(l),e&&e.error?a(i(e)):c(e))})}catch(e){clearTimeout(l),a(i(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:r||{}},o).catch(function(e){throw i(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"))}}(Me),Me.lobby=function(e){const t={code:null,host:null,status:null,members:[]},n={};let i=!1;function r(){i||(i=!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 r(),e._backendEmit(t,n)}return{get state(){return t},onUpdate:function(e){n.update=e,r()},onStarted:function(e){n.started=e,r()},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 i=e.config&&e.config.apiUrl||"",r=e.user&&e.user.getToken&&e.user.getToken();if(!i)throw new Error("No apiUrl configured");const o=await fetch(i.replace(/\/$/,"")+"/games/matchmake",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r},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()}}}(Me),Me.leaderboard=function(e){function t(t){return t&&t.serviceId||e.config&&e.config.serviceId}return{submit:function(n,i,r){return e._backendEmit("lb:submit",{service_id:t(r),score:n,metadata:null!=i?i:null})},scores:function(n,i){var r=Array.isArray(n)?n:[n];return e._backendEmit("lb:scores",{service_id:t(i),user_ids:r}).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)})}}}(Me),Me.cloud=function(e){function t(t){return t&&t.serviceId||e.config&&e.config.serviceId}function n(n,i,r,o){var s=Object.assign({service_id:t(o),scope:i},r);return e._backendEmit(n,s)}function i(e){return{get:function(t,i){return n("kv:get",e,{key:t},i).then(function(e){return e&&e.exists?e.value:null})},set:function(t,i,r){return n("kv:set",e,{key:t,value:i},r)},remove:function(t,i){return n("kv:remove",e,{key:t},i)},keys:function(t){return n("kv:keys",e,{},t).then(function(e){return e&&e.keys||[]})}}}var r=i("user");return r.shared=i("shared"),r.friends=i("friends"),r.friends.list=function(e,t){return n("kv:get","friends",{key:e,friends:!0},t).then(function(e){return(e&&e.entries||[]).map(function(e){return{userId:e.user_id,name:e.name||null,avatar:e.avatar||null,value:e.value,updatedAt:e.updated_at||null}})})},r.shared.incr=function(e,t,i){return n("kv:incr","shared",{key:e,delta:null==t?1:t},i).then(function(e){return e&&e.value})},r}(Me),Me.matchmaking=function(n){let r=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),r){const e=r;r=null,e.resolve(t)}}))}function u(o,s,u){if(a(),r){const n=r;r=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),r===d&&(r=null),t(e)}});return r=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&&r===d&&(r=null,d.resolve(c(e)))}).catch(function(e){r===d&&d.reject(i(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(r){const n=r;r=null,n.reject(new t(e.CANCELLED,"cancelled"))}return n._backendEmit("mm:cancel",{})}}}(Me),Me.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,i){return e._backendEmit("notify:set_pref",{service_id:t(i),muted:!!n})},isMuted:function(n){return e._backendEmit("notify:get_pref",{service_id:t(n)}).then(function(e){return!(!e||!e.muted)})}}}(Me),Me.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 i(e){const t={};return e.forEach(function(e){t[e]=!1}),t}function r(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(r(l,i(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",h),t(e))}function h(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(r(l,t.permissions))}window.addEventListener("message",h),u=setTimeout(function(){c||o.query(l).then(function(e){f(r(l,e))}).catch(function(){f(r(l,i(l)))})},o._requestTimeoutMs||12e4),e._post({type:"PERMISSION_REQUEST",_requestId:n,permissions:l,reason:d})})},query:function(r){const o=t(r);return n()?e._request("PERMISSION_QUERY",{permissions:o},8e3).then(function(e){return e&&e.permissions||{}}):Promise.resolve(i(o))},has:function(e){return o.query([e]).then(function(t){return!(!t||!t[e])})}};return o}(Me),Me.screen=function(e){var t=[],n=!1;function i(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 i="string"==typeof n.kind&&n.kind?n.kind:"screenshot",r=t.slice(),o=0;o<r.length;o++)try{r[o]({kind:i})}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",i),n=!0);var r=!1;return function(){if(!r){r=!0;var o=t.indexOf(e);o>=0&&t.splice(o,1),0===t.length&&function(){if(n){try{window.removeEventListener("message",i)}catch(e){}n=!1}}()}}},support:function(){var t=e.config&&e.config.screenCapture||null;return{block:!(!t||!t.block),detect:!(!t||!t.detect)}}}}(Me),Me.profile=function(n){function i(i,r){return"undefined"!=typeof window&&("ReactNativeWebView"in window||window.parent!==window)?n._request(i,r,3e4):Promise.reject(new t(e.UNSUPPORTED,"Profile content requires the Usion host"))}return{getContent:()=>i("PROFILE_CONTENT_GET",{}).then(e=>e.content),setContent:n=>!n||!Array.isArray(n.items)||n.items.length>50?Promise.reject(new t(e.INVALID_INPUT,"Profile content requires at most 50 items")):i("PROFILE_CONTENT_SET",{content:n}).then(e=>e.content),clearContent:()=>i("PROFILE_CONTENT_CLEAR",{}).then(()=>{})}}(Me),Me.call=function(e){return{capabilities:function(){return e._request("CALL_CAPABILITIES",{},5e3)},startAnalysis:async function(t){if(!t||!Array.isArray(t.capabilities)||"function"!=typeof t.onSample)throw new Error("capabilities and onSample are required");var n=null,i=!1,r=e.on("CALL_ANALYSIS_EVENT",function(e){i||null===n||e.subscriptionId!==n||t.onSample(e.sample)}),o=e.on("CALL_ANALYSIS_STOPPED",function(e){e.subscriptionId===n&&s()});function s(){i||(i=!0,r(),o(),"function"==typeof t.onStopped&&t.onStopped())}try{var c=await e._request("CALL_ANALYSIS_START",{capabilities:t.capabilities},12e4);if(!c.started||!Number.isInteger(c.subscriptionId))throw new Error("Invalid call analysis response");return n=c.subscriptionId,{stop:async function(){i||(s(),await e._request("CALL_ANALYSIS_STOP",{},5e3))}}}catch(e){throw s(),e}}}}(Me),Me.netcode=Re,Object.assign(Me,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||[]}}}(Me)),Object.assign(Me,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"})}}}(Me)),Object.assign(Me,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})}}}(Me)),Object.assign(Me,v),Object.assign(Me,b),Object.assign(Me,O),Me}();"undefined"!=typeof window?window.Usion=Usion:"undefined"!=typeof globalThis&&(globalThis.Usion=Usion);
1
+ /*! @usions/sdk v2.35.0 — minified build; source: packages/sdk/src/modules (github.com/ugshanyu/usionthemobile) */
2
+ var Usion=function(){"use strict";const e={PERMISSION_DENIED:"PERMISSION_DENIED",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",VOICE_UNSUPPORTED:"VOICE_UNSUPPORTED",VOICE_DISABLED:"VOICE_DISABLED",VOICE_UNAVAILABLE:"VOICE_UNAVAILABLE",VOICE_NO_ROOM:"VOICE_NO_ROOM",VOICE_NOT_IN_ROOM:"VOICE_NOT_IN_ROOM",VOICE_BAD_CHANNEL:"VOICE_BAD_CHANNEL",VOICE_FULL:"VOICE_FULL",VOICE_DECLINED:"VOICE_DECLINED",VOICE_MIC_DENIED:"VOICE_MIC_DENIED",VOICE_GUEST:"VOICE_GUEST",VOICE_FAILED:"VOICE_FAILED",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 i(i,r){if(i instanceof t)return i;if(i&&"object"==typeof i){const n="string"==typeof i.code&&e[i.code]?i.code:null,r=i.message||i.error;if(n){const e=new t(n,"string"==typeof r?r:n),o=null!=i.retry_after?i.retry_after:i.retryAfter;return"number"==typeof o&&isFinite(o)&&(e.retryAfter=o),e}i instanceof Error||"string"!=typeof r||(i=r)}const o=i&&i.message?i.message:String(i||"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(r||e.UNKNOWN,o)}const r=/^[a-z0-9][a-z0-9_-]{0,47}$/;function o(e,t){try{e(t)}catch(e){console.error("[Usion] call voice listener error:",e)}}function s(n){let i={on:!1,channel:null,scope:null,status:"idle",micOn:!1,peers:[]};const s=new Set,c=new Set;let a=!1;function u(){const e=n.config&&n.config.hostFeatures;return!(!e||!e.voice)}function l(){a||(a=!0,n.on("CALL_VOICE_CHANGED",function(e){e&&e.state&&d(e.state)}),n.on("CALL_VOICE_SPEAKING",function(e){const t=e&&Array.isArray(e.userIds)?e.userIds.filter(function(e){return"string"==typeof e}):[];c.forEach(function(e){o(e,t)})}))}function d(e){return i=function(e){if(!e||"object"!=typeof e)return{on:!1,channel:null,scope:null,status:"idle",micOn:!1,peers:[]};const t=Array.isArray(e.peers)?e.peers:[];return{on:!!e.on,channel:"string"==typeof e.channel?e.channel:null,scope:"room"===e.scope||"game"===e.scope?e.scope:null,status:["idle","connecting","connected","reconnecting"].indexOf(e.status)>=0?e.status:"idle",micOn:!!e.micOn,peers:t.filter(function(e){return e&&"string"==typeof e.userId}).map(function(e){return{userId:e.userId,name:"string"==typeof e.name?e.name:"",isMe:!!e.isMe,micOn:!!e.micOn,speaking:!!e.speaking}})}}(e),s.forEach(function(e){o(e,i)}),i}function f(r,o,s){return u()?(l(),n._request(r,o,s).then(function(e){return e&&e.state?d(e.state):i})):Promise.reject(new t(e.VOICE_UNSUPPORTED,"Voice needs a newer version of the Usion app"))}return{isAvailable:u,micOn:function(n){const i=n||{},o=null==i.channel?"main":i.channel,s=null==i.scope?"room":i.scope;return"string"==typeof o&&r.test(o)?"room"!==s&&"game"!==s?Promise.reject(new t(e.VOICE_BAD_CHANNEL,"scope must be 'room' or 'game'")):f("CALL_VOICE_ON",{channel:o,scope:s,listen:!!i.listen},6e4):Promise.reject(new t(e.VOICE_BAD_CHANNEL,"Channel names are 1-48 of a-z, 0-9, '-', '_' and start with a letter or digit"))},micOff:function(){return f("CALL_VOICE_OFF",{},5e3).then(function(){})},setMic:function(e){return f("CALL_VOICE_SET_MIC",{on:!!e},5e3)},mutePeer:function(n,i){return"string"==typeof n&&n?f("CALL_VOICE_MUTE_PEER",{userId:n,muted:!1!==i},5e3).then(function(){}):Promise.reject(new t(e.INVALID_INPUT,"userId required"))},state:function(){return u()?f("CALL_VOICE_STATE",{},5e3):Promise.resolve({on:!1,channel:null,scope:null,status:"idle",micOn:!1,peers:[]})},onChange:function(e){if(l(),s.add(e),i.on){const t=i;Promise.resolve().then(function(){s.has(e)&&i===t&&o(e,t)})}return function(){s.delete(e)}},onSpeaking:function(e){return l(),c.add(e),function(){c.delete(e)}}}}let c=0;const a={};function u(){return++c}let l=null;function d(e){return"undefined"==typeof window||(!!window.ReactNativeWebView||(window.parent===window||(!e||!e.source||e.source===window.parent)&&(null===l&&(l=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}()),!(l&&e&&e.origin&&e.origin!==l))))}const f={version:"2.35.0",config:{},_initialized:!1,_initCallback:null,_messageHandlerRegistered:!1,_results:[],_backButtonCallback:null,init:function(n,r){const o=this;return n&&"object"==typeof n&&(r=n,n=null),r=r||{},o._initialized?(n&&n(o.config),Promise.resolve(o.config)):(n&&(o._initCallback=n),o._initPromise||(o._initPromise=new Promise(function(e,t){o._initResolve=e,o._initReject=t}),o._initPromise.catch(function(){})),r.timeout>0&&!o._initTimer&&(o._initTimer=setTimeout(function(){o._initTimer=null,!o._initialized&&o._initReject&&o._initReject(new t(e.INIT_TIMEOUT,"No INIT from host within "+r.timeout+"ms — host silent or running standalone"))},r.timeout)),o._messageHandlerRegistered||(o._messageHandlerRegistered=!0,window.addEventListener("message",function(e){if(!d(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(o._initialized)return t.config.authToken&&(o.config.authToken=t.config.authToken,o.user&&(o.user._token=t.config.authToken)),void 0!==t.config.balance&&o.wallet&&(o.wallet._balance=t.config.balance),!0!==t.config.userIsAdult&&!1!==t.config.userIsAdult||!o.user||(o.config.userIsAdult=t.config.userIsAdult,o.user._isAdult=t.config.userIsAdult),void(t.config.hostFeatures&&"object"==typeof t.config.hostFeatures&&(o.config.hostFeatures=t.config.hostFeatures));o.config=t.config,o._initialized=!0,o._isEmbedded=!0,t.config.userId&&(o.user._id=t.config.userId,o.user._name=t.config.userName,o.user._avatar=t.config.userAvatar,o.user._token=t.config.authToken,o.user._isAdult=!0===t.config.userIsAdult||!1===t.config.userIsAdult?t.config.userIsAdult:null),t.config.sessionId&&(o.session._id=t.config.sessionId,o.session._data=t.config.sessionData||{}),void 0!==t.config.balance&&(o.wallet._balance=t.config.balance),t.config.results&&(o._results=t.config.results),o._initCallback&&o._initCallback(t.config),o._initTimer&&(clearTimeout(o._initTimer),o._initTimer=null),o._initResolve&&o._initResolve(t.config)}if(t._requestId&&a[t._requestId]){const{resolve:e,reject:n}=a[t._requestId];delete a[t._requestId],t.error?n(i(t)):e(t)}if("BALANCE_UPDATE"===t.type&&(o.wallet._balance=t.balance,o.wallet._balanceChangeHandler&&o.wallet._balanceChangeHandler(t.balance)),"BACK_BUTTON_PRESSED"===t.type&&o._backButtonCallback){var n=o._backButtonCallback;o._backButtonCallback=null,n()}if("BOT_MESSAGE"===t.type&&o.bot&&o.bot._messageHandler&&o.bot._messageHandler(t.message),"HOST_NAVIGATE"===t.type&&"string"==typeof t.path&&(o.config&&(o.config.launchPath=t.path),o._hostNavigateCallback&&o._hostNavigateCallback({path:t.path,tab:t.tab||null})),"BACKEND_EVENT"===t.type&&t.event&&o._backendHandlers){const e=o._backendHandlers[t.event];e&&e(t.data)}if("GAME_ROOM_ASSIGNED"===t.type&&t.roomId&&o.game){var r=t.roomId;o.config.roomId=r,o.config.mode="multiplayer",o.game._dispatch("roomAssigned",{roomId:r}),Promise.resolve().then(function(){return o.game.connect()}).then(function(){return o.game.join(r)}).catch(function(){})}}),this._setupInteractionBeacon(),this._post({type:"READY"})),o._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(i){if(!(i&&!1===i.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(i){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,i,r){const o=this;return r=r||5e3,new Promise(function(s,c){const l=u(),d=setTimeout(function(){delete a[l],c(new t(e.REQUEST_TIMEOUT,"Request timeout"))},r);a[l]={resolve:function(e){clearTimeout(d),s(e)},reject:function(e){clearTimeout(d),c(e)}},o._post({type:n,_requestId:l,...i})})}};var h="_d:",_="_migrated_v2";function p(e){return h+e}function m(e,t,n){return e._backendEmit(t,Object.assign({service_id:e.config&&e.config.serviceId,scope:"storage"},n))}function g(e,t){return e._request("STORAGE_GET",{key:t}).then(function(e){return e?e.value:null})}function y(e,t,n){return e._request("STORAGE_SET",{key:t,value:n})}function v(e,t){return e._request("STORAGE_REMOVE",{key:t})}function I(e){return e._request("STORAGE_KEYS",{}).then(function(e){return e&&e.keys||[]})}function E(e){return e.catch(function(){})}const w={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 i="string"==typeof e?document.querySelector(e):e,r="string"==typeof t?document.querySelector(t):t;function o(){const e=i.value.length;r.textContent=e+" / "+n,r.classList.remove("warning","error"),e>.9*n?r.classList.add("error"):e>.7*n&&r.classList.add("warning")}i&&r&&(i.addEventListener("input",o),o())},selectionGrid:function(e,t,n){const i=document.querySelector(e);if(!i)return;let r=null;return i.querySelectorAll(t).forEach(function(e){e.addEventListener("click",function(){i.querySelectorAll(t).forEach(function(e){e.classList.remove("selected")}),e.classList.add("selected"),r=e.dataset.value||e.dataset.id,n&&n(r,e)})}),{getSelected:function(){return r},clear:function(){i.querySelectorAll(t).forEach(function(e){e.classList.remove("selected")}),r=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)},shareToStory:function(e,t){var n={url:e};return(t=t||{}).filename&&(n.filename=t.filename),t.mimeType&&(n.mimeType=t.mimeType),t.stickerUrl&&(n.stickerUrl=t.stickerUrl),t.backgroundTopColor&&(n.backgroundTopColor=t.backgroundTopColor),t.backgroundBottomColor&&(n.backgroundBottomColor=t.backgroundBottomColor),t.title&&(n.title=t.title),t.text&&(n.text=t.text),this._request("SHARE_TO_STORY",n,12e4)},download:function(e,t,n){t&&"object"==typeof t&&(t=(n=t).filename),n=n||{};var i={url:e,filename:t||n.filename||"download.mp4"};return n.mimeType&&(i.mimeType=n.mimeType),n.destination&&(i.destination=n.destination),n.title&&(i.title=n.title),this._request("DOWNLOAD_FILE",i,12e4)},log:function(e){this._post({type:"LOG",msg:e}),console.log("[Usion]",e)},on:function(e,t){function n(n){if(!d(n))return;let i;try{i="string"==typeof n.data?JSON.parse(n.data):n.data}catch(e){return}i.type===e&&t(i)}return window.addEventListener("message",n),function(){window.removeEventListener("message",n)}}};var T=/[\x00-\x1f\x7f\s\\]/;function S(e){return"string"!=typeof e?"path must be a string":e.length>512?"path too long (max 512)":"/"!==e.charAt(0)||"/"===e.charAt(1)?"path must be a relative in-app path starting with a single '/'":-1!==e.indexOf("://")||T.test(e)?"path contains illegal characters":null}function A(e){return Array.from(e).length}var O=5242880,k=/^data:image\/(png|jpeg|webp);base64,/,C=/^[A-Za-z0-9+/]+={0,2}$/;function N(){var e="undefined"!=typeof globalThis?globalThis.crypto:void 0;if(e&&"function"==typeof e.randomUUID)return e.randomUUID();var t=new Array(16);if(e&&"function"==typeof e.getRandomValues){var n=new Uint8Array(16);e.getRandomValues(n);for(var i=0;i<16;i++)t[i]=n[i]}else for(var r=0;r<16;r++)t[r]=Math.floor(256*Math.random());t[6]=15&t[6]|64,t[8]=63&t[8]|128;var o=t.map(function(e){return(e+256).toString(16).slice(1)}).join("");return o.slice(0,8)+"-"+o.slice(8,12)+"-"+o.slice(12,16)+"-"+o.slice(16,20)+"-"+o.slice(20)}const P={canShareToFeed:function(e){var t=this.config&&this.config.hostFeatures;return!(!t||!0!==t.feedShare)&&("image"===e?!0===t.feedShareImage:"video"===e?!0===t.feedShareVideo:"videoUpload"===e?!0===t.feedShareVideoUpload:!e)},uploadFeedVideo:async function(n,i){if(!this.canShareToFeed("videoUpload"))throw new t(e.UNSUPPORTED,"Video uploads require a newer host");if(!n||"number"!=typeof n.size||"function"!=typeof n.slice||n.size<=0||n.size>3221225472||["video/mp4","video/quicktime","video/webm","video/x-matroska"].indexOf(n.type)<0)throw new t(e.INVALID_INPUT,"Choose a supported video of at most 3 GiB");var r=this,o=this.config||{},s=i||{};if(!(r.user&&r.user.getToken()&&o.serviceId&&o.apiUrl))throw new t(e.NOT_AUTHENTICATED,"Sign in to upload");var c=o.apiUrl.replace(/\/$/,"")+"/feed/video-uploads/"+encodeURIComponent(o.serviceId)+"/multipart",a=null;async function u(n,i,o,c){var a={Authorization:"Bearer "+r.user.getToken()};c&&(a["Content-Type"]=c);var u=await fetch(n,{method:i,headers:a,body:o,signal:s.signal});if(!u.ok)throw new t(429===u.status?e.RATE_LIMITED:401===u.status?e.NOT_AUTHENTICATED:403===u.status?e.PERMISSION_DENIED:u.status<500?e.INVALID_INPUT:e.UNKNOWN,"Video upload failed");return u.json()}function l(e){if("function"==typeof s.onProgress)try{s.onProgress({loaded:e,total:n.size})}catch(e){}}try{var d=await u(c,"POST",JSON.stringify({request_id:s.requestId||N(),file_size:n.size,file_type:n.type}),"application/json");if("string"!=typeof(a=d.file_id)||!a)throw new t(e.UNKNOWN,"Invalid upload session");var f=c+"/"+encodeURIComponent(a);if("ready"!==(d=await u(f,"GET")).status&&"completing"!==d.status){var h=d.part_size,_=new Set(d.uploaded_parts||[]),p=0;if(!Number.isInteger(h)||h<1)throw new t(e.UNKNOWN,"Invalid upload part size");for(var m=1,g=0;g<n.size;m++,g+=h){var y=n.slice(g,Math.min(g+h,n.size));if(!_.has(m))for(var v=0;;v++)try{await u(f+"/parts/"+m,"PUT",y,"application/octet-stream");break}catch(n){if(s.signal&&s.signal.aborted)throw n;if(v>=2||n instanceof t&&n.code!==e.UNKNOWN)throw n;await new Promise(function(e){setTimeout(e,500*(v+1))})}l(p+=y.size)}}var I=await u(f+"/complete","POST");if(!I||"string"!=typeof I.receipt)throw new t(e.UNKNOWN,"Invalid upload response");return l(n.size),{receipt:I.receipt}}catch(n){if(s.signal&&s.signal.aborted&&a){try{await fetch(c+"/"+encodeURIComponent(a),{method:"DELETE",headers:{Authorization:"Bearer "+r.user.getToken()}})}catch(e){}throw new t(e.CANCELLED,"Video upload cancelled")}throw n}},shareToFeed:function(n,i){if(i=i||{},"video"===n&&null==i.video&&null==i.videoReceipt)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: video is required"));var r="string"==typeof i.text?i.text.trim():"";if(!r)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: text is required"));var o={contentType:n||"text",text:r,requestId:"string"==typeof i.requestId&&i.requestId?i.requestId:N(),serviceId:this.config&&this.config.serviceId,serviceName:this.config&&this.config.serviceName};if(null!=i.path&&""!==i.path){var s=S(i.path);if(s)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: "+s));o.path=i.path}if(null!=i.card){var c=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return{error:"card must be an object"};var t="string"==typeof e.title?e.title.trim():"";if(!t)return{error:"card.title is required"};if(A(t)>200)return{error:"card.title too long (max 200)"};var n={title:t};if(null!=e.subtitle){if("string"!=typeof e.subtitle)return{error:"card.subtitle must be a string"};var i=e.subtitle.trim();if(A(i)>60)return{error:"card.subtitle too long (max 60)"};i&&(n.subtitle=i)}return{card:n}}(i.card);if("error"in c)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: "+c.error));o.card=c.card}if(null!=i.image){var a=function(e){var t="string"==typeof e&&k.exec(e);if(!t)return"image must be a data:image/(png|jpeg|webp);base64 URL";var n=e.slice(t[0].length),i="=="===n.slice(-2)?2:"="===n.slice(-1)?1:0;return Math.floor(3*n.length/4)-i>O?"image too large (max 5 MB)":n.length%4==0&&C.test(n)?null:"image is not valid base64"}(i.image);if(a)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: "+a));o.image=i.image}if(null!=i.video){if(null!=i.image||"string"!=typeof i.video||!/^data:video\/mp4;base64,/.test(i.video))return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: video must be an MP4 data URL without an image"));var u=i.video.slice(22),l="=="===u.slice(-2)?2:"="===u.slice(-1)?1:0;if(!u||u.length%4!=0||3*u.length/4-l>O||!C.test(u))return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: invalid video or video exceeds 5 MB"));if(!this.canShareToFeed("video"))return Promise.reject(new t(e.UNSUPPORTED,"shareToFeed: host does not support video"));o.video=i.video}if(null!=i.videoReceipt){if(null!=i.video||null!=i.image||"string"!=typeof i.videoReceipt||!i.videoReceipt||i.videoReceipt.length>8192)return Promise.reject(new t(e.INVALID_INPUT,"Invalid video receipt"));if(!this.canShareToFeed("videoUpload"))return Promise.reject(new t(e.UNSUPPORTED,"Video uploads require a newer host"));o.videoReceipt=i.videoReceipt}return this._request("SHARE_TO_FEED",o,6e5).then(function(e){return Object.assign({success:!0},e)})},openApp:function(n,i){if("string"!=typeof n||!n.trim())throw new t(e.INVALID_INPUT,"openApp: serviceId is required");var r={type:"OPEN_SERVICE",serviceId:n.trim()};if(null!=i&&""!==i){var o=S(i);if(o)throw new t(e.INVALID_INPUT,"openApp: "+o);r.path=i}this._post(r)}};function R(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 i(){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 r(){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 r=i().rtt||0,o=e.directMode&&n.lastInboundAt?Date.now()-n.lastInboundAt:0;return r<150&&o<2e3?"good":r<400&&o<5e3?"fair":"poor"}();if(t!==n.quality){var r=n.quality;n.quality=t,e._dispatch("networkQuality",{quality:t,prev:r,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 i=Date.now(),r=function(){};r.sentAt=i,r.statsOnly=!0,e._pongWaiters.push(r),n.lastProbeAt=i,e._sendDirect("ping",{t:i})}}function c(){var i=e.directSocket;if(e.directMode&&i&&1===i.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 r();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"),r(),e._dispatch("disconnect","liveness_timeout");try{i.close()}catch(e){}return}u>=n.liveness.probeAfterMs&&c-n.lastProbeAt>=n.liveness.probeAfterMs&&s()}r()}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 i=n.pendingInput;n.pendingInput=null,e._sendDirect("input",i)}}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,r=t?e.directSocket:null,o=i();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:r?r.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:{},i=isFinite(t.probeAfterMs)?Math.max(1e3,t.probeAfterMs):4e3,r=isFinite(t.deadAfterMs)?t.deadAfterMs:12e3;n.liveness={probeAfterMs:i,deadAfterMs:Math.max(r,i+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)}}r()},e._resOnClose=function(e){n.lastCloseCode=e&&"number"==typeof e.code?e.code:null,u(),r()},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),r()},e._resCanReuseToken=function(){if(4401===n.lastCloseCode)return!1;var t=e.directConfig;if(!t||!t.ws_url||!t.access_token)return!1;var i=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!=i&&i-Date.now()>3e4},e._resHoldInput=function(t){if(!n.backpressureBytes)return!1;var i=e.directSocket;return!(!i||!(null!=n.pendingInput||i.bufferedAmount>n.backpressureBytes))&&(n.pendingInput=t,n.drainTimer||(n.drainTimer=setTimeout(a,50)),!0)},e.on("disconnect",r),e.on("connectionState",r)}function M(n,i,r,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(i,r,function(e){u||(u=!0,clearTimeout(l),c(e||{}))})}catch(e){if(u)return;u=!0,clearTimeout(l),a(e)}})}function q(e,t){return e._joinPromise=t,t.catch(function(){e._joined=!1,e._joinPromise===t&&(e._joinPromise=null)}),t}function D(e,t,n){let i=(t-e)%n;const r=n/2;return i>r&&(i-=n),i<-r&&(i+=n),i}function j(e,t,n,i){return"deg"===i?e+D(e,t,360)*n:"rad"===i?e+D(e,t,2*Math.PI)*n:e+(t-e)*n}class U{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 L(e,t){return t?Array.isArray(e[t])?e[t]:[]:Array.isArray(e)?e:[]}class x{constructor(e={}){const t=e.serverFps||20;this._frameMs=1e3/t,this.vault=new U(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,i=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 i){const e=t-i;this._offset=null==this._offset?e:this._offset+.05*(e-this._offset)}const r=this._useServerTime&&"number"==typeof i?i:t;this.vault.add({time:r,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(),i=this.vault.latest();if(!i)return null;const r=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>i.time)return this._extrapolationMs>0?this._extrapolate(n,r,t):L(i.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(L(o.state,t),L(s.state,t),c,r)}_blend(e,t,n,i){const r={};for(let t=0;t<e.length;t++)r[e[t].id]=e[t];return t.map(e=>{const t=r[e.id],o=Object.assign({},e);if(t)for(let r=0;r<i.length;r++){const{key:s,type:c}=i[r],a=t[s],u=e[s];"number"==typeof a&&"number"==typeof u&&(o[s]=j(a,u,n,c))}return o})}_extrapolate(e,t,n){const i=this.vault.latest(),r=this.vault.prevLatest(),o=L(i.state,n);if(!r||i.time<=r.time)return o.map(e=>Object.assign({},e));const s=Math.min(e-i.time,this._extrapolationMs),c=i.time-r.time,a={},u=L(r.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],i=Object.assign({},e);if(n)for(let r=0;r<t.length;r++){const{key:o}=t[r],a=n[o],u=e[o];if("number"==typeof a&&"number"==typeof u){const e=(u-a)/c;i[o]=u+e*s}}return i})}}class B{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,i=null==t?-1:t;this._pending=this._pending.filter(e=>e.seq>i);let r=e;for(let e=0;e<this._pending.length;e++)r=this._apply(r,this._pending[e].input);if(this._smoothKeys&&n&&r)for(let e=0;e<this._smoothKeys.length;e++){const t=this._smoothKeys[e];"number"==typeof n[t]&&"number"==typeof r[t]&&(this._error[t]=(this._error[t]||0)+(n[t]-r[t]))}return this._state=r,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 i=this._smoothKeys[e];let r=this._error[i]||0;"number"==typeof n[i]&&0!==r&&(n[i]=n[i]+r),r*=1-t,Math.abs(r)<this._snapTo&&(r=0),this._error[i]=r}return n}reset(e){this._state=void 0!==e?e:null,this._seq=0,this._pending=[],this._error={}}}class V{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],i=this._slots[n];if("latest"===i.mode)void 0!==i.value&&e.push({type:n,data:i.value});else for(let t=0;t<i.list.length;t++)e.push({type:n,data:i.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 F{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 H=[{urls:"stun:stun.l.google.com:19302"}];function G(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}class W{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||H,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(G(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)&&(G(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)&&(G(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 W({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,i)=>{t.onMessage&&t.onMessage(e,n,i)},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 z="undefined"!=typeof TextEncoder?new TextEncoder:null,Q="undefined"!=typeof TextDecoder?new TextDecoder:null;function Y(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),z?z.encode(n):Uint8Array.from(Buffer.from(n,"utf8")))};var t,n}function K(e,t){if(1===e)try{return JSON.parse((n=t,Q?Q.decode(n):Buffer.from(n).toString("utf8")))}catch(e){return null}var n;return t}class X{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 i=[];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);i.push(K(t,n.slice())),this._buf=this._buf.subarray(4+e)}return i}}class ${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 X,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:i}=await n.read();if(i)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:K(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:i}=Y(t),r=new Uint8Array(5+i.length);return new DataView(r.buffer).setUint32(0,e>>>0,!1),r[4]=n,r.set(i,5),r}(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}=Y(e),i=new Uint8Array(5+n.length);return new DataView(i.buffer).setUint32(0,1+n.length,!1),i[4]=t,i.set(n,5),i}(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 Z{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 i=this;t._schedule(()=>e.apply(i,n),t._delay()),t.dupPct&&100*t._rand()<t.dupPct&&t._schedule(()=>e.apply(i,n),t._delay())}}flush(){if(this._clear)for(const e of this._timers)this._clear(e);this._timers.clear()}}class ee{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 te(e,t,n){return e+(t-e)*n}class ne{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 i=n-this._historyMs;for(;this._history.length>this._maxSize||this._history.length>2&&this._history[0].time<i;)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 ie(n[0].entities);if(e>=n[n.length-1].time)return ie(n[n.length-1].entities);let i=n[0],r=n[n.length-1];for(let t=n.length-1;t>0;t--)if(n[t-1].time<=e&&e<=n[t].time){i=n[t-1],r=n[t];break}const o=r.time-i.time,s=o>0?(e-i.time)/o:0,c=ie(i.entities),a={},u=ie(r.entities);for(const e in u){const n=u[e],i=c[e],r=Object.assign({},n);if(i){const e=t||Object.keys(n);for(let t=0;t<e.length;t++){const o=e[t];"number"==typeof i[o]&&"number"==typeof n[o]&&(r[o]=te(i[o],n[o],s))}}a[e]=r}return a}rewindForClient(e,t,n){const i=null!=(n=n||{}).maxRewindMs?n.maxRewindMs:250;let r=(e||0)/2+(t||0);return r>i&&(r=i),this.rewind(this._now()-r,n.keys)}}function ie(e){const t={};for(let n=0;n<e.length;n++)t[e[n].id]=e[n];return t}const re="_s",oe="_d",se="_a",ce="_n",ae="_ka",ue="_add",le="_del",de="_ord";function fe(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function he(e){if(!Array.isArray(e)||0===e.length)return!1;for(let t=0;t<e.length;t++){const n=e[t];if(!fe(n)||"string"!=typeof n.id&&"number"!=typeof n.id)return!1}return!0}function _e(e,t){if(e===t)return;const n=Array.isArray(e),i=Array.isArray(t);return n!==i||fe(e)!==fe(t)?{[re]:t}:i?he(e)&&he(t)?function(e,t){const n={},i=[];for(let t=0;t<e.length;t++)n[e[t].id]=e[t],i.push(e[t].id);const r=[],o={};let s=!1;for(let e=0;e<t.length;e++){const i=t[e];if(r.push(i.id),Object.prototype.hasOwnProperty.call(n,i.id)){const e=_e(n[i.id],i);void 0!==e&&(o[ae]||(o[ae]={}),o[ae][i.id]=e,s=!0)}else o[ue]||(o[ue]=[]),o[ue].push(i),s=!0}const c={};for(let e=0;e<r.length;e++)c[r[e]]=!0;for(let e=0;e<i.length;e++)c[i[e]]||(o[le]||(o[le]=[]),o[le].push(i[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})(i,r)||(o[de]=r,s=!0);return s?o:void 0}(e,t):function(e,t){const n={[se]:{}};let i=!1;for(let r=0;r<t.length;r++){const o=r<e.length?_e(e[r],t[r]):{[re]:t[r]};void 0!==o&&(n[se][r]=o,i=!0)}t.length!==e.length&&(n[ce]=t.length,i=!0);return i?n:void 0}(e,t):fe(t)?function(e,t){const n={};let i=!1;for(const r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;const o=_e(e[r],t[r]);void 0!==o&&(n[r]=o,i=!0)}const r=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(Object.prototype.hasOwnProperty.call(t,n)||r.push(n));r.length&&(n[oe]=r,i=!0);return i?n:void 0}(e,t):{[re]:t}}function pe(e,t){if(null==t)return e;if(Object.prototype.hasOwnProperty.call(t,re))return t[re];if(t[ae]||t[ue]||t[le]||t[de])return function(e,t){const n=Array.isArray(e)?e:[],i={},r=[];for(let e=0;e<n.length;e++){const t=n[e];!t||"string"!=typeof t.id&&"number"!=typeof t.id||(i[t.id]=t,r.push(t.id))}if(t[ae])for(const e in t[ae])Object.prototype.hasOwnProperty.call(t[ae],e)&&void 0!==i[e]&&(i[e]=pe(i[e],t[ae][e]));if(t[ue])for(let e=0;e<t[ue].length;e++){const n=t[ue][e];i[n.id]=n}const o={};if(t[le])for(let e=0;e<t[le].length;e++)o[t[le][e]]=!0;if(t[de]){const e=[];for(let n=0;n<t[de].length;n++){const r=t[de][n];void 0!==i[r]&&e.push(i[r])}return e}const s=[];for(let e=0;e<r.length;e++){const t=r[e];o[t]||s.push(i[t])}return s}(e,t);if(Object.prototype.hasOwnProperty.call(t,se)||Object.prototype.hasOwnProperty.call(t,ce)){const n=Array.isArray(e)?e:[],i=Object.prototype.hasOwnProperty.call(t,ce)?t[ce]:n.length,r=n.slice(0,i),o=t[se]||{};for(const e in o)Object.prototype.hasOwnProperty.call(o,e)&&(r[e]=pe(r[e],o[e]));return r}const n=fe(e)?Object.assign({},e):{},i=t[oe];for(const e in t)e!==oe&&Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=pe(n[e],t[e]));if(Array.isArray(i))for(let e=0;e<i.length;e++)delete n[i[e]];return n}function me(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(fe(t)){const n={};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[i]=e(t[i]));return n}return t}(e)}const ge="undefined"!=typeof TextEncoder?new TextEncoder:null,ye="undefined"!=typeof TextDecoder?new TextDecoder:null;function ve(e,t){for(t>>>=0;t>127;)e.push(127&t|128),t>>>=7;e.push(t)}function Ie(e,t){if(null==t)return void e.push(192);const n=typeof t;if("boolean"!==n)if("number"!==n){var i;if("string"===n){e.push(198);const n=ge?ge.encode(t):Buffer.from(t,"utf8");ve(e,n.length);for(let t=0;t<n.length;t++)e.push(n[t]);return}if(Array.isArray(t)){e.push(199),ve(e,t.length);for(let n=0;n<t.length;n++)Ie(e,t[n])}else{if("object"===n){const n=Object.keys(t);e.push(200),ve(e,n.length);for(let i=0;i<n.length;i++){const r=n[i],o=ge?ge.encode(r):Buffer.from(r,"utf8");ve(e,o.length);for(let t=0;t<o.length;t++)e.push(o[t]);Ie(e,t[r])}return}e.push(192)}}else if(Number.isInteger(t)&&t>=-2147483648&&t<=2147483647)e.push(196),ve(e,((i=t)<<1^i>>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 Ee(e){const t=[];return Ie(t,e),Uint8Array.from(t)}function we(e){return function(e){let t=0;const n=new DataView(e.buffer,e.byteOffset,e.byteLength);function i(){let n,i=0,r=0;do{n=e[t++],r|=(127&n)<<i,i+=7}while(128&n);return r>>>0}function r(){const n=i(),r=e.subarray(t,t+n);return t+=n,ye?ye.decode(r):Buffer.from(r).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=i())>>>1^-(1&s);case 197:{const e=n.getFloat64(t,!0);return t+=8,e}case 198:return r();case 199:{const e=i(),t=new Array(e);for(let n=0;n<e;n++)t[n]=o();return t}case 200:{const e=i(),t={};for(let n=0;n<e;n++)t[r()]=o();return t}}var s}}(e instanceof Uint8Array?e:new Uint8Array(e))()}function be(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 Te(e,t,n){if("number"!=typeof e||!isFinite(e))throw new Error("interestGrid."+n+": "+t+" must be a finite number");return e}function Se(e,t){if(Te(e,"radius",t),e<0)throw new Error("interestGrid."+t+": radius must be >= 0");return e}function Ae(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,i=new Map,r=new Map;function o(e,t){let n=i.get(e);n||(n=new Set,i.set(e,n)),n.add(t)}function s(e,t){const n=i.get(e);n&&(n.delete(t),0===n.size&&i.delete(e))}function c(e,r,o,s){const c=o*o,a=Math.floor((e-o)/t),u=Math.floor((e+o)/t),l=Math.floor((r-o)/t),d=Math.floor((r+o)/t);for(let t=a;t<=u;t++)for(let o=l;o<=d;o++){const a=i.get(t+","+o);if(a)for(const t of a){const i=n.get(t);if(!i)continue;const o=i.x-e,a=i.y-r;o*o+a*a<=c&&s(t)}}}return{upsert:function(e,i,r){be(e,"upsert"),Te(i,"x","upsert"),Te(r,"y","upsert");const c=Math.floor(i/t)+","+Math.floor(r/t),a=n.get(e);if(a)return a.x=i,a.y=r,void(a.key!==c&&(s(a.key,e),o(c,e),a.key=c));n.set(e,{x:i,y:r,key:c}),o(c,e)},remove:function(e){be(e,"remove");const t=n.get(e);t&&(n.delete(e),s(t.key,e))},query:function(e,t,n){Te(e,"x","query"),Te(t,"y","query"),Se(n,"query");const i=[];return c(e,t,n,function(e){i.push(e)}),i},observe:function(e,t,n,i){be(e,"observe"),Te(t,"x","observe"),Te(n,"y","observe"),Se(i,"observe");let o=r.get(e);o||(o={prev:new Set,next:new Set},r.set(e,o));const s=o.prev,a=o.next;a.clear();const u=[],l=[],d=[];c(t,n,i,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){be(e,"dropObserver"),r.delete(e)},size:function(){return n.size}}}function Oe(e,t){e.diff=_e,e.patch=pe,e.quantize=me,e.encode=Ee,e.decode=we,e.createInterpolation=function(e){return new x(e||{})},e.createPredictor=function(e){return new B(e||{})},e.createLagCompensator=function(e){return new ne(e||{})},e.createLockstep=function(e){return new ee(e||{})},e.createInterestGrid=function(e){return Ae(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 V({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",i=!1!==e.delta,r=null!=e.keyframeEvery?e.keyframeEvery:30,o=e.precision,s=!0===e.encode?Ee:"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 h(e){if(null==e)return;const t=null!=o?me(e,o):e;let a;if(!i||null===u||f>=r)d+=1,u=null==(h=t)?h:JSON.parse(JSON.stringify(h)),l=d,f=0,a={s:d,f:t};else{const e=_e(u,t);if(void 0===e)return;d+=1,f+=1,a={s:d,b:l,d:e}}var h;c(n,s?s(a):a)}const _=e.hz||20;let p;const m=a?null:new V({hz:_,autoStart:!1!==e.autoStart,onFlush:function(e){for(let t=0;t<e.length;t++)"__snap"===e[t].type&&(p=e[t].data);h(p)}});let g=null;function y(){m?m.start():g||"undefined"==typeof setInterval||(g=setInterval(function(){h(a())},Math.max(1,Math.round(1e3/_))))}return a&&!1!==e.autoStart&&y(),{send:function(e){m?m.queue("__snap",e):h(e)},flush:function(){m?m.flush():a&&h(a())},start:y,stop:function(){m&&m.stop(),g&&(clearInterval(g),g=null)},reset:function(){u=null,l=0,d=0,f=0}}},e.createSnapshotReceiver=function(e){const t=!0===(e=e||{}).decode?we:"function"==typeof e.decode?e.decode:null;let n=null,i=-1,r=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,r):(n=e.f,i=void 0!==e.s?e.s:0,r=e.f,o=i,r):void 0!==e.d?void 0!==e.b&&e.b!==i||void 0!==e.s&&e.s<=o?(s+=1,r):(r=pe(n,e.d),void 0!==e.s&&(o=e.s),r):r:r},get state(){return r},get stats(){return{appliedSeq:o,baseSeq:i,dropped:s}},reset:function(){n=null,i=-1,r=null,o=-1,s=0}}},e.replicate=function(e,t){t=t||{};let n=null!=e?e:{};const i=this.createSnapshotSender(Object.assign({},t,{source:function(){return n}}));return{get state(){return n},set state(e){n=e},flush:function(){i.flush()},start:function(){i.start()},stop:function(){i.stop()}}},e.replica=function(e){const t=(e=e||{}).channel||"state",n=this.createSnapshotReceiver({decode:e.decode}),i=e.interpolate?this.createInterpolation("object"==typeof e.interpolate?e.interpolate:{}):null,r="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);i&&null!=t&&i.add(t),s&&s(t)});return{get state(){return n.state},view:function(){return i?i.calc(r||"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",i=new W(Object.assign({},e,{sendSignal:function(e){t.realtime(n,e)}}));return this._onChannel(n,function(e){e&&e.type&&i.handleSignal(e)}),i},e.createMeshNetwork=function(e){const n=this,i=(e=e||{}).signalChannel||"mesh",r=e.selfId||t.user&&t.user.getId&&t.user.getId(),o=new J(Object.assign({},e,{selfId:r,sendSignal:function(e,t){n.realtime(i,{to:e,from:r,payload:t})}}));return this._onChannel(i,function(e){e&&e.to===r&&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 Z(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 $(Object.assign({},e,{url:n}))},e.ping=function(){const e=this;if(e._pingMeter||(e._pingMeter=new F),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 i=!1;const r=function(){i||(i=!0,t(e._pingMeter.end(n)))};r.sentAt=Date.now(),e._pongWaiters.push(r),e._sendDirect("ping",{t:Date.now()}),setTimeout(function(){if(i)return;i=!0;const o=e._pongWaiters.indexOf(r);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 i=!1;try{e.socket.emit("game:ping",{t:n},function(){i||(i=!0,t(e._pingMeter.sample(Date.now()-n)))})}catch(e){return void t(null)}setTimeout(function(){i||(i=!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 ke(e,t){e.syncedState=function(e,n){var i=this,r="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=0,h=new Map,_=[],p=[];function m(e){for(var n=_.slice(),i=0;i<n.length;i++)try{n[i](a,e)}catch(e){t.log("syncedState onChange error: "+e.message)}}function g(){if("all"===s)return!0;var e=i.playerId||t.user&&t.user.getId&&t.user.getId();return!(!e||!i._hostId||e!==i._hostId)}function y(){return i.directMode?Promise.resolve({success:!1,error:"not_supported_in_direct_mode"}):i.setState({__usionSyncedState:1,seq:u,state:a})}function v(e,n,i,o){if(void 0!==o){if(!Number.isSafeInteger(o)||o<=u)return!1;if(f=Math.max(f,o),o!==u+1)return h.size<1e3&&h.set(o,{playerId:e,type:n,data:i,sequence:o}),!1}var s;try{s=r(a,{playerId:e,type:n,data:i,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 I(){var e=0;for(h.forEach(function(e,t){t<=u&&h.delete(t)});h.has(u+1);){var t=h.get(u+1);if(!v(t.playerId,t.type,t.data,t.sequence))break;h.delete(t.sequence),e+=1}return e}function E(){if(!(f<=u||d===u)){d=u;try{i.requestSync(u)}catch(e){d=-1}}}function w(e){if(e){var t=!1;Number.isSafeInteger(e.sequence)&&(f=Math.max(f,e.sequence));var 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 r=i.slice().sort(function(e,t){return(e.sequence||0)-(t.sequence||0)}),o=0;o<r.length;o++){var s=r[o];s&&v(s.player_id,s.action_type,s.action_data,s.sequence)&&(t=!0)}I()&&(t=!0),t&&m("recover"),E()}}return p.push(i.on("action",function(e){if(e){var t=v(e.player_id,e.action_type,e.action_data,e.sequence)?1:0;(t+=I())&&(m("action"),function(e){o>0&&g()&&(l+=e)>=o&&(l=0,y())}(t)),E()}})),p.push(i.on("sync",w)),p.push(i.on("joined",w)),{get:function(){return a},commit:function(e,t,n){var r,o,s;return"string"==typeof e?(r=e,o=t,s=n):(r=c,o=e,s=t),i.directMode?(v(i.playerId,r,o,void 0)&&m("action"),i.action(r,o,s)):i.action(r,o,s)},onChange:function(e){return _.push(e),function(){var t=_.indexOf(e);t>=0&&_.splice(t,1)}},isAuthority:g,checkpoint:function(){return y()},getSequence:function(){return u},destroy:function(){for(var e=0;e<p.length;e++)try{p[e]()}catch(e){}p.length=0,_.length=0,h.clear()}}}}const Ce="__usion_players_v1",Ne=e=>["direct","turn","webrtc"].includes(e),Pe=()=>globalThis.crypto.randomUUID(),Re=e=>"string"==typeof e&&e.length>0&&e.length<=128;class Me{constructor(e,t,n={}){this.game=e,this.usion=t,this.options=n,this.selfId=t.user.getId(),this.roomId=null,this.closed=!1,this.online=!1,this.session=Pe(),this.peers=new Map,this.roster=new Set,this.listeners={message:new Set,status:new Set,log:new Set},this.logs=[],this.sequence=0,this.generation=0,this.lastHello=0,this.RTC=void 0===n.RTCPeerConnection?globalThis.RTCPeerConnection:n.RTCPeerConnection,this.iceServers=n.iceServers||[{urls:"stun:stun.l.google.com:19302"}],this.timeout=n.directTimeoutMs??6e3,this.unsubscribers=[e._onChannel(Ce,(e,t)=>this._incoming(e,t)),e.on("joined",e=>this._joined(e)),e.on("playerJoined",e=>this._roster(e)),e.on("playerLeft",e=>this._roster(e,!0)),e.on("sync",e=>this._roster(e)),e.on("roomAssigned",({roomId:e})=>{this._join(e).catch(()=>this._log("join_failed"))}),e.on("disconnect",()=>this._offline()),e.on("reconnect",()=>this._recover()),e.on("reconnected",()=>this._recover())],this.tick=setInterval(()=>this._tick(),1e3)}async start(){const e=this.options.roomId||this.game.roomId||this.usion.config.roomId;return e&&await this._join(e),this}_emit(e,t){for(const n of this.listeners[e])try{n(t)}catch{}}_listen(e,t){return this.listeners[e].add(t),()=>this.listeners[e].delete(t)}onMessage(e){return this._listen("message",e)}onStatusChange(e){return this._listen("status",e)}onLog(e){return this._listen("log",e)}getLogs(){return this.logs.map(e=>({...e}))}_log(e,t=void 0,n=void 0){const i={time:Date.now(),event:e,peerId:t,reason:n};this.logs.push(i),this.logs.length>100&&this.logs.shift(),this._emit("log",{...i})}getStatus(){return{roomId:this.roomId,state:this.closed?"closed":this.roomId?this.online?"connected":"offline":"waiting",peers:[...this.peers.values()].map(e=>({playerId:e.id,transport:this.online?e.mode:"offline",rttMs:e.rtt,sent:e.sent,received:e.received}))}}_status(){this._emit("status",this.getStatus())}_mode(e,t,n){e.mode=t,e.rtt=null,this._log("transport",e.id,n),this._status()}async _join(e){if(this.closed)return;const t=++this.generation;if(this.roomId!==e&&(this._clearPeers(),this.roster.clear(),this.session=Pe(),this.roomId=e),this.online=!1,await this.game.connect(),this.closed||t!==this.generation)return;const n=await this.game.join(e);this.closed||t!==this.generation||this._joined(n||{})}_joined(e){if(this.closed)return;(e.room_id||this.game.roomId)===this.roomId&&(this.online=!0,this._roster(e),this._hello(),this._status())}_recover(){this.closed||this.online||!this.roomId||this._join(this.roomId).catch(()=>this._log("rejoin_failed"))}_offline(){this.closed||(this.generation++,this.online=!1,this.session=Pe(),this._clearPeers(),this._log("offline"),this._status())}_roster(e,t=!1){if(!(this.closed||!e||e.room_id&&e.room_id!==this.roomId)){Array.isArray(e.player_ids)?this.roster=new Set(e.player_ids.filter(Re)):Re(e.player_id)&&(t?this.roster.delete(e.player_id):this.roster.add(e.player_id));for(const[n,i]of this.peers)(!this.roster.has(n)||t&&n===e.player_id)&&(this._closeRTC(i),this.peers.delete(n),this._log("peer_left",n));this._hello(),this._status()}}_relay(e,t){if(!this.online||this.closed)return!1;try{return this.game.realtime(Ce,{...e,v:1,room:this.roomId,session:this.session,to:t}),!0}catch{return this._log("relay_send_failed",t),!1}}_hello(e=void 0){this._relay({kind:"hello"},e)}_peer(e,t){let n=this.peers.get(e);if(n&&n.session!==t&&(this._closeRTC(n),this.peers.delete(e),n=null),!n){if(this.peers.size>=7)return this._log("peer_limit",e),null;n={id:e,session:t,mode:"relay",pc:null,dc:null,attempt:null,candidates:[],queue:Promise.resolve(),lastDirect:0,lastSequence:-1,rtt:null,sent:0,received:0,started:!1,pendingPing:null},this.peers.set(e,n),this._log("peer_joined",e),this._status()}return n}_incoming(e,t){const n=t?.player_id;if(this.closed||!this.online||!e||1!==e.v||e.room!==this.roomId||t.room_id!==this.roomId||!Re(n)||n===this.selfId||!this.roster.has(n)||!Re(e.session)||e.to&&e.to!==this.selfId)return;if("hello"===e.kind){const t=this.peers.get(n)?.session===e.session,i=this._peer(n,e.session);if(!i)return;return t||this._hello(n),void(this.selfId<n&&!i.started&&this._attempt(i))}const i=this.peers.get(n);if(i&&i.session===e.session&&e.target===this.session)if("offer"===e.kind&&this.selfId>n&&Re(e.attempt)){if(i.attempt===e.attempt)return;this._setup(i,e.attempt),i.pc&&this._signal(i,e)}else["answer","ice"].includes(e.kind)&&e.attempt===i.attempt?this._signal(i,e):"fallback"===e.kind&&e.attempt===i.attempt?this._fallback(i,"peer_requested",!1):"retry"===e.kind&&this.selfId<n?this._attempt(i):"data"===e.kind&&this._receive(i,e,"relay")}_control(e,t){return this._relay({...t,target:e.session,attempt:e.attempt},e.id)}_setup(e,t){if(this._closeRTC(e),e.attempt=t,e.started=!0,this.RTC&&!1!==this.options.direct){this._mode(e,"connecting","direct_attempt");try{const t=e.pc=new this.RTC({iceServers:this.iceServers});e.localCandidates=[],e.descriptionSent=!1,t.onicecandidate=n=>{if(e.pc!==t||!n.candidate)return;const i=n.candidate.toJSON();e.descriptionSent?this._control(e,{kind:"ice",candidate:i}):e.localCandidates.length<64&&e.localCandidates.push(i)},t.ondatachannel=n=>{e.pc===t&&this._channel(e,t,n.channel)},t.onconnectionstatechange=()=>{e.pc===t&&["failed","disconnected","closed"].includes(t.connectionState)&&this._fallback(e,t.connectionState)},e.timer=setTimeout(()=>{e.pc===t&&this._fallback(e,"direct_timeout")},this.timeout)}catch{this._fallback(e,"rtc_setup_failed")}}else this._fallback(e,"direct_unavailable")}_attempt(e){this._setup(e,Pe());const t=e.pc;if(t){try{this._channel(e,t,t.createDataChannel("usion-game",{ordered:!1,maxRetransmits:0}))}catch{return void this._fallback(e,"channel_failed")}e.queue=(async()=>{const n=await t.createOffer();e.pc===t&&(await t.setLocalDescription(n),e.pc===t&&this._description(e,"offer"))})().catch(()=>{e.pc===t&&this._fallback(e,"offer_failed")})}}_signal(e,t){const n=e.pc;n&&(e.queue=e.queue.then(async()=>{if(e.pc===n)if("ice"===t.kind)n.remoteDescription?await n.addIceCandidate(t.candidate):e.candidates.length<64&&e.candidates.push(t.candidate);else{if(await n.setRemoteDescription(t.description),e.pc!==n)return;const i=e.candidates;e.candidates=[];for(const e of i)await n.addIceCandidate(e);"offer"===t.kind&&(await n.setLocalDescription(await n.createAnswer()),e.pc===n&&this._description(e,"answer"))}}).catch(()=>{e.pc===n&&this._fallback(e,"negotiation_failed")}))}_description(e,t){this._control(e,{kind:t,description:e.pc.localDescription.toJSON()}),e.descriptionSent=!0;for(const t of e.localCandidates)this._control(e,{kind:"ice",candidate:t});e.localCandidates=[]}_channel(e,t,n){e.dc=n,n.onopen=()=>{e.pc===t&&(clearTimeout(e.timer),e.lastDirect=Date.now(),this._mode(e,"webrtc","channel_open"),this._inspectRoute(e,t))},n.onmessage=n=>{if(!(e.pc!==t||"string"!=typeof n.data||n.data.length>16384))try{this._receive(e,JSON.parse(n.data),"direct")}catch{}},n.onerror=n.onclose=()=>{e.pc===t&&this._fallback(e,"channel_closed")}}async _inspectRoute(e,t){if(t?.getStats)try{const n=await t.getStats();if(e.pc!==t||!Ne(e.mode))return;let i;if(n.forEach(e=>{"transport"===e.type&&e.selectedCandidatePairId&&(i=n.get(e.selectedCandidatePairId))}),i||n.forEach(e=>{"candidate-pair"===e.type&&e.nominated&&"succeeded"===e.state&&(i=e)}),!i)return;const r=n.get(i.localCandidateId),o=n.get(i.remoteCandidateId);if(!r?.candidateType||!o?.candidateType)return;const s="relay"===r.candidateType||"relay"===o.candidateType?"turn":"direct";s!==e.mode&&this._mode(e,s,"ice_route_selected")}catch{}}_closeRTC(e){clearTimeout(e.timer);const t=e.pc,n=e.dc;e.pc=e.dc=null,e.candidates=[],e.queue=Promise.resolve(),n&&(n.onopen=n.onmessage=n.onerror=n.onclose=null,n.close()),t&&(t.onicecandidate=t.ondatachannel=t.onconnectionstatechange=null,t.close())}_fallback(e,t,n=!0){n&&this._control(e,{kind:"fallback"}),this._closeRTC(e),this._mode(e,"relay",t)}_packet(e,t){const n={...t,kind:"data",room:this.roomId,session:this.session,target:e.session};if(Ne(e.mode)&&"open"===e.dc?.readyState)try{if(e.dc.bufferedAmount>65536)throw Error("backpressure");return e.dc.send(JSON.stringify(n)),!0}catch{this._fallback(e,"send_failed")}return this._control(e,n)}_receive(e,t,n){t.room===this.roomId&&t.session===e.session&&t.target===this.session&&("direct"===n&&(e.lastDirect=Date.now()),Number.isSafeInteger(t.ping)&&t.ping>0?this._packet(e,{pong:t.ping}):Number.isSafeInteger(t.pong)&&t.pong>0?t.pong===e.pendingPing&&(e.rtt=Date.now()-t.pong,e.pendingPing=null,this._status()):!Number.isSafeInteger(t.seq)||t.seq<=e.lastSequence||(e.lastSequence=t.seq,e.received++,this._emit("message",{data:t.data,playerId:e.id,transport:"direct"===n?Ne(e.mode)?e.mode:"webrtc":n})))}send(e,t){if(this.closed||!this.online)return!1;const n=JSON.stringify(e);if(void 0===n||(new TextEncoder).encode(n).length>4096)throw new Error("connectPlayers messages must be JSON, at most 4096 bytes");const i=JSON.parse(n),r=++this.sequence,o=t?[this.peers.get(t)].filter(Boolean):[...this.peers.values()];let s=o.length>0;for(const e of o){const t=this._packet(e,{data:i,seq:r});t&&e.sent++,s=s&&t}return s}forceRelay(e){for(const t of this.peers.values())e&&t.id!==e||this._fallback(t,"forced")}retryDirect(e){if(this.online&&!this.closed)for(const t of this.peers.values())e&&t.id!==e||(this.selfId<t.id?this._attempt(t):this._control(t,{kind:"retry"}))}async invite(){return this.game.invite()}_tick(){if(!this.online||this.closed)return;const e=Date.now();e-this.lastHello>=3e3&&(this.lastHello=e,this._hello());for(const t of this.peers.values())Ne(t.mode)&&e-(t.lastStats||0)>1e4&&(t.lastStats=e,this._inspectRoute(t,t.pc)),Ne(t.mode)&&e-t.lastDirect>3e3&&this._fallback(t,"direct_unresponsive"),t.pendingPing=e,this._packet(t,{ping:e})}_clearPeers(){for(const e of this.peers.values())this._closeRTC(e);this.peers.clear()}close(){if(!this.closed){this.closed=!0,this.generation++,clearInterval(this.tick),this._clearPeers(),this.unsubscribers.forEach(e=>e()),this._status();for(const e of Object.values(this.listeners))e.clear()}}}const qe={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 De={SnapshotInterpolation:x,Vault:U,Predictor:B,Coalescer:V,PingMeter:F,MeshConnection:W,MeshNetwork:J,WebTransportConnection:$,NetworkSim:Z,Lockstep:ee,LagCompensator:ne,diff:_e,patch:pe,quantize:me,encode:Ee,decode:we,createInterestGrid:Ae},je=Object.assign({},f);var Ue;return je.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()}})},openProfile:function(t){"string"==typeof t&&t&&0!==t.indexOf("guest_")&&e._post({type:"OPEN_USER_PROFILE",userId:t})}}}(je),je.storage=function(e){var t=null;function n(){return t||(t=m(e,"kv:get",{key:_}).then(function(t){if(!t||!t.exists||!0!==t.value)return Promise.all([m(e,"kv:keys",{}),I(e)]).then(function(t){var n=new Set(t[0]&&t[0].keys||[]);return Promise.all(t[1].map(function(t){var i=p(t);if(!n.has(i))return g(e,t).then(function(t){if(null!=t)return m(e,"kv:set",{key:i,value:t})})}))}).then(function(){return m(e,"kv:set",{key:_,value:!0})})}).catch(function(e){throw t=null,e}))}return{get:function(t){return n().then(function(){return m(e,"kv:get",{key:p(t)})}).then(function(n){return n&&n.exists?E(y(e,t,n.value)).then(function(){return n.value}):E(v(e,t)).then(function(){return null})}).catch(function(n){return g(e,t).then(function(e){if(null!=e)return e;throw n},function(){throw n})})},set:function(t,i){return n().then(function(){return m(e,"kv:set",{key:p(t),value:i})}).then(function(){return E(y(e,t,i))})},remove:function(t){return n().then(function(){return m(e,"kv:remove",{key:p(t)})}).then(function(){return E(v(e,t))})},clear:function(){return n().then(function(){return m(e,"kv:clear",{prefix:h})}).then(function(){return E(e._request("STORAGE_CLEAR",{}))})},keys:function(){return n().then(function(){return m(e,"kv:keys",{})}).then(function(e){return(e&&e.keys||[]).filter(function(e){return 0===e.indexOf(h)}).map(function(e){return e.slice(3)})}).catch(function(t){return I(e).catch(function(){throw t})})}}}(je),je.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,i){const r=this,o=i&&"object"==typeof i?i:null,s=o&&"string"==typeof o.idempotencyKey&&o.idempotencyKey?o.idempotencyKey:null;return new Promise(function(o,c){const a=u(),l=r._paymentTimeoutMs||6e4;let f=!1,h=null;function _(){clearTimeout(y),h&&clearTimeout(h),window.removeEventListener("message",g)}function p(e){f||(f=!0,_(),e&&void 0!==e.newBalance?r._balance=e.newBalance:(null!==r._balance&&(r._balance-=t),r.getBalance({fresh:!0}).catch(function(){})),o(e))}function m(e){f||(f=!0,_(),c(e))}function g(e){if(!d(e))return;let t;try{t="string"==typeof e.data?JSON.parse(e.data):e.data}catch(e){return}t&&t._requestId===a&&("PAYMENT_SUCCESS"===t.type?p(t):"PAYMENT_FAILED"===t.type&&m(new Error(t.reason||"Payment failed")))}window.addEventListener("message",g);const y=setTimeout(function(){const t=r._recoveryPollMs||2e3,n=r._recoveryMaxPolls||10,i=r._recoveryQueryTimeoutMs||8e3;let o=0,c=0;!function r(){f||e._request("PAYMENT_RESULT_QUERY",{paymentRequestId:a,idempotencyKey:s||void 0},i).then(function(e){if(f)return;const n=e&&e.status;if("succeeded"!==n)if("failed"!==n){if("pending"===n)return o=0,c=0,void(h=setTimeout(r,t));c=0,o+=1,o>=2?m(new Error("Payment confirmation timeout")):h=setTimeout(r,t)}else m(new Error(e.reason||"Payment failed"));else p({type:"PAYMENT_SUCCESS",_requestId:a,newBalance:e.newBalance,transactionId:e.transactionId,receiptToken:e.receiptToken})}).catch(function(){f||(c+=1,c>=n?m(new Error("Payment confirmation timeout")):h=setTimeout(r,t))})}()},l);e._post({type:"PAYMENT_REQUEST",_requestId:a,amount:t,reason:n,data:i,idempotencyKey:s||void 0})})},onBalanceChange:function(e){const t=this;return t._balanceChangeHandler=e,function(){t._balanceChangeHandler===e&&(t._balanceChangeHandler=null)}}}}(je),je.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"})}}}(je),je.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})}}}(je),je.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}}}(je),je.fileStorage=(Ue=je,{set:function(e,t,n){return Ue._request("FILE_STORAGE_SET",{key:e,base64Data:t,mimeType:n||"application/octet-stream"},3e4).then(function(){})},get:function(e){return Ue._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 Ue._request("FILE_STORAGE_REMOVE",{key:e}).then(function(){})}}),je.game=function(n){const r={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 i=this;return"direct"===(n.config&&n.config.connectionMode||"platform")?i.connectDirect():i._useProxy&&i.connected||i.socket&&i.connected?Promise.resolve():i._connecting&&i._connectPromise?i._connectPromise:window.__USION_PROXY__||window.parent!==window||window.ReactNativeWebView||n._isEmbedded?(n.log("Running in iframe – using parent app as socket proxy"),i._connectViaProxy()):(e=e||n.config.socketUrl,t=t||n.user.getToken(),e?t?(i._connecting=!0,i._connectPromise=new Promise(function(n,r){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 i._connecting=!1,void r(new Error("Failed to load Socket.IO client"));var a=document.createElement("script");a.src=o[c],a.onload=function(){i._initSocket(e,t,n,r)},a.onerror=function(){s(c+1)},document.head.appendChild(a)}(0)}else i._initSocket(e,t,n,r)}),i._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),i=this._eventHandlers[e];if(i)try{i.apply(null,t)}catch(t){n.log("game handler error ("+e+"): "+t.message)}const r=this._listeners[e];if(r&&r.length){const i=r.slice();for(let r=0;r<i.length;r++)try{i[r].apply(null,t)}catch(t){n.log("game listener error ("+e+"): "+t.message)}}},on:function(e,t){const n=this,i=function(e){let t=String(e||"");if(0===t.indexOf("game:")&&(t=t.slice(5)),qe[t])return qe[t];const n=t.replace(/([A-Z])/g,function(e){return"_"+e.toLowerCase()});return qe[n]||t}(e);return n._listeners[i]||(n._listeners[i]=[]),n._listeners[i].push(t),function(){const e=n._listeners[i];if(!e)return;const r=e.indexOf(t);r>=0&&e.splice(r,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,i=e.serviceId||t.config.serviceId,r=e.apiUrl||t.config.apiUrl||"",o=e.token||t.user.getToken();if(!n)return Promise.reject(new Error("No room ID provided"));if(!i)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:i,protocol_version:e.protocolVersion||t.config.protocolVersion||t.config.protocol_version||"2"},1e4);if(!r)return Promise.reject(new Error("No API URL provided"));if(!o)return Promise.reject(new Error("No auth token available"));var s=String(r).replace(/\/$/,"")+"/games/rooms/"+encodeURIComponent(n)+"/access";return fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o},body:JSON.stringify({service_id:i,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,i){if(e&&e.ws_url&&e.access_token){var r=e.ws_url,o=-1===r.indexOf("?")?"?":"&",s=r+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){}i(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),i(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 i(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 i=Math.min(1e3*Math.pow(2,t-1),15e3);setTimeout(n,i)}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 i=this._pongWaiters&&this._pongWaiters.length?this._pongWaiters.shift():null;return this._resOnPong&&this._resOnPong(i),i&&i(),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)}}}(r,n),R(r,n),function(e,t){e._initSocket=function(e,n,i,r){const o=this;if(o.socket&&o.socket.connected)return o._connecting=!1,void i();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),i()}),o.socket.on("connect_error",function(e){o._connecting=!1,t.log("Game socket error: "+e.message),o._dispatch("connectionError",e),r(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){r(e)}}}(r,n),function(n,r){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(i,o){n._proxyConnectResolve=function(){n.connected=!0,n._connecting=!1,r.log("Game socket connected via parent proxy"),i()},r._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(d(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(i(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":r.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)}}}))}}(r,n),function(n,r){function o(e){const t=e.roomId||r.config&&r.config.roomId,n=e.playerId||r.user&&"function"==typeof r.user.getId&&r.user.getId()||r.config&&r.config.userId;return t&&n?"_usion_game_state:"+n+":"+t:null}n.join=function(n){const o=this;if(n=n||r.config.roomId,o.roomId===n&&o._joinPromise)return o._joinPromise;if(o.roomId=n,o.playerId=r.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 i=new Promise(function(i,s){const c=function(e){s(e)};o._proxyJoinResolve=i,o._proxyJoinReject=c,r._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 q(o,i)}let s;return s=o.socket&&o.connected?n?M(o.socket,"game:join",{room_id:n},15e3,e.JOIN_TIMEOUT).then(function(e){if(e.error)throw o._joined=!1,i(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")),q(o,s)},n.joinWorld=function(e){const t=this;return e=e||{},r.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._playersConnection&&e._playersConnection.close(),e.directMode?(e.roomId&&e._sendDirect("leave",{}),e.roomId=null,e._lastSequence=0,e._joined=!1,void(e._joinPromise=null)):e._useProxy?(e.roomId&&r._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,i,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:i||{}}),Promise.resolve({success:!0});if(a&&!s.connected)return s._queueOfflineAction(n,i,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:i};return c&&(o.next_turn=c),r._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,i,o);throw new t(e.NOT_CONNECTED,"Not connected")}const r={room_id:s.roomId,action_type:n,action_data:i};return c&&(r.next_turn=c),s._emitAction(r,!0)})},n._emitAction=function(n,r){const o=this;return o.socket&&o.connected?M(o.socket,"game:action",n).then(function(t){if(t.error){const s=i(t);if(r&&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();r.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){r.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,i,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)")):(r.log("Queued action while offline: "+n),new Promise(function(e,t){s._offlineQueue.push({actionType:n,actionData:i,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();r.log("Flushing "+n.length+" queued action(s) after reconnect");const o=Promise.resolve().then(function r(){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),r()},function(t){const s=i(t);if(s.code!==e.NOT_CONNECTED&&s.code!==e.NOT_IN_ROOM)return n[0]===o&&n.shift(),o.reject(t),r()})});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,c=n&&1===n.__usionSyncedState&&Number.isSafeInteger(n.seq)&&n.seq>=0&&n.seq<=s?n.seq:s;return o._useProxy?r._request("GAME_SET_STATE",{room_id:o.roomId,state:n||{},sequence:c}).then(function(e){if(e&&e.error){const t=i(e);return{success:!1,error:t.message,code:t.code}}return e||{success:!0}}).catch(function(t){const n=i(t,e.REQUEST_TIMEOUT);return{success:!1,error:n.message,code:n.code}}):o.socket&&o.connected?M(o.socket,"game:set_state",{room_id:o.roomId,state:n||{},sequence:c}).then(function(e){if(e.error){const t=i(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?r._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=i(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?r._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?r._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?(r._post({type:"GAME_FORFEIT",room_id:n.roomId}),Promise.resolve({success:!0})):n.socket&&n.connected?M(n.socket,"game:forfeit",{room_id:n.roomId}).then(function(e){if(e.error)throw i(e);return e}):Promise.reject(new t(e.NOT_CONNECTED,"Not connected"))},n.reportResult=function(n,i){if(i=i||{},!((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||r.config&&r.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)),r._backendEmit("gc:match_result",{service_id:i.serviceId||r.config&&r.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),i=t.roomId||r.config&&r.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:i,invited:[]})}const o={roomId:i};return"number"==typeof e.maxPlayers&&e.maxPlayers>0&&(o.maxPlayers=e.maxPlayers),r._request("GAME_INVITE_REQUEST",o,e.timeout||12e4).then(function(e){const n=(e=e||{}).roomId||i||null,r={success:!!e.success,roomId:n,invited:Array.isArray(e.invited)?e.invited:[]};return r.success&&n?Promise.resolve().then(function(){return t.connect()}).then(function(){return t.join(n)}).then(function(){return r}).catch(function(){return r}):r}).catch(function(){return{success:!1,roomId:i,invited:[]}})},n.disconnect=function(){const e=this;if(e._playersConnection&&e._playersConnection.close(),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 r._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 i=Object.assign({},e||{});i._diag=r.diagnostics?r.diagnostics():void 0,r._post({type:"GAME_DEBUG",payload:i})}}catch(e){}},n.isMultiplayer=function(){return"multiplayer"===r.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)}}(r,n),Oe(r,n),function(e,t){e.connectPlayers=function(n={}){if(e._playersConnection&&!e._playersConnection.closed)return e._playersPromise;if(e.directMode||"direct"===t.config.connectionMode)return Promise.reject(new Error("connectPlayers requires platform room signaling"));if(!Re(t.user.getId()))return Promise.reject(new Error("Initialize Usion before connectPlayers"));if(void 0!==n.directTimeoutMs&&(!Number.isFinite(n.directTimeoutMs)||n.directTimeoutMs<1e3||n.directTimeoutMs>3e4))return Promise.reject(new Error("directTimeoutMs must be 1000–30000"));const i=e._playersConnection=new Me(e,t,n);return e._playersPromise=i.start().catch(e=>{throw i.close(),e}),e._playersPromise}}(r,n),function(e,t){e.getParticipants=async function(){const e=this.roomId;if(!e)throw new Error("Join a room before reading participants");for(let n=0;n<5;n++){const i=t.user.getToken();if(!i){if(n<4){await new Promise(e=>setTimeout(e,500));continue}throw new Error("Participant access needs an authenticated Usions session")}const r=String(t.config.apiUrl||"").replace(/\/$/,"");if(!r)throw new Error("No API URL provided");const o=await fetch(r+"/games/rooms/"+encodeURIComponent(e)+"/participants",{headers:{Authorization:"Bearer "+i},cache:"no-store"});if(401===o.status&&n<4){await new Promise(e=>setTimeout(e,500));continue}if(!o.ok)throw new Error("Participant access failed: HTTP "+o.status);const s=await o.json();if(this.roomId!==e)throw new Error("Room changed while loading participants");return s}}}(r,n),function(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 i(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",i),e.on("playerJoined",i),ke(e,t)}(r,n),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("visibilitychange",function(){if("visible"===document.visibilityState&&r.roomId)try{r.requestSync()}catch(e){}}),r}(je),je.UsionError=t,je.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 i=t._backendHandlers[e];i&&i(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,r,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,r||{},function(e){u||(u=!0,clearTimeout(l),e&&e.error?a(i(e)):c(e))})}catch(e){clearTimeout(l),a(i(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:r||{}},o).catch(function(e){throw i(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"))}}(je),je.lobby=function(e){const t={code:null,host:null,status:null,members:[]},n={};let i=!1;function r(){i||(i=!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 r(),e._backendEmit(t,n)}return{get state(){return t},onUpdate:function(e){n.update=e,r()},onStarted:function(e){n.started=e,r()},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 i=e.config&&e.config.apiUrl||"",r=e.user&&e.user.getToken&&e.user.getToken();if(!i)throw new Error("No apiUrl configured");const o=await fetch(i.replace(/\/$/,"")+"/games/matchmake",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r},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()}}}(je),je.leaderboard=function(e){function t(t){return t&&t.serviceId||e.config&&e.config.serviceId}return{submit:function(n,i,r){return e._backendEmit("lb:submit",{service_id:t(r),score:n,metadata:null!=i?i:null})},scores:function(n,i){var r=Array.isArray(n)?n:[n];return e._backendEmit("lb:scores",{service_id:t(i),user_ids:r}).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)})}}}(je),je.cloud=function(e){function t(t){return t&&t.serviceId||e.config&&e.config.serviceId}function n(n,i,r,o){var s=Object.assign({service_id:t(o),scope:i},r);return e._backendEmit(n,s)}function i(e){return{get:function(t,i){return n("kv:get",e,{key:t},i).then(function(e){return e&&e.exists?e.value:null})},set:function(t,i,r){return n("kv:set",e,{key:t,value:i},r)},remove:function(t,i){return n("kv:remove",e,{key:t},i)},keys:function(t){return n("kv:keys",e,{},t).then(function(e){return e&&e.keys||[]})}}}var r=i("user");return r.shared=i("shared"),r.friends=i("friends"),r.friends.list=function(e,t){return n("kv:get","friends",{key:e,friends:!0},t).then(function(e){return(e&&e.entries||[]).map(function(e){return{userId:e.user_id,name:e.name||null,avatar:e.avatar||null,value:e.value,updatedAt:e.updated_at||null}})})},r.shared.incr=function(e,t,i){return n("kv:incr","shared",{key:e,delta:null==t?1:t},i).then(function(e){return e&&e.value})},r}(je),je.matchmaking=function(n){let r=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),r){const e=r;r=null,e.resolve(t)}}))}function u(o,s,u){if(a(),r){const n=r;r=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),r===d&&(r=null),t(e)}});return r=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&&r===d&&(r=null,d.resolve(c(e)))}).catch(function(e){r===d&&d.reject(i(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(r){const n=r;r=null,n.reject(new t(e.CANCELLED,"cancelled"))}return n._backendEmit("mm:cancel",{})}}}(je),je.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,i){return e._backendEmit("notify:set_pref",{service_id:t(i),muted:!!n})},isMuted:function(n){return e._backendEmit("notify:get_pref",{service_id:t(n)}).then(function(e){return!(!e||!e.muted)})}}}(je),je.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 i(e){const t={};return e.forEach(function(e){t[e]=!1}),t}function r(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(s,c){const a=t(s),l=c&&"string"==typeof c.reason?c.reason:void 0;if(!n()){try{console.warn("[Usion] permissions.request needs the Usion app; resolving as not granted.")}catch(e){}return Promise.resolve(r(a,i(a)))}return new Promise(function(t){const n=u();let s=!1,c=null;function f(e){s||(s=!0,c&&clearTimeout(c),window.removeEventListener("message",h),t(e))}function h(e){if(!d(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(r(a,t.permissions))}window.addEventListener("message",h),c=setTimeout(function(){s||o.query(a).then(function(e){f(r(a,e))}).catch(function(){f(r(a,i(a)))})},o._requestTimeoutMs||12e4),e._post({type:"PERMISSION_REQUEST",_requestId:n,permissions:a,reason:l})})},query:function(r){const o=t(r);return n()?e._request("PERMISSION_QUERY",{permissions:o},8e3).then(function(e){return e&&e.permissions||{}}):Promise.resolve(i(o))},has:function(e){return o.query([e]).then(function(t){return!(!t||!t[e])})}};return o}(je),je.screen=function(e){var t=[],n=!1;function i(e){if(d(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 i="string"==typeof n.kind&&n.kind?n.kind:"screenshot",r=t.slice(),o=0;o<r.length;o++)try{r[o]({kind:i})}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",i),n=!0);var r=!1;return function(){if(!r){r=!0;var o=t.indexOf(e);o>=0&&t.splice(o,1),0===t.length&&function(){if(n){try{window.removeEventListener("message",i)}catch(e){}n=!1}}()}}},support:function(){var t=e.config&&e.config.screenCapture||null;return{block:!(!t||!t.block),detect:!(!t||!t.detect)}}}}(je),je.profile=function(n){function i(i,r){return"undefined"!=typeof window&&("ReactNativeWebView"in window||window.parent!==window)?n._request(i,r,3e4):Promise.reject(new t(e.UNSUPPORTED,"Profile content requires the Usion host"))}return{getContent:()=>i("PROFILE_CONTENT_GET",{}).then(e=>e.content),setContent:n=>!n||!Array.isArray(n.items)||n.items.length>50?Promise.reject(new t(e.INVALID_INPUT,"Profile content requires at most 50 items")):i("PROFILE_CONTENT_SET",{content:n}).then(e=>e.content),clearContent:()=>i("PROFILE_CONTENT_CLEAR",{}).then(()=>{})}}(je),je.call=function(e){return Object.assign(s(e),{capabilities:function(){return e._request("CALL_CAPABILITIES",{},5e3)},startAnalysis:async function(t){if(!t||!Array.isArray(t.capabilities)||"function"!=typeof t.onSample)throw new Error("capabilities and onSample are required");var n=null,i=!1,r=e.on("CALL_ANALYSIS_EVENT",function(e){i||null===n||e.subscriptionId!==n||t.onSample(e.sample)}),o=e.on("CALL_ANALYSIS_STOPPED",function(e){e.subscriptionId===n&&s()});function s(){i||(i=!0,r(),o(),"function"==typeof t.onStopped&&t.onStopped())}try{var c=await e._request("CALL_ANALYSIS_START",{capabilities:t.capabilities},12e4);if(!c.started||!Number.isInteger(c.subscriptionId))throw new Error("Invalid call analysis response");return n=c.subscriptionId,{stop:async function(){i||(s(),await e._request("CALL_ANALYSIS_STOP",{},5e3))}}}catch(e){throw s(),e}}})}(je),je.netcode=De,Object.assign(je,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||[]}}}(je)),Object.assign(je,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"})}}}(je)),Object.assign(je,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})}}}(je)),Object.assign(je,w),Object.assign(je,b),Object.assign(je,P),je}();"undefined"!=typeof window?window.Usion=Usion:"undefined"!=typeof globalThis&&(globalThis.Usion=Usion);
@@ -118,29 +118,68 @@ export const appLinkMethods = {
118
118
  return feature === 'image' ? features.feedShareImage === true : feature === 'video' ? features.feedShareVideo === true : feature === 'videoUpload' ? features.feedShareVideoUpload === true : !feature;
119
119
  },
120
120
 
121
- /** Upload a video directly, without crossing the host bridge as base64.
121
+ /** Upload a video in bounded, retryable parts, without sending it through the host bridge.
122
122
  * @param {Blob} file
123
+ * @param {{requestId?: string, signal?: AbortSignal, onProgress?: (progress: {loaded: number, total: number}) => void}} [options]
123
124
  * @returns {Promise<{receipt: string}>}
124
125
  */
125
- uploadFeedVideo: function(file) {
126
- if (!this.canShareToFeed('videoUpload')) return Promise.reject(new UsionError(ERROR_CODES.UNSUPPORTED, 'Video uploads require a newer host'));
126
+ uploadFeedVideo: async function(file, options) {
127
+ if (!this.canShareToFeed('videoUpload')) throw new UsionError(ERROR_CODES.UNSUPPORTED, 'Video uploads require a newer host');
127
128
  var allowed = ['video/mp4', 'video/quicktime', 'video/webm', 'video/x-matroska'];
128
- if (!file || typeof file.size !== 'number' || file.size <= 0 || file.size > 100 * 1024 * 1024 || allowed.indexOf(file.type) < 0) {
129
- return Promise.reject(new UsionError(ERROR_CODES.INVALID_INPUT, 'Choose a supported video of at most 100 MB'));
129
+ if (!file || typeof file.size !== 'number' || typeof file.slice !== 'function' || file.size <= 0 || file.size > 3 * 1024 * 1024 * 1024 || allowed.indexOf(file.type) < 0) {
130
+ throw new UsionError(ERROR_CODES.INVALID_INPUT, 'Choose a supported video of at most 3 GiB');
130
131
  }
131
- var token = this.user && this.user.getToken(), config = this.config || {};
132
- if (!token || !config.serviceId || !config.apiUrl) return Promise.reject(new UsionError(ERROR_CODES.NOT_AUTHENTICATED, 'Sign in to upload'));
133
- var form = new FormData();
134
- form.append('file', file, file.name || 'video');
135
- return fetch(config.apiUrl.replace(/\/$/, '') + '/feed/video-uploads/' + encodeURIComponent(config.serviceId), {
136
- method: 'POST', headers: { Authorization: 'Bearer ' + token }, body: form
137
- }).then(function(response) {
132
+ var sdk = this, config = this.config || {}, opts = options || {};
133
+ if (!sdk.user || !sdk.user.getToken() || !config.serviceId || !config.apiUrl) throw new UsionError(ERROR_CODES.NOT_AUTHENTICATED, 'Sign in to upload');
134
+ var base = config.apiUrl.replace(/\/$/, '') + '/feed/video-uploads/' + encodeURIComponent(config.serviceId) + '/multipart';
135
+ var sessionId = null;
136
+ async function call(url, method, body, contentType) {
137
+ var headers = { Authorization: 'Bearer ' + sdk.user.getToken() };
138
+ if (contentType) headers['Content-Type'] = contentType;
139
+ var response = await fetch(url, { method: method, headers: headers, body: body, signal: opts.signal });
138
140
  if (!response.ok) throw new UsionError(response.status === 429 ? ERROR_CODES.RATE_LIMITED : response.status === 401 ? ERROR_CODES.NOT_AUTHENTICATED : response.status === 403 ? ERROR_CODES.PERMISSION_DENIED : response.status < 500 ? ERROR_CODES.INVALID_INPUT : ERROR_CODES.UNKNOWN, 'Video upload failed');
139
141
  return response.json();
140
- }).then(function(result) {
142
+ }
143
+ function progress(loaded) {
144
+ if (typeof opts.onProgress === 'function') { try { opts.onProgress({ loaded: loaded, total: file.size }); } catch (_) {} }
145
+ }
146
+ try {
147
+ var state = await call(base, 'POST', JSON.stringify({ request_id: opts.requestId || newRequestId(), file_size: file.size, file_type: file.type }), 'application/json');
148
+ sessionId = state.file_id;
149
+ if (typeof sessionId !== 'string' || !sessionId) throw new UsionError(ERROR_CODES.UNKNOWN, 'Invalid upload session');
150
+ var path = base + '/' + encodeURIComponent(sessionId);
151
+ state = await call(path, 'GET');
152
+ if (state.status !== 'ready' && state.status !== 'completing') {
153
+ var size = state.part_size, completed = new Set(state.uploaded_parts || []), sent = 0;
154
+ if (!Number.isInteger(size) || size < 1) throw new UsionError(ERROR_CODES.UNKNOWN, 'Invalid upload part size');
155
+ for (var n = 1, offset = 0; offset < file.size; n++, offset += size) {
156
+ var chunk = file.slice(offset, Math.min(offset + size, file.size));
157
+ if (!completed.has(n)) {
158
+ for (var attempt = 0; ; attempt++) {
159
+ try { await call(path + '/parts/' + n, 'PUT', chunk, 'application/octet-stream'); break; }
160
+ catch (error) {
161
+ if (opts.signal && opts.signal.aborted) throw error;
162
+ if (attempt >= 2 || (error instanceof UsionError && error.code !== ERROR_CODES.UNKNOWN)) throw error;
163
+ await new Promise(function(resolve) { setTimeout(resolve, 500 * (attempt + 1)); });
164
+ }
165
+ }
166
+ }
167
+ sent += chunk.size; progress(sent);
168
+ }
169
+ }
170
+ var result = await call(path + '/complete', 'POST');
141
171
  if (!result || typeof result.receipt !== 'string') throw new UsionError(ERROR_CODES.UNKNOWN, 'Invalid upload response');
172
+ progress(file.size);
142
173
  return { receipt: result.receipt };
143
- });
174
+ } catch (error) {
175
+ // Explicit cancellation aborts the multipart session; other failures can
176
+ // resume with the same requestId, and abandoned uploads expire server-side.
177
+ if (opts.signal && opts.signal.aborted && sessionId) {
178
+ try { await fetch(base + '/' + encodeURIComponent(sessionId), { method: 'DELETE', headers: { Authorization: 'Bearer ' + sdk.user.getToken() } }); } catch (_) {}
179
+ throw new UsionError(ERROR_CODES.CANCELLED, 'Video upload cancelled');
180
+ }
181
+ throw error;
182
+ }
144
183
  },
145
184
 
146
185
  /**
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Usion.call voice — a game's own mic button.
3
+ *
4
+ * `micOn({ channel })` joins a named voice channel of this game with the mic
5
+ * on; everyone in the same channel talks. The host app does the audio, the mic
6
+ * permission, safety (mute, block, report) and limits — the game only ever
7
+ * sees state and events, never streams or tokens.
8
+ */
9
+ import { UsionError, ERROR_CODES } from './errors.js';
10
+
11
+ const CHANNEL_RE = /^[a-z0-9][a-z0-9_-]{0,47}$/;
12
+
13
+ /** @returns {import('../../types/index').VoiceState} */
14
+ function idleState() {
15
+ return { on: false, channel: null, scope: null, status: 'idle', micOn: false, peers: [] };
16
+ }
17
+
18
+ /**
19
+ * @param {any} raw
20
+ * @returns {import('../../types/index').VoiceState}
21
+ */
22
+ function normalizeState(raw) {
23
+ if (!raw || typeof raw !== 'object') return idleState();
24
+ const peers = Array.isArray(raw.peers) ? raw.peers : [];
25
+ return {
26
+ on: !!raw.on,
27
+ channel: typeof raw.channel === 'string' ? raw.channel : null,
28
+ scope: raw.scope === 'room' || raw.scope === 'game' ? raw.scope : null,
29
+ status: ['idle', 'connecting', 'connected', 'reconnecting'].indexOf(raw.status) >= 0 ? raw.status : 'idle',
30
+ micOn: !!raw.micOn,
31
+ peers: peers
32
+ .filter(/** @param {any} p */ function (p) { return p && typeof p.userId === 'string'; })
33
+ .map(/** @param {any} p */ function (p) {
34
+ return {
35
+ userId: p.userId,
36
+ name: typeof p.name === 'string' ? p.name : '',
37
+ isMe: !!p.isMe,
38
+ micOn: !!p.micOn,
39
+ speaking: !!p.speaking,
40
+ };
41
+ }),
42
+ };
43
+ }
44
+
45
+ /** @param {(...args: any[]) => void} cb @param {any} value */
46
+ function safeCall(cb, value) {
47
+ try { cb(value); } catch (e) { console.error('[Usion] call voice listener error:', e); }
48
+ }
49
+
50
+ /**
51
+ * @param {{ _request: (type: string, data: object, timeout: number) => Promise<any>, on: (type: string, cb: (e: any) => void) => (() => void), config?: any }} Usion
52
+ */
53
+ export function createVoiceApi(Usion) {
54
+ let last = idleState();
55
+ /** @type {Set<(s: import('../../types/index').VoiceState) => void>} */
56
+ const changeListeners = new Set();
57
+ /** @type {Set<(ids: string[]) => void>} */
58
+ const speakingListeners = new Set();
59
+ let wired = false;
60
+
61
+ function isAvailable() {
62
+ const features = Usion.config && Usion.config.hostFeatures;
63
+ return !!(features && features.voice);
64
+ }
65
+
66
+ function wire() {
67
+ if (wired) return;
68
+ wired = true;
69
+ Usion.on('CALL_VOICE_CHANGED', function (event) {
70
+ if (event && event.state) setState(event.state);
71
+ });
72
+ Usion.on('CALL_VOICE_SPEAKING', function (event) {
73
+ const ids = event && Array.isArray(event.userIds)
74
+ ? event.userIds.filter(/** @param {any} id */ function (id) { return typeof id === 'string'; })
75
+ : [];
76
+ speakingListeners.forEach(function (cb) { safeCall(cb, ids); });
77
+ });
78
+ }
79
+
80
+ /** @param {any} raw */
81
+ function setState(raw) {
82
+ last = normalizeState(raw);
83
+ changeListeners.forEach(function (cb) { safeCall(cb, last); });
84
+ return last;
85
+ }
86
+
87
+ /**
88
+ * @param {string} type @param {object} data @param {number} timeout
89
+ * @returns {Promise<import('../../types/index').VoiceState>}
90
+ */
91
+ function request(type, data, timeout) {
92
+ if (!isAvailable()) {
93
+ return Promise.reject(new UsionError(ERROR_CODES.VOICE_UNSUPPORTED,
94
+ 'Voice needs a newer version of the Usion app'));
95
+ }
96
+ wire();
97
+ return Usion._request(type, data, timeout).then(function (result) {
98
+ return result && result.state ? setState(result.state) : last;
99
+ });
100
+ }
101
+
102
+ return {
103
+ isAvailable: isAvailable,
104
+
105
+ /** @param {{ channel?: string, scope?: 'room'|'game', listen?: boolean }} [opts] */
106
+ micOn: function (opts) {
107
+ const o = opts || {};
108
+ const channel = o.channel == null ? 'main' : o.channel;
109
+ const scope = o.scope == null ? 'room' : o.scope;
110
+ if (typeof channel !== 'string' || !CHANNEL_RE.test(channel)) {
111
+ return Promise.reject(new UsionError(ERROR_CODES.VOICE_BAD_CHANNEL,
112
+ "Channel names are 1-48 of a-z, 0-9, '-', '_' and start with a letter or digit"));
113
+ }
114
+ if (scope !== 'room' && scope !== 'game') {
115
+ return Promise.reject(new UsionError(ERROR_CODES.VOICE_BAD_CHANNEL, "scope must be 'room' or 'game'"));
116
+ }
117
+ // 60s: the first time this covers the host's permission prompts.
118
+ return request('CALL_VOICE_ON', { channel: channel, scope: scope, listen: !!o.listen }, 60000);
119
+ },
120
+
121
+ micOff: function () {
122
+ return request('CALL_VOICE_OFF', {}, 5000).then(function () { return undefined; });
123
+ },
124
+
125
+ /** @param {boolean} on */
126
+ setMic: function (on) {
127
+ return request('CALL_VOICE_SET_MIC', { on: !!on }, 5000);
128
+ },
129
+
130
+ /** @param {string} userId @param {boolean} [muted] */
131
+ mutePeer: function (userId, muted) {
132
+ if (typeof userId !== 'string' || !userId) {
133
+ return Promise.reject(new UsionError(ERROR_CODES.INVALID_INPUT, 'userId required'));
134
+ }
135
+ return request('CALL_VOICE_MUTE_PEER', { userId: userId, muted: muted !== false }, 5000)
136
+ .then(function () { return undefined; });
137
+ },
138
+
139
+ state: function () {
140
+ if (!isAvailable()) return Promise.resolve(idleState());
141
+ return request('CALL_VOICE_STATE', {}, 5000);
142
+ },
143
+
144
+ /** @param {(s: import('../../types/index').VoiceState) => void} callback */
145
+ onChange: function (callback) {
146
+ wire();
147
+ changeListeners.add(callback);
148
+ // A listener added mid-call learns the current state once.
149
+ if (last.on) {
150
+ const current = last;
151
+ Promise.resolve().then(function () {
152
+ if (changeListeners.has(callback) && last === current) safeCall(callback, current);
153
+ });
154
+ }
155
+ return function () { changeListeners.delete(callback); };
156
+ },
157
+
158
+ /** @param {(userIds: string[]) => void} callback */
159
+ onSpeaking: function (callback) {
160
+ wire();
161
+ speakingListeners.add(callback);
162
+ return function () { speakingListeners.delete(callback); };
163
+ },
164
+ };
165
+ }
@@ -1,10 +1,12 @@
1
1
  /** Permission-gated, local call signals. Streams and device handles never cross this API. */
2
+ import { createVoiceApi } from './call-voice.js';
3
+
2
4
  /**
3
5
  * @param {{ _request: (type: string, data: object, timeout: number) => Promise<any>, on: (type: string, callback: (event: any) => void) => (() => void) }} Usion
4
6
  * @returns {import('../../types/index').CallModule}
5
7
  */
6
8
  export function createCallModule(Usion) {
7
- return {
9
+ return Object.assign(createVoiceApi(Usion), {
8
10
  capabilities: function () {
9
11
  return Usion._request('CALL_CAPABILITIES', {}, 5000);
10
12
  },
@@ -42,5 +44,5 @@ export function createCallModule(Usion) {
42
44
  };
43
45
  } catch (error) { cleanup(); throw error; }
44
46
  },
45
- };
47
+ });
46
48
  }
@@ -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.33.0', // synced from package.json by scripts/sync-version.mjs
71
+ version: '2.35.0', // synced from package.json by scripts/sync-version.mjs
72
72
  config: {},
73
73
  _initialized: false,
74
74
  _initCallback: null,
@@ -38,6 +38,17 @@ export const ERROR_CODES = {
38
38
  CANCELLED: 'CANCELLED', // Cancelled by a local cancel() call
39
39
  SUPERSEDED: 'SUPERSEDED', // Replaced by a newer identical request
40
40
  UNSUPPORTED: 'UNSUPPORTED', // Not available in this transport
41
+ VOICE_UNSUPPORTED: 'VOICE_UNSUPPORTED', // Host app too old for Usion.call voice
42
+ VOICE_DISABLED: 'VOICE_DISABLED', // Voice turned off for this game / platform
43
+ VOICE_UNAVAILABLE: 'VOICE_UNAVAILABLE', // Voice can't run here (private game, no channel)
44
+ VOICE_NO_ROOM: 'VOICE_NO_ROOM', // scope 'room' channel but no game room
45
+ VOICE_NOT_IN_ROOM: 'VOICE_NOT_IN_ROOM', // Not seated in the game room
46
+ VOICE_BAD_CHANNEL: 'VOICE_BAD_CHANNEL', // Invalid channel name or scope
47
+ VOICE_FULL: 'VOICE_FULL', // Channel at its participant cap
48
+ VOICE_DECLINED: 'VOICE_DECLINED', // User said no to the mic / to leaving a call
49
+ VOICE_MIC_DENIED: 'VOICE_MIC_DENIED', // OS microphone permission denied
50
+ VOICE_GUEST: 'VOICE_GUEST', // Web guest: log in to talk
51
+ VOICE_FAILED: 'VOICE_FAILED', // Couldn't connect (network)
41
52
  UNKNOWN: 'UNKNOWN', // Unmapped error (see message)
42
53
  };
43
54
 
package/types/index.d.ts CHANGED
@@ -47,7 +47,7 @@ export interface UsionConfig {
47
47
  * Host capabilities declared in INIT. Absent on older app builds — read
48
48
  * `feedShare` via `Usion.canShareToFeed()`. (SDK ≥ 2.33)
49
49
  */
50
- hostFeatures?: { feedShare?: boolean; feedShareImage?: boolean; feedShareVideo?: boolean; [feature: string]: boolean | undefined };
50
+ hostFeatures?: { feedShare?: boolean; feedShareImage?: boolean; feedShareVideo?: boolean; voice?: boolean; [feature: string]: boolean | undefined };
51
51
  }
52
52
 
53
53
  // ─── Payment ─────────────────────────────────────────────────────
@@ -196,7 +196,7 @@ export interface ShareToFeedData {
196
196
  image?: string;
197
197
  /** MP4 base64 data URL, at most 5 MB decoded; requires canShareToFeed('video'). */
198
198
  video?: string;
199
- /** Signed receipt returned by uploadFeedVideo (100 MB maximum). */
199
+ /** Signed receipt returned by uploadFeedVideo (3 GiB maximum). */
200
200
  videoReceipt?: string;
201
201
  /** @deprecated Ignored by current hosts. */
202
202
  media?: Array<{ type: 'image' | 'video' | 'audio'; url: string; thumbnailUrl?: string; width?: number; height?: number; duration?: number }>;
@@ -1227,7 +1227,51 @@ export type CallAnalysisCapability = 'headPosition' | 'voiceActivity';
1227
1227
  export type CallAnalysisSample =
1228
1228
  | { kind: 'face'; detected: boolean; x: number; y: number }
1229
1229
  | { kind: 'voice'; speaking: boolean };
1230
+ /** Where a voice channel lives: one game room (seated players only) or the whole game. */
1231
+ export type VoiceScope = 'room' | 'game';
1232
+ export interface VoicePeer {
1233
+ userId: string;
1234
+ name: string;
1235
+ isMe: boolean;
1236
+ micOn: boolean;
1237
+ speaking: boolean;
1238
+ }
1239
+ export interface VoiceState {
1240
+ /** I'm in a voice channel. */
1241
+ on: boolean;
1242
+ channel: string | null;
1243
+ scope: VoiceScope | null;
1244
+ status: 'idle' | 'connecting' | 'connected' | 'reconnecting';
1245
+ /** My mic is live. */
1246
+ micOn: boolean;
1247
+ /** Everyone in my channel, me included. */
1248
+ peers: VoicePeer[];
1249
+ }
1250
+ export interface MicOnOptions {
1251
+ /** Channel name the game picks: 1-48 of a-z, 0-9, '-', '_'. Default 'main'. */
1252
+ channel?: string;
1253
+ /** 'room' (default): only players seated in the current game room. 'game': everyone in this game using the same name. */
1254
+ scope?: VoiceScope;
1255
+ /** Join hearing others with the mic still off (spectators). Default false. */
1256
+ listen?: boolean;
1257
+ }
1230
1258
  export interface CallModule {
1259
+ /** True when the host app supports voice (SDK 2.35+ host). */
1260
+ isAvailable(): boolean;
1261
+ /** Join a voice channel with the mic on. Call it from a user tap — the host asks for the mic the first time. */
1262
+ micOn(options?: MicOnOptions): Promise<VoiceState>;
1263
+ /** Leave the voice channel. */
1264
+ micOff(): Promise<void>;
1265
+ /** Stay in the channel, stop or start talking. */
1266
+ setMic(on: boolean): Promise<VoiceState>;
1267
+ /** Only I stop (or start again) hearing this person. */
1268
+ mutePeer(userId: string, muted?: boolean): Promise<void>;
1269
+ /** Current state; idle when the host has no voice support. */
1270
+ state(): Promise<VoiceState>;
1271
+ /** Joins, leaves, mic and connection changes. */
1272
+ onChange(callback: (state: VoiceState) => void): UnsubscribeFn;
1273
+ /** Who is talking right now (at most 4 updates a second). */
1274
+ onSpeaking(callback: (userIds: string[]) => void): UnsubscribeFn;
1231
1275
  capabilities(): Promise<{ capabilities: CallAnalysisCapability[]; connected: boolean }>;
1232
1276
  startAnalysis(options: {
1233
1277
  capabilities: CallAnalysisCapability[];
@@ -1322,8 +1366,9 @@ export interface UsionSDK {
1322
1366
  * hosts drop it). `'video'` requires `feedShareVideo` (SDK ≥ 2.33.0-dev.9).
1323
1367
  */
1324
1368
  canShareToFeed(feature?: 'image' | 'video' | 'videoUpload'): boolean;
1325
- /** Upload a supported video directly; pass the returned receipt to shareToFeed. */
1326
- uploadFeedVideo(file: Blob): Promise<{ receipt: string }>;
1369
+ /** Upload a supported video (up to 3 GiB); pass its receipt to shareToFeed.
1370
+ * Keep requestId to resume the same file after an interruption. */
1371
+ uploadFeedVideo(file: Blob, options?: { requestId?: string; signal?: AbortSignal; onProgress?: (progress: { loaded: number; total: number }) => void }): Promise<{ receipt: string }>;
1327
1372
  /**
1328
1373
  * Post a short text to the signed-in user's Usions News Feed (it also shows
1329
1374
  * on their profile), stamped with this app and an optional in-app `path`.
@@ -1679,6 +1724,17 @@ export declare const ERROR_CODES: {
1679
1724
  readonly CANCELLED: 'CANCELLED';
1680
1725
  readonly SUPERSEDED: 'SUPERSEDED';
1681
1726
  readonly UNSUPPORTED: 'UNSUPPORTED';
1727
+ readonly VOICE_UNSUPPORTED: 'VOICE_UNSUPPORTED';
1728
+ readonly VOICE_DISABLED: 'VOICE_DISABLED';
1729
+ readonly VOICE_UNAVAILABLE: 'VOICE_UNAVAILABLE';
1730
+ readonly VOICE_NO_ROOM: 'VOICE_NO_ROOM';
1731
+ readonly VOICE_NOT_IN_ROOM: 'VOICE_NOT_IN_ROOM';
1732
+ readonly VOICE_BAD_CHANNEL: 'VOICE_BAD_CHANNEL';
1733
+ readonly VOICE_FULL: 'VOICE_FULL';
1734
+ readonly VOICE_DECLINED: 'VOICE_DECLINED';
1735
+ readonly VOICE_MIC_DENIED: 'VOICE_MIC_DENIED';
1736
+ readonly VOICE_GUEST: 'VOICE_GUEST';
1737
+ readonly VOICE_FAILED: 'VOICE_FAILED';
1682
1738
  readonly UNKNOWN: 'UNKNOWN';
1683
1739
  };
1684
1740