@idosgames/core 0.21.1 → 0.21.3

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.
@@ -1,2 +1,2 @@
1
- 'use strict';var o=class{getString(e){if(typeof localStorage>"u")return null;try{return localStorage.getItem(e)}catch{return null}}setString(e,r){if(!(typeof localStorage>"u"))try{localStorage.setItem(e,r);}catch{}}remove(e){if(!(typeof localStorage>"u"))try{localStorage.removeItem(e);}catch{}}},a=class{map=new Map;getString(e){return this.map.get(e)??null}setString(e,r){this.map.set(e,r);}remove(e){this.map.delete(e);}};function n(){return globalThis.Telegram?.WebApp??null}function s(){return crypto.randomUUID()}var g="idos_device_id",i=class{storage;constructor(e=new o){this.storage=e;}getPlatform(){return n()?.platform??"Web"}getFullURL(){return typeof location<"u"?location.href:""}getStartParameter(){let e=n()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){if(typeof document>"u")return null;let e=document.referrer;return e&&e.length>0?e:null}getTelegramInitDataRaw(){let e=n()?.initData;return e&&e.length>0?e:null}getDeviceID(){let e=this.storage.getString(g);return e||(e=s(),this.storage.setString(g,e)),e}getDeviceModel(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"Web"}shareLink(e){let r=n();if(r?.openTelegramLink){r.openTelegramLink(e);return}typeof window<"u"&&window.open(e,"_blank");}openInvoice(e){let r=n();if(r?.openInvoice){r.openInvoice(e);return}typeof window<"u"&&window.open(e,"_blank");}async showAd(e){let r=globalThis;typeof r.showAd=="function"&&await r.showAd(e);}async copyToClipboard(e){typeof navigator<"u"&&navigator.clipboard&&await navigator.clipboard.writeText(e);}};var p="idos_device_id",l=class{storage;constructor(e=new a){this.storage=e;}getPlatform(){return "Web"}getFullURL(){return ""}getStartParameter(){return null}getTelegramInitDataRaw(){return null}getDeviceID(){let e=this.storage.getString(p);return e||(e="noop-device",this.storage.setString(p,e)),e}getDeviceModel(){return "Noop"}shareLink(){}openInvoice(){}async showAd(){}async copyToClipboard(){}};var u=["https://idosgames.com","https://www.idosgames.com"];function m(t){return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t.endsWith(".localhost")}function f(t){if(u.includes(t))return true;if(typeof window>"u"||!m(window.location.hostname))return false;try{return m(new URL(t).hostname)}catch{return false}}
2
- exports.BrowserPlatformAdapter=i;exports.BrowserStorage=o;exports.MemoryStorage=a;exports.NoopPlatformAdapter=l;exports.PLATFORM_ORIGINS=u;exports.getTelegramWebApp=n;exports.isPlatformParentOrigin=f;
1
+ 'use strict';var i=class{getString(e){if(typeof localStorage>"u")return null;try{return localStorage.getItem(e)}catch{return null}}setString(e,r){if(!(typeof localStorage>"u"))try{localStorage.setItem(e,r);}catch{}}remove(e){if(!(typeof localStorage>"u"))try{localStorage.removeItem(e);}catch{}}},s=class{map=new Map;getString(e){return this.map.get(e)??null}setString(e,r){this.map.set(e,r);}remove(e){this.map.delete(e);}};function n(){return globalThis.Telegram?.WebApp??null}function I(){return crypto.randomUUID()}var S="idos_device_id",m=class{storage;constructor(e=new i){this.storage=e;}getPlatform(){return n()?.platform??"Web"}getFullURL(){return typeof location<"u"?location.href:""}getStartParameter(){let e=n()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){if(typeof document>"u")return null;let e=document.referrer;return e&&e.length>0?e:null}getTelegramInitDataRaw(){let e=n()?.initData;return e&&e.length>0?e:null}getDeviceID(){let e=this.storage.getString(S);return e||(e=I(),this.storage.setString(S,e)),e}getDeviceModel(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"Web"}shareLink(e){let r=n();if(r?.openTelegramLink){r.openTelegramLink(e);return}typeof window<"u"&&window.open(e,"_blank");}openInvoice(e){let r=n();if(r?.openInvoice){r.openInvoice(e);return}typeof window<"u"&&window.open(e,"_blank");}async showAd(e){let r=globalThis;typeof r.showAd=="function"&&await r.showAd(e);}async copyToClipboard(e){typeof navigator<"u"&&navigator.clipboard&&await navigator.clipboard.writeText(e);}};var _="idos_device_id",d=class{storage;constructor(e=new s){this.storage=e;}getPlatform(){return "Web"}getFullURL(){return ""}getStartParameter(){return null}getTelegramInitDataRaw(){return null}getDeviceID(){let e=this.storage.getString(_);return e||(e="noop-device",this.storage.setString(_,e)),e}getDeviceModel(){return "Noop"}shareLink(){}openInvoice(){}async showAd(){}async copyToClipboard(){}};var g=["https://idosgames.com","https://www.idosgames.com"];function v(t){return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t.endsWith(".localhost")}function p(t){if(g.includes(t))return true;if(typeof window>"u"||!v(window.location.hostname))return false;try{return v(new URL(t).hostname)}catch{return false}}var R="IDOS_PLATFORM_WALLET_ACK",U="PLATFORM_WALLET_UNAVAILABLE",h=5e3,E=18e4;function M(){let t=[...g],e=window.location.ancestorOrigins?.[0];return e&&!t.includes(e)&&p(e)&&t.push(e),t}function x(){return `wallet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function c(t,e,r,D={}){let u={ok:false,error:U,data:{}};if(typeof window>"u"||window.self===window.top)return Promise.resolve(u);let P=window.parent;if(!P)return Promise.resolve(u);let T=x(),L=D.answerTimeoutMs??E;return new Promise(O=>{let A=false,l,f=a=>{A||(A=true,window.removeEventListener("message",y),clearTimeout(l),O(a));},y=a=>{if(!p(a.origin))return;let o=a.data;if(!(!o||o.requestId!==T)){if(o.type===R){clearTimeout(l),l=setTimeout(()=>f({ok:false,error:"TIMEOUT",data:{}}),L);return}o.type===e&&f({ok:o.ok===true,error:typeof o.error=="string"?o.error:void 0,data:o});}};l=setTimeout(()=>f(u),h),window.addEventListener("message",y);for(let a of M())try{P.postMessage({type:t,requestId:T,...r},a);}catch{}})}var w={request:"IDOS_PLATFORM_TOPUP_REQUEST",response:"IDOS_PLATFORM_TOPUP_RESPONSE"},k=15*6e4,b=/^[a-z0-9]{8}-preview\.idos\.games$/;function W(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}return !b.test(window.location.hostname.toLowerCase())}async function F(t){let e=await c(w.request,w.response,{titleID:t.titleID,userID:t.userID,currencyID:t.currencyID,amount:t.amount},{answerTimeoutMs:k});return e.ok?{ok:true}:{ok:false,error:e.error}}
2
+ exports.BrowserPlatformAdapter=m;exports.BrowserStorage=i;exports.MemoryStorage=s;exports.NoopPlatformAdapter=d;exports.PLATFORM_BRIDGE_ACK=R;exports.PLATFORM_ORIGINS=g;exports.PLATFORM_PAGE_UNAVAILABLE=U;exports.PLATFORM_TOPUP_MESSAGES=w;exports.askPlatformPage=c;exports.canUsePlatformTopUp=W;exports.getTelegramWebApp=n;exports.isPlatformParentOrigin=p;exports.requestPlatformTopUp=F;
@@ -75,4 +75,58 @@ declare const PLATFORM_ORIGINS: readonly string[];
75
75
  */
76
76
  declare function isPlatformParentOrigin(origin: string): boolean;
77
77
 
78
- export { BrowserPlatformAdapter, BrowserStorage, KeyValueStorage, MemoryStorage, NoopPlatformAdapter, PLATFORM_ORIGINS, PlatformAdapter, type TelegramInitDataUnsafe, type TelegramWebApp, getTelegramWebApp, isPlatformParentOrigin };
78
+ /** Sent by the site the moment it receives any bridge request. Shared with the site — keep in step. */
79
+ declare const PLATFORM_BRIDGE_ACK = "IDOS_PLATFORM_WALLET_ACK";
80
+ /**
81
+ * The page around the game did not answer at all — an old site build without the bridge, or a
82
+ * parent that is not the platform. The value is the wallet bridge's historical one, kept as is.
83
+ */
84
+ declare const PLATFORM_PAGE_UNAVAILABLE = "PLATFORM_WALLET_UNAVAILABLE";
85
+ interface PlatformPageAnswer {
86
+ ok: boolean;
87
+ error?: string;
88
+ /** The answer message as the site sent it — the caller reads its own fields from here. */
89
+ data: Record<string, unknown>;
90
+ }
91
+ /**
92
+ * Posts `type` with `payload` to the parent page and resolves with its `responseType` answer.
93
+ * Never rejects: silence, a foreign origin and a refusal all resolve to `{ ok: false }` with a reason.
94
+ */
95
+ declare function askPlatformPage(type: string, responseType: string, payload: Record<string, unknown>, options?: {
96
+ answerTimeoutMs?: number;
97
+ }): Promise<PlatformPageAnswer>;
98
+
99
+ /** Message names. Shared with the website's `GameWalletLoginBridge` — keep both in step. */
100
+ declare const PLATFORM_TOPUP_MESSAGES: {
101
+ readonly request: "IDOS_PLATFORM_TOPUP_REQUEST";
102
+ readonly response: "IDOS_PLATFORM_TOPUP_RESPONSE";
103
+ };
104
+ interface PlatformTopUpRequest {
105
+ titleID: string;
106
+ /** The game's player. The site refuses when its own session is another account. */
107
+ userID: string;
108
+ currencyID: string;
109
+ /** Tokens to deposit, as an exact decimal string ("12.5"). */
110
+ amount: string;
111
+ }
112
+ interface PlatformTopUpResult {
113
+ /** The deposit is credited to the player's in-game balance. */
114
+ ok: boolean;
115
+ /**
116
+ * Why not: `CANCELLED`, `PENDING` (sent, the engine has not credited it yet), `ACCOUNT_MISMATCH`,
117
+ * `NOT_DEPOSITABLE`, `NO_WALLET`, `TIMEOUT`, `PLATFORM_WALLET_UNAVAILABLE`, …
118
+ */
119
+ error?: string;
120
+ }
121
+ /**
122
+ * Whether this page can ask the site for a top-up at all: it sits in a frame exactly one level deep
123
+ * (the platform's own `/app/{id}` page; on a foreign site the game is two frames deep, behind our
124
+ * `/embed` page) and is not the AI Coder preview. When the browser names the parent's origin, it must
125
+ * be the platform's. The site's ACK is still what really decides — this only spares a 5-second wait
126
+ * where an answer cannot come.
127
+ */
128
+ declare function canUsePlatformTopUp(): boolean;
129
+ /** Asks the idosgames.com page around the game to top the player's balance up. Never rejects. */
130
+ declare function requestPlatformTopUp(request: PlatformTopUpRequest): Promise<PlatformTopUpResult>;
131
+
132
+ export { BrowserPlatformAdapter, BrowserStorage, KeyValueStorage, MemoryStorage, NoopPlatformAdapter, PLATFORM_BRIDGE_ACK, PLATFORM_ORIGINS, PLATFORM_PAGE_UNAVAILABLE, PLATFORM_TOPUP_MESSAGES, PlatformAdapter, type PlatformPageAnswer, type PlatformTopUpRequest, type PlatformTopUpResult, type TelegramInitDataUnsafe, type TelegramWebApp, askPlatformPage, canUsePlatformTopUp, getTelegramWebApp, isPlatformParentOrigin, requestPlatformTopUp };
@@ -75,4 +75,58 @@ declare const PLATFORM_ORIGINS: readonly string[];
75
75
  */
76
76
  declare function isPlatformParentOrigin(origin: string): boolean;
77
77
 
78
- export { BrowserPlatformAdapter, BrowserStorage, KeyValueStorage, MemoryStorage, NoopPlatformAdapter, PLATFORM_ORIGINS, PlatformAdapter, type TelegramInitDataUnsafe, type TelegramWebApp, getTelegramWebApp, isPlatformParentOrigin };
78
+ /** Sent by the site the moment it receives any bridge request. Shared with the site — keep in step. */
79
+ declare const PLATFORM_BRIDGE_ACK = "IDOS_PLATFORM_WALLET_ACK";
80
+ /**
81
+ * The page around the game did not answer at all — an old site build without the bridge, or a
82
+ * parent that is not the platform. The value is the wallet bridge's historical one, kept as is.
83
+ */
84
+ declare const PLATFORM_PAGE_UNAVAILABLE = "PLATFORM_WALLET_UNAVAILABLE";
85
+ interface PlatformPageAnswer {
86
+ ok: boolean;
87
+ error?: string;
88
+ /** The answer message as the site sent it — the caller reads its own fields from here. */
89
+ data: Record<string, unknown>;
90
+ }
91
+ /**
92
+ * Posts `type` with `payload` to the parent page and resolves with its `responseType` answer.
93
+ * Never rejects: silence, a foreign origin and a refusal all resolve to `{ ok: false }` with a reason.
94
+ */
95
+ declare function askPlatformPage(type: string, responseType: string, payload: Record<string, unknown>, options?: {
96
+ answerTimeoutMs?: number;
97
+ }): Promise<PlatformPageAnswer>;
98
+
99
+ /** Message names. Shared with the website's `GameWalletLoginBridge` — keep both in step. */
100
+ declare const PLATFORM_TOPUP_MESSAGES: {
101
+ readonly request: "IDOS_PLATFORM_TOPUP_REQUEST";
102
+ readonly response: "IDOS_PLATFORM_TOPUP_RESPONSE";
103
+ };
104
+ interface PlatformTopUpRequest {
105
+ titleID: string;
106
+ /** The game's player. The site refuses when its own session is another account. */
107
+ userID: string;
108
+ currencyID: string;
109
+ /** Tokens to deposit, as an exact decimal string ("12.5"). */
110
+ amount: string;
111
+ }
112
+ interface PlatformTopUpResult {
113
+ /** The deposit is credited to the player's in-game balance. */
114
+ ok: boolean;
115
+ /**
116
+ * Why not: `CANCELLED`, `PENDING` (sent, the engine has not credited it yet), `ACCOUNT_MISMATCH`,
117
+ * `NOT_DEPOSITABLE`, `NO_WALLET`, `TIMEOUT`, `PLATFORM_WALLET_UNAVAILABLE`, …
118
+ */
119
+ error?: string;
120
+ }
121
+ /**
122
+ * Whether this page can ask the site for a top-up at all: it sits in a frame exactly one level deep
123
+ * (the platform's own `/app/{id}` page; on a foreign site the game is two frames deep, behind our
124
+ * `/embed` page) and is not the AI Coder preview. When the browser names the parent's origin, it must
125
+ * be the platform's. The site's ACK is still what really decides — this only spares a 5-second wait
126
+ * where an answer cannot come.
127
+ */
128
+ declare function canUsePlatformTopUp(): boolean;
129
+ /** Asks the idosgames.com page around the game to top the player's balance up. Never rejects. */
130
+ declare function requestPlatformTopUp(request: PlatformTopUpRequest): Promise<PlatformTopUpResult>;
131
+
132
+ export { BrowserPlatformAdapter, BrowserStorage, KeyValueStorage, MemoryStorage, NoopPlatformAdapter, PLATFORM_BRIDGE_ACK, PLATFORM_ORIGINS, PLATFORM_PAGE_UNAVAILABLE, PLATFORM_TOPUP_MESSAGES, PlatformAdapter, type PlatformPageAnswer, type PlatformTopUpRequest, type PlatformTopUpResult, type TelegramInitDataUnsafe, type TelegramWebApp, askPlatformPage, canUsePlatformTopUp, getTelegramWebApp, isPlatformParentOrigin, requestPlatformTopUp };
@@ -1 +1 @@
1
- export{e as BrowserPlatformAdapter,a as BrowserStorage,b as MemoryStorage,h as NoopPlatformAdapter,f as PLATFORM_ORIGINS,c as getTelegramWebApp,g as isPlatformParentOrigin}from'../chunk-DE75YD5H.js';
1
+ export{e as BrowserPlatformAdapter,a as BrowserStorage,b as MemoryStorage,n as NoopPlatformAdapter,h as PLATFORM_BRIDGE_ACK,f as PLATFORM_ORIGINS,i as PLATFORM_PAGE_UNAVAILABLE,k as PLATFORM_TOPUP_MESSAGES,j as askPlatformPage,l as canUsePlatformTopUp,c as getTelegramWebApp,g as isPlatformParentOrigin,m as requestPlatformTopUp}from'../chunk-YEBYHDZG.js';
@@ -1 +1 @@
1
- 'use strict';function m(n,e){return {ok:false,reason:n,error:e}}var f=16384;function g(n){let e=new Uint8Array(n.byteLength+1);return e[0]=0,e.set(n,1),e}function v(n,e){if(n.byteLength+1<=16384)return [g(n)];if(n.byteLength>67108864)throw new RangeError(`Message of ${n.byteLength} bytes exceeds 67108864.`);let s=Math.ceil(n.byteLength/16375),t=[];for(let i=0;i<s;i++){let r=n.subarray(i*16375,Math.min(n.byteLength,(i+1)*16375)),o=new Uint8Array(9+r.byteLength),a=new DataView(o.buffer);o[0]=1,a.setUint32(1,e>>>0),a.setUint16(5,i),a.setUint16(7,s),o.set(r,9),t.push(o);}return t}var c=class{id=-1;count=0;parts=[];bytes=0;push(e){if(e.byteLength<9)return null;let s=new DataView(e.buffer,e.byteOffset,e.byteLength),t=s.getUint32(1),i=s.getUint16(5),r=s.getUint16(7);if(i===0&&(this.id=t,this.count=r,this.parts=[],this.bytes=0),t!==this.id||i!==this.parts.length||r!==this.count)return this.reset(),null;let o=e.subarray(9);if(this.bytes+=o.byteLength,this.bytes>67108864)return this.reset(),null;if(this.parts.push(o),this.parts.length<this.count)return null;let a=new Uint8Array(this.bytes),l=0;for(let h of this.parts)a.set(h,l),l+=h.byteLength;return this.reset(),a}reset(){this.id=-1,this.count=0,this.parts=[],this.bytes=0;}};function p(n){let e=new Map;for(let s of n??[]){let t=s.Urls?.trim();if(!t)continue;let i=s.Username??void 0,r=s.Credential??void 0,o=`${i??""}\0${r??""}`,a=e.get(o);if(a){let h=Array.isArray(a.urls)?a.urls:[a.urls];h.includes(t)||h.push(t),a.urls=h;continue}let l={urls:[t]};i&&(l.username=i),r&&(l.credential=r),e.set(o,l);}return [...e.values()]}var C=4*1024*1024,A=5e3,d=class{constructor(e){this.o=e;this.peerId=e.peerId,this.offerer=e.offerer,this.lid=e.lid,this.pc=e.createPeerConnection({iceServers:e.iceServers}),this.pc.onicecandidate=s=>{if(!s.candidate){this.sendDescriptionIfReady();return}this.descriptionSent&&this.lateIce.push(s.candidate.toJSON()),this.flushLateIce();},this.pc.onconnectionstatechange=()=>{let s=this.pc.connectionState;(s==="failed"||s==="closed")&&this.close(`connection ${s}`);},this.pc.ondatachannel=s=>this.adopt(s.channel),this.openTimer=setTimeout(()=>{this.state==="connecting"&&this.close("connect timeout");},Math.max(15e3,e.peerTimeoutMs*3)),this.offerer&&(this.adopt(this.pc.createDataChannel("rel",{ordered:true})),this.adopt(this.pc.createDataChannel("fast",{ordered:false,maxRetransmits:0})),this.makeOffer());}o;peerId;offerer;lid;state="connecting";pc;rel=null;fast=null;reassembler=new c;pendingRemoteIce=[];descriptionSent=false;lateIce=[];lastRecv=Date.now();lastSend=0;msgSeq=1;keepaliveTimer=null;gatherTimer=null;openTimer=null;bytesIn=0;bytesOut=0;rttMs=0;pingSentAt=0;async makeOffer(){try{await this.pc.setLocalDescription(await this.pc.createOffer()),this.waitForGathering();}catch(e){this.close(`offer failed: ${String(e)}`);}}async handle(e){if(this.state!=="closed")try{if(e.t==="offer"&&!this.offerer)await this.pc.setRemoteDescription({type:"offer",sdp:e.sdp}),await this.drainRemoteIce(),await this.pc.setLocalDescription(await this.pc.createAnswer()),this.waitForGathering();else if(e.t==="answer"&&this.offerer){if(this.pc.signalingState!=="have-local-offer")return;await this.pc.setRemoteDescription({type:"answer",sdp:e.sdp}),await this.drainRemoteIce();}else if(e.t==="ice")if(!this.pc.remoteDescription)this.pendingRemoteIce.push(...e.c);else for(let s of e.c)await this.addIce(s);else e.t==="bye"&&this.close("peer closed the link");}catch(s){this.close(`signaling failed: ${String(s)}`);}}async drainRemoteIce(){let e=this.pendingRemoteIce.splice(0);for(let s of e)await this.addIce(s);}async addIce(e){try{await this.pc.addIceCandidate(e);}catch{}}waitForGathering(){if(this.pc.iceGatheringState==="complete"){this.sendDescriptionIfReady();return}this.gatherTimer=setTimeout(()=>this.sendDescriptionIfReady(),this.o.iceGatherTimeoutMs);}sendDescriptionIfReady(){if(this.descriptionSent||this.state==="closed")return;let e=this.pc.localDescription;e?.sdp&&(this.gatherTimer&&clearTimeout(this.gatherTimer),this.gatherTimer=null,this.descriptionSent=true,this.o.signal(this.offerer?{t:"offer",lid:this.lid,sdp:e.sdp}:{t:"answer",lid:this.lid,sdp:e.sdp}),this.flushLateIce());}flushLateIce(){if(!this.descriptionSent||this.lateIce.length===0)return;let e=this.lateIce;this.lateIce=[],this.o.signal({t:"ice",lid:this.lid,c:e});}adopt(e){if(e.binaryType="arraybuffer",e.label==="rel")this.rel=e;else if(e.label==="fast")this.fast=e;else return;e.onopen=()=>this.maybeOpen(),e.onclose=()=>this.close(`channel ${e.label} closed`),e.onmessage=s=>this.receive(e.label,s.data),e.readyState==="open"&&queueMicrotask(()=>this.maybeOpen());}maybeOpen(){this.state==="connecting"&&(this.rel?.readyState!=="open"||this.fast?.readyState!=="open"||(this.state="open",this.openTimer&&clearTimeout(this.openTimer),this.openTimer=null,this.lastRecv=Date.now(),this.keepaliveTimer=setInterval(()=>this.keepalive(),this.o.keepaliveMs),this.o.onOpen()));}keepalive(){if(this.state!=="open")return;let e=Date.now();if(e-this.lastRecv>this.o.peerTimeoutMs){this.close("peer timeout");return}(e-this.lastSend>=this.o.keepaliveMs||e-this.pingSentAt>=A)&&(this.pingSentAt=e,this.raw("fast",new Uint8Array([2])));}receive(e,s){if(!(s instanceof ArrayBuffer))return;let t=new Uint8Array(s);this.lastRecv=Date.now(),this.bytesIn+=t.byteLength;let i=t[0];if(i===0)this.o.onMessage(e,t.subarray(1));else if(i===1&&e==="rel"){let r=this.reassembler.push(t);r&&this.o.onMessage(e,r);}else i===2?this.raw("fast",new Uint8Array([3])):i===3?this.pingSentAt&&(this.rttMs=Date.now()-this.pingSentAt):i===4&&e==="rel"&&this.o.onNotice?.(t[1]??0);}send(e,s){if(this.state!=="open")return false;if(e==="fast")return s.byteLength+1>16384?false:this.raw("fast",g(s));if((this.rel?.bufferedAmount??0)>C)return false;let t=v(s,this.msgSeq++);for(let i of t)if(!this.raw("rel",i))return false;return true}notice(e){return this.state!=="open"?false:this.raw("rel",new Uint8Array([4,e]))}get relBuffered(){return this.rel?.bufferedAmount??0}raw(e,s){let t=e==="rel"?this.rel:this.fast;if(!t||t.readyState!=="open")return false;try{return t.send(s),this.lastSend=Date.now(),this.bytesOut+=s.byteLength,!0}catch{return false}}close(e="closed",s=false){if(this.state!=="closed"){this.state="closed",s&&this.descriptionSent&&this.o.signal({t:"bye",lid:this.lid}),this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.gatherTimer&&clearTimeout(this.gatherTimer),this.openTimer&&clearTimeout(this.openTimer),this.keepaliveTimer=this.gatherTimer=this.openTimer=null;for(let t of [this.rel,this.fast])if(t){t.onopen=t.onclose=t.onmessage=null;try{t.close();}catch{}}this.pc.onicecandidate=this.pc.onconnectionstatechange=this.pc.ondatachannel=null;try{this.pc.close();}catch{}this.reassembler.reset(),this.o.onClose(e);}}};function R(n){if(!n)return [];try{let e=JSON.parse(n);return !e||e.v!==1||!Array.isArray(e.m)?[]:e.m.filter(s=>!!s&&typeof s=="object"&&typeof s.t=="string")}catch{return []}}var u=class{constructor(e,s={}){this.send=e;this.perTargetGapMs=s.perTargetGapMs??650,this.globalGapMs=s.globalGapMs??180,this.maxPayloadBytes=s.maxPayloadBytes??15e3,this.maxAttempts=s.maxAttempts??4;}send;queues=new Map;lastSent=new Map;lastAny=0;inflight=false;timer=null;closed=false;perTargetGapMs;globalGapMs;maxPayloadBytes;maxAttempts;get busy(){return this.inflight||this.queues.size>0}enqueue(e,s){if(this.closed)return;let t=this.queues.get(e)??{msgs:[],attempts:0},i=t.msgs[t.msgs.length-1];s.t==="ice"&&i?.t==="ice"&&i.lid===s.lid?i.c.push(...s.c):t.msgs.push(s),this.queues.set(e,t),this.pump();}forget(e){this.queues.delete(e),this.lastSent.delete(e);}close(){this.closed=true,this.queues.clear(),this.timer&&clearTimeout(this.timer),this.timer=null;}pump(){if(this.closed||this.inflight||this.timer)return;let e=Date.now(),s=null,t=1/0;for(let i of this.queues.keys()){let r=Math.max((this.lastSent.get(i)??0)+this.perTargetGapMs,this.lastAny+this.globalGapMs);if(r<=e){s=i;break}t=Math.min(t,r-e);}if(s===null){t!==1/0&&(this.timer=setTimeout(()=>{this.timer=null,this.pump();},t));return}this.flush(s);}async flush(e){let s=this.queues.get(e);if(!s||s.msgs.length===0){this.queues.delete(e),this.pump();return}let t=[],i="";for(let l of s.msgs){let h=JSON.stringify({v:1,m:[...t,l]});if(t.length>0&&E(h)>this.maxPayloadBytes)break;t.push(l),i=h;}let r=s.msgs.slice(t.length);r.length?this.queues.set(e,{msgs:r,attempts:0}):this.queues.delete(e),this.inflight=true;let o=null;try{o=await this.send(e,"rtc",i);}catch{o=null;}this.inflight=false;let a=Date.now();if(this.lastSent.set(e,a),this.lastAny=a,!o?.ok&&!this.closed){let l=o?.ok===false?o.reason:"connection";if((l==="throttled"||l==="connection")&&s.attempts+1<this.maxAttempts){let T=this.queues.get(e);this.queues.set(e,{msgs:[...t,...T?.msgs??[]],attempts:s.attempts+1});}}this.pump();}};function E(n){return new TextEncoder().encode(n).byteLength}var O={pollFastMs:1e3,pollHostIdleMs:2500,pollClientIdleMs:2e4,fastWindowMs:15e3,keepaliveMs:1e3,peerTimeoutMs:6e3,iceGatherTimeoutMs:1200,maxSignalPayloadBytes:15e3,signalPerTargetGapMs:650,signalGlobalGapMs:180},y=class n{constructor(e,s,t,i){this.client=e;this.selfId=s,this.roomId=t.RoomID??"",this.topology=t.Topology??"Mesh",this.chatMode=t.ChatMode??"ServerRelay",this.mode=t.Mode??null,this.ownerId=t.OwnerUserID??"",this.hostId=t.HostUserID??"",this.lastSeq=t.Seq??0,this.iceServers=p(t.IceServers),this.o={...O,leaveOnPageHide:true,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0)),createPeerConnection:i.createPeerConnection??(r=>new RTCPeerConnection(r))};for(let r of t.Members??[])r.UserID&&this.members.set(r.UserID,r);this.outbox=new u((r,o,a)=>this.client.multiplayer.sendSignal(this.roomId,r,o,a),{maxPayloadBytes:this.o.maxSignalPayloadBytes,perTargetGapMs:this.o.signalPerTargetGapMs,globalGapMs:this.o.signalGlobalGapMs}),this.fastUntil=Date.now()+this.o.fastWindowMs,this.o.leaveOnPageHide&&typeof window<"u"&&window.addEventListener("pagehide",this.onPageHide);}client;roomId;selfId;topology;chatMode;mode;ownerId;hostId;members=new Map;o;iceServers;lastSeq;links=new Map;everOpen=new Set;retry=new Map;wantSentAt=new Map;extraPeers=new Set;outbox;pollTimer=null;polling=false;pollSoonMs=null;pollBackoff=0;fastUntil=0;refreshTimer=null;stopped=false;successor=null;listeners=new Map;onPageHide=()=>this.leaveOnUnload();static async create(e,s,t={},i={}){let r=e.auth.context?.userID;if(!r)return m("unauthorized","Not logged in.");let o=await e.multiplayer.createRoom(s,t);return o.ok?{ok:true,data:n.start(e,r,o.data,i)}:o}static async join(e,s,t,i={}){let r=e.auth.context?.userID;if(!r)return m("unauthorized","Not logged in.");let o=await e.multiplayer.joinRoom(s,t);return o.ok?{ok:true,data:n.start(e,r,o.data,i)}:o}static start(e,s,t,i){let r=new n(e,s,t,i);return r.reconcile(),r.schedulePoll(0),r}get isHost(){return this.hostId===this.selfId}get isOwner(){return this.ownerId===this.selfId}get closed(){return this.stopped}on(e,s){let t=this.listeners.get(e)??new Set;return t.add(s),this.listeners.set(e,t),()=>t.delete(s)}openPeers(){return [...this.links.values()].filter(e=>e.state==="open").map(e=>e.peerId)}isOpen(e){return this.links.get(e)?.state==="open"}linkStats(e){let s=this.links.get(e);return s?{rttMs:s.rttMs,bytesIn:s.bytesIn,bytesOut:s.bytesOut,buffered:s.relBuffered}:null}send(e,s,t){return this.links.get(e)?.send(s,t)??false}broadcast(e,s,t){let i=0;for(let r of this.links.values())r.peerId!==t&&r.state==="open"&&r.send(e,s)&&i++;return i}setExtraPeers(e){this.extraPeers=new Set([...e].filter(s=>s!==this.selfId)),this.reconcile();}setSuccessor(e){this.successor=e&&e!==this.selfId?e:null;}async claimHost(){let e=await this.client.multiplayer.claimHost(this.roomId);return e.ok&&this.applySnapshot(e.data),e}async kick(e,s=false){let t=await this.client.multiplayer.kickMember(this.roomId,e,s);return t.ok&&this.links.get(e)?.notice(1),t}unban(e){return this.client.multiplayer.unbanMember(this.roomId,e)}async leave(){if(this.stopped)return;let e=this.isHost?this.successor??void 0:void 0;this.stop(),this.emit("left",{}),await this.client.multiplayer.leaveRoom(this.roomId,{successorUserID:e});}async refreshMembers(){let e=await this.client.multiplayer.getRoom(this.roomId);e.ok&&this.applySnapshot(e.data);}schedulePoll(e){if(!this.stopped){if(this.polling){this.pollSoonMs=Math.min(this.pollSoonMs??e,e);return}this.pollTimer&&clearTimeout(this.pollTimer),this.pollTimer=setTimeout(()=>{this.pollOnce();},e);}}nextPollDelay(){return Date.now()<this.fastUntil||this.outbox.busy||[...this.links.values()].some(s=>s.state==="connecting")||[...this.wanted()].some(s=>!this.links.has(s))?this.o.pollFastMs:this.isHost?this.o.pollHostIdleMs:this.o.pollClientIdleMs}async pollOnce(){if(this.stopped)return;this.pollTimer=null,this.polling=true,this.pollSoonMs=null;let e=await this.client.multiplayer.poll(this.roomId,this.lastSeq);if(this.polling=false,this.stopped)return;let s=this.pollSoonMs;if(this.pollSoonMs=null,e.ok){this.pollBackoff=0;for(let t of e.data.Envelopes??[])this.handleEnvelope(t);this.lastSeq=e.data.MaxSeq??this.lastSeq,this.reconcile(),this.schedulePoll(Math.min(this.nextPollDelay(),s??1/0));return}if(e.reason==="server"){let t=e.error??"";if(/not a member/i.test(t))return this.end("removed",{reason:t});if(/no longer exists|not found/i.test(t))return this.end("roomClosed",{});if(/disabled/i.test(t))return this.end("roomClosed",{})}this.pollBackoff=Math.min(this.pollBackoff+1,5),this.schedulePoll(this.o.pollFastMs*(1+this.pollBackoff));}handleEnvelope(e){let s=e.FromUserID??"";switch(e.Type){case "Signal":e.ToUserID===this.selfId&&e.Kind==="rtc"&&this.handleSignals(s,R(e.Payload));break;case "PlayerJoined":{let t=e.Payload||s;if(!t||t===this.selfId)break;if(!this.members.has(t)){let i={UserID:t};this.members.set(t,i),this.emit("memberJoined",{member:i});}this.fastUntil=Date.now()+this.o.fastWindowMs,this.scheduleRefresh();break}case "PlayerLeft":{let t=e.Payload||s,i=e.Kind==="kicked"?"kicked":e.Kind==="timeout"?"timeout":"left";if(t===this.selfId){i!=="left"&&this.end("removed",{reason:i});break}this.dropMember(t,i,i==="kicked"?s:void 0);break}case "HostChanged":{let t=e.Payload??"";if(t&&t!==this.hostId){let i=this.hostId||null;this.hostId=t,this.fastUntil=Date.now()+this.o.fastWindowMs,this.emit("hostChanged",{hostId:t,previousHostId:i});}break}case "RoomClosed":this.end("roomClosed",{});break;case "MemberState":this.scheduleRefresh();break;case "Chat":this.emit("chat",{from:s,text:e.Payload??""});break}}dropMember(e,s,t){let i=this.members.delete(e);this.closeLink(e,"member left"),this.outbox.forget(e),this.wantSentAt.delete(e);let r=this.retry.get(e);r?.timer&&clearTimeout(r.timer),this.retry.delete(e),this.extraPeers.delete(e),this.successor===e&&(this.successor=null),i&&this.emit("memberLeft",{userId:e,kind:s,by:t});}scheduleRefresh(){this.refreshTimer||this.stopped||(this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.refreshMembers();},400));}applySnapshot(e){if(this.stopped)return;e.IceServers?.length&&(this.iceServers=p(e.IceServers)),e.OwnerUserID&&(this.ownerId=e.OwnerUserID);let s=new Map;for(let t of e.Members??[])t.UserID&&s.set(t.UserID,t);for(let t of [...this.members.keys()])!s.has(t)&&t!==this.selfId&&this.dropMember(t,"left");for(let[t,i]of s){let r=this.members.has(t);this.members.set(t,i),!r&&t!==this.selfId&&this.emit("memberJoined",{member:i});}if(e.HostUserID&&e.HostUserID!==this.hostId){let t=this.hostId||null;this.hostId=e.HostUserID,this.emit("hostChanged",{hostId:e.HostUserID,previousHostId:t});}this.emit("membersUpdated",{members:[...this.members.values()]}),this.reconcile();}wanted(){let e=new Set,s=[...this.members.keys()].filter(t=>t!==this.selfId);if(this.topology==="Mesh"||this.isHost)for(let t of s)e.add(t);else this.hostId&&this.hostId!==this.selfId&&this.members.has(this.hostId)&&e.add(this.hostId);for(let t of this.extraPeers)this.members.has(t)&&e.add(t);return e}reconcile(){if(this.stopped)return;let e=Date.now();for(let s of this.wanted())if(!(this.links.has(s)||this.retry.get(s)?.timer))if(this.selfId<s)this.openLink(s,true,I());else {let t=this.wantSentAt.get(s)??0;e-t>8e3&&(this.wantSentAt.set(s,e),this.outbox.enqueue(s,{t:"want"}));}}handleSignals(e,s){if(!(!e||e===this.selfId)){this.members.has(e)||(this.members.set(e,{UserID:e}),this.scheduleRefresh());for(let t of s){let i=this.links.get(e);if(t.t==="want"){(!i||i.state==="closed")&&this.openLink(e,true,I());continue}if(t.t==="offer"){if(i?.lid===t.lid)continue;i&&this.closeLink(e,"replaced by a new offer"),this.openLink(e,false,t.lid).handle(t);continue}i&&i.lid===t.lid&&i.handle(t);}}}openLink(e,s,t){this.wantSentAt.delete(e);let i=new d({peerId:e,offerer:s,lid:t,iceServers:this.iceServers,createPeerConnection:this.o.createPeerConnection,signal:r=>this.outbox.enqueue(e,r),iceGatherTimeoutMs:this.o.iceGatherTimeoutMs,keepaliveMs:this.o.keepaliveMs,peerTimeoutMs:this.o.peerTimeoutMs,onOpen:()=>{this.everOpen.add(e),this.retry.delete(e),this.emit("peerOpen",{peerId:e});},onClose:r=>this.onLinkClosed(i,r),onMessage:(r,o)=>this.emit("message",{from:e,channel:r,data:o}),onNotice:r=>{r===1&&this.schedulePoll(0);}});return this.links.set(e,i),this.schedulePoll(Math.min(this.o.pollFastMs,250)),i}closeLink(e,s){let t=this.links.get(e);t&&(this.links.delete(e),t.close(s,true));}onLinkClosed(e,s){let t=e.peerId,i=this.links.get(t)===e;if(i&&this.links.delete(t),this.everOpen.delete(t)&&this.emit("peerClose",{peerId:t,reason:s}),!i||this.stopped||!this.members.has(t)||!this.wanted().has(t))return;let r=this.retry.get(t)??{attempts:0,timer:null},o=Math.min(15e3,1e3*2**r.attempts);r.attempts++,r.timer=setTimeout(()=>{r.timer=null,this.wantSentAt.delete(t),this.reconcile();},o),this.retry.set(t,r);}emit(e,s){for(let t of this.listeners.get(e)??[])try{t(s);}catch(i){console.error(`[RealtimeSession] ${String(e)} handler failed`,i);}}end(e,s){this.stopped||(this.stop(),this.emit(e,s));}stop(){this.stopped=true,this.pollTimer&&clearTimeout(this.pollTimer),this.refreshTimer&&clearTimeout(this.refreshTimer),this.pollTimer=this.refreshTimer=null;for(let e of this.retry.values())e.timer&&clearTimeout(e.timer);this.retry.clear(),this.outbox.close();for(let e of [...this.links.keys()]){let s=this.links.get(e);this.links.delete(e),s?.close("session closed");}typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide);}leaveOnUnload(){if(this.stopped)return;let e=this.isHost?this.successor??void 0:void 0;this.stop(),this.emit("left",{}),this.client.multiplayer.leaveRoom(this.roomId,{successorUserID:e,keepalive:true});}};function I(){let n=globalThis.crypto;return n&&"randomUUID"in n?n.randomUUID().slice(0,12):Math.random().toString(36).slice(2,14)}exports.MAX_MESSAGE_BYTES=f;exports.RealtimeSession=y;exports.toRtcIceServers=p;
1
+ 'use strict';function p(n,e){return {ok:false,reason:n,error:e}}var f=16384;function g(n){let e=new Uint8Array(n.byteLength+1);return e[0]=0,e.set(n,1),e}function v(n,e){if(n.byteLength+1<=16384)return [g(n)];if(n.byteLength>67108864)throw new RangeError(`Message of ${n.byteLength} bytes exceeds 67108864.`);let s=Math.ceil(n.byteLength/16375),t=[];for(let i=0;i<s;i++){let r=n.subarray(i*16375,Math.min(n.byteLength,(i+1)*16375)),o=new Uint8Array(9+r.byteLength),a=new DataView(o.buffer);o[0]=1,a.setUint32(1,e>>>0),a.setUint16(5,i),a.setUint16(7,s),o.set(r,9),t.push(o);}return t}var c=class{id=-1;count=0;parts=[];bytes=0;push(e){if(e.byteLength<9)return null;let s=new DataView(e.buffer,e.byteOffset,e.byteLength),t=s.getUint32(1),i=s.getUint16(5),r=s.getUint16(7);if(i===0&&(this.id=t,this.count=r,this.parts=[],this.bytes=0),t!==this.id||i!==this.parts.length||r!==this.count)return this.reset(),null;let o=e.subarray(9);if(this.bytes+=o.byteLength,this.bytes>67108864)return this.reset(),null;if(this.parts.push(o),this.parts.length<this.count)return null;let a=new Uint8Array(this.bytes),l=0;for(let h of this.parts)a.set(h,l),l+=h.byteLength;return this.reset(),a}reset(){this.id=-1,this.count=0,this.parts=[],this.bytes=0;}};function d(n){let e=new Map;for(let s of n??[]){let t=s.Urls?.trim();if(!t)continue;let i=s.Username??void 0,r=s.Credential??void 0,o=`${i??""}\0${r??""}`,a=e.get(o);if(a){let h=Array.isArray(a.urls)?a.urls:[a.urls];h.includes(t)||h.push(t),a.urls=h;continue}let l={urls:[t]};i&&(l.username=i),r&&(l.credential=r),e.set(o,l);}return [...e.values()]}var C=4*1024*1024,A=5e3,u=class{constructor(e){this.o=e;this.peerId=e.peerId,this.offerer=e.offerer,this.lid=e.lid,this.pc=e.createPeerConnection({iceServers:e.iceServers}),this.pc.onicecandidate=s=>{if(!s.candidate){this.sendDescriptionIfReady();return}this.descriptionSent&&this.lateIce.push(s.candidate.toJSON()),this.flushLateIce();},this.pc.onconnectionstatechange=()=>{let s=this.pc.connectionState;(s==="failed"||s==="closed")&&this.close(`connection ${s}`);},this.pc.ondatachannel=s=>this.adopt(s.channel),this.openTimer=setTimeout(()=>{this.state==="connecting"&&this.close("connect timeout");},Math.max(15e3,e.peerTimeoutMs*3)),this.offerer&&(this.adopt(this.pc.createDataChannel("rel",{ordered:true})),this.adopt(this.pc.createDataChannel("fast",{ordered:false,maxRetransmits:0})),this.makeOffer());}o;peerId;offerer;lid;state="connecting";pc;rel=null;fast=null;reassembler=new c;pendingRemoteIce=[];descriptionSent=false;lateIce=[];lastRecv=Date.now();lastSend=0;msgSeq=1;keepaliveTimer=null;gatherTimer=null;openTimer=null;bytesIn=0;bytesOut=0;rttMs=0;pingSentAt=0;async makeOffer(){try{await this.pc.setLocalDescription(await this.pc.createOffer()),this.waitForGathering();}catch(e){this.close(`offer failed: ${String(e)}`);}}async handle(e){if(this.state!=="closed")try{if(e.t==="offer"&&!this.offerer)await this.pc.setRemoteDescription({type:"offer",sdp:e.sdp}),await this.drainRemoteIce(),await this.pc.setLocalDescription(await this.pc.createAnswer()),this.waitForGathering();else if(e.t==="answer"&&this.offerer){if(this.pc.signalingState!=="have-local-offer")return;await this.pc.setRemoteDescription({type:"answer",sdp:e.sdp}),await this.drainRemoteIce();}else if(e.t==="ice")if(!this.pc.remoteDescription)this.pendingRemoteIce.push(...e.c);else for(let s of e.c)await this.addIce(s);else e.t==="bye"&&this.close("peer closed the link");}catch(s){this.close(`signaling failed: ${String(s)}`);}}async drainRemoteIce(){let e=this.pendingRemoteIce.splice(0);for(let s of e)await this.addIce(s);}async addIce(e){try{await this.pc.addIceCandidate(e);}catch{}}waitForGathering(){if(this.pc.iceGatheringState==="complete"){this.sendDescriptionIfReady();return}this.gatherTimer=setTimeout(()=>this.sendDescriptionIfReady(),this.o.iceGatherTimeoutMs);}sendDescriptionIfReady(){if(this.descriptionSent||this.state==="closed")return;let e=this.pc.localDescription;e?.sdp&&(this.gatherTimer&&clearTimeout(this.gatherTimer),this.gatherTimer=null,this.descriptionSent=true,this.o.signal(this.offerer?{t:"offer",lid:this.lid,sdp:e.sdp}:{t:"answer",lid:this.lid,sdp:e.sdp}),this.flushLateIce());}flushLateIce(){if(!this.descriptionSent||this.lateIce.length===0)return;let e=this.lateIce;this.lateIce=[],this.o.signal({t:"ice",lid:this.lid,c:e});}adopt(e){if(e.binaryType="arraybuffer",e.label==="rel")this.rel=e;else if(e.label==="fast")this.fast=e;else return;e.onopen=()=>this.maybeOpen(),e.onclose=()=>this.close(`channel ${e.label} closed`),e.onmessage=s=>this.receive(e.label,s.data),e.readyState==="open"&&queueMicrotask(()=>this.maybeOpen());}maybeOpen(){this.state==="connecting"&&(this.rel?.readyState!=="open"||this.fast?.readyState!=="open"||(this.state="open",this.openTimer&&clearTimeout(this.openTimer),this.openTimer=null,this.lastRecv=Date.now(),this.keepaliveTimer=setInterval(()=>this.keepalive(),this.o.keepaliveMs),this.o.onOpen()));}keepalive(){if(this.state!=="open")return;let e=Date.now();if(e-this.lastRecv>this.o.peerTimeoutMs){this.close("peer timeout");return}(e-this.lastSend>=this.o.keepaliveMs||e-this.pingSentAt>=A)&&(this.pingSentAt=e,this.raw("fast",new Uint8Array([2])));}receive(e,s){if(!(s instanceof ArrayBuffer))return;let t=new Uint8Array(s);this.lastRecv=Date.now(),this.bytesIn+=t.byteLength;let i=t[0];if(i===0)this.o.onMessage(e,t.subarray(1));else if(i===1&&e==="rel"){let r=this.reassembler.push(t);r&&this.o.onMessage(e,r);}else i===2?this.raw("fast",new Uint8Array([3])):i===3?this.pingSentAt&&(this.rttMs=Date.now()-this.pingSentAt):i===4&&e==="rel"&&this.o.onNotice?.(t[1]??0);}send(e,s){if(this.state!=="open")return false;if(e==="fast")return s.byteLength+1>16384?false:this.raw("fast",g(s));if((this.rel?.bufferedAmount??0)>C)return false;let t=v(s,this.msgSeq++);for(let i of t)if(!this.raw("rel",i))return false;return true}notice(e){return this.state!=="open"?false:this.raw("rel",new Uint8Array([4,e]))}get relBuffered(){return this.rel?.bufferedAmount??0}raw(e,s){let t=e==="rel"?this.rel:this.fast;if(!t||t.readyState!=="open")return false;try{return t.send(s),this.lastSend=Date.now(),this.bytesOut+=s.byteLength,!0}catch{return false}}close(e="closed",s=false){if(this.state!=="closed"){this.state="closed",s&&this.descriptionSent&&this.o.signal({t:"bye",lid:this.lid}),this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.gatherTimer&&clearTimeout(this.gatherTimer),this.openTimer&&clearTimeout(this.openTimer),this.keepaliveTimer=this.gatherTimer=this.openTimer=null;for(let t of [this.rel,this.fast])if(t){t.onopen=t.onclose=t.onmessage=null;try{t.close();}catch{}}this.pc.onicecandidate=this.pc.onconnectionstatechange=this.pc.ondatachannel=null;try{this.pc.close();}catch{}this.reassembler.reset(),this.o.onClose(e);}}};function R(n){if(!n)return [];try{let e=JSON.parse(n);return !e||e.v!==1||!Array.isArray(e.m)?[]:e.m.filter(s=>!!s&&typeof s=="object"&&typeof s.t=="string")}catch{return []}}var m=class{constructor(e,s={}){this.send=e;this.perTargetGapMs=s.perTargetGapMs??650,this.globalGapMs=s.globalGapMs??180,this.maxPayloadBytes=s.maxPayloadBytes??15e3,this.maxAttempts=s.maxAttempts??4;}send;queues=new Map;lastSent=new Map;lastAny=0;inflight=false;timer=null;closed=false;perTargetGapMs;globalGapMs;maxPayloadBytes;maxAttempts;get busy(){return this.inflight||this.queues.size>0}enqueue(e,s){if(this.closed)return;let t=this.queues.get(e)??{msgs:[],attempts:0},i=t.msgs[t.msgs.length-1];s.t==="ice"&&i?.t==="ice"&&i.lid===s.lid?i.c.push(...s.c):t.msgs.push(s),this.queues.set(e,t),this.pump();}forget(e){this.queues.delete(e),this.lastSent.delete(e);}close(){this.closed=true,this.queues.clear(),this.timer&&clearTimeout(this.timer),this.timer=null;}pump(){if(this.closed||this.inflight||this.timer)return;let e=Date.now(),s=null,t=1/0;for(let i of this.queues.keys()){let r=Math.max((this.lastSent.get(i)??0)+this.perTargetGapMs,this.lastAny+this.globalGapMs);if(r<=e){s=i;break}t=Math.min(t,r-e);}if(s===null){t!==1/0&&(this.timer=setTimeout(()=>{this.timer=null,this.pump();},t));return}this.flush(s);}async flush(e){let s=this.queues.get(e);if(!s||s.msgs.length===0){this.queues.delete(e),this.pump();return}let t=[],i="";for(let l of s.msgs){let h=JSON.stringify({v:1,m:[...t,l]});if(t.length>0&&E(h)>this.maxPayloadBytes)break;t.push(l),i=h;}let r=s.msgs.slice(t.length);r.length?this.queues.set(e,{msgs:r,attempts:0}):this.queues.delete(e),this.inflight=true;let o=null;try{o=await this.send(e,"rtc",i);}catch{o=null;}this.inflight=false;let a=Date.now();if(this.lastSent.set(e,a),this.lastAny=a,!o?.ok&&!this.closed){let l=o?.ok===false?o.reason:"connection";if((l==="throttled"||l==="connection")&&s.attempts+1<this.maxAttempts){let T=this.queues.get(e);this.queues.set(e,{msgs:[...t,...T?.msgs??[]],attempts:s.attempts+1});}}this.pump();}};function E(n){return new TextEncoder().encode(n).byteLength}var P={pollFastMs:1e3,pollHostIdleMs:2500,pollClientIdleMs:2e4,fastWindowMs:15e3,keepaliveMs:1e3,peerTimeoutMs:6e3,iceGatherTimeoutMs:1200,maxSignalPayloadBytes:15e3,signalPerTargetGapMs:650,signalGlobalGapMs:180},y=class n{constructor(e,s,t,i){this.client=e;this.selfId=s,this.roomId=t.RoomID??"",this.topology=t.Topology??"Mesh",this.chatMode=t.ChatMode??"ServerRelay",this.mode=t.Mode??null,this.ownerId=t.OwnerUserID??"",this.hostId=t.HostUserID??"",this.lastSeq=t.Seq??0,this.iceServers=d(t.IceServers),this.o={...P,leaveOnPageHide:true,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0)),createPeerConnection:i.createPeerConnection??(r=>new RTCPeerConnection(r))};for(let r of t.Members??[])r.UserID&&this.members.set(r.UserID,r);this.outbox=new m((r,o,a)=>this.client.multiplayer.sendSignal(this.roomId,r,o,a),{maxPayloadBytes:this.o.maxSignalPayloadBytes,perTargetGapMs:this.o.signalPerTargetGapMs,globalGapMs:this.o.signalGlobalGapMs}),this.fastUntil=Date.now()+this.o.fastWindowMs,this.o.leaveOnPageHide&&typeof window<"u"&&window.addEventListener("pagehide",this.onPageHide);}client;roomId;selfId;topology;chatMode;mode;ownerId;hostId;members=new Map;o;iceServers;lastSeq;links=new Map;everOpen=new Set;retry=new Map;wantSentAt=new Map;extraPeers=new Set;outbox;pollTimer=null;polling=false;pollSoonMs=null;pollBackoff=0;fastUntil=0;refreshTimer=null;stopped=false;successor=null;listeners=new Map;onPageHide=()=>this.leaveOnUnload();static async create(e,s,t={},i={}){let r=e.auth.context?.userID;if(!r)return p("unauthorized","Not logged in.");let o=await e.multiplayer.createRoom(s,t);return o.ok?{ok:true,data:n.start(e,r,o.data,i)}:o}static async join(e,s,t,i={}){let r=e.auth.context?.userID;if(!r)return p("unauthorized","Not logged in.");let o=await e.multiplayer.joinRoom(s,t);return o.ok?{ok:true,data:n.start(e,r,o.data,i)}:o}static start(e,s,t,i){let r=new n(e,s,t,i);return r.reconcile(),r.schedulePoll(0),r}get isHost(){return this.hostId===this.selfId}get isOwner(){return this.ownerId===this.selfId}get closed(){return this.stopped}on(e,s){let t=this.listeners.get(e)??new Set;return t.add(s),this.listeners.set(e,t),()=>t.delete(s)}openPeers(){return [...this.links.values()].filter(e=>e.state==="open").map(e=>e.peerId)}isOpen(e){return this.links.get(e)?.state==="open"}linkStats(e){let s=this.links.get(e);return s?{rttMs:s.rttMs,bytesIn:s.bytesIn,bytesOut:s.bytesOut,buffered:s.relBuffered}:null}send(e,s,t){return this.links.get(e)?.send(s,t)??false}broadcast(e,s,t){let i=0;for(let r of this.links.values())r.peerId!==t&&r.state==="open"&&r.send(e,s)&&i++;return i}setExtraPeers(e){this.extraPeers=new Set([...e].filter(s=>s!==this.selfId)),this.reconcile();}setSuccessor(e){this.successor=e&&e!==this.selfId?e:null;}async claimHost(){let e=await this.client.multiplayer.claimHost(this.roomId);return e.ok&&this.applySnapshot(e.data),e}async kick(e,s=false){let t=await this.client.multiplayer.kickMember(this.roomId,e,s);return t.ok&&this.links.get(e)?.notice(1),t}unban(e){return this.client.multiplayer.unbanMember(this.roomId,e)}async leave(){if(this.stopped)return;let e=this.isHost?this.successor??void 0:void 0;this.stop(),this.emit("left",{}),await this.client.multiplayer.leaveRoom(this.roomId,{successorUserID:e});}async refreshMembers(){let e=await this.client.multiplayer.getRoom(this.roomId);e.ok&&this.applySnapshot(e.data);}schedulePoll(e){if(!this.stopped){if(this.polling){this.pollSoonMs=Math.min(this.pollSoonMs??e,e);return}this.pollTimer&&clearTimeout(this.pollTimer),this.pollTimer=setTimeout(()=>{this.pollOnce();},e);}}nextPollDelay(){return Date.now()<this.fastUntil||this.outbox.busy||[...this.links.values()].some(s=>s.state==="connecting")||[...this.wanted()].some(s=>!this.links.has(s))?this.o.pollFastMs:this.isHost?this.o.pollHostIdleMs:this.o.pollClientIdleMs}async pollOnce(){if(this.stopped)return;this.pollTimer=null,this.polling=true,this.pollSoonMs=null;let e=await this.client.multiplayer.poll(this.roomId,this.lastSeq);if(this.polling=false,this.stopped)return;let s=this.pollSoonMs;if(this.pollSoonMs=null,e.ok){this.pollBackoff=0;for(let t of e.data.Envelopes??[])this.handleEnvelope(t);this.lastSeq=e.data.MaxSeq??this.lastSeq,this.reconcile(),this.schedulePoll(Math.min(this.nextPollDelay(),s??1/0));return}if(e.reason==="server"){let t=e.error??"";if(/not a member/i.test(t))return this.end("removed",{reason:t});if(/no longer exists|not found/i.test(t))return this.end("roomClosed",{});if(/disabled/i.test(t))return this.end("roomClosed",{})}this.pollBackoff=Math.min(this.pollBackoff+1,5),this.schedulePoll(this.o.pollFastMs*(1+this.pollBackoff));}handleEnvelope(e){let s=e.FromUserID??"";switch(e.Type){case "Signal":e.ToUserID===this.selfId&&e.Kind==="rtc"&&this.handleSignals(s,R(e.Payload));break;case "PlayerJoined":{let t=e.Payload||s;if(!t||t===this.selfId)break;if(!this.members.has(t)){let i={UserID:t};this.members.set(t,i),this.emit("memberJoined",{member:i});}this.fastUntil=Date.now()+this.o.fastWindowMs,this.scheduleRefresh();break}case "PlayerLeft":{let t=e.Payload||s,i=e.Kind==="kicked"?"kicked":e.Kind==="timeout"?"timeout":"left";if(t===this.selfId){i!=="left"&&this.end("removed",{reason:i});break}this.dropMember(t,i,i==="kicked"?s:void 0);break}case "HostChanged":{let t=e.Payload??"";if(t&&t!==this.hostId){let i=this.hostId||null;this.hostId=t,this.fastUntil=Date.now()+this.o.fastWindowMs,this.emit("hostChanged",{hostId:t,previousHostId:i});}break}case "RoomClosed":this.end("roomClosed",{});break;case "MemberState":this.scheduleRefresh();break;case "Chat":this.emit("chat",{from:s,text:e.Payload??""});break}}dropMember(e,s,t){let i=this.members.delete(e);this.closeLink(e,"member left"),this.outbox.forget(e),this.wantSentAt.delete(e);let r=this.retry.get(e);r?.timer&&clearTimeout(r.timer),this.retry.delete(e),this.extraPeers.delete(e),this.successor===e&&(this.successor=null),i&&this.emit("memberLeft",{userId:e,kind:s,by:t});}scheduleRefresh(){this.refreshTimer||this.stopped||(this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.refreshMembers();},400));}applySnapshot(e){if(this.stopped)return;e.IceServers?.length&&(this.iceServers=d(e.IceServers)),e.OwnerUserID&&(this.ownerId=e.OwnerUserID);let s=new Map;for(let t of e.Members??[])t.UserID&&s.set(t.UserID,t);for(let t of [...this.members.keys()])!s.has(t)&&t!==this.selfId&&this.dropMember(t,"left");for(let[t,i]of s){let r=this.members.has(t);this.members.set(t,i),!r&&t!==this.selfId&&this.emit("memberJoined",{member:i});}if(e.HostUserID&&e.HostUserID!==this.hostId){let t=this.hostId||null;this.hostId=e.HostUserID,this.emit("hostChanged",{hostId:e.HostUserID,previousHostId:t});}this.emit("membersUpdated",{members:[...this.members.values()]}),this.reconcile();}wanted(){let e=new Set,s=[...this.members.keys()].filter(t=>t!==this.selfId);if(this.topology==="Mesh"||this.isHost)for(let t of s)e.add(t);else this.hostId&&this.hostId!==this.selfId&&this.members.has(this.hostId)&&e.add(this.hostId);for(let t of this.extraPeers)this.members.has(t)&&e.add(t);return e}reconcile(){if(this.stopped)return;let e=Date.now();for(let s of this.wanted())if(!(this.links.has(s)||this.retry.get(s)?.timer))if(this.selfId<s)this.openLink(s,true,I());else {let t=this.wantSentAt.get(s)??0;e-t>8e3&&(this.wantSentAt.set(s,e),this.outbox.enqueue(s,{t:"want"}));}}handleSignals(e,s){if(!(!e||e===this.selfId)){this.members.has(e)||(this.members.set(e,{UserID:e}),this.scheduleRefresh());for(let t of s){let i=this.links.get(e);if(t.t==="want"){(!i||i.state==="closed")&&this.openLink(e,true,I());continue}if(t.t==="offer"){if(i?.lid===t.lid)continue;i&&this.closeLink(e,"replaced by a new offer"),this.openLink(e,false,t.lid).handle(t);continue}i&&i.lid===t.lid&&i.handle(t);}}}openLink(e,s,t){this.wantSentAt.delete(e);let i=new u({peerId:e,offerer:s,lid:t,iceServers:this.iceServers,createPeerConnection:this.o.createPeerConnection,signal:r=>this.outbox.enqueue(e,r),iceGatherTimeoutMs:this.o.iceGatherTimeoutMs,keepaliveMs:this.o.keepaliveMs,peerTimeoutMs:this.o.peerTimeoutMs,onOpen:()=>{this.everOpen.add(e),this.retry.delete(e),this.emit("peerOpen",{peerId:e});},onClose:r=>this.onLinkClosed(i,r),onMessage:(r,o)=>this.emit("message",{from:e,channel:r,data:o}),onNotice:r=>{r===1&&this.schedulePoll(0);}});return this.links.set(e,i),this.schedulePoll(Math.min(this.o.pollFastMs,250)),i}closeLink(e,s){let t=this.links.get(e);t&&(this.links.delete(e),t.close(s,true));}onLinkClosed(e,s){let t=e.peerId,i=this.links.get(t)===e;if(i&&this.links.delete(t),this.everOpen.delete(t)&&this.emit("peerClose",{peerId:t,reason:s}),!i||this.stopped||!this.members.has(t)||!this.wanted().has(t))return;let r=this.retry.get(t)??{attempts:0,timer:null},o=Math.min(15e3,1e3*2**r.attempts);r.attempts++,r.timer=setTimeout(()=>{r.timer=null,this.wantSentAt.delete(t),this.reconcile();},o),this.retry.set(t,r);}emit(e,s){for(let t of this.listeners.get(e)??[])try{t(s);}catch(i){console.error(`[RealtimeSession] ${String(e)} handler failed`,i);}}end(e,s){this.stopped||(this.stop(),this.emit(e,s));}stop(){this.stopped=true,this.pollTimer&&clearTimeout(this.pollTimer),this.refreshTimer&&clearTimeout(this.refreshTimer),this.pollTimer=this.refreshTimer=null;for(let e of this.retry.values())e.timer&&clearTimeout(e.timer);this.retry.clear(),this.outbox.close();for(let e of [...this.links.keys()]){let s=this.links.get(e);this.links.delete(e),s?.close("session closed");}typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide);}leaveOnUnload(){if(this.stopped)return;let e=this.isHost?this.successor??void 0:void 0;this.stop(),this.emit("left",{}),this.client.multiplayer.leaveRoom(this.roomId,{successorUserID:e,keepalive:true});}};function I(){let n=globalThis.crypto;return n&&"randomUUID"in n?n.randomUUID().slice(0,12):Math.random().toString(36).slice(2,14)}exports.MAX_MESSAGE_BYTES=f;exports.RealtimeSession=y;exports.toRtcIceServers=d;
@@ -1,5 +1,5 @@
1
- import { I as IceServer } from '../RealtimeSession-DYW2tJ1g.cjs';
2
- export { C as ChannelName, M as MemberLeftKind, R as RealtimeClient, a as RealtimeSession, b as RealtimeSessionEvents, c as RealtimeSessionOptions } from '../RealtimeSession-DYW2tJ1g.cjs';
1
+ import { I as IceServer } from '../RealtimeSession-wV_8qMas.cjs';
2
+ export { C as ChannelName, M as MemberLeftKind, R as RealtimeClient, a as RealtimeSession, b as RealtimeSessionEvents, c as RealtimeSessionOptions } from '../RealtimeSession-wV_8qMas.cjs';
3
3
  import 'zod';
4
4
  import '../PlatformAdapter-DU_8HalI.cjs';
5
5
  import 'decimal.js';
@@ -1,5 +1,5 @@
1
- import { I as IceServer } from '../RealtimeSession-BUWeAEQT.js';
2
- export { C as ChannelName, M as MemberLeftKind, R as RealtimeClient, a as RealtimeSession, b as RealtimeSessionEvents, c as RealtimeSessionOptions } from '../RealtimeSession-BUWeAEQT.js';
1
+ import { I as IceServer } from '../RealtimeSession-C5VICo95.js';
2
+ export { C as ChannelName, M as MemberLeftKind, R as RealtimeClient, a as RealtimeSession, b as RealtimeSessionEvents, c as RealtimeSessionOptions } from '../RealtimeSession-C5VICo95.js';
3
3
  import 'zod';
4
4
  import '../PlatformAdapter-DU_8HalI.js';
5
5
  import 'decimal.js';
@@ -1 +1 @@
1
- import {b}from'../chunk-76ZM4DUB.js';var f=16384;function g(o){let e=new Uint8Array(o.byteLength+1);return e[0]=0,e.set(o,1),e}function v(o,e){if(o.byteLength+1<=16384)return [g(o)];if(o.byteLength>67108864)throw new RangeError(`Message of ${o.byteLength} bytes exceeds 67108864.`);let s=Math.ceil(o.byteLength/16375),t=[];for(let i=0;i<s;i++){let r=o.subarray(i*16375,Math.min(o.byteLength,(i+1)*16375)),n=new Uint8Array(9+r.byteLength),a=new DataView(n.buffer);n[0]=1,a.setUint32(1,e>>>0),a.setUint16(5,i),a.setUint16(7,s),n.set(r,9),t.push(n);}return t}var c=class{id=-1;count=0;parts=[];bytes=0;push(e){if(e.byteLength<9)return null;let s=new DataView(e.buffer,e.byteOffset,e.byteLength),t=s.getUint32(1),i=s.getUint16(5),r=s.getUint16(7);if(i===0&&(this.id=t,this.count=r,this.parts=[],this.bytes=0),t!==this.id||i!==this.parts.length||r!==this.count)return this.reset(),null;let n=e.subarray(9);if(this.bytes+=n.byteLength,this.bytes>67108864)return this.reset(),null;if(this.parts.push(n),this.parts.length<this.count)return null;let a=new Uint8Array(this.bytes),l=0;for(let h of this.parts)a.set(h,l),l+=h.byteLength;return this.reset(),a}reset(){this.id=-1,this.count=0,this.parts=[],this.bytes=0;}};function p(o){let e=new Map;for(let s of o??[]){let t=s.Urls?.trim();if(!t)continue;let i=s.Username??void 0,r=s.Credential??void 0,n=`${i??""}\0${r??""}`,a=e.get(n);if(a){let h=Array.isArray(a.urls)?a.urls:[a.urls];h.includes(t)||h.push(t),a.urls=h;continue}let l={urls:[t]};i&&(l.username=i),r&&(l.credential=r),e.set(n,l);}return [...e.values()]}var C=4*1024*1024,A=5e3,d=class{constructor(e){this.o=e;this.peerId=e.peerId,this.offerer=e.offerer,this.lid=e.lid,this.pc=e.createPeerConnection({iceServers:e.iceServers}),this.pc.onicecandidate=s=>{if(!s.candidate){this.sendDescriptionIfReady();return}this.descriptionSent&&this.lateIce.push(s.candidate.toJSON()),this.flushLateIce();},this.pc.onconnectionstatechange=()=>{let s=this.pc.connectionState;(s==="failed"||s==="closed")&&this.close(`connection ${s}`);},this.pc.ondatachannel=s=>this.adopt(s.channel),this.openTimer=setTimeout(()=>{this.state==="connecting"&&this.close("connect timeout");},Math.max(15e3,e.peerTimeoutMs*3)),this.offerer&&(this.adopt(this.pc.createDataChannel("rel",{ordered:true})),this.adopt(this.pc.createDataChannel("fast",{ordered:false,maxRetransmits:0})),this.makeOffer());}o;peerId;offerer;lid;state="connecting";pc;rel=null;fast=null;reassembler=new c;pendingRemoteIce=[];descriptionSent=false;lateIce=[];lastRecv=Date.now();lastSend=0;msgSeq=1;keepaliveTimer=null;gatherTimer=null;openTimer=null;bytesIn=0;bytesOut=0;rttMs=0;pingSentAt=0;async makeOffer(){try{await this.pc.setLocalDescription(await this.pc.createOffer()),this.waitForGathering();}catch(e){this.close(`offer failed: ${String(e)}`);}}async handle(e){if(this.state!=="closed")try{if(e.t==="offer"&&!this.offerer)await this.pc.setRemoteDescription({type:"offer",sdp:e.sdp}),await this.drainRemoteIce(),await this.pc.setLocalDescription(await this.pc.createAnswer()),this.waitForGathering();else if(e.t==="answer"&&this.offerer){if(this.pc.signalingState!=="have-local-offer")return;await this.pc.setRemoteDescription({type:"answer",sdp:e.sdp}),await this.drainRemoteIce();}else if(e.t==="ice")if(!this.pc.remoteDescription)this.pendingRemoteIce.push(...e.c);else for(let s of e.c)await this.addIce(s);else e.t==="bye"&&this.close("peer closed the link");}catch(s){this.close(`signaling failed: ${String(s)}`);}}async drainRemoteIce(){let e=this.pendingRemoteIce.splice(0);for(let s of e)await this.addIce(s);}async addIce(e){try{await this.pc.addIceCandidate(e);}catch{}}waitForGathering(){if(this.pc.iceGatheringState==="complete"){this.sendDescriptionIfReady();return}this.gatherTimer=setTimeout(()=>this.sendDescriptionIfReady(),this.o.iceGatherTimeoutMs);}sendDescriptionIfReady(){if(this.descriptionSent||this.state==="closed")return;let e=this.pc.localDescription;e?.sdp&&(this.gatherTimer&&clearTimeout(this.gatherTimer),this.gatherTimer=null,this.descriptionSent=true,this.o.signal(this.offerer?{t:"offer",lid:this.lid,sdp:e.sdp}:{t:"answer",lid:this.lid,sdp:e.sdp}),this.flushLateIce());}flushLateIce(){if(!this.descriptionSent||this.lateIce.length===0)return;let e=this.lateIce;this.lateIce=[],this.o.signal({t:"ice",lid:this.lid,c:e});}adopt(e){if(e.binaryType="arraybuffer",e.label==="rel")this.rel=e;else if(e.label==="fast")this.fast=e;else return;e.onopen=()=>this.maybeOpen(),e.onclose=()=>this.close(`channel ${e.label} closed`),e.onmessage=s=>this.receive(e.label,s.data),e.readyState==="open"&&queueMicrotask(()=>this.maybeOpen());}maybeOpen(){this.state==="connecting"&&(this.rel?.readyState!=="open"||this.fast?.readyState!=="open"||(this.state="open",this.openTimer&&clearTimeout(this.openTimer),this.openTimer=null,this.lastRecv=Date.now(),this.keepaliveTimer=setInterval(()=>this.keepalive(),this.o.keepaliveMs),this.o.onOpen()));}keepalive(){if(this.state!=="open")return;let e=Date.now();if(e-this.lastRecv>this.o.peerTimeoutMs){this.close("peer timeout");return}(e-this.lastSend>=this.o.keepaliveMs||e-this.pingSentAt>=A)&&(this.pingSentAt=e,this.raw("fast",new Uint8Array([2])));}receive(e,s){if(!(s instanceof ArrayBuffer))return;let t=new Uint8Array(s);this.lastRecv=Date.now(),this.bytesIn+=t.byteLength;let i=t[0];if(i===0)this.o.onMessage(e,t.subarray(1));else if(i===1&&e==="rel"){let r=this.reassembler.push(t);r&&this.o.onMessage(e,r);}else i===2?this.raw("fast",new Uint8Array([3])):i===3?this.pingSentAt&&(this.rttMs=Date.now()-this.pingSentAt):i===4&&e==="rel"&&this.o.onNotice?.(t[1]??0);}send(e,s){if(this.state!=="open")return false;if(e==="fast")return s.byteLength+1>16384?false:this.raw("fast",g(s));if((this.rel?.bufferedAmount??0)>C)return false;let t=v(s,this.msgSeq++);for(let i of t)if(!this.raw("rel",i))return false;return true}notice(e){return this.state!=="open"?false:this.raw("rel",new Uint8Array([4,e]))}get relBuffered(){return this.rel?.bufferedAmount??0}raw(e,s){let t=e==="rel"?this.rel:this.fast;if(!t||t.readyState!=="open")return false;try{return t.send(s),this.lastSend=Date.now(),this.bytesOut+=s.byteLength,!0}catch{return false}}close(e="closed",s=false){if(this.state!=="closed"){this.state="closed",s&&this.descriptionSent&&this.o.signal({t:"bye",lid:this.lid}),this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.gatherTimer&&clearTimeout(this.gatherTimer),this.openTimer&&clearTimeout(this.openTimer),this.keepaliveTimer=this.gatherTimer=this.openTimer=null;for(let t of [this.rel,this.fast])if(t){t.onopen=t.onclose=t.onmessage=null;try{t.close();}catch{}}this.pc.onicecandidate=this.pc.onconnectionstatechange=this.pc.ondatachannel=null;try{this.pc.close();}catch{}this.reassembler.reset(),this.o.onClose(e);}}};function R(o){if(!o)return [];try{let e=JSON.parse(o);return !e||e.v!==1||!Array.isArray(e.m)?[]:e.m.filter(s=>!!s&&typeof s=="object"&&typeof s.t=="string")}catch{return []}}var u=class{constructor(e,s={}){this.send=e;this.perTargetGapMs=s.perTargetGapMs??650,this.globalGapMs=s.globalGapMs??180,this.maxPayloadBytes=s.maxPayloadBytes??15e3,this.maxAttempts=s.maxAttempts??4;}send;queues=new Map;lastSent=new Map;lastAny=0;inflight=false;timer=null;closed=false;perTargetGapMs;globalGapMs;maxPayloadBytes;maxAttempts;get busy(){return this.inflight||this.queues.size>0}enqueue(e,s){if(this.closed)return;let t=this.queues.get(e)??{msgs:[],attempts:0},i=t.msgs[t.msgs.length-1];s.t==="ice"&&i?.t==="ice"&&i.lid===s.lid?i.c.push(...s.c):t.msgs.push(s),this.queues.set(e,t),this.pump();}forget(e){this.queues.delete(e),this.lastSent.delete(e);}close(){this.closed=true,this.queues.clear(),this.timer&&clearTimeout(this.timer),this.timer=null;}pump(){if(this.closed||this.inflight||this.timer)return;let e=Date.now(),s=null,t=1/0;for(let i of this.queues.keys()){let r=Math.max((this.lastSent.get(i)??0)+this.perTargetGapMs,this.lastAny+this.globalGapMs);if(r<=e){s=i;break}t=Math.min(t,r-e);}if(s===null){t!==1/0&&(this.timer=setTimeout(()=>{this.timer=null,this.pump();},t));return}this.flush(s);}async flush(e){let s=this.queues.get(e);if(!s||s.msgs.length===0){this.queues.delete(e),this.pump();return}let t=[],i="";for(let l of s.msgs){let h=JSON.stringify({v:1,m:[...t,l]});if(t.length>0&&E(h)>this.maxPayloadBytes)break;t.push(l),i=h;}let r=s.msgs.slice(t.length);r.length?this.queues.set(e,{msgs:r,attempts:0}):this.queues.delete(e),this.inflight=true;let n=null;try{n=await this.send(e,"rtc",i);}catch{n=null;}this.inflight=false;let a=Date.now();if(this.lastSent.set(e,a),this.lastAny=a,!n?.ok&&!this.closed){let l=n?.ok===false?n.reason:"connection";if((l==="throttled"||l==="connection")&&s.attempts+1<this.maxAttempts){let T=this.queues.get(e);this.queues.set(e,{msgs:[...t,...T?.msgs??[]],attempts:s.attempts+1});}}this.pump();}};function E(o){return new TextEncoder().encode(o).byteLength}var D={pollFastMs:1e3,pollHostIdleMs:2500,pollClientIdleMs:2e4,fastWindowMs:15e3,keepaliveMs:1e3,peerTimeoutMs:6e3,iceGatherTimeoutMs:1200,maxSignalPayloadBytes:15e3,signalPerTargetGapMs:650,signalGlobalGapMs:180},y=class o{constructor(e,s,t,i){this.client=e;this.selfId=s,this.roomId=t.RoomID??"",this.topology=t.Topology??"Mesh",this.chatMode=t.ChatMode??"ServerRelay",this.mode=t.Mode??null,this.ownerId=t.OwnerUserID??"",this.hostId=t.HostUserID??"",this.lastSeq=t.Seq??0,this.iceServers=p(t.IceServers),this.o={...D,leaveOnPageHide:true,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0)),createPeerConnection:i.createPeerConnection??(r=>new RTCPeerConnection(r))};for(let r of t.Members??[])r.UserID&&this.members.set(r.UserID,r);this.outbox=new u((r,n,a)=>this.client.multiplayer.sendSignal(this.roomId,r,n,a),{maxPayloadBytes:this.o.maxSignalPayloadBytes,perTargetGapMs:this.o.signalPerTargetGapMs,globalGapMs:this.o.signalGlobalGapMs}),this.fastUntil=Date.now()+this.o.fastWindowMs,this.o.leaveOnPageHide&&typeof window<"u"&&window.addEventListener("pagehide",this.onPageHide);}client;roomId;selfId;topology;chatMode;mode;ownerId;hostId;members=new Map;o;iceServers;lastSeq;links=new Map;everOpen=new Set;retry=new Map;wantSentAt=new Map;extraPeers=new Set;outbox;pollTimer=null;polling=false;pollSoonMs=null;pollBackoff=0;fastUntil=0;refreshTimer=null;stopped=false;successor=null;listeners=new Map;onPageHide=()=>this.leaveOnUnload();static async create(e,s,t={},i={}){let r=e.auth.context?.userID;if(!r)return b("unauthorized","Not logged in.");let n=await e.multiplayer.createRoom(s,t);return n.ok?{ok:true,data:o.start(e,r,n.data,i)}:n}static async join(e,s,t,i={}){let r=e.auth.context?.userID;if(!r)return b("unauthorized","Not logged in.");let n=await e.multiplayer.joinRoom(s,t);return n.ok?{ok:true,data:o.start(e,r,n.data,i)}:n}static start(e,s,t,i){let r=new o(e,s,t,i);return r.reconcile(),r.schedulePoll(0),r}get isHost(){return this.hostId===this.selfId}get isOwner(){return this.ownerId===this.selfId}get closed(){return this.stopped}on(e,s){let t=this.listeners.get(e)??new Set;return t.add(s),this.listeners.set(e,t),()=>t.delete(s)}openPeers(){return [...this.links.values()].filter(e=>e.state==="open").map(e=>e.peerId)}isOpen(e){return this.links.get(e)?.state==="open"}linkStats(e){let s=this.links.get(e);return s?{rttMs:s.rttMs,bytesIn:s.bytesIn,bytesOut:s.bytesOut,buffered:s.relBuffered}:null}send(e,s,t){return this.links.get(e)?.send(s,t)??false}broadcast(e,s,t){let i=0;for(let r of this.links.values())r.peerId!==t&&r.state==="open"&&r.send(e,s)&&i++;return i}setExtraPeers(e){this.extraPeers=new Set([...e].filter(s=>s!==this.selfId)),this.reconcile();}setSuccessor(e){this.successor=e&&e!==this.selfId?e:null;}async claimHost(){let e=await this.client.multiplayer.claimHost(this.roomId);return e.ok&&this.applySnapshot(e.data),e}async kick(e,s=false){let t=await this.client.multiplayer.kickMember(this.roomId,e,s);return t.ok&&this.links.get(e)?.notice(1),t}unban(e){return this.client.multiplayer.unbanMember(this.roomId,e)}async leave(){if(this.stopped)return;let e=this.isHost?this.successor??void 0:void 0;this.stop(),this.emit("left",{}),await this.client.multiplayer.leaveRoom(this.roomId,{successorUserID:e});}async refreshMembers(){let e=await this.client.multiplayer.getRoom(this.roomId);e.ok&&this.applySnapshot(e.data);}schedulePoll(e){if(!this.stopped){if(this.polling){this.pollSoonMs=Math.min(this.pollSoonMs??e,e);return}this.pollTimer&&clearTimeout(this.pollTimer),this.pollTimer=setTimeout(()=>{this.pollOnce();},e);}}nextPollDelay(){return Date.now()<this.fastUntil||this.outbox.busy||[...this.links.values()].some(s=>s.state==="connecting")||[...this.wanted()].some(s=>!this.links.has(s))?this.o.pollFastMs:this.isHost?this.o.pollHostIdleMs:this.o.pollClientIdleMs}async pollOnce(){if(this.stopped)return;this.pollTimer=null,this.polling=true,this.pollSoonMs=null;let e=await this.client.multiplayer.poll(this.roomId,this.lastSeq);if(this.polling=false,this.stopped)return;let s=this.pollSoonMs;if(this.pollSoonMs=null,e.ok){this.pollBackoff=0;for(let t of e.data.Envelopes??[])this.handleEnvelope(t);this.lastSeq=e.data.MaxSeq??this.lastSeq,this.reconcile(),this.schedulePoll(Math.min(this.nextPollDelay(),s??1/0));return}if(e.reason==="server"){let t=e.error??"";if(/not a member/i.test(t))return this.end("removed",{reason:t});if(/no longer exists|not found/i.test(t))return this.end("roomClosed",{});if(/disabled/i.test(t))return this.end("roomClosed",{})}this.pollBackoff=Math.min(this.pollBackoff+1,5),this.schedulePoll(this.o.pollFastMs*(1+this.pollBackoff));}handleEnvelope(e){let s=e.FromUserID??"";switch(e.Type){case "Signal":e.ToUserID===this.selfId&&e.Kind==="rtc"&&this.handleSignals(s,R(e.Payload));break;case "PlayerJoined":{let t=e.Payload||s;if(!t||t===this.selfId)break;if(!this.members.has(t)){let i={UserID:t};this.members.set(t,i),this.emit("memberJoined",{member:i});}this.fastUntil=Date.now()+this.o.fastWindowMs,this.scheduleRefresh();break}case "PlayerLeft":{let t=e.Payload||s,i=e.Kind==="kicked"?"kicked":e.Kind==="timeout"?"timeout":"left";if(t===this.selfId){i!=="left"&&this.end("removed",{reason:i});break}this.dropMember(t,i,i==="kicked"?s:void 0);break}case "HostChanged":{let t=e.Payload??"";if(t&&t!==this.hostId){let i=this.hostId||null;this.hostId=t,this.fastUntil=Date.now()+this.o.fastWindowMs,this.emit("hostChanged",{hostId:t,previousHostId:i});}break}case "RoomClosed":this.end("roomClosed",{});break;case "MemberState":this.scheduleRefresh();break;case "Chat":this.emit("chat",{from:s,text:e.Payload??""});break}}dropMember(e,s,t){let i=this.members.delete(e);this.closeLink(e,"member left"),this.outbox.forget(e),this.wantSentAt.delete(e);let r=this.retry.get(e);r?.timer&&clearTimeout(r.timer),this.retry.delete(e),this.extraPeers.delete(e),this.successor===e&&(this.successor=null),i&&this.emit("memberLeft",{userId:e,kind:s,by:t});}scheduleRefresh(){this.refreshTimer||this.stopped||(this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.refreshMembers();},400));}applySnapshot(e){if(this.stopped)return;e.IceServers?.length&&(this.iceServers=p(e.IceServers)),e.OwnerUserID&&(this.ownerId=e.OwnerUserID);let s=new Map;for(let t of e.Members??[])t.UserID&&s.set(t.UserID,t);for(let t of [...this.members.keys()])!s.has(t)&&t!==this.selfId&&this.dropMember(t,"left");for(let[t,i]of s){let r=this.members.has(t);this.members.set(t,i),!r&&t!==this.selfId&&this.emit("memberJoined",{member:i});}if(e.HostUserID&&e.HostUserID!==this.hostId){let t=this.hostId||null;this.hostId=e.HostUserID,this.emit("hostChanged",{hostId:e.HostUserID,previousHostId:t});}this.emit("membersUpdated",{members:[...this.members.values()]}),this.reconcile();}wanted(){let e=new Set,s=[...this.members.keys()].filter(t=>t!==this.selfId);if(this.topology==="Mesh"||this.isHost)for(let t of s)e.add(t);else this.hostId&&this.hostId!==this.selfId&&this.members.has(this.hostId)&&e.add(this.hostId);for(let t of this.extraPeers)this.members.has(t)&&e.add(t);return e}reconcile(){if(this.stopped)return;let e=Date.now();for(let s of this.wanted())if(!(this.links.has(s)||this.retry.get(s)?.timer))if(this.selfId<s)this.openLink(s,true,I());else {let t=this.wantSentAt.get(s)??0;e-t>8e3&&(this.wantSentAt.set(s,e),this.outbox.enqueue(s,{t:"want"}));}}handleSignals(e,s){if(!(!e||e===this.selfId)){this.members.has(e)||(this.members.set(e,{UserID:e}),this.scheduleRefresh());for(let t of s){let i=this.links.get(e);if(t.t==="want"){(!i||i.state==="closed")&&this.openLink(e,true,I());continue}if(t.t==="offer"){if(i?.lid===t.lid)continue;i&&this.closeLink(e,"replaced by a new offer"),this.openLink(e,false,t.lid).handle(t);continue}i&&i.lid===t.lid&&i.handle(t);}}}openLink(e,s,t){this.wantSentAt.delete(e);let i=new d({peerId:e,offerer:s,lid:t,iceServers:this.iceServers,createPeerConnection:this.o.createPeerConnection,signal:r=>this.outbox.enqueue(e,r),iceGatherTimeoutMs:this.o.iceGatherTimeoutMs,keepaliveMs:this.o.keepaliveMs,peerTimeoutMs:this.o.peerTimeoutMs,onOpen:()=>{this.everOpen.add(e),this.retry.delete(e),this.emit("peerOpen",{peerId:e});},onClose:r=>this.onLinkClosed(i,r),onMessage:(r,n)=>this.emit("message",{from:e,channel:r,data:n}),onNotice:r=>{r===1&&this.schedulePoll(0);}});return this.links.set(e,i),this.schedulePoll(Math.min(this.o.pollFastMs,250)),i}closeLink(e,s){let t=this.links.get(e);t&&(this.links.delete(e),t.close(s,true));}onLinkClosed(e,s){let t=e.peerId,i=this.links.get(t)===e;if(i&&this.links.delete(t),this.everOpen.delete(t)&&this.emit("peerClose",{peerId:t,reason:s}),!i||this.stopped||!this.members.has(t)||!this.wanted().has(t))return;let r=this.retry.get(t)??{attempts:0,timer:null},n=Math.min(15e3,1e3*2**r.attempts);r.attempts++,r.timer=setTimeout(()=>{r.timer=null,this.wantSentAt.delete(t),this.reconcile();},n),this.retry.set(t,r);}emit(e,s){for(let t of this.listeners.get(e)??[])try{t(s);}catch(i){console.error(`[RealtimeSession] ${String(e)} handler failed`,i);}}end(e,s){this.stopped||(this.stop(),this.emit(e,s));}stop(){this.stopped=true,this.pollTimer&&clearTimeout(this.pollTimer),this.refreshTimer&&clearTimeout(this.refreshTimer),this.pollTimer=this.refreshTimer=null;for(let e of this.retry.values())e.timer&&clearTimeout(e.timer);this.retry.clear(),this.outbox.close();for(let e of [...this.links.keys()]){let s=this.links.get(e);this.links.delete(e),s?.close("session closed");}typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide);}leaveOnUnload(){if(this.stopped)return;let e=this.isHost?this.successor??void 0:void 0;this.stop(),this.emit("left",{}),this.client.multiplayer.leaveRoom(this.roomId,{successorUserID:e,keepalive:true});}};function I(){let o=globalThis.crypto;return o&&"randomUUID"in o?o.randomUUID().slice(0,12):Math.random().toString(36).slice(2,14)}export{f as MAX_MESSAGE_BYTES,y as RealtimeSession,p as toRtcIceServers};
1
+ import {b}from'../chunk-CS7ACWDY.js';var f=16384;function g(o){let e=new Uint8Array(o.byteLength+1);return e[0]=0,e.set(o,1),e}function v(o,e){if(o.byteLength+1<=16384)return [g(o)];if(o.byteLength>67108864)throw new RangeError(`Message of ${o.byteLength} bytes exceeds 67108864.`);let s=Math.ceil(o.byteLength/16375),t=[];for(let i=0;i<s;i++){let r=o.subarray(i*16375,Math.min(o.byteLength,(i+1)*16375)),n=new Uint8Array(9+r.byteLength),a=new DataView(n.buffer);n[0]=1,a.setUint32(1,e>>>0),a.setUint16(5,i),a.setUint16(7,s),n.set(r,9),t.push(n);}return t}var c=class{id=-1;count=0;parts=[];bytes=0;push(e){if(e.byteLength<9)return null;let s=new DataView(e.buffer,e.byteOffset,e.byteLength),t=s.getUint32(1),i=s.getUint16(5),r=s.getUint16(7);if(i===0&&(this.id=t,this.count=r,this.parts=[],this.bytes=0),t!==this.id||i!==this.parts.length||r!==this.count)return this.reset(),null;let n=e.subarray(9);if(this.bytes+=n.byteLength,this.bytes>67108864)return this.reset(),null;if(this.parts.push(n),this.parts.length<this.count)return null;let a=new Uint8Array(this.bytes),l=0;for(let h of this.parts)a.set(h,l),l+=h.byteLength;return this.reset(),a}reset(){this.id=-1,this.count=0,this.parts=[],this.bytes=0;}};function p(o){let e=new Map;for(let s of o??[]){let t=s.Urls?.trim();if(!t)continue;let i=s.Username??void 0,r=s.Credential??void 0,n=`${i??""}\0${r??""}`,a=e.get(n);if(a){let h=Array.isArray(a.urls)?a.urls:[a.urls];h.includes(t)||h.push(t),a.urls=h;continue}let l={urls:[t]};i&&(l.username=i),r&&(l.credential=r),e.set(n,l);}return [...e.values()]}var C=4*1024*1024,A=5e3,d=class{constructor(e){this.o=e;this.peerId=e.peerId,this.offerer=e.offerer,this.lid=e.lid,this.pc=e.createPeerConnection({iceServers:e.iceServers}),this.pc.onicecandidate=s=>{if(!s.candidate){this.sendDescriptionIfReady();return}this.descriptionSent&&this.lateIce.push(s.candidate.toJSON()),this.flushLateIce();},this.pc.onconnectionstatechange=()=>{let s=this.pc.connectionState;(s==="failed"||s==="closed")&&this.close(`connection ${s}`);},this.pc.ondatachannel=s=>this.adopt(s.channel),this.openTimer=setTimeout(()=>{this.state==="connecting"&&this.close("connect timeout");},Math.max(15e3,e.peerTimeoutMs*3)),this.offerer&&(this.adopt(this.pc.createDataChannel("rel",{ordered:true})),this.adopt(this.pc.createDataChannel("fast",{ordered:false,maxRetransmits:0})),this.makeOffer());}o;peerId;offerer;lid;state="connecting";pc;rel=null;fast=null;reassembler=new c;pendingRemoteIce=[];descriptionSent=false;lateIce=[];lastRecv=Date.now();lastSend=0;msgSeq=1;keepaliveTimer=null;gatherTimer=null;openTimer=null;bytesIn=0;bytesOut=0;rttMs=0;pingSentAt=0;async makeOffer(){try{await this.pc.setLocalDescription(await this.pc.createOffer()),this.waitForGathering();}catch(e){this.close(`offer failed: ${String(e)}`);}}async handle(e){if(this.state!=="closed")try{if(e.t==="offer"&&!this.offerer)await this.pc.setRemoteDescription({type:"offer",sdp:e.sdp}),await this.drainRemoteIce(),await this.pc.setLocalDescription(await this.pc.createAnswer()),this.waitForGathering();else if(e.t==="answer"&&this.offerer){if(this.pc.signalingState!=="have-local-offer")return;await this.pc.setRemoteDescription({type:"answer",sdp:e.sdp}),await this.drainRemoteIce();}else if(e.t==="ice")if(!this.pc.remoteDescription)this.pendingRemoteIce.push(...e.c);else for(let s of e.c)await this.addIce(s);else e.t==="bye"&&this.close("peer closed the link");}catch(s){this.close(`signaling failed: ${String(s)}`);}}async drainRemoteIce(){let e=this.pendingRemoteIce.splice(0);for(let s of e)await this.addIce(s);}async addIce(e){try{await this.pc.addIceCandidate(e);}catch{}}waitForGathering(){if(this.pc.iceGatheringState==="complete"){this.sendDescriptionIfReady();return}this.gatherTimer=setTimeout(()=>this.sendDescriptionIfReady(),this.o.iceGatherTimeoutMs);}sendDescriptionIfReady(){if(this.descriptionSent||this.state==="closed")return;let e=this.pc.localDescription;e?.sdp&&(this.gatherTimer&&clearTimeout(this.gatherTimer),this.gatherTimer=null,this.descriptionSent=true,this.o.signal(this.offerer?{t:"offer",lid:this.lid,sdp:e.sdp}:{t:"answer",lid:this.lid,sdp:e.sdp}),this.flushLateIce());}flushLateIce(){if(!this.descriptionSent||this.lateIce.length===0)return;let e=this.lateIce;this.lateIce=[],this.o.signal({t:"ice",lid:this.lid,c:e});}adopt(e){if(e.binaryType="arraybuffer",e.label==="rel")this.rel=e;else if(e.label==="fast")this.fast=e;else return;e.onopen=()=>this.maybeOpen(),e.onclose=()=>this.close(`channel ${e.label} closed`),e.onmessage=s=>this.receive(e.label,s.data),e.readyState==="open"&&queueMicrotask(()=>this.maybeOpen());}maybeOpen(){this.state==="connecting"&&(this.rel?.readyState!=="open"||this.fast?.readyState!=="open"||(this.state="open",this.openTimer&&clearTimeout(this.openTimer),this.openTimer=null,this.lastRecv=Date.now(),this.keepaliveTimer=setInterval(()=>this.keepalive(),this.o.keepaliveMs),this.o.onOpen()));}keepalive(){if(this.state!=="open")return;let e=Date.now();if(e-this.lastRecv>this.o.peerTimeoutMs){this.close("peer timeout");return}(e-this.lastSend>=this.o.keepaliveMs||e-this.pingSentAt>=A)&&(this.pingSentAt=e,this.raw("fast",new Uint8Array([2])));}receive(e,s){if(!(s instanceof ArrayBuffer))return;let t=new Uint8Array(s);this.lastRecv=Date.now(),this.bytesIn+=t.byteLength;let i=t[0];if(i===0)this.o.onMessage(e,t.subarray(1));else if(i===1&&e==="rel"){let r=this.reassembler.push(t);r&&this.o.onMessage(e,r);}else i===2?this.raw("fast",new Uint8Array([3])):i===3?this.pingSentAt&&(this.rttMs=Date.now()-this.pingSentAt):i===4&&e==="rel"&&this.o.onNotice?.(t[1]??0);}send(e,s){if(this.state!=="open")return false;if(e==="fast")return s.byteLength+1>16384?false:this.raw("fast",g(s));if((this.rel?.bufferedAmount??0)>C)return false;let t=v(s,this.msgSeq++);for(let i of t)if(!this.raw("rel",i))return false;return true}notice(e){return this.state!=="open"?false:this.raw("rel",new Uint8Array([4,e]))}get relBuffered(){return this.rel?.bufferedAmount??0}raw(e,s){let t=e==="rel"?this.rel:this.fast;if(!t||t.readyState!=="open")return false;try{return t.send(s),this.lastSend=Date.now(),this.bytesOut+=s.byteLength,!0}catch{return false}}close(e="closed",s=false){if(this.state!=="closed"){this.state="closed",s&&this.descriptionSent&&this.o.signal({t:"bye",lid:this.lid}),this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.gatherTimer&&clearTimeout(this.gatherTimer),this.openTimer&&clearTimeout(this.openTimer),this.keepaliveTimer=this.gatherTimer=this.openTimer=null;for(let t of [this.rel,this.fast])if(t){t.onopen=t.onclose=t.onmessage=null;try{t.close();}catch{}}this.pc.onicecandidate=this.pc.onconnectionstatechange=this.pc.ondatachannel=null;try{this.pc.close();}catch{}this.reassembler.reset(),this.o.onClose(e);}}};function R(o){if(!o)return [];try{let e=JSON.parse(o);return !e||e.v!==1||!Array.isArray(e.m)?[]:e.m.filter(s=>!!s&&typeof s=="object"&&typeof s.t=="string")}catch{return []}}var u=class{constructor(e,s={}){this.send=e;this.perTargetGapMs=s.perTargetGapMs??650,this.globalGapMs=s.globalGapMs??180,this.maxPayloadBytes=s.maxPayloadBytes??15e3,this.maxAttempts=s.maxAttempts??4;}send;queues=new Map;lastSent=new Map;lastAny=0;inflight=false;timer=null;closed=false;perTargetGapMs;globalGapMs;maxPayloadBytes;maxAttempts;get busy(){return this.inflight||this.queues.size>0}enqueue(e,s){if(this.closed)return;let t=this.queues.get(e)??{msgs:[],attempts:0},i=t.msgs[t.msgs.length-1];s.t==="ice"&&i?.t==="ice"&&i.lid===s.lid?i.c.push(...s.c):t.msgs.push(s),this.queues.set(e,t),this.pump();}forget(e){this.queues.delete(e),this.lastSent.delete(e);}close(){this.closed=true,this.queues.clear(),this.timer&&clearTimeout(this.timer),this.timer=null;}pump(){if(this.closed||this.inflight||this.timer)return;let e=Date.now(),s=null,t=1/0;for(let i of this.queues.keys()){let r=Math.max((this.lastSent.get(i)??0)+this.perTargetGapMs,this.lastAny+this.globalGapMs);if(r<=e){s=i;break}t=Math.min(t,r-e);}if(s===null){t!==1/0&&(this.timer=setTimeout(()=>{this.timer=null,this.pump();},t));return}this.flush(s);}async flush(e){let s=this.queues.get(e);if(!s||s.msgs.length===0){this.queues.delete(e),this.pump();return}let t=[],i="";for(let l of s.msgs){let h=JSON.stringify({v:1,m:[...t,l]});if(t.length>0&&E(h)>this.maxPayloadBytes)break;t.push(l),i=h;}let r=s.msgs.slice(t.length);r.length?this.queues.set(e,{msgs:r,attempts:0}):this.queues.delete(e),this.inflight=true;let n=null;try{n=await this.send(e,"rtc",i);}catch{n=null;}this.inflight=false;let a=Date.now();if(this.lastSent.set(e,a),this.lastAny=a,!n?.ok&&!this.closed){let l=n?.ok===false?n.reason:"connection";if((l==="throttled"||l==="connection")&&s.attempts+1<this.maxAttempts){let T=this.queues.get(e);this.queues.set(e,{msgs:[...t,...T?.msgs??[]],attempts:s.attempts+1});}}this.pump();}};function E(o){return new TextEncoder().encode(o).byteLength}var D={pollFastMs:1e3,pollHostIdleMs:2500,pollClientIdleMs:2e4,fastWindowMs:15e3,keepaliveMs:1e3,peerTimeoutMs:6e3,iceGatherTimeoutMs:1200,maxSignalPayloadBytes:15e3,signalPerTargetGapMs:650,signalGlobalGapMs:180},y=class o{constructor(e,s,t,i){this.client=e;this.selfId=s,this.roomId=t.RoomID??"",this.topology=t.Topology??"Mesh",this.chatMode=t.ChatMode??"ServerRelay",this.mode=t.Mode??null,this.ownerId=t.OwnerUserID??"",this.hostId=t.HostUserID??"",this.lastSeq=t.Seq??0,this.iceServers=p(t.IceServers),this.o={...D,leaveOnPageHide:true,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0)),createPeerConnection:i.createPeerConnection??(r=>new RTCPeerConnection(r))};for(let r of t.Members??[])r.UserID&&this.members.set(r.UserID,r);this.outbox=new u((r,n,a)=>this.client.multiplayer.sendSignal(this.roomId,r,n,a),{maxPayloadBytes:this.o.maxSignalPayloadBytes,perTargetGapMs:this.o.signalPerTargetGapMs,globalGapMs:this.o.signalGlobalGapMs}),this.fastUntil=Date.now()+this.o.fastWindowMs,this.o.leaveOnPageHide&&typeof window<"u"&&window.addEventListener("pagehide",this.onPageHide);}client;roomId;selfId;topology;chatMode;mode;ownerId;hostId;members=new Map;o;iceServers;lastSeq;links=new Map;everOpen=new Set;retry=new Map;wantSentAt=new Map;extraPeers=new Set;outbox;pollTimer=null;polling=false;pollSoonMs=null;pollBackoff=0;fastUntil=0;refreshTimer=null;stopped=false;successor=null;listeners=new Map;onPageHide=()=>this.leaveOnUnload();static async create(e,s,t={},i={}){let r=e.auth.context?.userID;if(!r)return b("unauthorized","Not logged in.");let n=await e.multiplayer.createRoom(s,t);return n.ok?{ok:true,data:o.start(e,r,n.data,i)}:n}static async join(e,s,t,i={}){let r=e.auth.context?.userID;if(!r)return b("unauthorized","Not logged in.");let n=await e.multiplayer.joinRoom(s,t);return n.ok?{ok:true,data:o.start(e,r,n.data,i)}:n}static start(e,s,t,i){let r=new o(e,s,t,i);return r.reconcile(),r.schedulePoll(0),r}get isHost(){return this.hostId===this.selfId}get isOwner(){return this.ownerId===this.selfId}get closed(){return this.stopped}on(e,s){let t=this.listeners.get(e)??new Set;return t.add(s),this.listeners.set(e,t),()=>t.delete(s)}openPeers(){return [...this.links.values()].filter(e=>e.state==="open").map(e=>e.peerId)}isOpen(e){return this.links.get(e)?.state==="open"}linkStats(e){let s=this.links.get(e);return s?{rttMs:s.rttMs,bytesIn:s.bytesIn,bytesOut:s.bytesOut,buffered:s.relBuffered}:null}send(e,s,t){return this.links.get(e)?.send(s,t)??false}broadcast(e,s,t){let i=0;for(let r of this.links.values())r.peerId!==t&&r.state==="open"&&r.send(e,s)&&i++;return i}setExtraPeers(e){this.extraPeers=new Set([...e].filter(s=>s!==this.selfId)),this.reconcile();}setSuccessor(e){this.successor=e&&e!==this.selfId?e:null;}async claimHost(){let e=await this.client.multiplayer.claimHost(this.roomId);return e.ok&&this.applySnapshot(e.data),e}async kick(e,s=false){let t=await this.client.multiplayer.kickMember(this.roomId,e,s);return t.ok&&this.links.get(e)?.notice(1),t}unban(e){return this.client.multiplayer.unbanMember(this.roomId,e)}async leave(){if(this.stopped)return;let e=this.isHost?this.successor??void 0:void 0;this.stop(),this.emit("left",{}),await this.client.multiplayer.leaveRoom(this.roomId,{successorUserID:e});}async refreshMembers(){let e=await this.client.multiplayer.getRoom(this.roomId);e.ok&&this.applySnapshot(e.data);}schedulePoll(e){if(!this.stopped){if(this.polling){this.pollSoonMs=Math.min(this.pollSoonMs??e,e);return}this.pollTimer&&clearTimeout(this.pollTimer),this.pollTimer=setTimeout(()=>{this.pollOnce();},e);}}nextPollDelay(){return Date.now()<this.fastUntil||this.outbox.busy||[...this.links.values()].some(s=>s.state==="connecting")||[...this.wanted()].some(s=>!this.links.has(s))?this.o.pollFastMs:this.isHost?this.o.pollHostIdleMs:this.o.pollClientIdleMs}async pollOnce(){if(this.stopped)return;this.pollTimer=null,this.polling=true,this.pollSoonMs=null;let e=await this.client.multiplayer.poll(this.roomId,this.lastSeq);if(this.polling=false,this.stopped)return;let s=this.pollSoonMs;if(this.pollSoonMs=null,e.ok){this.pollBackoff=0;for(let t of e.data.Envelopes??[])this.handleEnvelope(t);this.lastSeq=e.data.MaxSeq??this.lastSeq,this.reconcile(),this.schedulePoll(Math.min(this.nextPollDelay(),s??1/0));return}if(e.reason==="server"){let t=e.error??"";if(/not a member/i.test(t))return this.end("removed",{reason:t});if(/no longer exists|not found/i.test(t))return this.end("roomClosed",{});if(/disabled/i.test(t))return this.end("roomClosed",{})}this.pollBackoff=Math.min(this.pollBackoff+1,5),this.schedulePoll(this.o.pollFastMs*(1+this.pollBackoff));}handleEnvelope(e){let s=e.FromUserID??"";switch(e.Type){case "Signal":e.ToUserID===this.selfId&&e.Kind==="rtc"&&this.handleSignals(s,R(e.Payload));break;case "PlayerJoined":{let t=e.Payload||s;if(!t||t===this.selfId)break;if(!this.members.has(t)){let i={UserID:t};this.members.set(t,i),this.emit("memberJoined",{member:i});}this.fastUntil=Date.now()+this.o.fastWindowMs,this.scheduleRefresh();break}case "PlayerLeft":{let t=e.Payload||s,i=e.Kind==="kicked"?"kicked":e.Kind==="timeout"?"timeout":"left";if(t===this.selfId){i!=="left"&&this.end("removed",{reason:i});break}this.dropMember(t,i,i==="kicked"?s:void 0);break}case "HostChanged":{let t=e.Payload??"";if(t&&t!==this.hostId){let i=this.hostId||null;this.hostId=t,this.fastUntil=Date.now()+this.o.fastWindowMs,this.emit("hostChanged",{hostId:t,previousHostId:i});}break}case "RoomClosed":this.end("roomClosed",{});break;case "MemberState":this.scheduleRefresh();break;case "Chat":this.emit("chat",{from:s,text:e.Payload??""});break}}dropMember(e,s,t){let i=this.members.delete(e);this.closeLink(e,"member left"),this.outbox.forget(e),this.wantSentAt.delete(e);let r=this.retry.get(e);r?.timer&&clearTimeout(r.timer),this.retry.delete(e),this.extraPeers.delete(e),this.successor===e&&(this.successor=null),i&&this.emit("memberLeft",{userId:e,kind:s,by:t});}scheduleRefresh(){this.refreshTimer||this.stopped||(this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.refreshMembers();},400));}applySnapshot(e){if(this.stopped)return;e.IceServers?.length&&(this.iceServers=p(e.IceServers)),e.OwnerUserID&&(this.ownerId=e.OwnerUserID);let s=new Map;for(let t of e.Members??[])t.UserID&&s.set(t.UserID,t);for(let t of [...this.members.keys()])!s.has(t)&&t!==this.selfId&&this.dropMember(t,"left");for(let[t,i]of s){let r=this.members.has(t);this.members.set(t,i),!r&&t!==this.selfId&&this.emit("memberJoined",{member:i});}if(e.HostUserID&&e.HostUserID!==this.hostId){let t=this.hostId||null;this.hostId=e.HostUserID,this.emit("hostChanged",{hostId:e.HostUserID,previousHostId:t});}this.emit("membersUpdated",{members:[...this.members.values()]}),this.reconcile();}wanted(){let e=new Set,s=[...this.members.keys()].filter(t=>t!==this.selfId);if(this.topology==="Mesh"||this.isHost)for(let t of s)e.add(t);else this.hostId&&this.hostId!==this.selfId&&this.members.has(this.hostId)&&e.add(this.hostId);for(let t of this.extraPeers)this.members.has(t)&&e.add(t);return e}reconcile(){if(this.stopped)return;let e=Date.now();for(let s of this.wanted())if(!(this.links.has(s)||this.retry.get(s)?.timer))if(this.selfId<s)this.openLink(s,true,I());else {let t=this.wantSentAt.get(s)??0;e-t>8e3&&(this.wantSentAt.set(s,e),this.outbox.enqueue(s,{t:"want"}));}}handleSignals(e,s){if(!(!e||e===this.selfId)){this.members.has(e)||(this.members.set(e,{UserID:e}),this.scheduleRefresh());for(let t of s){let i=this.links.get(e);if(t.t==="want"){(!i||i.state==="closed")&&this.openLink(e,true,I());continue}if(t.t==="offer"){if(i?.lid===t.lid)continue;i&&this.closeLink(e,"replaced by a new offer"),this.openLink(e,false,t.lid).handle(t);continue}i&&i.lid===t.lid&&i.handle(t);}}}openLink(e,s,t){this.wantSentAt.delete(e);let i=new d({peerId:e,offerer:s,lid:t,iceServers:this.iceServers,createPeerConnection:this.o.createPeerConnection,signal:r=>this.outbox.enqueue(e,r),iceGatherTimeoutMs:this.o.iceGatherTimeoutMs,keepaliveMs:this.o.keepaliveMs,peerTimeoutMs:this.o.peerTimeoutMs,onOpen:()=>{this.everOpen.add(e),this.retry.delete(e),this.emit("peerOpen",{peerId:e});},onClose:r=>this.onLinkClosed(i,r),onMessage:(r,n)=>this.emit("message",{from:e,channel:r,data:n}),onNotice:r=>{r===1&&this.schedulePoll(0);}});return this.links.set(e,i),this.schedulePoll(Math.min(this.o.pollFastMs,250)),i}closeLink(e,s){let t=this.links.get(e);t&&(this.links.delete(e),t.close(s,true));}onLinkClosed(e,s){let t=e.peerId,i=this.links.get(t)===e;if(i&&this.links.delete(t),this.everOpen.delete(t)&&this.emit("peerClose",{peerId:t,reason:s}),!i||this.stopped||!this.members.has(t)||!this.wanted().has(t))return;let r=this.retry.get(t)??{attempts:0,timer:null},n=Math.min(15e3,1e3*2**r.attempts);r.attempts++,r.timer=setTimeout(()=>{r.timer=null,this.wantSentAt.delete(t),this.reconcile();},n),this.retry.set(t,r);}emit(e,s){for(let t of this.listeners.get(e)??[])try{t(s);}catch(i){console.error(`[RealtimeSession] ${String(e)} handler failed`,i);}}end(e,s){this.stopped||(this.stop(),this.emit(e,s));}stop(){this.stopped=true,this.pollTimer&&clearTimeout(this.pollTimer),this.refreshTimer&&clearTimeout(this.refreshTimer),this.pollTimer=this.refreshTimer=null;for(let e of this.retry.values())e.timer&&clearTimeout(e.timer);this.retry.clear(),this.outbox.close();for(let e of [...this.links.keys()]){let s=this.links.get(e);this.links.delete(e),s?.close("session closed");}typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide);}leaveOnUnload(){if(this.stopped)return;let e=this.isHost?this.successor??void 0:void 0;this.stop(),this.emit("left",{}),this.client.multiplayer.leaveRoom(this.roomId,{successorUserID:e,keepalive:true});}};function I(){let o=globalThis.crypto;return o&&"randomUUID"in o?o.randomUUID().slice(0,12):Math.random().toString(36).slice(2,14)}export{f as MAX_MESSAGE_BYTES,y as RealtimeSession,p as toRtcIceServers};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@idosgames/core",
3
- "version": "0.21.1",
3
+ "version": "0.21.3",
4
4
  "description": "Engine-agnostic core of the IDosGames SDK (transport, auth, cache, services, events).",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1 +0,0 @@
1
- function t(e){return {ok:true,data:e}}function o(e,r){return {ok:false,reason:e,error:r}}function n(e){return e.ok}function a(e){return !e.ok}export{t as a,o as b,n as c,a as d};
@@ -1,2 +0,0 @@
1
- var o=class{getString(e){if(typeof localStorage>"u")return null;try{return localStorage.getItem(e)}catch{return null}}setString(e,r){if(!(typeof localStorage>"u"))try{localStorage.setItem(e,r);}catch{}}remove(e){if(!(typeof localStorage>"u"))try{localStorage.removeItem(e);}catch{}}},a=class{map=new Map;getString(e){return this.map.get(e)??null}setString(e,r){this.map.set(e,r);}remove(e){this.map.delete(e);}};function n(){return globalThis.Telegram?.WebApp??null}function s(){return crypto.randomUUID()}var g="idos_device_id",i=class{storage;constructor(e=new o){this.storage=e;}getPlatform(){return n()?.platform??"Web"}getFullURL(){return typeof location<"u"?location.href:""}getStartParameter(){let e=n()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){if(typeof document>"u")return null;let e=document.referrer;return e&&e.length>0?e:null}getTelegramInitDataRaw(){let e=n()?.initData;return e&&e.length>0?e:null}getDeviceID(){let e=this.storage.getString(g);return e||(e=s(),this.storage.setString(g,e)),e}getDeviceModel(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"Web"}shareLink(e){let r=n();if(r?.openTelegramLink){r.openTelegramLink(e);return}typeof window<"u"&&window.open(e,"_blank");}openInvoice(e){let r=n();if(r?.openInvoice){r.openInvoice(e);return}typeof window<"u"&&window.open(e,"_blank");}async showAd(e){let r=globalThis;typeof r.showAd=="function"&&await r.showAd(e);}async copyToClipboard(e){typeof navigator<"u"&&navigator.clipboard&&await navigator.clipboard.writeText(e);}};var p="idos_device_id",l=class{storage;constructor(e=new a){this.storage=e;}getPlatform(){return "Web"}getFullURL(){return ""}getStartParameter(){return null}getTelegramInitDataRaw(){return null}getDeviceID(){let e=this.storage.getString(p);return e||(e="noop-device",this.storage.setString(p,e)),e}getDeviceModel(){return "Noop"}shareLink(){}openInvoice(){}async showAd(){}async copyToClipboard(){}};var u=["https://idosgames.com","https://www.idosgames.com"];function m(t){return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t.endsWith(".localhost")}function f(t){if(u.includes(t))return true;if(typeof window>"u"||!m(window.location.hostname))return false;try{return m(new URL(t).hostname)}catch{return false}}
2
- export{o as a,a as b,n as c,s as d,i as e,u as f,f as g,l as h};