@idosgames/core 0.19.0 → 0.20.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.
@@ -1 +1 @@
1
- import {b}from'../chunk-76ZM4DUB.js';var f=16384;function g(o){let e=new Uint8Array(o.byteLength+1);return e[0]=0,e.set(o,1),e}function v(o,e){if(o.byteLength+1<=16384)return [g(o)];if(o.byteLength>67108864)throw new RangeError(`Message of ${o.byteLength} bytes exceeds 67108864.`);let s=Math.ceil(o.byteLength/16375),t=[];for(let i=0;i<s;i++){let r=o.subarray(i*16375,Math.min(o.byteLength,(i+1)*16375)),n=new Uint8Array(9+r.byteLength),a=new DataView(n.buffer);n[0]=1,a.setUint32(1,e>>>0),a.setUint16(5,i),a.setUint16(7,s),n.set(r,9),t.push(n);}return t}var c=class{id=-1;count=0;parts=[];bytes=0;push(e){if(e.byteLength<9)return null;let s=new DataView(e.buffer,e.byteOffset,e.byteLength),t=s.getUint32(1),i=s.getUint16(5),r=s.getUint16(7);if(i===0&&(this.id=t,this.count=r,this.parts=[],this.bytes=0),t!==this.id||i!==this.parts.length||r!==this.count)return this.reset(),null;let n=e.subarray(9);if(this.bytes+=n.byteLength,this.bytes>67108864)return this.reset(),null;if(this.parts.push(n),this.parts.length<this.count)return null;let a=new Uint8Array(this.bytes),l=0;for(let h of this.parts)a.set(h,l),l+=h.byteLength;return this.reset(),a}reset(){this.id=-1,this.count=0,this.parts=[],this.bytes=0;}};function p(o){let e=new Map;for(let s of o??[]){let t=s.Urls?.trim();if(!t)continue;let i=s.Username??void 0,r=s.Credential??void 0,n=`${i??""}\0${r??""}`,a=e.get(n);if(a){let h=Array.isArray(a.urls)?a.urls:[a.urls];h.includes(t)||h.push(t),a.urls=h;continue}let l={urls:[t]};i&&(l.username=i),r&&(l.credential=r),e.set(n,l);}return [...e.values()]}var C=4*1024*1024,A=5e3,d=class{constructor(e){this.o=e;this.peerId=e.peerId,this.offerer=e.offerer,this.lid=e.lid,this.pc=e.createPeerConnection({iceServers:e.iceServers}),this.pc.onicecandidate=s=>{if(!s.candidate){this.sendDescriptionIfReady();return}this.descriptionSent&&this.lateIce.push(s.candidate.toJSON()),this.flushLateIce();},this.pc.onconnectionstatechange=()=>{let s=this.pc.connectionState;(s==="failed"||s==="closed")&&this.close(`connection ${s}`);},this.pc.ondatachannel=s=>this.adopt(s.channel),this.openTimer=setTimeout(()=>{this.state==="connecting"&&this.close("connect timeout");},Math.max(15e3,e.peerTimeoutMs*3)),this.offerer&&(this.adopt(this.pc.createDataChannel("rel",{ordered:true})),this.adopt(this.pc.createDataChannel("fast",{ordered:false,maxRetransmits:0})),this.makeOffer());}o;peerId;offerer;lid;state="connecting";pc;rel=null;fast=null;reassembler=new c;pendingRemoteIce=[];descriptionSent=false;lateIce=[];lastRecv=Date.now();lastSend=0;msgSeq=1;keepaliveTimer=null;gatherTimer=null;openTimer=null;bytesIn=0;bytesOut=0;rttMs=0;pingSentAt=0;async makeOffer(){try{await this.pc.setLocalDescription(await this.pc.createOffer()),this.waitForGathering();}catch(e){this.close(`offer failed: ${String(e)}`);}}async handle(e){if(this.state!=="closed")try{if(e.t==="offer"&&!this.offerer)await this.pc.setRemoteDescription({type:"offer",sdp:e.sdp}),await this.drainRemoteIce(),await this.pc.setLocalDescription(await this.pc.createAnswer()),this.waitForGathering();else if(e.t==="answer"&&this.offerer){if(this.pc.signalingState!=="have-local-offer")return;await this.pc.setRemoteDescription({type:"answer",sdp:e.sdp}),await this.drainRemoteIce();}else if(e.t==="ice")if(!this.pc.remoteDescription)this.pendingRemoteIce.push(...e.c);else for(let s of e.c)await this.addIce(s);else e.t==="bye"&&this.close("peer closed the link");}catch(s){this.close(`signaling failed: ${String(s)}`);}}async drainRemoteIce(){let e=this.pendingRemoteIce.splice(0);for(let s of e)await this.addIce(s);}async addIce(e){try{await this.pc.addIceCandidate(e);}catch{}}waitForGathering(){if(this.pc.iceGatheringState==="complete"){this.sendDescriptionIfReady();return}this.gatherTimer=setTimeout(()=>this.sendDescriptionIfReady(),this.o.iceGatherTimeoutMs);}sendDescriptionIfReady(){if(this.descriptionSent||this.state==="closed")return;let e=this.pc.localDescription;e?.sdp&&(this.gatherTimer&&clearTimeout(this.gatherTimer),this.gatherTimer=null,this.descriptionSent=true,this.o.signal(this.offerer?{t:"offer",lid:this.lid,sdp:e.sdp}:{t:"answer",lid:this.lid,sdp:e.sdp}),this.flushLateIce());}flushLateIce(){if(!this.descriptionSent||this.lateIce.length===0)return;let e=this.lateIce;this.lateIce=[],this.o.signal({t:"ice",lid:this.lid,c:e});}adopt(e){if(e.binaryType="arraybuffer",e.label==="rel")this.rel=e;else if(e.label==="fast")this.fast=e;else return;e.onopen=()=>this.maybeOpen(),e.onclose=()=>this.close(`channel ${e.label} closed`),e.onmessage=s=>this.receive(e.label,s.data),e.readyState==="open"&&queueMicrotask(()=>this.maybeOpen());}maybeOpen(){this.state==="connecting"&&(this.rel?.readyState!=="open"||this.fast?.readyState!=="open"||(this.state="open",this.openTimer&&clearTimeout(this.openTimer),this.openTimer=null,this.lastRecv=Date.now(),this.keepaliveTimer=setInterval(()=>this.keepalive(),this.o.keepaliveMs),this.o.onOpen()));}keepalive(){if(this.state!=="open")return;let e=Date.now();if(e-this.lastRecv>this.o.peerTimeoutMs){this.close("peer timeout");return}(e-this.lastSend>=this.o.keepaliveMs||e-this.pingSentAt>=A)&&(this.pingSentAt=e,this.raw("fast",new Uint8Array([2])));}receive(e,s){if(!(s instanceof ArrayBuffer))return;let t=new Uint8Array(s);this.lastRecv=Date.now(),this.bytesIn+=t.byteLength;let i=t[0];if(i===0)this.o.onMessage(e,t.subarray(1));else if(i===1&&e==="rel"){let r=this.reassembler.push(t);r&&this.o.onMessage(e,r);}else i===2?this.raw("fast",new Uint8Array([3])):i===3?this.pingSentAt&&(this.rttMs=Date.now()-this.pingSentAt):i===4&&e==="rel"&&this.o.onNotice?.(t[1]??0);}send(e,s){if(this.state!=="open")return false;if(e==="fast")return s.byteLength+1>16384?false:this.raw("fast",g(s));if((this.rel?.bufferedAmount??0)>C)return false;let t=v(s,this.msgSeq++);for(let i of t)if(!this.raw("rel",i))return false;return true}notice(e){return this.state!=="open"?false:this.raw("rel",new Uint8Array([4,e]))}get relBuffered(){return this.rel?.bufferedAmount??0}raw(e,s){let t=e==="rel"?this.rel:this.fast;if(!t||t.readyState!=="open")return false;try{return t.send(s),this.lastSend=Date.now(),this.bytesOut+=s.byteLength,!0}catch{return false}}close(e="closed",s=false){if(this.state!=="closed"){this.state="closed",s&&this.descriptionSent&&this.o.signal({t:"bye",lid:this.lid}),this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.gatherTimer&&clearTimeout(this.gatherTimer),this.openTimer&&clearTimeout(this.openTimer),this.keepaliveTimer=this.gatherTimer=this.openTimer=null;for(let t of [this.rel,this.fast])if(t){t.onopen=t.onclose=t.onmessage=null;try{t.close();}catch{}}this.pc.onicecandidate=this.pc.onconnectionstatechange=this.pc.ondatachannel=null;try{this.pc.close();}catch{}this.reassembler.reset(),this.o.onClose(e);}}};function R(o){if(!o)return [];try{let e=JSON.parse(o);return !e||e.v!==1||!Array.isArray(e.m)?[]:e.m.filter(s=>!!s&&typeof s=="object"&&typeof s.t=="string")}catch{return []}}var u=class{constructor(e,s={}){this.send=e;this.perTargetGapMs=s.perTargetGapMs??650,this.globalGapMs=s.globalGapMs??180,this.maxPayloadBytes=s.maxPayloadBytes??15e3,this.maxAttempts=s.maxAttempts??4;}send;queues=new Map;lastSent=new Map;lastAny=0;inflight=false;timer=null;closed=false;perTargetGapMs;globalGapMs;maxPayloadBytes;maxAttempts;get busy(){return this.inflight||this.queues.size>0}enqueue(e,s){if(this.closed)return;let t=this.queues.get(e)??{msgs:[],attempts:0},i=t.msgs[t.msgs.length-1];s.t==="ice"&&i?.t==="ice"&&i.lid===s.lid?i.c.push(...s.c):t.msgs.push(s),this.queues.set(e,t),this.pump();}forget(e){this.queues.delete(e),this.lastSent.delete(e);}close(){this.closed=true,this.queues.clear(),this.timer&&clearTimeout(this.timer),this.timer=null;}pump(){if(this.closed||this.inflight||this.timer)return;let e=Date.now(),s=null,t=1/0;for(let i of this.queues.keys()){let r=Math.max((this.lastSent.get(i)??0)+this.perTargetGapMs,this.lastAny+this.globalGapMs);if(r<=e){s=i;break}t=Math.min(t,r-e);}if(s===null){t!==1/0&&(this.timer=setTimeout(()=>{this.timer=null,this.pump();},t));return}this.flush(s);}async flush(e){let s=this.queues.get(e);if(!s||s.msgs.length===0){this.queues.delete(e),this.pump();return}let t=[],i="";for(let l of s.msgs){let h=JSON.stringify({v:1,m:[...t,l]});if(t.length>0&&E(h)>this.maxPayloadBytes)break;t.push(l),i=h;}let r=s.msgs.slice(t.length);r.length?this.queues.set(e,{msgs:r,attempts:0}):this.queues.delete(e),this.inflight=true;let n=null;try{n=await this.send(e,"rtc",i);}catch{n=null;}this.inflight=false;let a=Date.now();if(this.lastSent.set(e,a),this.lastAny=a,!n?.ok&&!this.closed){let l=n?.ok===false?n.reason:"connection";if((l==="throttled"||l==="connection")&&s.attempts+1<this.maxAttempts){let T=this.queues.get(e);this.queues.set(e,{msgs:[...t,...T?.msgs??[]],attempts:s.attempts+1});}}this.pump();}};function E(o){return new TextEncoder().encode(o).byteLength}var D={pollFastMs:1e3,pollHostIdleMs:2500,pollClientIdleMs:2e4,fastWindowMs:15e3,keepaliveMs:1e3,peerTimeoutMs:6e3,iceGatherTimeoutMs:1200,maxSignalPayloadBytes:15e3,signalPerTargetGapMs:650,signalGlobalGapMs:180},y=class o{constructor(e,s,t,i){this.client=e;this.selfId=s,this.roomId=t.RoomID??"",this.topology=t.Topology??"Mesh",this.chatMode=t.ChatMode??"ServerRelay",this.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;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(),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.client.multiplayer.leaveRoom(this.roomId,{successorUserID:e,keepalive:true});}};function I(){let o=globalThis.crypto;return o&&"randomUUID"in o?o.randomUUID().slice(0,12):Math.random().toString(36).slice(2,14)}export{f as MAX_MESSAGE_BYTES,y as RealtimeSession,p as toRtcIceServers};
1
+ import {b}from'../chunk-76ZM4DUB.js';var f=16384;function g(o){let e=new Uint8Array(o.byteLength+1);return e[0]=0,e.set(o,1),e}function v(o,e){if(o.byteLength+1<=16384)return [g(o)];if(o.byteLength>67108864)throw new RangeError(`Message of ${o.byteLength} bytes exceeds 67108864.`);let s=Math.ceil(o.byteLength/16375),t=[];for(let i=0;i<s;i++){let r=o.subarray(i*16375,Math.min(o.byteLength,(i+1)*16375)),n=new Uint8Array(9+r.byteLength),a=new DataView(n.buffer);n[0]=1,a.setUint32(1,e>>>0),a.setUint16(5,i),a.setUint16(7,s),n.set(r,9),t.push(n);}return t}var c=class{id=-1;count=0;parts=[];bytes=0;push(e){if(e.byteLength<9)return null;let s=new DataView(e.buffer,e.byteOffset,e.byteLength),t=s.getUint32(1),i=s.getUint16(5),r=s.getUint16(7);if(i===0&&(this.id=t,this.count=r,this.parts=[],this.bytes=0),t!==this.id||i!==this.parts.length||r!==this.count)return this.reset(),null;let n=e.subarray(9);if(this.bytes+=n.byteLength,this.bytes>67108864)return this.reset(),null;if(this.parts.push(n),this.parts.length<this.count)return null;let a=new Uint8Array(this.bytes),l=0;for(let h of this.parts)a.set(h,l),l+=h.byteLength;return this.reset(),a}reset(){this.id=-1,this.count=0,this.parts=[],this.bytes=0;}};function p(o){let e=new Map;for(let s of o??[]){let t=s.Urls?.trim();if(!t)continue;let i=s.Username??void 0,r=s.Credential??void 0,n=`${i??""}\0${r??""}`,a=e.get(n);if(a){let h=Array.isArray(a.urls)?a.urls:[a.urls];h.includes(t)||h.push(t),a.urls=h;continue}let l={urls:[t]};i&&(l.username=i),r&&(l.credential=r),e.set(n,l);}return [...e.values()]}var C=4*1024*1024,A=5e3,d=class{constructor(e){this.o=e;this.peerId=e.peerId,this.offerer=e.offerer,this.lid=e.lid,this.pc=e.createPeerConnection({iceServers:e.iceServers}),this.pc.onicecandidate=s=>{if(!s.candidate){this.sendDescriptionIfReady();return}this.descriptionSent&&this.lateIce.push(s.candidate.toJSON()),this.flushLateIce();},this.pc.onconnectionstatechange=()=>{let s=this.pc.connectionState;(s==="failed"||s==="closed")&&this.close(`connection ${s}`);},this.pc.ondatachannel=s=>this.adopt(s.channel),this.openTimer=setTimeout(()=>{this.state==="connecting"&&this.close("connect timeout");},Math.max(15e3,e.peerTimeoutMs*3)),this.offerer&&(this.adopt(this.pc.createDataChannel("rel",{ordered:true})),this.adopt(this.pc.createDataChannel("fast",{ordered:false,maxRetransmits:0})),this.makeOffer());}o;peerId;offerer;lid;state="connecting";pc;rel=null;fast=null;reassembler=new c;pendingRemoteIce=[];descriptionSent=false;lateIce=[];lastRecv=Date.now();lastSend=0;msgSeq=1;keepaliveTimer=null;gatherTimer=null;openTimer=null;bytesIn=0;bytesOut=0;rttMs=0;pingSentAt=0;async makeOffer(){try{await this.pc.setLocalDescription(await this.pc.createOffer()),this.waitForGathering();}catch(e){this.close(`offer failed: ${String(e)}`);}}async handle(e){if(this.state!=="closed")try{if(e.t==="offer"&&!this.offerer)await this.pc.setRemoteDescription({type:"offer",sdp:e.sdp}),await this.drainRemoteIce(),await this.pc.setLocalDescription(await this.pc.createAnswer()),this.waitForGathering();else if(e.t==="answer"&&this.offerer){if(this.pc.signalingState!=="have-local-offer")return;await this.pc.setRemoteDescription({type:"answer",sdp:e.sdp}),await this.drainRemoteIce();}else if(e.t==="ice")if(!this.pc.remoteDescription)this.pendingRemoteIce.push(...e.c);else for(let s of e.c)await this.addIce(s);else e.t==="bye"&&this.close("peer closed the link");}catch(s){this.close(`signaling failed: ${String(s)}`);}}async drainRemoteIce(){let e=this.pendingRemoteIce.splice(0);for(let s of e)await this.addIce(s);}async addIce(e){try{await this.pc.addIceCandidate(e);}catch{}}waitForGathering(){if(this.pc.iceGatheringState==="complete"){this.sendDescriptionIfReady();return}this.gatherTimer=setTimeout(()=>this.sendDescriptionIfReady(),this.o.iceGatherTimeoutMs);}sendDescriptionIfReady(){if(this.descriptionSent||this.state==="closed")return;let e=this.pc.localDescription;e?.sdp&&(this.gatherTimer&&clearTimeout(this.gatherTimer),this.gatherTimer=null,this.descriptionSent=true,this.o.signal(this.offerer?{t:"offer",lid:this.lid,sdp:e.sdp}:{t:"answer",lid:this.lid,sdp:e.sdp}),this.flushLateIce());}flushLateIce(){if(!this.descriptionSent||this.lateIce.length===0)return;let e=this.lateIce;this.lateIce=[],this.o.signal({t:"ice",lid:this.lid,c:e});}adopt(e){if(e.binaryType="arraybuffer",e.label==="rel")this.rel=e;else if(e.label==="fast")this.fast=e;else return;e.onopen=()=>this.maybeOpen(),e.onclose=()=>this.close(`channel ${e.label} closed`),e.onmessage=s=>this.receive(e.label,s.data),e.readyState==="open"&&queueMicrotask(()=>this.maybeOpen());}maybeOpen(){this.state==="connecting"&&(this.rel?.readyState!=="open"||this.fast?.readyState!=="open"||(this.state="open",this.openTimer&&clearTimeout(this.openTimer),this.openTimer=null,this.lastRecv=Date.now(),this.keepaliveTimer=setInterval(()=>this.keepalive(),this.o.keepaliveMs),this.o.onOpen()));}keepalive(){if(this.state!=="open")return;let e=Date.now();if(e-this.lastRecv>this.o.peerTimeoutMs){this.close("peer timeout");return}(e-this.lastSend>=this.o.keepaliveMs||e-this.pingSentAt>=A)&&(this.pingSentAt=e,this.raw("fast",new Uint8Array([2])));}receive(e,s){if(!(s instanceof ArrayBuffer))return;let t=new Uint8Array(s);this.lastRecv=Date.now(),this.bytesIn+=t.byteLength;let i=t[0];if(i===0)this.o.onMessage(e,t.subarray(1));else if(i===1&&e==="rel"){let r=this.reassembler.push(t);r&&this.o.onMessage(e,r);}else i===2?this.raw("fast",new Uint8Array([3])):i===3?this.pingSentAt&&(this.rttMs=Date.now()-this.pingSentAt):i===4&&e==="rel"&&this.o.onNotice?.(t[1]??0);}send(e,s){if(this.state!=="open")return false;if(e==="fast")return s.byteLength+1>16384?false:this.raw("fast",g(s));if((this.rel?.bufferedAmount??0)>C)return false;let t=v(s,this.msgSeq++);for(let i of t)if(!this.raw("rel",i))return false;return true}notice(e){return this.state!=="open"?false:this.raw("rel",new Uint8Array([4,e]))}get relBuffered(){return this.rel?.bufferedAmount??0}raw(e,s){let t=e==="rel"?this.rel:this.fast;if(!t||t.readyState!=="open")return false;try{return t.send(s),this.lastSend=Date.now(),this.bytesOut+=s.byteLength,!0}catch{return false}}close(e="closed",s=false){if(this.state!=="closed"){this.state="closed",s&&this.descriptionSent&&this.o.signal({t:"bye",lid:this.lid}),this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.gatherTimer&&clearTimeout(this.gatherTimer),this.openTimer&&clearTimeout(this.openTimer),this.keepaliveTimer=this.gatherTimer=this.openTimer=null;for(let t of [this.rel,this.fast])if(t){t.onopen=t.onclose=t.onmessage=null;try{t.close();}catch{}}this.pc.onicecandidate=this.pc.onconnectionstatechange=this.pc.ondatachannel=null;try{this.pc.close();}catch{}this.reassembler.reset(),this.o.onClose(e);}}};function R(o){if(!o)return [];try{let e=JSON.parse(o);return !e||e.v!==1||!Array.isArray(e.m)?[]:e.m.filter(s=>!!s&&typeof s=="object"&&typeof s.t=="string")}catch{return []}}var u=class{constructor(e,s={}){this.send=e;this.perTargetGapMs=s.perTargetGapMs??650,this.globalGapMs=s.globalGapMs??180,this.maxPayloadBytes=s.maxPayloadBytes??15e3,this.maxAttempts=s.maxAttempts??4;}send;queues=new Map;lastSent=new Map;lastAny=0;inflight=false;timer=null;closed=false;perTargetGapMs;globalGapMs;maxPayloadBytes;maxAttempts;get busy(){return this.inflight||this.queues.size>0}enqueue(e,s){if(this.closed)return;let t=this.queues.get(e)??{msgs:[],attempts:0},i=t.msgs[t.msgs.length-1];s.t==="ice"&&i?.t==="ice"&&i.lid===s.lid?i.c.push(...s.c):t.msgs.push(s),this.queues.set(e,t),this.pump();}forget(e){this.queues.delete(e),this.lastSent.delete(e);}close(){this.closed=true,this.queues.clear(),this.timer&&clearTimeout(this.timer),this.timer=null;}pump(){if(this.closed||this.inflight||this.timer)return;let e=Date.now(),s=null,t=1/0;for(let i of this.queues.keys()){let r=Math.max((this.lastSent.get(i)??0)+this.perTargetGapMs,this.lastAny+this.globalGapMs);if(r<=e){s=i;break}t=Math.min(t,r-e);}if(s===null){t!==1/0&&(this.timer=setTimeout(()=>{this.timer=null,this.pump();},t));return}this.flush(s);}async flush(e){let s=this.queues.get(e);if(!s||s.msgs.length===0){this.queues.delete(e),this.pump();return}let t=[],i="";for(let l of s.msgs){let h=JSON.stringify({v:1,m:[...t,l]});if(t.length>0&&E(h)>this.maxPayloadBytes)break;t.push(l),i=h;}let r=s.msgs.slice(t.length);r.length?this.queues.set(e,{msgs:r,attempts:0}):this.queues.delete(e),this.inflight=true;let n=null;try{n=await this.send(e,"rtc",i);}catch{n=null;}this.inflight=false;let a=Date.now();if(this.lastSent.set(e,a),this.lastAny=a,!n?.ok&&!this.closed){let l=n?.ok===false?n.reason:"connection";if((l==="throttled"||l==="connection")&&s.attempts+1<this.maxAttempts){let T=this.queues.get(e);this.queues.set(e,{msgs:[...t,...T?.msgs??[]],attempts:s.attempts+1});}}this.pump();}};function E(o){return new TextEncoder().encode(o).byteLength}var D={pollFastMs:1e3,pollHostIdleMs:2500,pollClientIdleMs:2e4,fastWindowMs:15e3,keepaliveMs:1e3,peerTimeoutMs:6e3,iceGatherTimeoutMs:1200,maxSignalPayloadBytes:15e3,signalPerTargetGapMs:650,signalGlobalGapMs:180},y=class o{constructor(e,s,t,i){this.client=e;this.selfId=s,this.roomId=t.RoomID??"",this.topology=t.Topology??"Mesh",this.chatMode=t.ChatMode??"ServerRelay",this.mode=t.Mode??null,this.ownerId=t.OwnerUserID??"",this.hostId=t.HostUserID??"",this.lastSeq=t.Seq??0,this.iceServers=p(t.IceServers),this.o={...D,leaveOnPageHide:true,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0)),createPeerConnection:i.createPeerConnection??(r=>new RTCPeerConnection(r))};for(let r of t.Members??[])r.UserID&&this.members.set(r.UserID,r);this.outbox=new u((r,n,a)=>this.client.multiplayer.sendSignal(this.roomId,r,n,a),{maxPayloadBytes:this.o.maxSignalPayloadBytes,perTargetGapMs:this.o.signalPerTargetGapMs,globalGapMs:this.o.signalGlobalGapMs}),this.fastUntil=Date.now()+this.o.fastWindowMs,this.o.leaveOnPageHide&&typeof window<"u"&&window.addEventListener("pagehide",this.onPageHide);}client;roomId;selfId;topology;chatMode;mode;ownerId;hostId;members=new Map;o;iceServers;lastSeq;links=new Map;everOpen=new Set;retry=new Map;wantSentAt=new Map;extraPeers=new Set;outbox;pollTimer=null;polling=false;pollSoonMs=null;pollBackoff=0;fastUntil=0;refreshTimer=null;stopped=false;successor=null;listeners=new Map;onPageHide=()=>this.leaveOnUnload();static async create(e,s,t={},i={}){let r=e.auth.context?.userID;if(!r)return b("unauthorized","Not logged in.");let n=await e.multiplayer.createRoom(s,t);return n.ok?{ok:true,data:o.start(e,r,n.data,i)}:n}static async join(e,s,t,i={}){let r=e.auth.context?.userID;if(!r)return b("unauthorized","Not logged in.");let n=await e.multiplayer.joinRoom(s,t);return n.ok?{ok:true,data:o.start(e,r,n.data,i)}:n}static start(e,s,t,i){let r=new o(e,s,t,i);return r.reconcile(),r.schedulePoll(0),r}get isHost(){return this.hostId===this.selfId}get isOwner(){return this.ownerId===this.selfId}get closed(){return this.stopped}on(e,s){let t=this.listeners.get(e)??new Set;return t.add(s),this.listeners.set(e,t),()=>t.delete(s)}openPeers(){return [...this.links.values()].filter(e=>e.state==="open").map(e=>e.peerId)}isOpen(e){return this.links.get(e)?.state==="open"}linkStats(e){let s=this.links.get(e);return s?{rttMs:s.rttMs,bytesIn:s.bytesIn,bytesOut:s.bytesOut,buffered:s.relBuffered}:null}send(e,s,t){return this.links.get(e)?.send(s,t)??false}broadcast(e,s,t){let i=0;for(let r of this.links.values())r.peerId!==t&&r.state==="open"&&r.send(e,s)&&i++;return i}setExtraPeers(e){this.extraPeers=new Set([...e].filter(s=>s!==this.selfId)),this.reconcile();}setSuccessor(e){this.successor=e&&e!==this.selfId?e:null;}async claimHost(){let e=await this.client.multiplayer.claimHost(this.roomId);return e.ok&&this.applySnapshot(e.data),e}async kick(e,s=false){let t=await this.client.multiplayer.kickMember(this.roomId,e,s);return t.ok&&this.links.get(e)?.notice(1),t}unban(e){return this.client.multiplayer.unbanMember(this.roomId,e)}async leave(){if(this.stopped)return;let e=this.isHost?this.successor??void 0:void 0;this.stop(),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.client.multiplayer.leaveRoom(this.roomId,{successorUserID:e,keepalive:true});}};function I(){let o=globalThis.crypto;return o&&"randomUUID"in o?o.randomUUID().slice(0,12):Math.random().toString(36).slice(2,14)}export{f as MAX_MESSAGE_BYTES,y as RealtimeSession,p as toRtcIceServers};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@idosgames/core",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "Engine-agnostic core of the IDosGames SDK (transport, auth, cache, services, events).",
5
5
  "type": "module",
6
6
  "license": "MIT",