@idosgames/core 0.21.5 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +40 -0
- package/dist/{RealtimeSession-BBJ3gAb8.d.cts → VoiceController-C6b08lqX.d.cts} +197 -17
- package/dist/{RealtimeSession-D7evucmN.d.ts → VoiceController-DeqV4QI0.d.ts} +197 -17
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/platform/index.d.cts +2 -1
- package/dist/platform/index.d.ts +2 -1
- package/dist/realtime/index.cjs +1 -1
- package/dist/realtime/index.d.cts +2 -2
- package/dist/realtime/index.d.ts +2 -2
- package/dist/realtime/index.js +1 -1
- package/package.json +1 -1
|
@@ -114,7 +114,8 @@ interface PlatformTopUpResult {
|
|
|
114
114
|
ok: boolean;
|
|
115
115
|
/**
|
|
116
116
|
* Why not: `CANCELLED`, `PENDING` (sent, the engine has not credited it yet), `ACCOUNT_MISMATCH`,
|
|
117
|
-
* `NOT_DEPOSITABLE`, `NO_WALLET`, `TIMEOUT`, `PLATFORM_WALLET_UNAVAILABLE`,
|
|
117
|
+
* `NOT_DEPOSITABLE`, `NO_WALLET`, `TIMEOUT`, `PLATFORM_WALLET_UNAVAILABLE`, `BUSY` (a top-up window is already
|
|
118
|
+
* open), `COOLDOWN` (the previous top-up failed less than 30 s ago — the site pauses repeat requests), …
|
|
118
119
|
*/
|
|
119
120
|
error?: string;
|
|
120
121
|
}
|
package/dist/platform/index.d.ts
CHANGED
|
@@ -114,7 +114,8 @@ interface PlatformTopUpResult {
|
|
|
114
114
|
ok: boolean;
|
|
115
115
|
/**
|
|
116
116
|
* Why not: `CANCELLED`, `PENDING` (sent, the engine has not credited it yet), `ACCOUNT_MISMATCH`,
|
|
117
|
-
* `NOT_DEPOSITABLE`, `NO_WALLET`, `TIMEOUT`, `PLATFORM_WALLET_UNAVAILABLE`,
|
|
117
|
+
* `NOT_DEPOSITABLE`, `NO_WALLET`, `TIMEOUT`, `PLATFORM_WALLET_UNAVAILABLE`, `BUSY` (a top-up window is already
|
|
118
|
+
* open), `COOLDOWN` (the previous top-up failed less than 30 s ago — the site pauses repeat requests), …
|
|
118
119
|
*/
|
|
119
120
|
error?: string;
|
|
120
121
|
}
|
package/dist/realtime/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
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
|
+
'use strict';function d(o){return {ok:true,data:o}}function c(o,e){return {ok:false,reason:o,error:e}}var g=16384;function v(o){let e=new Uint8Array(o.byteLength+1);return e[0]=0,e.set(o,1),e}function b(o,e){if(o.byteLength+1<=16384)return [v(o)];if(o.byteLength>67108864)throw new RangeError(`Message of ${o.byteLength} bytes exceeds 67108864.`);let i=Math.ceil(o.byteLength/16375),t=[];for(let s=0;s<i;s++){let r=o.subarray(s*16375,Math.min(o.byteLength,(s+1)*16375)),n=new Uint8Array(9+r.byteLength),a=new DataView(n.buffer);n[0]=1,a.setUint32(1,e>>>0),a.setUint16(5,s),a.setUint16(7,i),n.set(r,9),t.push(n);}return t}var u=class{id=-1;count=0;parts=[];bytes=0;push(e){if(e.byteLength<9)return null;let i=new DataView(e.buffer,e.byteOffset,e.byteLength),t=i.getUint32(1),s=i.getUint16(5),r=i.getUint16(7);if(s===0&&(this.id=t,this.count=r,this.parts=[],this.bytes=0),t!==this.id||s!==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 i of o??[]){let t=i.Urls?.trim();if(!t)continue;let s=i.Username??void 0,r=i.Credential??void 0,n=`${s??""}\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]};s&&(l.username=s),r&&(l.credential=r),e.set(n,l);}return [...e.values()]}var E=4*1024*1024,P=5e3,m=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=i=>{if(!i.candidate){this.sendDescriptionIfReady();return}this.descriptionSent&&this.lateIce.push(i.candidate.toJSON()),this.flushLateIce();},this.pc.onconnectionstatechange=()=>{let i=this.pc.connectionState;(i==="failed"||i==="closed")&&this.close(`connection ${i}`);},this.pc.ondatachannel=i=>this.adopt(i.channel),this.pc.ontrack=i=>{i.track?.kind!=="audio"||this.state==="closed"||(this.remoteAudio=i.track,this.o.onAudio?.(i.track));},this.openTimer=setTimeout(()=>{this.state==="connecting"&&this.close("connect timeout");},Math.max(15e3,e.peerTimeoutMs*3)),this.offerer&&(e.audio&&(this.audioTx=this.pc.addTransceiver("audio",{direction:"sendrecv"})),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 u;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;audioTx=null;micTrack=null;remoteAudio=null;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}),this.o.audio&&this.adoptAudio(),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 i of e.c)await this.addIce(i);else e.t==="bye"&&this.close("peer closed the link");}catch(i){this.close(`signaling failed: ${String(i)}`);}}adoptAudio(){let e=this.pc.getTransceivers().find(i=>i.receiver.track?.kind==="audio"&&i.currentDirection!=="stopped")??null;e&&(e.direction="sendrecv",this.audioTx=e,this.micTrack&&this.applyMic());}setMicTrack(e){this.micTrack=e,this.applyMic();}applyMic(){!this.audioTx||this.state==="closed"||this.audioTx.sender.replaceTrack(this.micTrack).catch(()=>{});}async drainRemoteIce(){let e=this.pendingRemoteIce.splice(0);for(let i of e)await this.addIce(i);}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=i=>this.receive(e.label,i.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>=P)&&(this.pingSentAt=e,this.raw("fast",new Uint8Array([2])));}receive(e,i){if(!(i instanceof ArrayBuffer))return;let t=new Uint8Array(i);this.lastRecv=Date.now(),this.bytesIn+=t.byteLength;let s=t[0];if(s===0)this.o.onMessage(e,t.subarray(1));else if(s===1&&e==="rel"){let r=this.reassembler.push(t);r&&this.o.onMessage(e,r);}else s===2?this.raw("fast",new Uint8Array([3])):s===3?this.pingSentAt&&(this.rttMs=Date.now()-this.pingSentAt):s===4&&e==="rel"&&this.o.onNotice?.(t[1]??0);}send(e,i){if(this.state!=="open")return false;if(e==="fast")return i.byteLength+1>16384?false:this.raw("fast",v(i));if((this.rel?.bufferedAmount??0)>E)return false;let t=b(i,this.msgSeq++);for(let s of t)if(!this.raw("rel",s))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,i){let t=e==="rel"?this.rel:this.fast;if(!t||t.readyState!=="open")return false;try{return t.send(i),this.lastSend=Date.now(),this.bytesOut+=i.byteLength,!0}catch{return false}}close(e="closed",i=false){if(this.state!=="closed"){this.state="closed",i&&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=this.pc.ontrack=null,this.audioTx=null,this.remoteAudio=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(i=>!!i&&typeof i=="object"&&typeof i.t=="string")}catch{return []}}var f=class{constructor(e,i={}){this.send=e;this.perTargetGapMs=i.perTargetGapMs??650,this.globalGapMs=i.globalGapMs??180,this.maxPayloadBytes=i.maxPayloadBytes??15e3,this.maxAttempts=i.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,i){if(this.closed)return;let t=this.queues.get(e)??{msgs:[],attempts:0},s=t.msgs[t.msgs.length-1];i.t==="ice"&&s?.t==="ice"&&s.lid===i.lid?s.c.push(...i.c):t.msgs.push(i),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(),i=null,t=1/0;for(let s of this.queues.keys()){let r=Math.max((this.lastSent.get(s)??0)+this.perTargetGapMs,this.lastAny+this.globalGapMs);if(r<=e){i=s;break}t=Math.min(t,r-e);}if(i===null){t!==1/0&&(this.timer=setTimeout(()=>{this.timer=null,this.pump();},t));return}this.flush(i);}async flush(e){let i=this.queues.get(e);if(!i||i.msgs.length===0){this.queues.delete(e),this.pump();return}let t=[],s="";for(let l of i.msgs){let h=JSON.stringify({v:1,m:[...t,l]});if(t.length>0&&O(h)>this.maxPayloadBytes)break;t.push(l),s=h;}let r=i.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",s);}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")&&i.attempts+1<this.maxAttempts){let A=this.queues.get(e);this.queues.set(e,{msgs:[...t,...A?.msgs??[]],attempts:i.attempts+1});}}this.pump();}};function O(o){return new TextEncoder().encode(o).byteLength}var L={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,i,t,s){this.client=e;this.selfId=i,this.roomId=t.RoomID??"",this.topology=t.Topology??"Mesh",this.chatMode=t.ChatMode??"ServerRelay",this.mode=t.Mode??null,this.voice=t.Voice===true,this.ownerId=t.OwnerUserID??"",this.hostId=t.HostUserID??"",this.lastSeq=t.Seq??0,this.iceServers=p(t.IceServers),this.o={...L,leaveOnPageHide:true,...Object.fromEntries(Object.entries(s).filter(([,r])=>r!==void 0)),createPeerConnection:s.createPeerConnection??(r=>new RTCPeerConnection(r))};for(let r of t.Members??[])r.UserID&&this.members.set(r.UserID,r);this.outbox=new f((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;voice;ownerId;hostId;members=new Map;o;iceServers;lastSeq;links=new Map;dataPeers=new Set;micTrack=null;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,i,t={},s={}){let r=e.auth.context?.userID;if(!r)return c("unauthorized","Not logged in.");let n=await e.multiplayer.createRoom(i,t);return n.ok?{ok:true,data:o.start(e,r,n.data,s)}:n}static async join(e,i,t,s={}){let r=e.auth.context?.userID;if(!r)return c("unauthorized","Not logged in.");let n=await e.multiplayer.joinRoom(i,t);return n.ok?{ok:true,data:o.start(e,r,n.data,s)}:n}static start(e,i,t,s){let r=new o(e,i,t,s);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,i){let t=this.listeners.get(e)??new Set;return t.add(i),this.listeners.set(e,t),()=>t.delete(i)}openPeers(){return [...this.links.values()].filter(e=>e.state==="open"&&this.dataPeers.has(e.peerId)).map(e=>e.peerId)}isOpen(e){return this.dataPeers.has(e)&&this.links.get(e)?.state==="open"}linkStats(e){let i=this.links.get(e);return i?{rttMs:i.rttMs,bytesIn:i.bytesIn,bytesOut:i.bytesOut,buffered:i.relBuffered}:null}send(e,i,t){return this.dataPeers.has(e)?this.links.get(e)?.send(i,t)??false:false}broadcast(e,i,t){let s=0;for(let r of this.links.values())r.peerId!==t&&r.state==="open"&&this.dataPeers.has(r.peerId)&&r.send(e,i)&&s++;return s}setMicTrack(e){this.micTrack=this.voice?e:null;for(let i of this.links.values())i.setMicTrack(this.micTrack);}remoteAudio(e){return this.links.get(e)?.remoteAudio??null}setExtraPeers(e){this.extraPeers=new Set([...e].filter(i=>i!==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,i=false){let t=await this.client.multiplayer.kickMember(this.roomId,e,i);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(i=>i.state==="connecting")||[...this.wanted()].some(i=>!this.links.has(i))?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 i=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(),i??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 i=e.FromUserID??"";switch(e.Type){case "Signal":e.ToUserID===this.selfId&&e.Kind==="rtc"&&this.handleSignals(i,R(e.Payload));break;case "PlayerJoined":{let t=e.Payload||i;if(!t||t===this.selfId)break;if(!this.members.has(t)){let s={UserID:t};this.members.set(t,s),this.emit("memberJoined",{member:s});}if(this.fastUntil=Date.now()+this.o.fastWindowMs,this.scheduleRefresh(),this.voice&&this.isHost)for(let s of this.links.values())s.peerId!==t&&s.state==="open"&&s.notice(1);break}case "PlayerLeft":{let t=e.Payload||i,s=e.Kind==="kicked"?"kicked":e.Kind==="timeout"?"timeout":"left";if(t===this.selfId){s!=="left"&&this.end("removed",{reason:s});break}this.dropMember(t,s,s==="kicked"?i:void 0);break}case "HostChanged":{let t=e.Payload??"";if(t&&t!==this.hostId){let s=this.hostId||null;this.hostId=t,this.fastUntil=Date.now()+this.o.fastWindowMs,this.emit("hostChanged",{hostId:t,previousHostId:s});}break}case "RoomClosed":this.end("roomClosed",{});break;case "MemberState":this.scheduleRefresh();break;case "Chat":this.emit("chat",{from:i,text:e.Payload??""});break}}dropMember(e,i,t){let s=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),s&&this.emit("memberLeft",{userId:e,kind:i,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 i=new Map;for(let t of e.Members??[])t.UserID&&i.set(t.UserID,t);for(let t of [...this.members.keys()])!i.has(t)&&t!==this.selfId&&this.dropMember(t,"left");for(let[t,s]of i){let r=this.members.has(t);this.members.set(t,s),!r&&t!==this.selfId&&this.emit("memberJoined",{member:s});}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=this.dataWanted();if(this.voice)for(let i of this.members.keys())i!==this.selfId&&e.add(i);return e}dataWanted(){let e=new Set,i=[...this.members.keys()].filter(t=>t!==this.selfId);if(this.topology==="Mesh"||this.isHost)for(let t of i)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(),i=this.dataWanted();for(let t of this.links.values())t.state==="open"&&i.has(t.peerId)&&this.announce(t.peerId);for(let t of this.wanted())if(!(this.links.has(t)||this.retry.get(t)?.timer))if(this.selfId<t)this.openLink(t,true,w());else {let s=this.wantSentAt.get(t)??0;e-s>8e3&&(this.wantSentAt.set(t,e),this.outbox.enqueue(t,{t:"want"}));}}handleSignals(e,i){if(!(!e||e===this.selfId)){this.members.has(e)||(this.members.set(e,{UserID:e}),this.scheduleRefresh());for(let t of i){let s=this.links.get(e);if(t.t==="want"){(!s||s.state==="closed")&&this.openLink(e,true,w());continue}if(t.t==="offer"){if(s?.lid===t.lid)continue;s&&this.closeLink(e,"replaced by a new offer"),this.openLink(e,false,t.lid).handle(t);continue}s&&s.lid===t.lid&&s.handle(t);}}}openLink(e,i,t){this.wantSentAt.delete(e);let s=new m({peerId:e,offerer:i,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.retry.delete(e),this.dataWanted().has(e)&&this.announce(e);},onClose:r=>this.onLinkClosed(s,r),onMessage:(r,n)=>this.emit("message",{from:e,channel:r,data:n}),onNotice:r=>{r===1&&this.schedulePoll(0);},audio:this.voice,onAudio:r=>{this.links.get(e)===s&&this.emit("peerAudio",{peerId:e,track:r});}});return this.micTrack&&s.setMicTrack(this.micTrack),this.links.set(e,s),this.schedulePoll(Math.min(this.o.pollFastMs,250)),s}closeLink(e,i){let t=this.links.get(e);t&&(this.links.delete(e),t.close(i,true));}onLinkClosed(e,i){let t=e.peerId,s=this.links.get(t)===e;if(s&&this.links.delete(t),this.voice&&!this.links.has(t)&&this.emit("peerAudio",{peerId:t,track:null}),this.dataPeers.delete(t)&&this.emit("peerClose",{peerId:t,reason:i}),!s||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);}announce(e){this.dataPeers.has(e)||(this.dataPeers.add(e),this.emit("peerOpen",{peerId:e}));}emit(e,i){for(let t of this.listeners.get(e)??[])try{t(i);}catch(s){console.error(`[RealtimeSession] ${String(e)} handler failed`,s);}}end(e,i){this.stopped||(this.stop(),this.emit(e,i));}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 i=this.links.get(e);this.links.delete(e),i?.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 w(){let o=globalThis.crypto;return o&&"randomUUID"in o?o.randomUUID().slice(0,12):Math.random().toString(36).slice(2,14)}var M=class{constructor(e,i={}){this.session=e;if(this.o={speakingThreshold:i.speakingThreshold??.02,levelIntervalMs:i.levelIntervalMs??100,speakingHoldMs:i.speakingHoldMs??300,attachElement:i.attachElement??D,getUserMedia:i.getUserMedia,createAudioContext:i.createAudioContext,createStream:i.createStream},!!e.voice){this.offs.push(e.on("peerAudio",({peerId:t,track:s})=>s?this.addPeer(t,s):this.removePeer(t)),e.on("memberLeft",({userId:t})=>this.removePeer(t)),e.on("left",()=>this.destroy()),e.on("removed",()=>this.destroy()),e.on("roomClosed",()=>this.destroy()));for(let t of e.members.keys()){let s=e.remoteAudio(t);s&&this.addPeer(t,s);}typeof document<"u"&&(document.addEventListener("pointerdown",this.onGesture,true),document.addEventListener("keydown",this.onGesture,true));}}session;o;ctx=null;micStream=null;self=null;peers=new Map;muted=new Set;volumes=new Map;speakingIds=new Set;levelMap=new Map;modeValue="off";modeSeq=0;wantMode="off";acquiring=null;pushed=false;timer=null;destroyed=false;offs=[];listeners=new Map;onGesture=()=>{this.resume(),this.ctx?.state==="running"&&this.stopGestureWatch();};stopGestureWatch(){typeof document>"u"||(document.removeEventListener("pointerdown",this.onGesture,true),document.removeEventListener("keydown",this.onGesture,true));}get available(){return this.session.voice&&!this.destroyed}get mode(){return this.modeValue}get transmitting(){return this.micStream!=null&&(this.modeValue==="open"||this.modeValue==="push"&&this.pushed)}micTrack(){return this.micStream?.getAudioTracks()[0]??null}peerTracks(){let e=[];for(let i of this.peers.keys()){let t=this.session.remoteAudio(i);t&&e.push(t);}return e}isSpeaking(e){return this.speakingIds.has(e)}speaking(){return [...this.speakingIds]}level(e){return this.levelMap.get(e)??0}isPeerMuted(e){return this.muted.has(e)}peerVolume(e){return this.volumes.get(e)??1}hasVoice(e){return this.peers.has(e)}on(e,i){let t=this.listeners.get(e)??new Set;return t.add(i),this.listeners.set(e,t),()=>t.delete(i)}graph(){if(!this.ctx)return null;let e=new Map;for(let[i,t]of this.peers)e.set(i,t.gain??t.source);return {context:this.ctx,mic:this.self?.source??null,peers:e}}async setMode(e){if(!this.available)return c("client","Voice chat is off in this room.");let i=++this.modeSeq;if(this.wantMode=e,this.resume(),e==="off")return this.modeValue="off",this.pushed=false,this.releaseMic(),this.emit("change",{}),d(e);if(!this.micStream){this.acquiring??=this.acquireMic().finally(()=>{this.acquiring=null;});let t=await this.acquiring;if(!t.ok)return t}return this.destroyed?c("client","The room is closed."):i!==this.modeSeq?(this.wantMode==="off"&&this.releaseMic(),d(this.wantMode)):(this.modeValue=e,this.applyTransmit(),this.emit("change",{}),d(e))}setPushed(e){this.pushed!==e&&(this.pushed=e,this.modeValue==="push"&&(this.applyTransmit(),this.emit("change",{})));}setPeerMuted(e,i){i?this.muted.add(e):this.muted.delete(e),this.applyGain(e),this.emit("change",{});}setPeerVolume(e,i){let t=Number.isFinite(i)?Math.min(2,Math.max(0,i)):1;this.volumes.set(e,t),this.applyGain(e),this.emit("change",{});}resume(){this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume();}destroy(){if(this.destroyed)return;this.destroyed=true;for(let i of this.offs.splice(0))i();this.stopGestureWatch(),this.releaseMic();for(let i of [...this.peers.keys()])this.removePeer(i);this.stopTimer();let e=this.ctx;this.ctx=null,e&&e.state!=="closed"&&e.close().catch(()=>{}),this.modeValue="off",this.emit("change",{}),this.listeners.clear();}async acquireMic(){let e=this.o.getUserMedia??(typeof navigator<"u"&&navigator.mediaDevices?.getUserMedia?r=>navigator.mediaDevices.getUserMedia(r):null);if(!e)return c("client","This browser has no microphone access.");let i;try{i=await e({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1});}catch(r){return c("unauthorized",`Microphone refused: ${String(r)}`)}let t=i.getAudioTracks()[0];if(!t||this.destroyed){for(let r of i.getTracks())r.stop();return c("client","No microphone track.")}this.micStream=i,t.enabled=false,t.onended=()=>{this.micStream?.getAudioTracks()[0]===t&&(this.modeValue=this.wantMode="off",this.pushed=false,this.releaseMic(),this.emit("change",{}));},this.session.setMicTrack(t);let s=this.context();return s&&(this.self=this.makeVoice(s,i,false)),this.ensureTimer(),d(this.modeValue)}releaseMic(){if(this.micStream){this.session.setMicTrack(null);for(let e of this.micStream.getTracks())e.stop();this.micStream=null,this.self&&(this.disposeVoice(this.self),this.self=null),this.setSpeaking(this.session.selfId,false),this.levelMap.delete(this.session.selfId);}}applyTransmit(){let e=this.micStream?.getAudioTracks()[0];e&&(e.enabled=this.transmitting);}addPeer(e,i){if(this.destroyed)return;this.removePeer(e,false);let t=this.context();if(!t)return;let s=this.o.createStream?this.o.createStream([i]):new MediaStream([i]);this.peers.set(e,this.makeVoice(t,s,true)),this.applyGain(e),this.ensureTimer(),this.emit("change",{});}removePeer(e,i=true){let t=this.peers.get(e);t&&(this.peers.delete(e),this.disposeVoice(t),this.setSpeaking(e,false),this.levelMap.delete(e),!this.peers.size&&!this.self&&this.stopTimer(),i&&this.emit("change",{}));}applyGain(e){let i=this.peers.get(e);i?.gain&&(i.gain.gain.value=this.muted.has(e)?0:this.peerVolume(e));}makeVoice(e,i,t){let s=e.createMediaStreamSource(i),r=e.createAnalyser();r.fftSize=512,s.connect(r);let n=null,a=()=>{};return t&&(n=e.createGain(),s.connect(n),n.connect(e.destination),a=this.o.attachElement(i)),{source:s,analyser:r,gain:n,detach:a,level:0,loudUntil:0}}disposeVoice(e){try{e.source.disconnect(),e.analyser.disconnect(),e.gain?.disconnect();}catch{}e.detach();}context(){if(this.ctx)return this.ctx;try{this.ctx=this.o.createAudioContext?this.o.createAudioContext():new AudioContext;}catch{return null}return this.ctx}ensureTimer(){this.timer||this.destroyed||(this.timer=setInterval(()=>this.measure(),this.o.levelIntervalMs));}stopTimer(){this.timer&&clearInterval(this.timer),this.timer=null;}measure(){let e=Date.now(),i=new Float32Array(512),t=(s,r,n)=>{r.analyser.getFloatTimeDomainData(i);let a=0;for(let h=0;h<i.length;h++)a+=i[h]*i[h];let l=n?Math.sqrt(a/i.length):0;r.level=l,this.levelMap.set(s,l),l>this.o.speakingThreshold&&(r.loudUntil=e+this.o.speakingHoldMs),this.setSpeaking(s,e<r.loudUntil);};this.self&&t(this.session.selfId,this.self,this.transmitting);for(let[s,r]of this.peers)t(s,r,!this.muted.has(s));this.emit("levels",{levels:this.levelMap});}setSpeaking(e,i){this.speakingIds.has(e)!==i&&(i?this.speakingIds.add(e):this.speakingIds.delete(e),this.emit("change",{}));}emit(e,i){for(let t of this.listeners.get(e)??[])try{t(i);}catch(s){console.error(`[VoiceController] ${String(e)} handler failed`,s);}}};function D(o){if(typeof Audio>"u")return ()=>{};let e=new Audio;return e.muted=true,e.srcObject=o,e.play().catch(()=>{}),()=>{e.pause(),e.srcObject=null;}}exports.MAX_MESSAGE_BYTES=g;exports.RealtimeSession=y;exports.VoiceController=M;exports.toRtcIceServers=p;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { I as IceServer } from '../
|
|
2
|
-
export { C as ChannelName, M as MemberLeftKind, R as RealtimeClient,
|
|
1
|
+
import { I as IceServer } from '../VoiceController-C6b08lqX.cjs';
|
|
2
|
+
export { C as ChannelName, M as MemberLeftKind, a as MicMode, R as RealtimeClient, b as RealtimeSession, c as RealtimeSessionEvents, d as RealtimeSessionOptions, V as VoiceController, e as VoiceControllerEvents, f as VoiceControllerOptions } from '../VoiceController-C6b08lqX.cjs';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import '../PlatformAdapter-DU_8HalI.cjs';
|
|
5
5
|
import 'decimal.js';
|
package/dist/realtime/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { I as IceServer } from '../
|
|
2
|
-
export { C as ChannelName, M as MemberLeftKind, R as RealtimeClient,
|
|
1
|
+
import { I as IceServer } from '../VoiceController-DeqV4QI0.js';
|
|
2
|
+
export { C as ChannelName, M as MemberLeftKind, a as MicMode, R as RealtimeClient, b as RealtimeSession, c as RealtimeSessionEvents, d as RealtimeSessionOptions, V as VoiceController, e as VoiceControllerEvents, f as VoiceControllerOptions } from '../VoiceController-DeqV4QI0.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import '../PlatformAdapter-DU_8HalI.js';
|
|
5
5
|
import 'decimal.js';
|
package/dist/realtime/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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};
|
|
1
|
+
import {b as b$1,a}from'../chunk-CS7ACWDY.js';var g=16384;function v(o){let e=new Uint8Array(o.byteLength+1);return e[0]=0,e.set(o,1),e}function b(o,e){if(o.byteLength+1<=16384)return [v(o)];if(o.byteLength>67108864)throw new RangeError(`Message of ${o.byteLength} bytes exceeds 67108864.`);let i=Math.ceil(o.byteLength/16375),t=[];for(let s=0;s<i;s++){let r=o.subarray(s*16375,Math.min(o.byteLength,(s+1)*16375)),n=new Uint8Array(9+r.byteLength),a=new DataView(n.buffer);n[0]=1,a.setUint32(1,e>>>0),a.setUint16(5,s),a.setUint16(7,i),n.set(r,9),t.push(n);}return t}var u=class{id=-1;count=0;parts=[];bytes=0;push(e){if(e.byteLength<9)return null;let i=new DataView(e.buffer,e.byteOffset,e.byteLength),t=i.getUint32(1),s=i.getUint16(5),r=i.getUint16(7);if(s===0&&(this.id=t,this.count=r,this.parts=[],this.bytes=0),t!==this.id||s!==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 i of o??[]){let t=i.Urls?.trim();if(!t)continue;let s=i.Username??void 0,r=i.Credential??void 0,n=`${s??""}\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]};s&&(l.username=s),r&&(l.credential=r),e.set(n,l);}return [...e.values()]}var E=4*1024*1024,P=5e3,m=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=i=>{if(!i.candidate){this.sendDescriptionIfReady();return}this.descriptionSent&&this.lateIce.push(i.candidate.toJSON()),this.flushLateIce();},this.pc.onconnectionstatechange=()=>{let i=this.pc.connectionState;(i==="failed"||i==="closed")&&this.close(`connection ${i}`);},this.pc.ondatachannel=i=>this.adopt(i.channel),this.pc.ontrack=i=>{i.track?.kind!=="audio"||this.state==="closed"||(this.remoteAudio=i.track,this.o.onAudio?.(i.track));},this.openTimer=setTimeout(()=>{this.state==="connecting"&&this.close("connect timeout");},Math.max(15e3,e.peerTimeoutMs*3)),this.offerer&&(e.audio&&(this.audioTx=this.pc.addTransceiver("audio",{direction:"sendrecv"})),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 u;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;audioTx=null;micTrack=null;remoteAudio=null;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}),this.o.audio&&this.adoptAudio(),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 i of e.c)await this.addIce(i);else e.t==="bye"&&this.close("peer closed the link");}catch(i){this.close(`signaling failed: ${String(i)}`);}}adoptAudio(){let e=this.pc.getTransceivers().find(i=>i.receiver.track?.kind==="audio"&&i.currentDirection!=="stopped")??null;e&&(e.direction="sendrecv",this.audioTx=e,this.micTrack&&this.applyMic());}setMicTrack(e){this.micTrack=e,this.applyMic();}applyMic(){!this.audioTx||this.state==="closed"||this.audioTx.sender.replaceTrack(this.micTrack).catch(()=>{});}async drainRemoteIce(){let e=this.pendingRemoteIce.splice(0);for(let i of e)await this.addIce(i);}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=i=>this.receive(e.label,i.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>=P)&&(this.pingSentAt=e,this.raw("fast",new Uint8Array([2])));}receive(e,i){if(!(i instanceof ArrayBuffer))return;let t=new Uint8Array(i);this.lastRecv=Date.now(),this.bytesIn+=t.byteLength;let s=t[0];if(s===0)this.o.onMessage(e,t.subarray(1));else if(s===1&&e==="rel"){let r=this.reassembler.push(t);r&&this.o.onMessage(e,r);}else s===2?this.raw("fast",new Uint8Array([3])):s===3?this.pingSentAt&&(this.rttMs=Date.now()-this.pingSentAt):s===4&&e==="rel"&&this.o.onNotice?.(t[1]??0);}send(e,i){if(this.state!=="open")return false;if(e==="fast")return i.byteLength+1>16384?false:this.raw("fast",v(i));if((this.rel?.bufferedAmount??0)>E)return false;let t=b(i,this.msgSeq++);for(let s of t)if(!this.raw("rel",s))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,i){let t=e==="rel"?this.rel:this.fast;if(!t||t.readyState!=="open")return false;try{return t.send(i),this.lastSend=Date.now(),this.bytesOut+=i.byteLength,!0}catch{return false}}close(e="closed",i=false){if(this.state!=="closed"){this.state="closed",i&&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=this.pc.ontrack=null,this.audioTx=null,this.remoteAudio=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(i=>!!i&&typeof i=="object"&&typeof i.t=="string")}catch{return []}}var f=class{constructor(e,i={}){this.send=e;this.perTargetGapMs=i.perTargetGapMs??650,this.globalGapMs=i.globalGapMs??180,this.maxPayloadBytes=i.maxPayloadBytes??15e3,this.maxAttempts=i.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,i){if(this.closed)return;let t=this.queues.get(e)??{msgs:[],attempts:0},s=t.msgs[t.msgs.length-1];i.t==="ice"&&s?.t==="ice"&&s.lid===i.lid?s.c.push(...i.c):t.msgs.push(i),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(),i=null,t=1/0;for(let s of this.queues.keys()){let r=Math.max((this.lastSent.get(s)??0)+this.perTargetGapMs,this.lastAny+this.globalGapMs);if(r<=e){i=s;break}t=Math.min(t,r-e);}if(i===null){t!==1/0&&(this.timer=setTimeout(()=>{this.timer=null,this.pump();},t));return}this.flush(i);}async flush(e){let i=this.queues.get(e);if(!i||i.msgs.length===0){this.queues.delete(e),this.pump();return}let t=[],s="";for(let l of i.msgs){let h=JSON.stringify({v:1,m:[...t,l]});if(t.length>0&&O(h)>this.maxPayloadBytes)break;t.push(l),s=h;}let r=i.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",s);}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")&&i.attempts+1<this.maxAttempts){let A=this.queues.get(e);this.queues.set(e,{msgs:[...t,...A?.msgs??[]],attempts:i.attempts+1});}}this.pump();}};function O(o){return new TextEncoder().encode(o).byteLength}var L={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,i,t,s){this.client=e;this.selfId=i,this.roomId=t.RoomID??"",this.topology=t.Topology??"Mesh",this.chatMode=t.ChatMode??"ServerRelay",this.mode=t.Mode??null,this.voice=t.Voice===true,this.ownerId=t.OwnerUserID??"",this.hostId=t.HostUserID??"",this.lastSeq=t.Seq??0,this.iceServers=p(t.IceServers),this.o={...L,leaveOnPageHide:true,...Object.fromEntries(Object.entries(s).filter(([,r])=>r!==void 0)),createPeerConnection:s.createPeerConnection??(r=>new RTCPeerConnection(r))};for(let r of t.Members??[])r.UserID&&this.members.set(r.UserID,r);this.outbox=new f((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;voice;ownerId;hostId;members=new Map;o;iceServers;lastSeq;links=new Map;dataPeers=new Set;micTrack=null;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,i,t={},s={}){let r=e.auth.context?.userID;if(!r)return b$1("unauthorized","Not logged in.");let n=await e.multiplayer.createRoom(i,t);return n.ok?{ok:true,data:o.start(e,r,n.data,s)}:n}static async join(e,i,t,s={}){let r=e.auth.context?.userID;if(!r)return b$1("unauthorized","Not logged in.");let n=await e.multiplayer.joinRoom(i,t);return n.ok?{ok:true,data:o.start(e,r,n.data,s)}:n}static start(e,i,t,s){let r=new o(e,i,t,s);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,i){let t=this.listeners.get(e)??new Set;return t.add(i),this.listeners.set(e,t),()=>t.delete(i)}openPeers(){return [...this.links.values()].filter(e=>e.state==="open"&&this.dataPeers.has(e.peerId)).map(e=>e.peerId)}isOpen(e){return this.dataPeers.has(e)&&this.links.get(e)?.state==="open"}linkStats(e){let i=this.links.get(e);return i?{rttMs:i.rttMs,bytesIn:i.bytesIn,bytesOut:i.bytesOut,buffered:i.relBuffered}:null}send(e,i,t){return this.dataPeers.has(e)?this.links.get(e)?.send(i,t)??false:false}broadcast(e,i,t){let s=0;for(let r of this.links.values())r.peerId!==t&&r.state==="open"&&this.dataPeers.has(r.peerId)&&r.send(e,i)&&s++;return s}setMicTrack(e){this.micTrack=this.voice?e:null;for(let i of this.links.values())i.setMicTrack(this.micTrack);}remoteAudio(e){return this.links.get(e)?.remoteAudio??null}setExtraPeers(e){this.extraPeers=new Set([...e].filter(i=>i!==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,i=false){let t=await this.client.multiplayer.kickMember(this.roomId,e,i);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(i=>i.state==="connecting")||[...this.wanted()].some(i=>!this.links.has(i))?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 i=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(),i??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 i=e.FromUserID??"";switch(e.Type){case "Signal":e.ToUserID===this.selfId&&e.Kind==="rtc"&&this.handleSignals(i,R(e.Payload));break;case "PlayerJoined":{let t=e.Payload||i;if(!t||t===this.selfId)break;if(!this.members.has(t)){let s={UserID:t};this.members.set(t,s),this.emit("memberJoined",{member:s});}if(this.fastUntil=Date.now()+this.o.fastWindowMs,this.scheduleRefresh(),this.voice&&this.isHost)for(let s of this.links.values())s.peerId!==t&&s.state==="open"&&s.notice(1);break}case "PlayerLeft":{let t=e.Payload||i,s=e.Kind==="kicked"?"kicked":e.Kind==="timeout"?"timeout":"left";if(t===this.selfId){s!=="left"&&this.end("removed",{reason:s});break}this.dropMember(t,s,s==="kicked"?i:void 0);break}case "HostChanged":{let t=e.Payload??"";if(t&&t!==this.hostId){let s=this.hostId||null;this.hostId=t,this.fastUntil=Date.now()+this.o.fastWindowMs,this.emit("hostChanged",{hostId:t,previousHostId:s});}break}case "RoomClosed":this.end("roomClosed",{});break;case "MemberState":this.scheduleRefresh();break;case "Chat":this.emit("chat",{from:i,text:e.Payload??""});break}}dropMember(e,i,t){let s=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),s&&this.emit("memberLeft",{userId:e,kind:i,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 i=new Map;for(let t of e.Members??[])t.UserID&&i.set(t.UserID,t);for(let t of [...this.members.keys()])!i.has(t)&&t!==this.selfId&&this.dropMember(t,"left");for(let[t,s]of i){let r=this.members.has(t);this.members.set(t,s),!r&&t!==this.selfId&&this.emit("memberJoined",{member:s});}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=this.dataWanted();if(this.voice)for(let i of this.members.keys())i!==this.selfId&&e.add(i);return e}dataWanted(){let e=new Set,i=[...this.members.keys()].filter(t=>t!==this.selfId);if(this.topology==="Mesh"||this.isHost)for(let t of i)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(),i=this.dataWanted();for(let t of this.links.values())t.state==="open"&&i.has(t.peerId)&&this.announce(t.peerId);for(let t of this.wanted())if(!(this.links.has(t)||this.retry.get(t)?.timer))if(this.selfId<t)this.openLink(t,true,w());else {let s=this.wantSentAt.get(t)??0;e-s>8e3&&(this.wantSentAt.set(t,e),this.outbox.enqueue(t,{t:"want"}));}}handleSignals(e,i){if(!(!e||e===this.selfId)){this.members.has(e)||(this.members.set(e,{UserID:e}),this.scheduleRefresh());for(let t of i){let s=this.links.get(e);if(t.t==="want"){(!s||s.state==="closed")&&this.openLink(e,true,w());continue}if(t.t==="offer"){if(s?.lid===t.lid)continue;s&&this.closeLink(e,"replaced by a new offer"),this.openLink(e,false,t.lid).handle(t);continue}s&&s.lid===t.lid&&s.handle(t);}}}openLink(e,i,t){this.wantSentAt.delete(e);let s=new m({peerId:e,offerer:i,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.retry.delete(e),this.dataWanted().has(e)&&this.announce(e);},onClose:r=>this.onLinkClosed(s,r),onMessage:(r,n)=>this.emit("message",{from:e,channel:r,data:n}),onNotice:r=>{r===1&&this.schedulePoll(0);},audio:this.voice,onAudio:r=>{this.links.get(e)===s&&this.emit("peerAudio",{peerId:e,track:r});}});return this.micTrack&&s.setMicTrack(this.micTrack),this.links.set(e,s),this.schedulePoll(Math.min(this.o.pollFastMs,250)),s}closeLink(e,i){let t=this.links.get(e);t&&(this.links.delete(e),t.close(i,true));}onLinkClosed(e,i){let t=e.peerId,s=this.links.get(t)===e;if(s&&this.links.delete(t),this.voice&&!this.links.has(t)&&this.emit("peerAudio",{peerId:t,track:null}),this.dataPeers.delete(t)&&this.emit("peerClose",{peerId:t,reason:i}),!s||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);}announce(e){this.dataPeers.has(e)||(this.dataPeers.add(e),this.emit("peerOpen",{peerId:e}));}emit(e,i){for(let t of this.listeners.get(e)??[])try{t(i);}catch(s){console.error(`[RealtimeSession] ${String(e)} handler failed`,s);}}end(e,i){this.stopped||(this.stop(),this.emit(e,i));}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 i=this.links.get(e);this.links.delete(e),i?.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 w(){let o=globalThis.crypto;return o&&"randomUUID"in o?o.randomUUID().slice(0,12):Math.random().toString(36).slice(2,14)}var M=class{constructor(e,i={}){this.session=e;if(this.o={speakingThreshold:i.speakingThreshold??.02,levelIntervalMs:i.levelIntervalMs??100,speakingHoldMs:i.speakingHoldMs??300,attachElement:i.attachElement??D,getUserMedia:i.getUserMedia,createAudioContext:i.createAudioContext,createStream:i.createStream},!!e.voice){this.offs.push(e.on("peerAudio",({peerId:t,track:s})=>s?this.addPeer(t,s):this.removePeer(t)),e.on("memberLeft",({userId:t})=>this.removePeer(t)),e.on("left",()=>this.destroy()),e.on("removed",()=>this.destroy()),e.on("roomClosed",()=>this.destroy()));for(let t of e.members.keys()){let s=e.remoteAudio(t);s&&this.addPeer(t,s);}typeof document<"u"&&(document.addEventListener("pointerdown",this.onGesture,true),document.addEventListener("keydown",this.onGesture,true));}}session;o;ctx=null;micStream=null;self=null;peers=new Map;muted=new Set;volumes=new Map;speakingIds=new Set;levelMap=new Map;modeValue="off";modeSeq=0;wantMode="off";acquiring=null;pushed=false;timer=null;destroyed=false;offs=[];listeners=new Map;onGesture=()=>{this.resume(),this.ctx?.state==="running"&&this.stopGestureWatch();};stopGestureWatch(){typeof document>"u"||(document.removeEventListener("pointerdown",this.onGesture,true),document.removeEventListener("keydown",this.onGesture,true));}get available(){return this.session.voice&&!this.destroyed}get mode(){return this.modeValue}get transmitting(){return this.micStream!=null&&(this.modeValue==="open"||this.modeValue==="push"&&this.pushed)}micTrack(){return this.micStream?.getAudioTracks()[0]??null}peerTracks(){let e=[];for(let i of this.peers.keys()){let t=this.session.remoteAudio(i);t&&e.push(t);}return e}isSpeaking(e){return this.speakingIds.has(e)}speaking(){return [...this.speakingIds]}level(e){return this.levelMap.get(e)??0}isPeerMuted(e){return this.muted.has(e)}peerVolume(e){return this.volumes.get(e)??1}hasVoice(e){return this.peers.has(e)}on(e,i){let t=this.listeners.get(e)??new Set;return t.add(i),this.listeners.set(e,t),()=>t.delete(i)}graph(){if(!this.ctx)return null;let e=new Map;for(let[i,t]of this.peers)e.set(i,t.gain??t.source);return {context:this.ctx,mic:this.self?.source??null,peers:e}}async setMode(e){if(!this.available)return b$1("client","Voice chat is off in this room.");let i=++this.modeSeq;if(this.wantMode=e,this.resume(),e==="off")return this.modeValue="off",this.pushed=false,this.releaseMic(),this.emit("change",{}),a(e);if(!this.micStream){this.acquiring??=this.acquireMic().finally(()=>{this.acquiring=null;});let t=await this.acquiring;if(!t.ok)return t}return this.destroyed?b$1("client","The room is closed."):i!==this.modeSeq?(this.wantMode==="off"&&this.releaseMic(),a(this.wantMode)):(this.modeValue=e,this.applyTransmit(),this.emit("change",{}),a(e))}setPushed(e){this.pushed!==e&&(this.pushed=e,this.modeValue==="push"&&(this.applyTransmit(),this.emit("change",{})));}setPeerMuted(e,i){i?this.muted.add(e):this.muted.delete(e),this.applyGain(e),this.emit("change",{});}setPeerVolume(e,i){let t=Number.isFinite(i)?Math.min(2,Math.max(0,i)):1;this.volumes.set(e,t),this.applyGain(e),this.emit("change",{});}resume(){this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume();}destroy(){if(this.destroyed)return;this.destroyed=true;for(let i of this.offs.splice(0))i();this.stopGestureWatch(),this.releaseMic();for(let i of [...this.peers.keys()])this.removePeer(i);this.stopTimer();let e=this.ctx;this.ctx=null,e&&e.state!=="closed"&&e.close().catch(()=>{}),this.modeValue="off",this.emit("change",{}),this.listeners.clear();}async acquireMic(){let e=this.o.getUserMedia??(typeof navigator<"u"&&navigator.mediaDevices?.getUserMedia?r=>navigator.mediaDevices.getUserMedia(r):null);if(!e)return b$1("client","This browser has no microphone access.");let i;try{i=await e({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1});}catch(r){return b$1("unauthorized",`Microphone refused: ${String(r)}`)}let t=i.getAudioTracks()[0];if(!t||this.destroyed){for(let r of i.getTracks())r.stop();return b$1("client","No microphone track.")}this.micStream=i,t.enabled=false,t.onended=()=>{this.micStream?.getAudioTracks()[0]===t&&(this.modeValue=this.wantMode="off",this.pushed=false,this.releaseMic(),this.emit("change",{}));},this.session.setMicTrack(t);let s=this.context();return s&&(this.self=this.makeVoice(s,i,false)),this.ensureTimer(),a(this.modeValue)}releaseMic(){if(this.micStream){this.session.setMicTrack(null);for(let e of this.micStream.getTracks())e.stop();this.micStream=null,this.self&&(this.disposeVoice(this.self),this.self=null),this.setSpeaking(this.session.selfId,false),this.levelMap.delete(this.session.selfId);}}applyTransmit(){let e=this.micStream?.getAudioTracks()[0];e&&(e.enabled=this.transmitting);}addPeer(e,i){if(this.destroyed)return;this.removePeer(e,false);let t=this.context();if(!t)return;let s=this.o.createStream?this.o.createStream([i]):new MediaStream([i]);this.peers.set(e,this.makeVoice(t,s,true)),this.applyGain(e),this.ensureTimer(),this.emit("change",{});}removePeer(e,i=true){let t=this.peers.get(e);t&&(this.peers.delete(e),this.disposeVoice(t),this.setSpeaking(e,false),this.levelMap.delete(e),!this.peers.size&&!this.self&&this.stopTimer(),i&&this.emit("change",{}));}applyGain(e){let i=this.peers.get(e);i?.gain&&(i.gain.gain.value=this.muted.has(e)?0:this.peerVolume(e));}makeVoice(e,i,t){let s=e.createMediaStreamSource(i),r=e.createAnalyser();r.fftSize=512,s.connect(r);let n=null,a=()=>{};return t&&(n=e.createGain(),s.connect(n),n.connect(e.destination),a=this.o.attachElement(i)),{source:s,analyser:r,gain:n,detach:a,level:0,loudUntil:0}}disposeVoice(e){try{e.source.disconnect(),e.analyser.disconnect(),e.gain?.disconnect();}catch{}e.detach();}context(){if(this.ctx)return this.ctx;try{this.ctx=this.o.createAudioContext?this.o.createAudioContext():new AudioContext;}catch{return null}return this.ctx}ensureTimer(){this.timer||this.destroyed||(this.timer=setInterval(()=>this.measure(),this.o.levelIntervalMs));}stopTimer(){this.timer&&clearInterval(this.timer),this.timer=null;}measure(){let e=Date.now(),i=new Float32Array(512),t=(s,r,n)=>{r.analyser.getFloatTimeDomainData(i);let a=0;for(let h=0;h<i.length;h++)a+=i[h]*i[h];let l=n?Math.sqrt(a/i.length):0;r.level=l,this.levelMap.set(s,l),l>this.o.speakingThreshold&&(r.loudUntil=e+this.o.speakingHoldMs),this.setSpeaking(s,e<r.loudUntil);};this.self&&t(this.session.selfId,this.self,this.transmitting);for(let[s,r]of this.peers)t(s,r,!this.muted.has(s));this.emit("levels",{levels:this.levelMap});}setSpeaking(e,i){this.speakingIds.has(e)!==i&&(i?this.speakingIds.add(e):this.speakingIds.delete(e),this.emit("change",{}));}emit(e,i){for(let t of this.listeners.get(e)??[])try{t(i);}catch(s){console.error(`[VoiceController] ${String(e)} handler failed`,s);}}};function D(o){if(typeof Audio>"u")return ()=>{};let e=new Audio;return e.muted=true,e.srcObject=o,e.play().catch(()=>{}),()=>{e.pause(),e.srcObject=null;}}export{g as MAX_MESSAGE_BYTES,y as RealtimeSession,M as VoiceController,p as toRtcIceServers};
|