@indiegems/gem-web-sdk 5.9.0 → 5.11.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/brand/gem-hero-128.png +0 -0
- package/brand/gem-hero-256.png +0 -0
- package/brand/gem-hero-384.png +0 -0
- package/brand/gem-hero-512.png +0 -0
- package/brand/gem-hero-768.png +0 -0
- package/brand/gem-icon-20-1.5x.png +0 -0
- package/brand/gem-icon-20-1x.png +0 -0
- package/brand/gem-icon-20-2x.png +0 -0
- package/brand/gem-icon-20-3x.png +0 -0
- package/brand/gem-icon-32-1.5x.png +0 -0
- package/brand/gem-icon-32-1x.png +0 -0
- package/brand/gem-icon-32-2x.png +0 -0
- package/brand/gem-icon-32-3x.png +0 -0
- package/brand/trophy-hero-128.png +0 -0
- package/brand/trophy-hero-256.png +0 -0
- package/brand/trophy-hero-384.png +0 -0
- package/brand/trophy-hero-512.png +0 -0
- package/brand/trophy-hero-768.png +0 -0
- package/dist/game.d.ts +55 -33
- package/dist/gem-web-sdk.bridge.js +1 -1
- package/dist/gem-web-sdk.esm.js +2 -2
- package/dist/gem-web-sdk.game.js +2 -2
- package/dist/gem-web-sdk.min.js +2 -2
- package/dist/gem-web-sdk.sdk.js +2 -2
- package/dist/gem-web-sdk.server.js +2 -2
- package/dist/index.d.ts +79 -22
- package/dist/sdk.d.ts +56 -34
- package/dist/server.d.ts +10 -2
- package/package.json +5 -3
- package/schema/bridge.v1.json +167 -36
package/dist/gem-web-sdk.esm.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:5.9.0]";var y="gem-web-bridge",Z={min:1,max:1},ge=65536,On=8,Xe=5e3,Dn=1024,Lt=1e4;function Ot(n){return Object.freeze(Object.assign(Object.create(null),n))}var Ye=Ot({"gem.handshake":30,"gem.handshake.accept":5,"gem.token":30,"gem.token.denied":30,"gem.player":12,"gem.pause":120,"gem.prefs":60,"gem.cohorts":12,"gem.viewport":60,"gem.deviceSettings":12,"gem.willTerminate":10,"gem.roomEvent":120,"gem.socketState":12,"gem.seatedEvent":60,"gem.signalEvent":1800,"gem.dedicatedEvent":120,"gem.partyResult":30,"gem.clusterTarget":12,"gem.devtools":30,"gem.screenshot":6,"gem.screenshot.denied":12,"gem.requestContext":12,"gem.gameContext":12,"gem.signal":1200,"gem.dedicatedOffer":60,"gem.partyRequest":12,"gem.ready":5,"gem.progress":600,"gem.requestToken":12,"gem.requestLocalServer":6,"gem.localServer":30,"gem.localServer.denied":30,"gem.exit":5,"gem.openExternal":6,"gem.requestFullscreen":30,"gem.audioState":120,"gem.rewardCue":60,"gem.frameStats":120,"gem.error":60,"gem.requestPurchase":12,"gem.purchaseResult":30,"gem.deviceSettings.put":30,"gem.deviceSettings.result":30,"gem.requestAd":6,"gem.adResult":12,"gem.requestSignIn":6,"gem.signInResult":12,__malformed:60}),fe="__malformed",Ba=["gem.handshake","gem.token","gem.token.denied","gem.player","gem.pause","gem.prefs","gem.cohorts","gem.viewport","gem.deviceSettings","gem.willTerminate","gem.roomEvent","gem.socketState","gem.seatedEvent","gem.signalEvent","gem.dedicatedEvent","gem.partyResult","gem.clusterTarget","gem.devtools","gem.screenshot","gem.requestContext","gem.localServer","gem.localServer.denied","gem.error","gem.purchaseResult","gem.deviceSettings.result","gem.adResult","gem.signInResult"],Ja=["gem.handshake.accept","gem.screenshot.denied","gem.gameContext","gem.signal","gem.dedicatedOffer","gem.partyRequest","gem.ready","gem.progress","gem.requestToken","gem.requestLocalServer","gem.exit","gem.openExternal","gem.requestFullscreen","gem.audioState","gem.rewardCue","gem.frameStats","gem.error","gem.requestPurchase","gem.deviceSettings.put","gem.requestAd","gem.requestSignIn"],zr=Ot({"gem.requestAd":"ads","gem.adResult":"ads","gem.requestSignIn":"signIn","gem.signInResult":"signIn","gem.requestPurchase":"purchases","gem.purchaseResult":"purchases","gem.devtools":"devtools","gem.screenshot":"screenshot","gem.screenshot.denied":"screenshot","gem.requestContext":"feedbackContext","gem.gameContext":"feedbackContext","gem.roomEvent":"rooms","gem.signal":"p2p","gem.signalEvent":"p2p","gem.dedicatedOffer":"dedicated","gem.dedicatedEvent":"dedicated","gem.clusterTarget":"clusterTarget","gem.partyRequest":"parties","gem.partyResult":"parties","gem.seatedEvent":"partySeating","gem.socketState":"socketState","gem.audioState":"audioState","gem.rewardCue":"rewardCue","gem.frameStats":"frameStats","gem.viewport":"viewport","gem.requestLocalServer":"localHost","gem.localServer":"localHost","gem.localServer.denied":"localHost","gem.cohorts":"cohorts","gem.deviceSettings":"deviceSettings","gem.deviceSettings.put":"deviceSettings","gem.deviceSettings.result":"deviceSettings"}),Qr=Object.freeze([["gem.asyncOpponents.","asyncOpponents"]]);function ze(n){let e=zr[n];if(e!==void 0)return e;for(let[t,r]of Qr)if(n.startsWith(t))return r}function Qe(n){let e=/^([a-z][a-z0-9+.-]*):\/\/([a-z0-9.-]+|\[[0-9a-f:.]+\])(:([0-9]{1,5}))?$/i.exec(n);return e===null?false:e[4]===void 0||Number(e[4])<=65535}function Zr(n){let e;try{e=new URL(n);}catch{return false}return e.username!==""||e.password!==""?false:e.protocol==="https:"?true:e.protocol==="http:"&&(e.hostname==="localhost"||e.hostname==="127.0.0.1")}function ei(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function Mt(n,e,t){if(e>On)return `nesting deeper than ${On}`;if(++t.nodes>Xe)return `more than ${Xe} values`;if(t.bytes>ge)return `over the ${ge} byte limit`;if(n==null)return t.bytes+=4,null;let r=typeof n;if(r==="boolean")return t.bytes+=5,null;if(r==="number")return t.bytes+=8,null;if(r==="string")return t.bytes+=n.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let i=n;if(t.seen.has(i))return "a repeated or cyclic object reference";if(t.seen.add(i),Array.isArray(n)){if(n.length>Dn)return `an array of ${n.length} entries, over the ${Dn} limit`;t.bytes+=2;for(let a of n){let d=Mt(a,e+1,t);if(d)return d}return null}let o=Object.getPrototypeOf(n);if(o!==Object.prototype&&o!==null)return "a value that is not a plain object";t.bytes+=2;let s=n;for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;if(++t.nodes>Xe)return `more than ${Xe} values`;if(t.bytes+=a.length*3+4,t.bytes>ge)return `over the ${ge} byte limit`;let d=Mt(s[a],e+1,t);if(d)return d}return null}function ti(n){let e={nodes:0,bytes:0,seen:new Set},t=Mt(n,0,e);return t?`message contains ${t}`:e.bytes>ge?`message is over the ${ge} byte limit`:null}var ni={origin:[Qe,"not a well-formed origin"],url:[Zr,"not a safe absolute http(s) URL"],bcp47:[ei,"not a well-formed BCP 47 tag"]};function Gn(n,e,t){for(let r of e){let i=t===""?r.n:`${t}.${r.n}`,o=n[r.n];if(o==null){if(r.o)continue;return `${i}: required`}let s=jn(o,r,i);if(s)return s}return null}function jn(n,e,t){switch(e.k){case "string":{if(typeof n!="string")return `${t}: expected string`;if(n.length>e.max)return `${t}: exceeds ${e.max} characters`;if(e.f){let[r,i]=ni[e.f];if(!r(n))return `${t}: ${i}`}return null}case "int":return typeof n!="number"||!Number.isInteger(n)?`${t}: expected integer`:n<e.lo||n>e.hi?`${t}: out of range ${e.lo}..${e.hi}`:null;case "boolean":return typeof n=="boolean"?null:`${t}: expected boolean`;case "enum":{let r=e.v;return r.includes(n)?null:`${t}: not one of ${r.join("|")}`}case "object":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected object`:Gn(n,e.fs,t);case "json":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected a plain object`:null;case "array":{if(!Array.isArray(n))return `${t}: expected array`;if(n.length>e.max)return `${t}: exceeds ${e.max} items`;let r=e.it,i=`${t}[]`;for(let o of n){if(o==null){if(r.o)continue;return `${i}: required`}let s=jn(o,r,i);if(s)return s}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}function v(n,e){return t=>{let r=ti(t);if(r)return r;if(typeof t!="object"||t===null||Array.isArray(t))return "message: expected object";let i=t;return i.gem!==y?"gem: wrong protocol marker":i.type!==n?`type: expected ${n}`:Gn(i,e,"")}}var ri=v("gem.handshake",[{n:"versions",k:"object",fs:[{n:"min",k:"int",lo:1,hi:1e3},{n:"max",k:"int",lo:1,hi:1e3}]},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}},{n:"embedder",k:"string",max:2048,f:"origin"}]),ii=v("gem.handshake.accept",[{n:"v",k:"int",lo:1,hi:1e3},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}}]),oi=v("gem.token",[{n:"token",k:"string",max:4096},{n:"requestId",k:"string",o:1,max:64},{n:"generation",k:"int",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"string",o:1,max:512,f:"url"},{n:"playerId",k:"string",max:64},{n:"gameId",k:"string",max:64},{n:"channel",k:"enum",v:["dev","test","release"]},{n:"gameVersion",k:"string",o:1,max:64},{n:"expiresAt",k:"int",lo:0,hi:4102444800},{n:"chainEndsAt",k:"int",lo:0,hi:4102444800},{n:"allowDevTools",k:"boolean",o:1}]),ai=v("gem.token.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:36e5},{n:"reason",k:"enum",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"string",max:64}]),si=v("gem.player",[{n:"untrusted",k:"object",fs:[{n:"displayName",k:"string",max:64},{n:"displayHandle",k:"string",max:80}]},{n:"displayTag",k:"string",max:8},{n:"avatarUrl",k:"string",o:1,max:2048,f:"url"}]),di=v("gem.pause",[{n:"paused",k:"boolean"}]),li=v("gem.prefs",[{n:"reducedMotion",k:"boolean"},{n:"muted",k:"boolean"},{n:"showFrameStats",k:"boolean",o:1},{n:"locale",k:"string",max:35,f:"bcp47"}]),ci=v("gem.cohorts",[{n:"cohorts",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"experimentId",k:"string",max:36},{n:"variantKey",k:"string",max:32}]}}]),ui=v("gem.viewport",[{n:"insets",k:"object",fs:[{n:"top",k:"int",lo:0,hi:4096},{n:"right",k:"int",lo:0,hi:4096},{n:"bottom",k:"int",lo:0,hi:4096},{n:"left",k:"int",lo:0,hi:4096}]}]),mi=v("gem.deviceSettings",[{n:"settings",k:"json",o:1}]),pi=v("gem.willTerminate",[{n:"reason",k:"enum",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"int",lo:0,hi:6e4}]),hi=v("gem.roomEvent",[{n:"event",k:"enum",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"string",max:64},{n:"matchId",k:"string",o:1,max:64},{n:"version",k:"int",o:1,lo:0,hi:2147483647},{n:"reason",k:"string",o:1,max:64},{n:"platform",k:"enum",o:1,v:["universal","mobile"]}]),gi=v("gem.socketState",[{n:"connected",k:"boolean"},{n:"reason",k:"enum",o:1,v:["connecting","dropped","watchdog","terminal"]}]),fi=v("gem.seatedEvent",[{n:"roomId",k:"string",max:64}]),yi=v("gem.signalEvent",[{n:"event",k:"enum",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),vi=v("gem.dedicatedEvent",[{n:"event",k:"enum",v:["answer","error","matchEnded"]},{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",o:1,max:10240},{n:"sessionId",k:"string",o:1,max:64},{n:"code",k:"string",o:1,max:64},{n:"message",k:"string",o:1,max:256},{n:"reason",k:"string",o:1,max:64}]),bi=v("gem.partyResult",[{n:"requestId",k:"string",max:64},{n:"partyId",k:"string",o:1,max:64}]),wi=v("gem.clusterTarget",[{n:"clusterTargetId",k:"string",max:64}]),ki=v("gem.devtools",[{n:"action",k:"enum",v:["open","close","toggle"]}]),Si=v("gem.screenshot",[{n:"maxWidth",k:"int",lo:1,hi:7680},{n:"maxHeight",k:"int",lo:1,hi:4320}]),Ri=v("gem.screenshot.denied",[{n:"reason",k:"enum",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"boolean"}]),_i=v("gem.requestContext",[]),Ei=v("gem.gameContext",[{n:"context",k:"json"}]),xi=v("gem.signal",[{n:"signal",k:"enum",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Ti=v("gem.dedicatedOffer",[{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",max:10240},{n:"intent",k:"enum",v:["initial","ice_restart","full_reconnect"]}]),Ai=v("gem.partyRequest",[{n:"requestId",k:"string",max:64}]),Ii=v("gem.ready",[]),Pi=v("gem.progress",[{n:"loaded",k:"int",lo:0,hi:1099511627776},{n:"total",k:"int",lo:0,hi:1099511627776}]),Ci=v("gem.requestToken",[{n:"requestId",k:"string",max:64},{n:"reason",k:"enum",v:["initial","expiring","rejected"]}]),Mi=v("gem.requestLocalServer",[{n:"requestId",k:"string",max:64},{n:"gameRoomId",k:"string",max:64}]),Li=v("gem.localServer",[{n:"requestId",k:"string",max:64},{n:"serverId",k:"string",o:1,max:128}]),Oi=v("gem.localServer.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"reason",k:"enum",v:["refused","unavailable"]}]),Di=v("gem.exit",[{n:"reason",k:"string",o:1,max:64}]),Gi=v("gem.openExternal",[{n:"url",k:"string",max:2048,f:"url"}]),ji=v("gem.requestFullscreen",[{n:"enabled",k:"boolean"}]),Ni=v("gem.audioState",[{n:"muted",k:"boolean"}]),Fi=v("gem.rewardCue",[{n:"currencySlug",k:"string",max:32},{n:"expected",k:"int",o:1,lo:1,hi:1e9},{n:"origin",k:"object",o:1,fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384}]}]),$i=v("gem.frameStats",[{n:"fps",k:"int",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"int",lo:0,hi:1e5}]),qi=v("gem.error",[{n:"code",k:"enum",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"string",o:1,max:256}]),Ui=v("gem.requestPurchase",[{n:"requestId",k:"string",max:64},{n:"purchaseKind",k:"enum",v:["item","recipe"]},{n:"targetId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"quantity",k:"int",o:1,lo:1,hi:10},{n:"catalogId",k:"string",o:1,max:64}]),Hi=v("gem.purchaseResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["ok","declined","unavailable"]},{n:"purchaseId",k:"string",o:1,max:64}]),Wi=v("gem.deviceSettings.put",[{n:"requestId",k:"string",max:64},{n:"settings",k:"json"}]),Ki=v("gem.deviceSettings.result",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["stored","too_large","unavailable"]}]),Vi=v("gem.requestAd",[{n:"requestId",k:"string",max:64},{n:"placement",k:"string",max:32},{n:"format",k:"enum",v:["interstitial","rewarded"]}]),Bi=v("gem.adResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["shown","no_ad","unavailable"]}]),Ji=v("gem.requestSignIn",[{n:"requestId",k:"string",max:64}]),Xi=v("gem.signInResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["signed_in","declined","unavailable"]}]),se=Ot({"gem.handshake":ri,"gem.handshake.accept":ii,"gem.token":oi,"gem.token.denied":ai,"gem.player":si,"gem.pause":di,"gem.prefs":li,"gem.cohorts":ci,"gem.viewport":ui,"gem.deviceSettings":mi,"gem.willTerminate":pi,"gem.roomEvent":hi,"gem.socketState":gi,"gem.seatedEvent":fi,"gem.signalEvent":yi,"gem.dedicatedEvent":vi,"gem.partyResult":bi,"gem.clusterTarget":wi,"gem.devtools":ki,"gem.screenshot":Si,"gem.screenshot.denied":Ri,"gem.requestContext":_i,"gem.gameContext":Ei,"gem.signal":xi,"gem.dedicatedOffer":Ti,"gem.partyRequest":Ai,"gem.ready":Ii,"gem.progress":Pi,"gem.requestToken":Ci,"gem.requestLocalServer":Mi,"gem.localServer":Li,"gem.localServer.denied":Oi,"gem.exit":Di,"gem.openExternal":Gi,"gem.requestFullscreen":ji,"gem.audioState":Ni,"gem.rewardCue":Fi,"gem.frameStats":$i,"gem.error":qi,"gem.requestPurchase":Ui,"gem.purchaseResult":Hi,"gem.deviceSettings.put":Wi,"gem.deviceSettings.result":Ki,"gem.requestAd":Vi,"gem.adResult":Bi,"gem.requestSignIn":Ji,"gem.signInResult":Xi});var Ce=16384,Ze=24;function R(n){return e=>typeof e=="string"&&e.length>0&&e.length<=n?e:void 0}function ee(n,e){return t=>typeof t=="number"&&Number.isInteger(t)&&t>=n&&t<=e?t:void 0}function ye(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function Nn(n){return typeof n=="boolean"?n:void 0}var L=R(64),Me=ee(0,2147483647);function Dt(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(e.length>=64)break;let r=L(t);typeof r=="string"&&e.push(r);}return e}function x(n,e,t){return {to:n,from:e,read:t,required:true}}function _(n,e,t){return {to:n,from:e,read:t,required:false}}function ve(n,e){let t={};for(let r of e){let i=r.read(n[r.from]);if(i===void 0){if(r.required)return null;continue}t[r.to]=i;}return t}function Le(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e=n;return typeof e.type!="string"||typeof e.data!="object"||e.data===null||Array.isArray(e.data)?null:{type:e.type,data:e.data}}var Fn=[x("sdp","sdp",R(10240)),x("signaling_intent","intent",ye("initial","ice_restart","full_reconnect"))];function et(n,e,t){if(typeof t!="object"||t===null||Array.isArray(t))return {reason:"offer: data must be an object"};let r=t,i=ve(r,Fn);return i===null?{reason:`offer: '${Fn.find(s=>s.read(r[s.from])===void 0)?.from??"?"}' is missing or out of bounds`}:{frame:{type:"webrtc_offer",match_id:n,game_id:e,...i}}}var Gt=Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"})),Yi=new Set(["error"]),zi=Object.freeze(Object.assign(Object.create(null),{answer:[x("sdp","sdp",R(10240)),_("sessionId","session_id",R(64))],error:[_("code","code",R(64)),_("message","message",R(256))],matchEnded:[_("reason","reason",R(64))]}));function tt(n,e,t){let r=Le(n);if(r===null)return null;let i=Gt[r.type];if(i===void 0)return null;let o=L(r.data.match_id);if(typeof o!="string"||!(Yi.has(i)?t(o):r.data.game_id===e))return null;let a=ve(r.data,zi[i]??[]);return a===null?null:{event:i,matchId:o,...a}}var Qi=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=ye("disconnected","failed","closed")(e.iceState),r=ee(0,4102444800)(e.lastSeenAt);if(!(t===void 0&&r===void 0))return {...t===void 0?{}:{ice_state:t},...r===void 0?{}:{last_seen_timestamp:r}}},Zi=Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[x("sdp","sdp",R(10240)),x("signaling_intent","intent",ye("initial","ice_restart","full_reconnect")),_("sdp_hash","sdpHash",R(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[x("peer_id","peerId",L),x("sdp","sdp",R(10240)),x("assigned_peer_id","assignedPeerId",ee(0,4294967295)),_("sdp_hash","sdpHash",R(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[x("peer_id","peerId",L),x("candidate","candidate",R(512)),_("sdp_mid","sdpMid",R(64)),_("sdp_mline_index","sdpMLineIndex",ee(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[x("host_epoch","hostEpoch",Me)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[x("host_epoch","hostEpoch",Me),_("evidence","evidence",Qi)]}}));function nt(n,e,t,r){let i=Zi[n];if(i===void 0)return {reason:`unknown signal '${n}'`};if(typeof r!="object"||r===null||Array.isArray(r))return {reason:`${n}: data must be an object`};let o=r,s=ve(o,i.args);if(s===null){let a=i.args.find(d=>d.required&&d.read(o[d.from])===void 0);return {reason:`${n}: '${a?.from??"?"}' is missing or out of bounds`}}return {frame:{type:i.type,match_id:e,...i.gameScoped?{game_id:t}:{},...s}}}var eo=Object.freeze(Object.assign(Object.create(null),{p2p_hello:"hello",p2p_sdp_offer:"offer",p2p_sdp_answer:"answer",p2p_ice_candidate:"ice",p2p_peer_joined:"peerJoined",p2p_peer_left:"peerLeft",p2p_host_migration:"migration",p2p_match_ended:"matchEnded",p2p_error:"error"})),to=new Set(["error"]),no=Object.freeze(Object.assign(Object.create(null),{hello:[x("playerId","player_id",L),x("hostPlayerId","host_player_id",L),x("hostEpoch","host_epoch",Me),_("members","members",Dt)],offer:[x("fromPlayerId","from_player_id",L),x("sdp","sdp",R(10240)),_("sessionId","signaling_session_id",R(128)),_("sdpHash","sdp_hash",R(128)),_("iceUfrag","ice_ufrag",R(64)),_("intent","signaling_intent",ye("initial","ice_restart","full_reconnect"))],answer:[x("fromPlayerId","from_player_id",L),x("sdp","sdp",R(10240)),_("sessionId","signaling_session_id",R(128)),_("sdpHash","sdp_hash",R(128)),_("iceUfrag","ice_ufrag",R(64)),_("assignedPeerId","assigned_peer_id",ee(0,4294967295))],ice:[x("fromPlayerId","from_player_id",L),x("candidate","candidate",R(512)),_("sdpMid","sdp_mid",R(64)),_("sdpMLineIndex","sdp_m_line_index",ee(0,255)),_("sdpMLineIndexAlt","sdp_mline_index",ee(0,255))],peerJoined:[x("playerId","player_id",L)],peerLeft:[x("playerId","player_id",L),_("reason","reason",R(64))],migration:[x("hostPlayerId","new_host_player_id",L),x("hostEpoch","host_epoch",Me),_("reason","reason",R(64)),_("kickedPlayerIds","kicked_player_ids",Dt),_("migrationComplete","migration_complete",Nn)],matchEnded:[_("reason","reason",R(64))],error:[_("code","code",R(64)),_("message","message",R(256))]}));function rt(n,e,t){let r=Le(n);if(r===null)return null;let i=eo[r.type];if(i===void 0)return null;let o=L(r.data.match_id);if(typeof o!="string"||!(to.has(i)?t(o):r.data.game_id===e))return null;let a=ve(r.data,no[i]??[]);return a===null?null:{event:i,matchId:o,data:a}}var ro=Object.freeze(Object.assign(Object.create(null),{party_invite_received:"inviteReceived",party_member_joined:"memberJoined",party_member_left:"memberLeft",party_member_kicked:"memberKicked",party_leader_transferred:"leaderTransferred",party_updated:"updated",party_disbanded:"disbanded",party_game_room_joined:"gameRoomJoined",party_game_room_left:"gameRoomLeft"}));function Oe(n){let e=Le(n);if(e===null)return null;let t=ro[e.type];if(t===void 0)return null;let r=e.data,i=L(r.party_id);if(typeof i!="string")return null;let o=ee(0,Number.MAX_SAFE_INTEGER)(r.version),s=L(r.game_room_id),a=L(r.game_id),d=L(r.inviter_player_id),l=R(80)(r.inviter_display_tag),p=R(64)(r.party_name);return {event:t,partyId:i,...o===void 0?{}:{version:o},...s===void 0?{}:{gameRoomId:s},...a===void 0?{}:{gameId:a},...d===void 0?{}:{inviterPlayerId:d},...l===void 0?{}:{inviterDisplayTag:l},...p===void 0?{}:{partyName:p}}}var re={now:()=>Date.now(),setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n)},te=class{constructor(e=re){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let t=Ye[e];if(t===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??t,s=Math.max(0,r-i),a=Math.min(t,o+s*t/6e4);return a<1?(this.tokens.set(e,a),this.lastRefill.set(e,r),false):(this.tokens.set(e,a-1),this.lastRefill.set(e,r),true)}};function we(n,e){return n.toLowerCase()===e.toLowerCase()}function it(n){let e=n.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function qn(n,e){if(typeof e!="string"||e==="")return false;let t,r;try{t=new URL(n),r=new URL(e);}catch{return false}return t.protocol!=="http:"&&t.protocol!=="https:"||r.protocol!=="http:"&&r.protocol!=="https:"||t.username!==""||t.password!==""||t.pathname!=="/"||t.search!==""||t.hash!==""||t.port===""?false:it(t.hostname)&&it(r.hostname)}function jt(n,e){if(n.min>n.max||e.min>e.max)return null;let t=Math.min(n.max,e.max),r=Math.max(n.min,e.min);return t>=r?t:null}var io=["universal","mobile"],oo={game_room_updated:"updated",game_room_match_started:"match_started",game_room_match_ready:"match_ready",game_room_match_failed:"match_failed",game_room_version_stale:"version_stale",match_ended:"updated",p2p_match_ended:"updated"},ao=new Set(["match_ended","p2p_match_ended"]),De=64,so=8,$t=class{constructor(e,t){this.clock=e;this.limit=t;}clock;limit;windowStart=0;used=0;allow(){let e=this.clock.now();return e-this.windowStart>=1e3&&(this.windowStart=e,this.used=0),this.used>=this.limit?false:(this.used+=1,true)}};function Nt(n){if(!(typeof n!="string"||n.length===0||n.length>De))return n}function lo(n){return n instanceof Error?n.message:String(n)}function Un(n,e){if(!n.has(e)){if(n.size>=so){let t=n.values().next().value;t!==void 0&&n.delete(t);}n.add(e);}}function Ft(){return new MessageChannel}var co=6e4/(Ye["gem.handshake"]??1),uo=6e4,qt=class{constructor(e){this.options=e;if(!Qe(e.frameOrigin))throw new Error(`GemHost: frameOrigin must be a concrete origin, got '${e.frameOrigin}'. '*' and 'null' are refused \u2014 the handshake transfers the MessagePort, so an imprecise targetOrigin gives the session away.`);if(!Qe(e.embedderOrigin))throw new Error(`GemHost: embedderOrigin must be a concrete origin, got '${e.embedderOrigin}'.`);this.clock=e.clock??re,this.inbound=new te(this.clock),this.outbound=new te(this.clock),this.socketWindow=new $t(this.clock,24);}options;state="idle";port=null;version=null;timeoutHandle=null;reofferHandle=null;makeChannel=Ft;offered=[];offersMade=0;localDenials=0;chainEndsAt=null;gameId=null;peerCapabilities=[];knownMatches=new Set;askedMatches=new Set;clock;inbound;outbound;socketWindow;get currentState(){return this.state}get frameCapabilities(){return this.peerCapabilities}frameSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}start(e=Ft){if(this.state!=="idle"){this.fail("handshake_duplicate",`cannot start from state '${this.state}'`);return}if(typeof e=="function")this.makeChannel=e;else if(e&&e.port1&&e.port2){let t=e,r=false;this.makeChannel=()=>r?Ft():(r=true,t);}else throw new Error("GemHost.start: pass a function returning { port1, port2 } \u2014 omit it entirely to get a fresh MessageChannel per offer, which is what an embedder normally wants.");this.transition("handshaking"),this.offer(),this.scheduleReoffer(),this.timeoutHandle=this.clock.setTimeout(()=>{this.timeoutHandle=null,this.state==="handshaking"&&this.fail("handshake_timeout",`no answer from ${this.options.frameOrigin} to ${this.offersMade} handshake ${this.offersMade===1?"offer":"offers"} in the first ${Lt}ms; the offers continue for as long as this page holds the frame. This page presented embedder origin ${this.options.embedderOrigin}. A frame answers none of them if it carries no bridge at all, if it has not started listening yet, or if that origin is missing from the embedders it will accept \u2014 this side cannot tell which, and does not try.`);},Lt);}offer(){if(!this.outbound.allow("gem.handshake"))return false;let e=this.makeChannel(),t=e.port1;return t.onmessage=r=>this.receive(r.data,t),t.start?.(),this.offered.push({port:t,at:this.clock.now()}),this.offersMade+=1,this.options.frame.postMessage({gem:y,type:"gem.handshake",versions:{min:Z.min,max:Z.max},embedder:this.options.embedderOrigin,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}},this.options.frameOrigin,[e.port2]),true}scheduleReoffer(){this.reofferHandle=this.clock.setTimeout(()=>{this.reofferHandle=null,this.state==="handshaking"&&(this.offer(),this.pruneStaleOffers(),this.scheduleReoffer());},co);}pruneStaleOffers(){let e=this.clock.now()-uo;for(;this.offered.length>0&&(this.offered[0]?.at??e)<e;){let t=this.offered.shift();if(t===void 0)break;t.port.onmessage=null,t.port.close();}}adopt(e){for(let t of this.offered)t.port!==e&&(t.port.onmessage=null,t.port.close());this.offered.length=0,this.port=e;}static checkHandshakeOrigin(e,t,r){return we(e.origin,t)?e.source!==r?"source is not the mounted frame":null:`origin '${e.origin}' is not the expected frame origin`}sendToken(e){if(!Number.isInteger(e.chainEndsAt)||e.chainEndsAt<0){this.fail("internal","refusing a grant whose chainEndsAt is not a whole number of seconds >= 0");return}let t=this.chainEndsAt??e.chainEndsAt;if(this.chainExpired()){this.fail("token_unavailable","token chain ceiling reached");return}this.send({gem:y,type:"gem.token",token:e.token,expiresAt:e.expiresAt,chainEndsAt:t,generation:e.generation,playerId:e.playerId,gameId:e.gameId,channel:e.channel,...e.gameVersion===void 0?{}:{gameVersion:e.gameVersion},...e.requestId===void 0?{}:{requestId:e.requestId},...e.apiBaseUrl===void 0?{}:{apiBaseUrl:e.apiBaseUrl},...e.allowDevTools===true?{allowDevTools:true}:{},...e.garden===void 0?{}:{garden:e.garden}})&&(this.chainEndsAt=t,this.gameId??=e.gameId);}relayRoomEvent(e){if(this.gameId===null||typeof e!="object"||e===null||Array.isArray(e))return false;let t=e;if(typeof t.type!="string")return false;let r=oo[t.type];if(r===void 0||typeof t.data!="object"||t.data===null||Array.isArray(t.data))return false;let i=t.data;if(i.game_id!==this.gameId)return false;let o=Nt(i.game_room_id);if(o===void 0)return false;let s=ao.has(t.type)?void 0:Nt(i.match_id);s!==void 0&&this.rememberMatch(s);let a=typeof i.version=="number"?i.version:void 0,d=typeof i.reason=="string"?i.reason.slice(0,De):void 0,l=r==="version_stale"&&io.includes(i.platform)?i.platform:void 0;return this.sendRoomEvent({event:r,roomId:o,...s===void 0?{}:{matchId:s},...a===void 0?{}:{version:a},...d===void 0?{}:{reason:d},...l===void 0?{}:{platform:l}})}sendRoomEvent(e){return this.frameSupports("rooms")?this.send({gem:y,type:"gem.roomEvent",event:e.event,roomId:e.roomId,...e.matchId===void 0?{}:{matchId:e.matchId},...e.version===void 0?{}:{version:e.version},...e.reason===void 0?{}:{reason:e.reason},...e.platform===void 0?{}:{platform:e.platform}}):false}sendSocketState(e){return this.frameSupports("socketState")?this.send({gem:y,type:"gem.socketState",connected:e.connected,...e.connected?{}:{reason:e.reason}}):false}sendSeatedEvent(e){return this.frameSupports("partySeating")?this.send({gem:y,type:"gem.seatedEvent",roomId:e}):false}relaySeatedEvent(e){if(this.gameId===null)return false;let t=Oe(e);if(t===null||t.event!=="gameRoomJoined"||t.gameId!==this.gameId)return false;let r=Nt(t.gameRoomId);return r===void 0?false:this.sendSeatedEvent(r)}relaySocketEvent(e){let t=[];this.relayRoomEvent(e)&&t.push("room"),this.relaySignalEvent(e)&&t.push("signal"),this.relayDedicatedEvent(e)&&t.push("dedicated");let r=Oe(e);return r!==null&&(this.options.onPartyEvent?.(r),this.relaySeatedEvent(e),t.push("party")),t}relaySignalEvent(e){if(this.gameId===null)return false;let t=rt(e,this.gameId,r=>this.knowsMatch(r));return t===null?false:(t.event==="hello"&&this.rememberMatch(t.matchId),this.sendSignalEvent(t))}sendSignalEvent(e){return this.frameSupports("p2p")?this.send({gem:y,type:"gem.signalEvent",event:e.event,matchId:e.matchId,data:e.data}):false}relayDedicatedEvent(e){if(this.gameId===null)return false;let t=tt(e,this.gameId,r=>this.knowsMatch(r));return t===null?false:this.sendDedicatedEvent(t)}sendDedicatedEvent(e){return this.frameSupports("dedicated")?this.send({gem:y,type:"gem.dedicatedEvent",event:e.event,matchId:e.matchId,...e.sdp===void 0?{}:{sdp:e.sdp},...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.code===void 0?{}:{code:e.code},...e.message===void 0?{}:{message:e.message},...e.reason===void 0?{}:{reason:e.reason}}):false}knowsMatch(e){return this.knownMatches.has(e)||this.askedMatches.has(e)}rememberMatch(e){Un(this.knownMatches,e);}rememberAsked(e){Un(this.askedMatches,e);}answerPartyRequest(e,t){return this.send({gem:y,type:"gem.partyResult",requestId:e,...t===void 0?{}:{partyId:t}})}answerPurchase(e,t,r){return this.send({gem:y,type:"gem.purchaseResult",requestId:e,outcome:t,...r===void 0||t!=="ok"?{}:{purchaseId:r}})}answerDeviceSettingsPut(e,t){return this.send({gem:y,type:"gem.deviceSettings.result",requestId:e,outcome:t})}sendDeviceSettings(e){return this.frameSupports("deviceSettings")?this.send({gem:y,type:"gem.deviceSettings",...e===void 0?{}:{settings:e}}):false}answerAd(e,t){return this.send({gem:y,type:"gem.adResult",requestId:e,outcome:t})}answerSignIn(e,t){return this.send({gem:y,type:"gem.signInResult",requestId:e,outcome:t})}denyToken(e){this.send({gem:y,type:"gem.token.denied",requestId:e.requestId,retryable:e.retryable,reason:e.reason,correlationId:e.correlationId,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}});}grantLocalServer(e){return this.frameSupports("localHost")?this.send({gem:y,type:"gem.localServer",requestId:e.requestId,...e.serverId===void 0?{}:{serverId:e.serverId}}):false}denyLocalServer(e){return this.frameSupports("localHost")?this.send({gem:y,type:"gem.localServer.denied",requestId:e.requestId,retryable:e.retryable,reason:e.reason}):false}sendClusterTarget(e){return typeof e!="string"||e.trim().length===0||e.length>De?(this.fail("internal",`refusing to send '${String(e)}' as a cluster target \u2014 it must be a non-blank string of at most ${De} characters. Omit the message entirely when there is no answer: the frame then leaves the field out and gem-api chooses.`),false):this.frameSupports("clusterTarget")?this.send({gem:y,type:"gem.clusterTarget",clusterTargetId:e}):false}sendPlayer(e){this.send({gem:y,type:"gem.player",untrusted:{displayName:e.untrusted.displayName,displayHandle:e.untrusted.displayHandle},displayTag:e.displayTag,...e.avatarUrl===void 0?{}:{avatarUrl:e.avatarUrl}});}chainExpired(){return this.chainEndsAt!==null&&this.clock.now()/1e3>=this.chainEndsAt}localCorrelationId(){return `local-${++this.localDenials}`}sendPause(e){this.send({gem:y,type:"gem.pause",paused:e});}sendDevtools(e){this.send({gem:y,type:"gem.devtools",action:e});}requestScreenshot(e,t){return this.frameSupports("screenshot")?this.send({gem:y,type:"gem.screenshot",maxWidth:t.maxWidth,maxHeight:t.maxHeight},[e]):false}requestContext(){return this.frameSupports("feedbackContext")?this.send({gem:y,type:"gem.requestContext"}):false}sendPrefs(e){this.send({gem:y,type:"gem.prefs",...e});}sendCohorts(e){return this.frameSupports("cohorts")?this.send({gem:y,type:"gem.cohorts",cohorts:e.map(t=>({experimentId:t.experimentId,variantKey:t.variantKey}))}):false}sendViewport(e){return this.frameSupports("viewport")?this.send({gem:y,type:"gem.viewport",insets:{top:e.insets.top,right:e.insets.right,bottom:e.insets.bottom,left:e.insets.left}}):false}sendWillTerminate(e,t){this.send({gem:y,type:"gem.willTerminate",reason:e,graceMs:t});}close(){this.timeoutHandle!==null&&(this.clock.clearTimeout(this.timeoutHandle),this.timeoutHandle=null),this.reofferHandle!==null&&(this.clock.clearTimeout(this.reofferHandle),this.reofferHandle=null);for(let e of this.offered)e.port.onmessage=null,e.port.close();this.offered.length=0,this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="unsupported"&&this.transition("closed");}transition(e){this.state!==e&&(this.state=e,this.options.onStateChange?.(e));}fail(e,t){this.options.onError?.(e,t);}send(e,t){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let r=e.type;if(!this.outbound.allow(r))return this.fail("rate_limited",`parent exceeded its own limit for ${r}`),false;let i=se[r]?.(e);return i?(this.fail("internal",`refusing to send malformed ${r}: ${i}`),false):(t===void 0?this.port.postMessage({...e,v:this.version}):this.port.postMessage({...e,v:this.version},t),true)}receive(e,t){if(this.state==="closed"||this.state==="unsupported")return;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string"){this.refuseMalformed("invalid_message","message has no type");return}let i=se[r];if(!i){this.refuseMalformed("unsupported",`unknown message type ${JSON.stringify(r.slice(0,De))}`);return}if(!this.inbound.allow(r)){this.fail("rate_limited",`frame exceeded the limit for ${r}`);return}let o=ze(r);if(o!==void 0&&!this.options.capabilities?.includes(o)){this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this parent did not advertise`);return}let s=i(e);if(s){this.fail("invalid_message",`${r}: ${s}`);return}let a=e;r!=="gem.handshake.accept"&&!this.versionMatches(a,r)||this.dispatch(r,a,t);}refuseMalformed(e,t){if(!this.inbound.allow(fe)){this.options.onDropped?.(e,t);return}this.fail(e,t);}versionMatches(e,t){return e.v===this.version?true:(this.fail("invalid_message",`${t}: expected v ${String(this.version)}, got ${String(e.v)}`),false)}forwardSignal(e){let t=this.options.onSendSignal;if(t===void 0){this.fail("unsupported","this parent advertised `p2p` but wired no onSendSignal, so signaling has nowhere to go");return}if(this.gameId===null){this.options.onDropped?.("internal","gem.signal before any token was issued");return}if(e.signal!=="join"&&!this.knownMatches.has(e.matchId)){this.fail("unsupported",`gem.signal names match '${e.matchId}', which this player's socket has not mentioned`);return}if(!this.socketWindow.allow()){this.fail("rate_limited","signaling exceeded this parent per-second socket budget");return}let r=nt(e.signal,e.matchId,this.gameId,e.data);if("reason"in r){this.fail("invalid_message",`gem.signal: ${r.reason}`);return}this.withinFrameSize("gem.signal",r.frame,"Trickle ICE candidates rather than gathering them into the offer.")&&(this.rememberAsked(e.matchId),t(r.frame));}forwardDedicatedOffer(e){let t=this.options.onSendSignal;if(t===void 0){this.fail("unsupported","this parent advertised `dedicated` but wired no onSendSignal, so the offer has nowhere to go");return}if(this.gameId===null){this.options.onDropped?.("internal","gem.dedicatedOffer before any token was issued");return}if(!this.socketWindow.allow()){this.fail("rate_limited","signaling exceeded this parent per-second socket budget");return}let r=et(e.matchId,this.gameId,{sdp:e.sdp,intent:e.intent});if("reason"in r){this.fail("invalid_message",`gem.dedicatedOffer: ${r.reason}`);return}if(this.withinFrameSize("gem.dedicatedOffer",r.frame,"A complete gathered offer fits; one that does not is carrying media sections this path does not permit, or candidates from ICE servers this path does not use.")){this.rememberAsked(e.matchId);try{t(r.frame);}catch(i){this.sendDedicatedEvent({event:"error",matchId:e.matchId,code:"embedder_relay_unavailable",message:"the page could not put the offer on the player socket"}),this.fail("internal",`gem.dedicatedOffer: the socket refused the send: ${lo(i)}`);}}}withinFrameSize(e,t,r){let i=JSON.stringify(t).length;return i<=16384?true:(this.fail("invalid_message",`${e} builds a ${i}-byte socket frame, over the ${16384}-byte limit gem-api enforces, so the socket would drop it and then fail to establish. ${r}`),false)}dispatch(e,t,r){if(e==="gem.handshake.accept"){if(this.state!=="handshaking"){this.fail("handshake_duplicate","handshake already settled");return}let i=t.v;if(i<Z.min||i>Z.max){this.transition("unsupported"),this.fail("version_mismatch",`frame chose v${i}, outside our supported range`),this.close();return}this.adopt(r),this.version=i,this.peerCapabilities=t.capabilities??[],this.timeoutHandle!==null&&(this.clock.clearTimeout(this.timeoutHandle),this.timeoutHandle=null),this.reofferHandle!==null&&(this.clock.clearTimeout(this.reofferHandle),this.reofferHandle=null),this.transition("connected");return}if(this.state!=="connected"){this.fail("invalid_message",`${e} received before the handshake completed`);return}switch(e){case "gem.ready":this.options.onReady?.();break;case "gem.progress":this.options.onProgress?.(t);break;case "gem.requestToken":{let i=t;if(this.chainExpired()){this.denyToken({requestId:i.requestId,retryable:false,reason:"chain_exhausted",correlationId:this.localCorrelationId()});break}this.options.onRequestToken?.(i);break}case "gem.requestLocalServer":{this.options.onRequestLocalServer?.(t);break}case "gem.exit":this.options.onExit?.(t),this.close();break;case "gem.openExternal":this.options.onOpenExternal?.(t);break;case "gem.requestFullscreen":this.options.onRequestFullscreen?.(t);break;case "gem.audioState":this.options.onAudioState?.(t);break;case "gem.rewardCue":this.options.onRewardCue?.(t);break;case "gem.frameStats":this.options.onFrameStats?.(t);break;case "gem.screenshot.denied":this.options.onScreenshotDenied?.(t);break;case "gem.gameContext":this.options.onGameContext?.(t);break;case "gem.signal":this.forwardSignal(t);break;case "gem.dedicatedOffer":this.forwardDedicatedOffer(t);break;case "gem.partyRequest":{let i=t;if(this.options.onPartyRequest===void 0){this.answerPartyRequest(i.requestId);break}this.options.onPartyRequest(i);break}case "gem.requestPurchase":{let i=t;if(!this.frameSupports("purchases")){this.fail("unsupported_capability","refusing gem.requestPurchase: the frame did not advertise 'purchases', so it cannot receive gem.purchaseResult. Nothing was prompted and nothing was spent.");break}if(this.options.onRequestPurchase===void 0){this.answerPurchase(i.requestId,"unavailable");break}this.options.onRequestPurchase(i);break}case "gem.deviceSettings.put":{let i=t;if(!this.frameSupports("deviceSettings")){this.fail("unsupported_capability","refusing gem.deviceSettings.put: the frame did not advertise 'deviceSettings', so it cannot receive gem.deviceSettings.result. Nothing was stored.");break}if(this.options.onDeviceSettingsPut===void 0){this.answerDeviceSettingsPut(i.requestId,"unavailable");break}this.options.onDeviceSettingsPut(i);break}case "gem.requestAd":{let i=t;if(!this.frameSupports("ads")){this.fail("unsupported_capability","refusing gem.requestAd: the frame did not advertise 'ads', so it cannot receive gem.adResult. Nothing was rendered.");break}if(this.options.onRequestAd===void 0){this.answerAd(i.requestId,"no_ad");break}this.options.onRequestAd(i);break}case "gem.requestSignIn":{let i=t;if(!this.frameSupports("signIn")){this.fail("unsupported_capability","refusing gem.requestSignIn: the frame did not advertise 'signIn', so it cannot receive gem.signInResult. Nothing was rendered.");break}if(this.options.onRequestSignIn===void 0){this.answerSignIn(i.requestId,"unavailable");break}this.options.onRequestSignIn(i);break}case "gem.error":this.fail(t.code,t.message);break;default:this.fail("unsupported",`no parent handler for '${e}'`);}}};var H=class{#e;constructor(e){this.#e=e,Object.freeze(this);}toString(){return "[gem: use gem.text.toPlain()]"}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function le(n){return new H(n)}var mo={toPlain(n){return H.unwrap(n)},compare(n,e,t){let r=n instanceof H?H.unwrap(n):n,i=e instanceof H?H.unwrap(e):e,o;try{o=new Intl.Collator(t);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(n,e){let t=n instanceof H?H.unwrap(n):n,r=e instanceof H?H.unwrap(e):e;return t.normalize("NFC")===r.normalize("NFC")}};function U(n){if(typeof n!="string")return;let e=n.trim();return e.length===0?void 0:e}var po=2e3;function ho(n){let e,t=false,r=null;return {resolve(){if(e!==void 0)return Promise.resolve(e);if(t||!n.bridge.parentSupports("clusterTarget"))return Promise.resolve(void 0);if(r!==null)return r.promise;let i,o=new Promise(s=>{let a=false,d=null;i=l=>{a||(a=true,r=null,n.clock.clearTimeout(d),s(l));},d=n.clock.setTimeout(()=>{t=true,i(void 0);},n.timeoutMs??po);});return r={promise:o,settle:i},o},accept(i){let o=U(i);o!==void 0&&(e=o,r?.settle(o));}}}function Hn(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function Wn(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}var go=1e4,Ut=class{constructor(e){this.options=e;if(e.expectedSource===void 0||e.expectedSource===null)throw new Error("GemFrame: expectedSource is required and must not be null \u2014 pass window.parent. The handshake transfers the MessagePort, and origin alone does not say WHICH document on that origin sent it.");this.expectedSource=e.expectedSource,this.clock=e.clock??re,this.inbound=new te(this.clock),this.outbound=new te(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(a=>we(a,e.origin))||qn(e.origin,this.options.selfOrigin)))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=se["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!we(i.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${i.embedder}' but arrived from '${e.origin}'`),false;let o=e.ports?.[0];if(!o)return this.refuse(e,"handshake transferred no MessagePort"),false;let s=jt(Z,i.versions);return s===null?(o.onmessage=null,o.postMessage({gem:y,type:"gem.error",code:"version_mismatch",message:`frame supports v${Z.min}..v${Z.max}`}),o.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=o,this.version=s,o.onmessage=a=>this.receive(a.data,a.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],o.postMessage({gem:y,type:"gem.handshake.accept",v:s,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:y,type:"gem.ready"});}settled(e=go){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(t=>{let r=o=>{this.clock.clearTimeout(i),t(o);},i=this.clock.setTimeout(()=>{let o=this.settleWaiters.indexOf(r);o>=0&&this.settleWaiters.splice(o,1),t(this.state);},e);this.settleWaiters.push(r);})}progress(e,t){this.send({gem:y,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:y,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:y,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),true):false}exit(e){this.send(e===void 0?{gem:y,type:"gem.exit"}:{gem:y,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:y,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:y,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:y,type:"gem.audioState",muted:e}),true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let t={gem:y,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(t.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(t.origin={x:Hn(e.origin.x),y:Hn(e.origin.y)}),this.send(t),true}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:y,type:"gem.frameStats",fps:Wn(e.fps,1e3),frameTimeP95Ms:Wn(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:y,type:"gem.gameContext",context:e}),true)}signal(e,t,r){this.send({gem:y,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:y,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:y,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,i,o,s){return this.send({gem:y,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...s===void 0?{}:{catalogId:s}})}putDeviceSettings(e,t){return this.send({gem:y,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:y,type:"gem.requestAd",requestId:e,placement:t,format:r})}requestSignIn(e){return this.send({gem:y,type:"gem.requestSignIn",requestId:e})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let t of this.settleWaiters.splice(0))t(e);this.options.onStateChange?.(e);}}refuseMalformed(e,t){if(!this.inbound.allow(fe)){this.options.onDropped?.(e,t);return}this.fail(e,t);}dropUnknownType(e){this.inbound.allow(fe)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,t){e.ports?.[0]?.close?.(),this.inbound.allow(fe)&&this.options.onRefused?.(t);}fail(e,t){this.options.onError?.(e,t),this.state==="connected"&&this.port&&this.send({gem:y,type:"gem.error",code:e,...t===void 0?{}:{message:t}});}send(e){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let t=e.type;if(!this.outbound.allow(t))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${t}`),false;let r=se[t]?.(e);return r?(this.options.onError?.("internal",`refusing to send malformed ${t}: ${r}`),false):(this.port.postMessage(this.version===null?e:{...e,v:this.version}),true)}receive(e,t=[]){let r=false;try{r=this.dispatchInbound(e,t);}finally{r||Kn(t);}}dispatchInbound(e,t){if(this.state!=="connected")return false;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string")return this.refuseMalformed("invalid_message","message has no type"),false;let i=se[r];if(!i)return this.dropUnknownType(r),false;if(!this.inbound.allow(r))return this.fail("rate_limited",`parent exceeded the limit for ${r}`),false;let o=ze(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let s=i(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(a);break;case "gem.pause":this.options.onPause?.(a);break;case "gem.prefs":this.options.onPrefs?.(a);break;case "gem.cohorts":this.options.onCohorts?.(a);break;case "gem.viewport":this.options.onViewport?.(a);break;case "gem.willTerminate":this.options.onWillTerminate?.(a);break;case "gem.devtools":this.options.onDevtools?.(a.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let d=t[0];if(!d){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let l={maxWidth:a.maxWidth,maxHeight:a.maxHeight};if(!this.options.onScreenshot){d.close(),this.screenshotDenied("not_wired",false);break}return Kn(t.slice(1)),this.options.onScreenshot(l,d,(p,u)=>this.screenshotDenied(p,u)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer":this.options.onLocalServer?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{let d=a.untrusted;this.options.onPlayer?.({displayName:le(d.displayName),displayHandle:le(d.displayHandle),displayTag:a.displayTag,avatarUrl:a.avatarUrl});break}case "gem.roomEvent":this.options.onRoomEvent?.(a);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(a);break;case "gem.socketState":this.options.onSocketState?.(a);break;case "gem.signalEvent":this.options.onSignalEvent?.(a);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(a);break;case "gem.clusterTarget":this.options.onClusterTarget?.(a);break;case "gem.partyResult":this.options.onPartyResult?.(a);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(a);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(a);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(a);break;case "gem.adResult":this.options.onAdResult?.(a);break;case "gem.signInResult":this.options.onSignInResult?.(a);break;case "gem.error":this.options.onError?.(a.code,a.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,t){this.send({gem:y,type:"gem.screenshot.denied",reason:e,retryable:t});}};function Kn(n){for(let e of n)try{e?.close?.();}catch{}}var fo=16384;function yo(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e;try{e=JSON.stringify(n);}catch{return null}return typeof e!="string"?null:vo(e)}function vo(n){let e=0;for(let t=0;t<n.length;t+=1){let r=n.charCodeAt(t);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let i=n.charCodeAt(t+1);i>=56320&&i<=57343?(e+=4,t+=1):e+=3;}else e+=3;}return e}var Vn=["p2p","dedicated","unknown"],ot=["connection_setup_duration_seconds","reconnect_latency_seconds","datachannel_rtt_seconds","p2p_join_to_play_latency_seconds","ice_restart_outcome_total","connection_failures_total","transport_permanent_failures_total","transport_quality_score","host_migration_outcome_total","turn_relay_usage_ratio"];var ce=class{constructor(e){this.options=e;}options;async post(e,t){let r=this.options.gameId();if(r===null||r==="")return;let i=bo(e,this.options.transport,(this.options.now??Date.now)());i.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:i},t);}report(e){this.post(e).catch(()=>{});}};function bo(n,e,t){let r=Math.floor(t/1e3);return n.filter(i=>ot.includes(i.type)).slice(0,100).map(i=>{let o=wo(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function wo(n){if(n!==void 0)return Vn.includes(n)?n:"unknown"}function Ht(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}var W=class extends Error{constructor(t,r,i,o,s){super(`${t} (${r}): ${i}`);this.reason=t;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=s;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}};var So=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),c=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="DedicatedServerError",this.retryable=So.has(t),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var Bn=["explicit","stale_cleanup","game_room_closed","replaced","migration_failed","host_left","insufficient_players","all_left","expired","migration_rate_exceeded","game_room_gone","failed","idle","reclaimed"],Ro=new Set(Bn);function ke(n){return typeof n=="string"&&Ro.has(n)?n:"unknown"}var Ge="webrtc_dedicated",Kt=["universal","mobile","web"];var _o="p2p_unavailable",Jn=3e4,Xn=1e3,Yn=2e4;async function at(n){let e=U(n.clusterTargetId),t=n.clock??re,r=n.retry??{},i=r.budgetMs??Jn,o=r.maxDelayMs??Yn,s=r.initialDelayMs??Xn,a=t.now(),d=a+i,l=0;for(;;){l++;try{let p=await Bt(n.signal,"while allocating",()=>n.client.post(`${Zn(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!Eo(p)||i<=0)throw p;if(p.status===503&&p.code===_o)throw new c("p2p_unavailable",`room ${n.roomId} starts a peer-to-peer match, which allocates no server \u2014 so this refusal is not capacity and waiting cannot help: ${p.message}`,{cause:p});let u=Math.min(o,s*2**(l-1)),h=Math.min(o,(p.retryAfterSeconds??0)*1e3),f=Math.max(u/2,h)+Math.random()*(u/2);if(t.now()+f>d)throw xo(n,p,l,t.now()-a,i);if(r.onWaiting?.({attempt:l,elapsedMs:t.now()-a,budgetMs:i,nextAttemptInMs:f,status:p.status,message:p.message}),await lt(t,f,n.signal),n.signal?.aborted)throw Wt("while waiting to allocate")}}}function Eo(n){return n instanceof W?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function xo(n,e,t,r,i){let o=`${t} attempt${t===1?"":"s"} over ${r}ms of a ${i}ms budget`;return e.status===429?new c("start_rate_limited",`the platform was still limiting match starts for room ${n.roomId} after ${o}: ${e.message}`,{cause:e}):new c("no_server_ready",`the platform had no server ready for room ${n.roomId} after ${o}: ${e.message}`,{cause:e})}var To=12e4,Ao=1e3;async function st(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??Ao,i=n.timeoutMs??To,o=e.now()+i,s=zn(n),a={seen:n.knownToExist===true};for(;;){let d=await Qn(n,s,a);if(d.outcome!==null)return d.outcome;if(e.now()+r>o)throw new c("timeout",`match ${t} was still ${d.status} after ${i}ms`);await lt(e,r,n.signal);}}async function Vt(n){return (await Qn(n,zn(n),{seen:n.knownToExist===true})).outcome}function zn(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${Zn(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function Qn(n,e,t){let{matchId:r}=n,i=n.clock.now(),o;try{o=await Bt(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(s){if(s instanceof W&&s.reason==="not_found")return {status:"not_found",outcome:t.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(t.seen=true,o.status==="ready")return {status:"ready",outcome:Io(r,o,i)};if(o.status==="failed"){let s=o.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:ke(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function dt(n){let e=await Bt(n.signal,"while listing cluster targets",()=>n.client.get("/v1/ping/targets",n.signal)),t=[];for(let r of e.targets??[]){let i=r?.cluster_target_id;typeof i!="string"||i.length===0||t.push({id:i,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return t}async function Bt(n,e,t){if(n?.aborted)throw Wt(e);try{return await t()}catch(r){throw n?.aborted?Wt(e,r):r}}function Wt(n,e){return new c("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function Io(n,e,t){let r=e.join_credential,i=e.expires_in_seconds,o=typeof r=="string"&&typeof i=="number";return {status:"ready",matchId:n,protocol:e.protocol??"unknown",...o?{joinCredential:r,credentialExpiresAt:t+i*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function Zn(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function lt(n,e,t){return t?.aborted?Promise.resolve():new Promise(r=>{let i=()=>{n.clearTimeout(o),t?.removeEventListener("abort",i),r();},o=n.setTimeout(i,e);t?.addEventListener("abort",i);})}var Po=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),Xt="embedder_relay_unavailable",Co="embedder_no_relay",Mo=new Set([Xt]),Yt=new Set([Co]),ct=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new Jt(this)}handleEvent(e){let t=this.pending.get(e.matchId);if(t!==void 0){if(e.event==="matchEnded"){t.refuse(new c("match_ended",`the match ended while the offer was in flight (${e.reason??"no reason given"}), so no server is left to answer it`));return}if(e.event==="answer"){if(typeof e.sdp!="string"||e.sdp.length===0){t.refuse(new c("signaling_failed","the parent relayed an answer with no SDP in it"));return}t.settle({sdp:e.sdp});return}t.refuse(Lo(e.code,e.message));}}register(e,t){this.pending.get(e)?.refuse(new c("signaling_failed","a newer offer for this match superseded the one in flight")),this.pending.set(e,t);}release(e,t){this.pending.get(e)===t&&this.pending.delete(e);}transport(){let e=this.options.bridge;if(e===null)throw new c("signaling_unavailable","this game is not running inside a page that holds the player's notification socket, so there is nothing to carry an offer. Dedicated signaling needs that socket and only the page can hold one \u2014 see public-docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new c("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See public-docs/dedicated-server-flow.md \xA72.");return e}};function Lo(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new c(Oo(n),r,{platformCode:n})}function Oo(n){return n===void 0||Mo.has(n)?"signaling_failed":Yt.has(n)?"offer_refused":Po.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var Jt=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,t){if(this.closed)return Promise.reject(new c("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(i){return Promise.reject(i)}return t?.aborted?Promise.reject(new c("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let s=()=>{a(),o(new c("aborted","the caller aborted the signaling exchange"));},a=()=>{t?.removeEventListener("abort",s),this.hub.release(e.matchId,d),this.teardown===a&&(this.teardown=null);},d={settle:l=>{a(),i(l);},refuse:l=>{a(),o(l);}};this.teardown=a,t?.addEventListener("abort",s),this.hub.register(e.matchId,d);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(l){d.refuse(l instanceof c?l:new c("signaling_failed",l instanceof Error?l.message:String(l),{cause:l}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var er="match_ended:",tr="server_shutdown:",nr="kicked:",Do=123;function Go(n){if(typeof n!="string"||n.length===0||n.length>Do)return {kind:"other"};if(n.startsWith(er)){let e=ke(n.slice(er.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(tr)?{kind:"server_shutdown",cause:n.slice(tr.length)}:n.startsWith(nr)?{kind:"kicked",detail:n.slice(nr.length)}:{kind:"other"}}function zt(n,e,t){let r=Go(t),i=r.kind==="kicked"?"kicked":"link_closed";n.notifyMatchDisconnected(i).catch(()=>{}),r.kind==="match_ended"&&n.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}var jo="join",No="welcome",Fo="rejected",Qt=25e3,$o=1e3,Zt=1;function en(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var qo={credential_expired:"credential_expired",credential_reused:"credential_reused",credential_timeout:"timeout",join_rate_limited:"join_rate_limited",expected_join:"join_refused",invalid_credential:"join_refused",credential_not_for_this_channel:"join_refused"};function tn(n){let e=typeof n=="string"?n:"unknown";return new c(qo[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function je(n){let{channel:e,clock:t}=n;return new Promise((r,i)=>{let o=false,s=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??Qt),a=t.setTimeout(()=>A(new c("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(s,$o)),d=P=>{let O=P.data;if(typeof O!="string"){u(O);return}let M;try{M=JSON.parse(O);}catch{u(O);return}if(o){u(O);return}if(M.t===No){let m=en(M.heartbeat_interval);f({...typeof M.player_id=="string"?{playerId:M.player_id}:{},...typeof M.match_id=="string"?{matchId:M.match_id}:{},...m===void 0?{}:{heartbeatIntervalMs:m}});return}if(M.t===Fo){A(tn(M.reason));return}u(O);},l=()=>{A(new c("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},p=()=>{A(new c("aborted","the caller aborted during the join exchange"));},u=P=>{o&&n.onMessage?.(P);},h=()=>{t.clearTimeout(a),e.removeEventListener("close",l),n.signal?.removeEventListener("abort",p);},g=()=>{e.removeEventListener("message",d);},f=P=>{o=true,h(),n.onMessage===void 0&&g(),r({welcome:P,detach:g});},A=P=>{o||(o=true,h(),g(),i(P));};if(e.addEventListener("message",d),e.addEventListener("close",l),n.signal?.aborted){p();return}n.signal?.addEventListener("abort",p);try{e.send(JSON.stringify({t:jo,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:Zt}:{}}));}catch(P){A(new c("connection_failed",`the join frame could not be sent on the open channel: ${String(P)}`,{cause:P}));}})}function ut(){return {exchange(){return Promise.reject(new c("signaling_unavailable","no signaling channel is wired. The exchange rides the notification WebSocket, and POST /v1/ws/ticket accepts only account credentials \u2014 a game frame holds a game-scoped token and cannot mint one \u2014 so it has to be relayed by the page embedding this game. Run inside a parent that advertises `dedicated`, or pass your own `signaling` implementation. See public-docs/dedicated-server-flow.md \xA72."))},close(){}}}var ue=1,Ne=2,nn=4,an=8,Uo=2,Ho=1e3,sn="heartbeat timeout",mt="gem-uu",pt=2,ir="gem_transports";function Fe(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!Wo(r)||e.includes(r)||e.push(r);}return e}function Wo(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function ht(n,e){if(typeof n!="object"||n===null)return null;let t=n[ir];if(typeof t!="object"||t===null)return null;let r=t;return typeof r.v!="number"||r.v<1||typeof r.host!="string"||typeof r.port!="number"||e!==void 0&&r.match_id!==e?null:r}function gt(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var or=new TextEncoder,ar=new TextDecoder;function dn(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function ln(n){let e=0;return n?.reliable===false&&(e|=ue),n?.ordered===false&&(e|=Ne),e}function cn(n){return {reliable:(n&ue)===0,ordered:(n&Ne)===0}}var un={reliable:true,ordered:true};function sr(n){return JSON.stringify({t:"join",credential:n,wire:pt,heartbeat:Zt})}function dr(n){let e;try{e=JSON.parse(n);}catch{throw new c("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let t=en(e.heartbeat_interval);return {...e.player_id===void 0?{}:{playerId:e.player_id},...e.match_id===void 0?{}:{matchId:e.match_id},...t===void 0?{}:{heartbeatIntervalMs:t}}}throw e.t==="rejected"?tn(e.reason):new c("join_refused","the server answered the join out of protocol")}function mn(){return typeof globalThis.WebTransport=="function"&&pn===null}function ft(){return pn}var pn=null;var rr="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Ko(n){let e=Ht(n);if(e.byteLength!==32)throw new c("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var rn=class{buffered=new Uint8Array(0);push(e){let t=new Uint8Array(this.buffered.byteLength+e.byteLength);t.set(this.buffered,0),t.set(e,this.buffered.byteLength),this.buffered=t;let r=[];for(;!(this.buffered.byteLength<4);){let o=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(o===0||o>1<<20)throw new c("connection_failed",`a control-stream record claims ${o} bytes`);if(this.buffered.byteLength<4+o)break;let s=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:s[0]??0,payload:s.slice(1)});}return r}};function on(n,e){let t=new Uint8Array(5+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength+1,true),t[4]=n,t.set(e,5),t}async function $e(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webTransport;if(t===void 0){let a=globalThis.WebTransport;if(a===void 0)throw new c("connection_failed","this environment has no WebTransport");t=n.certHashBase64===void 0?new a(n.url):new a(n.url,{serverCertificateHashes:[{algorithm:"sha-256",value:Ko(n.certHashBase64)}]});}let r=t,i=a=>{try{r.close();}catch{}throw a},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(pn=rr,i(new c("connection_failed",`${rr}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,d)=>{setTimeout(()=>d(new c("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,s]);let a=r.incomingBidirectionalStreams.getReader(),d=await Promise.race([a.read(),s]);if(a.releaseLock(),d.done||d.value===void 0)return i(new c("connection_failed","the session ended before the control stream arrived"));let l=d.value,p=l.writable.getWriter();await p.write(on(nn,or.encode(sr(n.credential))));let u=new rn,h=l.readable.getReader(),g;for(;g===void 0;){let f=await Promise.race([h.read(),s]);if(f.done||f.value===void 0)return i(new c("connection_failed","the control stream closed before the join was answered"));for(let A of u.push(f.value)){g=dr(ar.decode(A.payload));break}}return {link:Vo(r,p,h,u,n.log??(f=>console.warn(f)),cr(g,n.clock)),welcome:g}}catch(a){return i(a)}}function Vo(n,e,t,r,i,o){let s,a,d=false,l=f=>{if(!d){d=true,p.stop();try{n.close();}catch{}a?.(f);}},p=gn(o,()=>l(sn)),u=(f,A)=>{p.heard(),(f&an)===0&&s!==void 0&&((f&nn)!==0?s(ar.decode(A),un):s(A,cn(f)));};(async()=>{try{for(;;){let f=await t.read();if(f.done||f.value===void 0)break;for(let A of r.push(f.value))u(A.flags,A.payload);}}catch{}l("stream closed");})();let h,g;try{let f=n.datagrams;if(f?.readable!==void 0&&f.writable!==void 0){let A=f.readable.getReader();g=f.writable.getWriter(),h=f,(async()=>{try{for(;;){let P=await A.read();if(P.done||P.value===void 0)break;let O=P.value;O.byteLength!==0&&u((O[0]??0)|ue|Ne,O.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(f){h=void 0,g=void 0,i(`[gem] webtransport datagram lane unusable (${gt(f)}); unreliable sends ride the stream`);}return n.closed.then(f=>l(lr(f?.reason)??"session closed"),()=>l("session failed")),{transport:"webtransport",send(f,A){if(d)return;if(typeof f=="string"){e.write(on(nn,or.encode(f))).catch(()=>l("write failed"));return}let P=ln(A);if((P&ue)!==0&&g!==void 0){let O=dn(P,f),M=h?.maxDatagramSize;if(M===void 0||O.byteLength<=M){g.write(O).catch(()=>{});return}}e.write(on(P,f)).catch(()=>l("write failed"));},onMessage(f){s=f;},onClose(f){a=f;},close(){l("closed");}}}function hn(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webSocket;if(t===void 0){let i=globalThis.WebSocket;if(i===void 0)return Promise.reject(new c("connection_failed","this environment has no WebSocket"));t=new i(n.url);}let r=t;return r.binaryType="arraybuffer",new Promise((i,o)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),o(new c("timeout","websocket did not come up in time")));},e),d=g=>{s||(s=true,clearTimeout(a),r.close(),o(g));},l=()=>{r.send(sr(n.credential));},p=g=>{if(s)return;if(typeof g.data!="string"){d(new c("join_refused","the server sent binary before answering the join"));return}let f;try{f=dr(g.data);}catch(A){d(A);return}s=true,clearTimeout(a),r.removeEventListener("open",l),r.removeEventListener("message",p),r.removeEventListener("close",u),r.removeEventListener("error",h),i({link:Bo(r,cr(f,n.clock)),welcome:f});},u=()=>{d(new c("connection_failed","the websocket closed before the join was answered"));},h=()=>{d(new c("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",l),r.addEventListener("message",p),r.addEventListener("close",u),r.addEventListener("error",h),r.readyState===1&&l();})}function lr(n){return typeof n=="string"&&n.length>0?n:void 0}function cr(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function gn(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,Ho)*Uo,i=t.now(),o=null,s=()=>{o=null;let a=t.now()-i;if(a>=r){e();return}o=t.setTimeout(s,r-a);};return o=t.setTimeout(s,r),{heard:()=>{i=t.now();},stop:()=>{o!==null&&(t.clearTimeout(o),o=null);}}}function Bo(n,e){let t,r,i=false,o=a=>{if(!i){i=true,s.stop();try{n.close();}catch{}r?.(a);}},s=gn(e,()=>o(sn));return n.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){t?.(a.data,un);return}let d=new Uint8Array(a.data);if(d.byteLength===0)return;let l=d[0]??0;(l&an)===0&&t?.(d.slice(1),cn(l));})),n.addEventListener("close",(a=>o(lr(a?.reason)??"socket closed"))),{transport:"websocket",send(a,d){if(!i){if(typeof a=="string"){n.send(a);return}n.send(dn(ln(d),a));}},onMessage(a){t=a;},onClose(a){r=a;},close(){o("closed");}}}function fn(n,e,t,r){let i,o,s=false,a=t,d=u=>{if(!s){s=true,l.stop();try{n.close();}catch{}try{e.close();}catch{}o?.(u);}},l=gn(r,()=>d(sn)),p=(u,h)=>{if(l.heard(),typeof u=="string"){i?.(u,un);return}let g=new Uint8Array(u);if(g.byteLength===0)return;let f=g[0]??0;(f&an)===0&&i?.(g.slice(1),cn(f|h));};if(n.addEventListener("message",(u=>p(u.data,0))),n.addEventListener("close",(()=>d("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let u=e.connectionState;(u==="failed"||u==="closed")&&d(`connection ${u}`);})),a!==void 0){let u=a;u.addEventListener("message",(h=>p(h.data,ue|Ne))),u.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(u,h){if(s)return;if(typeof u=="string"){n.send(u);return}let g=ln(h),f=dn(g,u);if((g&ue)!==0&&a!==void 0&&a.readyState==="open"){a.send(f);return}n.send(f);},onMessage(u){i=u;},onClose(u){o=u;},close(){d("closed");}}}var ur=10240,mr=2048,Jo=new TextEncoder;function pr(n){return Jo.encode(n).length}function ie(n,e){let t=i=>{throw new c("invalid_sdp",`the ${e} ${i}`)},r=pr(n);r>=ur&&t(`is ${r} bytes, over the ${ur} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),n.startsWith("v=")||t("does not start with 'v=', so it is not SDP"),n.includes("\0")&&t("contains a null byte"),/\r(?!\n)/.test(n)&&t("contains a bare carriage return");for(let i of n.split(/\r\n|\n/)){let o=pr(i);o>mr&&t(`has a ${o}-byte line, over the ${mr} limit`);}}function yt(n){for(let e of n.split(/\r\n|\n/)){if(!e.startsWith("m="))continue;let[t,r="0"]=e.slice(2).trim().split(/\s+/);if(!(t!=="audio"&&t!=="video")&&r.split("/")[0]!=="0")return true}return false}var Xo=3e3,Yo=1e4,zo=15e3;async function qe(n){let e=n.peerConnection;try{gr(n,"before the handshake started"),yn(n);let t=e.createDataChannel(n.channelLabel??"gem",{ordered:!0});for(let s of n.extraChannels??[]){let a=e.createDataChannel(s.label,{...s.ordered===void 0?{}:{ordered:s.ordered},...s.maxRetransmits===void 0?{}:{maxRetransmits:s.maxRetransmits}});n.onExtraChannel?.(s.label,a);}let r=await e.createOffer();await e.setLocalDescription(r),await ea(e,n),yn(n);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new c("invalid_sdp","the offer carried no SDP");ie(i,"offer"),hr(i,"offer");let o=await Zo(n,i);if(yn(n),typeof o?.sdp!="string")throw new c("invalid_sdp","the signaling channel answered without an SDP");return ie(o.sdp,"answer"),hr(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await ta(t,n),gr(n,"before the channel opened"),t}catch(t){throw e.close(),Qo(t)}}function Qo(n){return n instanceof c?n:vr(n)?me():new c("connection_failed",br(n),{cause:n})}function hr(n,e){if(yt(n))throw new c("media_refused",`the ${e} carries an active audio or video section. This path carries a data channel only; voice belongs to the platform voice service.`)}async function Zo(n,e){let t=n.exchangeTimeoutMs??Yo,r=yr(n,t),i=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(o=>{throw o instanceof c?o:vr(o)?me():new c("signaling_failed",br(o),{cause:o})});return na(i,n,r,()=>r.exhausted?vn("while the offer was in flight"):new c("timeout",`no answer arrived within ${t}ms`))}function ea(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let i=()=>{t.clearTimeout(s),n.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{n.iceGatheringState==="complete"&&i();},s=t.setTimeout(i,e.gatherTimeoutMs??Xo);n.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function ta(n,e){if(e.signal?.aborted)return Promise.reject(me());if(n.readyState==="open")return Promise.resolve();if(n.readyState!=="connecting")return Promise.reject(new c("connection_failed",`the data channel was already '${n.readyState}' when the answer was applied`));let{clock:t}=e,r=e.openTimeoutMs??zo,i=yr(e,r);return new Promise((o,s)=>{let a=()=>{t.clearTimeout(h),n.removeEventListener("open",d),n.removeEventListener("close",l),n.removeEventListener("error",l),e.signal?.removeEventListener("abort",p);},d=()=>{a(),o();},l=g=>{a(),s(new c("connection_failed","the data channel failed before it opened",fr(g)===void 0?void 0:{cause:fr(g)}));},p=()=>{a(),s(me());},u=()=>{a(),s(i.exhausted?vn("while the channel was still opening"):new c("timeout",`the data channel did not open within ${r}ms`));},h=t.setTimeout(u,i.ms);n.addEventListener("open",d),n.addEventListener("close",l),n.addEventListener("error",l),e.signal?.addEventListener("abort",p);})}function yr(n,e){if(n.credentialExpiresAt===void 0)return {ms:e,exhausted:false};let t=n.credentialExpiresAt-n.clock.now();return t<=e?{ms:Math.max(0,t),exhausted:true}:{ms:e,exhausted:false}}function na(n,e,t,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(me()):new Promise((s,a)=>{let d=u=>{i.clearTimeout(p),o?.removeEventListener("abort",l),u();},l=()=>d(()=>a(me())),p=i.setTimeout(()=>d(()=>a(r())),t.ms);o?.addEventListener("abort",l),n.then(u=>d(()=>s(u)),u=>d(()=>a(u)));})}function gr(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw vn(`already ${e}`)}function vn(n){return new c("credential_expired",`the join credential ran out ${n} \u2014 poll match status again for a fresh one`)}function yn(n){if(n.signal?.aborted)throw me()}function me(){return new c("aborted","the caller aborted the connection attempt")}function vr(n){return n?.name==="AbortError"}function fr(n){return n?.error}function br(n){return n instanceof Error?n.message:String(n)}var Ue="0.1.0-beta",wr="0-beta",Se="web",ra=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;function ia(n){let e=ra.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function kr(n,e){let t=oa(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:Ue};let i=ia(r);if(i===null)throw new c("misconfigured",`${e} refused: engineVersion '${r}' is not semver, so no engine line can be derived from it and gem-api answers 400. Omit it \u2014 a browser game has no engine version of its own, and the SDK reports '${Ue}' for it.`);if(i!==wr)throw new c("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${wr}' is the only line a web dedicated-server fleet runs. gem-api uses the line \u2014 the semver major plus any prerelease tag \u2014 verbatim as the fleet's label selector, so a match on '${i}' would match nothing and be reported as a capacity shortfall rather than as this. Omit engineVersion: a browser game has no engine version of its own, and the SDK reports '${Ue}' for it.`);return {...n,platform:t,engineVersion:r}}function oa(n,e){if(n===void 0||n===Se)return Se;if(!Kt.includes(n))throw new c("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${Kt.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${Se}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${Se}' and is deprecated \u2014 remove the field. A browser game publishes its bundle in the web package dimension, so a client reporting anything else is version-checked against a dimension it has nothing in, and every blacklist, release and expiry check passes without looking at this build.`),Se}function aa(n){let{client:e,clock:t,rooms:r}=n,i=n.signaling??ut,o=n.log??(m=>console.warn(m)),s=new ce({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,d=(m,b)=>{let S=a.get(m)??new Set;S.add(b),a.set(m,S);},l=(m,b)=>{let S=a.get(m);S!==void 0&&(S.delete(b),S.size===0&&a.delete(m));},p=async m=>{if(r.isHost&&!ga(r)&&r.currentRoom?.matchId===void 0){let b=U(m.clusterTargetId);await r.startMatch({...b===void 0?{}:{clusterTargetId:b},...m.retry===void 0?{}:{retry:m.retry},...m.signal===void 0?{}:{signal:m.signal}});}return Tr(r.matchConnectionState==="suspended"?await r.reconnectToMatch(bn(m)):await r.awaitMatch(bn(m)))},u=async m=>Tr(await r.pollMatchStatus(bn(m))),h=async(m,b)=>{let S=false;try{let w=await p(m),D=r.currentRoom?.transports;if(D!==void 0&&!D.includes("webrtc"))throw new c("misconfigured",`the room template offers (${D.join(", ")||"no transports"}), not webrtc, which is all this path dials. Connect through gem.match.connect(), or pass \`transports: []\` here to negotiate across the template's list.`);let I=m.peerConnection??Ar();S=!0;let G=await qe({peerConnection:I,signaling:b,clock:t,matchId:w.matchId,credentialExpiresAt:w.credentialExpiresAt,...vt(m,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),F=null;if(m.presentCredential!==!1)try{F=await je({channel:G,clock:t,credential:w.joinCredential,credentialExpiresAt:w.credentialExpiresAt,...vt(m,"onMessage","signal"),...m.welcomeTimeoutMs===void 0?{}:{ceilingMs:m.welcomeTimeoutMs}});}catch($){throw B(G),B(I),$}return ha(r,w,G,I,b,m.reportDisconnect!==!1,m.reportConnected!==!1,F,{remember:d,forget:l},m.onMatchEnded)}catch(w){throw S&&xr(s,w),B(b),w}},g=async(m,b,S,w,D,I)=>{if(m==="webtransport"){let C=w?.webtransport;if(C===void 0)throw new c("misconfigured","webtransport is not advertised");let Y={credential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,clock:t};if(typeof C.named_url=="string"&&C.named_url!==""){let ne=Math.max(Math.floor(I/2),1e3);try{return await $e({url:C.named_url,timeoutMs:ne,log:o,...Y})}catch(oe){if(ft()!==null)throw oe;return o(`[gem] webtransport named dial failed (${gt(oe)}); retrying the pinned dial`),$e({url:C.url,certHashBase64:C.cert_sha256_b64,timeoutMs:ne,log:o,...Y})}}return $e({url:C.url,certHashBase64:C.cert_sha256_b64,timeoutMs:I,...Y})}if(m==="websocket"){let C=w?.websocket;if(C===void 0)throw new c("misconfigured","websocket is not advertised");return hn({url:C.url,credential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,clock:t,timeoutMs:I})}let G=b.peerConnection??Ar(),F,$=await qe({peerConnection:G,signaling:D,clock:t,matchId:S.matchId,credentialExpiresAt:S.credentialExpiresAt,extraChannels:[{label:mt,ordered:false,maxRetransmits:0}],onExtraChannel:(C,Y)=>{C===mt&&(F=Y);},...vt(b,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...b.exchangeTimeoutMs===void 0&&b.redial===true?{exchangeTimeoutMs:da}:{}}),V;try{V=await je({channel:$,clock:t,credential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,wire:pt,heartbeat:!0,...vt(b,"signal"),...b.welcomeTimeoutMs===void 0?{}:{ceilingMs:b.welcomeTimeoutMs}});}catch(C){throw B($),B(G),C}let E=V.welcome.heartbeatIntervalMs;return {link:fn($,G,F,E===void 0?void 0:{clock:t,intervalMs:E}),welcome:V.welcome,channel:$,peerConnection:G}},f=(m,b,S,w,D)=>{let I=false,G;w.link.onClose(E=>{!I&&m.reportDisconnect!==false&&zt(r,b.matchId,E),G?.(E);}),m.reportDisconnect!==false&&m.reportConnected!==false&&r.notifyMatchConnected(b.matchId);let F={transport:w.link.transport,send:(E,C)=>w.link.send(E,C),onMessage:E=>w.link.onMessage(E),onClose:E=>{G=E;},close:()=>w.link.close()},$=()=>{I||(I=true,B(w.link),B(D));},V=E=>{if(!I){try{m.onMatchEnded?.(E);}catch{}$();}};return d(b.matchId,V),{matchId:b.matchId,transport:S,link:F,joinCredential:b.joinCredential,credentialExpiresAt:b.credentialExpiresAt,welcome:w.welcome,...w.channel===void 0?{}:{channel:w.channel},...w.peerConnection===void 0?{}:{peerConnection:w.peerConnection},close(){l(b.matchId,V),$();}}},A=async(m,b)=>{let S=r.currentRoom?.id,w=r.gameId,D=()=>({advert:ht(r.currentRoom?.settings,m),template:r.currentRoom?.transports??null});if(S===void 0||w===null)return D();try{let I=await e.get(`/v2/games/${encodeURIComponent(w)}/game-rooms/${encodeURIComponent(S)}`,b);return {advert:ht(I.settings,m),template:Fe(I.transports)??r.currentRoom?.transports??null}}catch{return D()}},P=(m,b)=>{let S=m??Sr;return b.length===0?S:S.filter(w=>b.includes(w))},O=async(m,b,S)=>{try{let w=await p(m),{advert:D,template:I}=await A(w.matchId,m.signal),G=P(I,b),F=G.filter(j=>ua(j,D)),$=ft();if($!==null&&G.includes("webtransport")&&D?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${$} (learned on an earlier dial in this page)`),F.length===0){let j=I===null?`the default order (${Sr.join(", ")})`:`the room template's transports (${I.join(", ")||"none"})`;throw new c("misconfigured",`none of ${j}`+(b.length>0?`, narrowed to (${b.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let V=m.transportAttemptTimeoutMs??sa,E=()=>m.deadlineAt===void 0?1/0:m.deadlineAt-t.now(),C=j=>n.signalingReady===void 0||j<=0?Promise.resolve(!0):n.signalingReady(j),Y=[],ne=[];for(let j of F){if(E()<_r){o(`[gem] ${j} rung not tried: the reconnect budget is spent`);break}ne.length>0&&w.credentialExpiresAt-t.now()<Er&&(w=await u(m)),ne.push(j);let Mn=!1,Ln=!1,Je={attempts:0,waitedMs:0};for(;;){if(j==="webrtc"&&m.redial===!0){let Q=Math.min(Rr,E());await C(Q)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(Q)}ms; offering anyway`);}let Yr=Math.max(Math.min(V,E()),_r);try{return f(m,w,j,await g(j,m,w,D,S,Yr),S)}catch(Q){let q=Q instanceof c?Q:new c("connection_failed",Q instanceof Error?Q.message:String(Q),{cause:Q});if(j==="webrtc"&&xr(s,q),(q.reason==="credential_expired"||q.reason==="credential_reused")&&!Mn){Mn=!0,w=await u(m);continue}if(j==="webrtc"&&q.reason==="signaling_failed"&&q.platformCode===Xt&&!Ln){Ln=!0;let ae=Math.min(Rr,E());if(o(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(ae)}ms for the socket before offering again`),await C(ae))continue}if(q.reason==="join_rate_limited"){let ae=ca(Je,Math.random,E());if(ae!==null){if(Je.attempts+=1,Je.waitedMs+=ae,o(`[gem] ${j} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ae)}ms before presenting again (retry ${Je.attempts} of ${Pr.maxAttempts})`),await lt(t,ae,m.signal),m.signal?.aborted)throw new c("aborted","the caller aborted while waiting out a join rate limit");w.credentialExpiresAt-t.now()<Er&&(w=await u(m));continue}}if(la.has(q.reason)||q.reason==="credential_expired"||j==="webrtc"&&Ir(q)){o(`[gem] ${j} rung failed (${q.reason}): ${gt(q.cause??q)} \u2014 `+(ne.length<F.length?`falling through to ${F[ne.length]}`:"no rungs left")),Y.push(q);break}throw o(`[gem] ${j} rung refused the session (${q.reason}): ${q.message}`),q}}}let oe=Y[Y.length-1];throw oe===void 0?new c("timeout",`the reconnect budget ran out before any transport (${F.join(", ")}) could be tried`):new c(oe.reason,`every transport tried (${ne.join(", ")}) failed; the last said: ${oe.message}`,{cause:Y,platformCode:oe.platformCode})}catch(w){throw B(S),w}};return {listClusterTargets:async(m={})=>dt({client:e,...m}),handleMatchEnded(m,b){let S=a.get(m);if(S!==void 0){a.delete(m);for(let w of S)w(b);}},connect:(async(m={})=>{let b=m.signaling??i();return m.transports===void 0?h(m,b):O(m,m.transports,b)})}}var Sr=["webtransport","webrtc","websocket"],sa=1e4,da=5e3,Rr=3e3,_r=1e3,Er=1e4,la=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Ir(n){return n.platformCode!==void 0&&Yt.has(n.platformCode)}var Pr={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function ca(n,e=Math.random,t=1/0){let r=Pr;if(n.attempts>=r.maxAttempts)return null;let i=Math.min(r.budgetMs-n.waitedMs,t);if(i<r.initialDelayMs)return null;let o=r.initialDelayMs*r.factor**n.attempts;return Math.min(o+e()*r.jitterMs,i)}function ua(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&mn():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||ma(e.websocket.url)}function ma(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return it(e)}function bn(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var pa=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function xr(n,e){e instanceof c&&(!pa.has(e.reason)&&!Ir(e)||n.report([{type:"connection_failures_total",value:1}]));}function ha(n,e,t,r,i,o,s,a,d,l){let p=false,u=()=>{p||zt(n,e.matchId,void 0);};o&&(t.addEventListener("close",u),s&&n.notifyMatchConnected(e.matchId));let h=()=>{p||(p=true,t.removeEventListener("close",u),a?.detach(),B(t),B(r),B(i));},g=f=>{if(!p){try{l?.(f);}catch{}h();}};return d.remember(e.matchId,g),{matchId:e.matchId,channel:t,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){d.forget(e.matchId,g),h();}}}function ga(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function Tr(n){if(n.status==="failed")throw new c("allocation_failed",`match ${n.matchId} did not come up: ${n.reason}`);if(n.status==="ended")throw new c("match_ended",`match ${n.matchId} ended (${n.reason}) before this side connected.`);if(n.protocol!==Ge)throw new c("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${Ge}' is reachable from a frame; host and port on this response are advisory and must not be dialled.`);let{joinCredential:e,credentialExpiresAt:t}=n;if(e===void 0||t===void 0)throw new c("connection_failed",`match ${n.matchId} is ready but issued no join credential, so the server would refuse the channel once it opened \u2014 poll match status again.`);return {...n,joinCredential:e,credentialExpiresAt:t}}function Ar(){let n=globalThis.RTCPeerConnection;if(!n)throw new c("misconfigured","this environment has no RTCPeerConnection. Pass `peerConnection` to connect against a stand-in, which is how the flow is tested outside a browser.");return new n({iceServers:[]})}function B(n){try{n.close();}catch{}}function vt(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var Re=class{constructor(e){this.options=e;this.reporter=new ce({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,t,r){let i=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:t},r);return {credential:bt(i.credential)??"",hostFingerprint:bt(i.host_fingerprint)??"",hostEpoch:wt(i.host_epoch)??0,expiresAt:(wt(i.expires_at)??0)*1e3}}async turnLease(e,t,r){let i=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:t},r),o=[];for(let d of Array.isArray(i.ice_servers)?i.ice_servers:[]){let l=d,p=(Array.isArray(l.urls)?l.urls:[]).filter(u=>typeof u=="string"&&u.length>0);p.length!==0&&o.push({urls:p,username:bt(l.username)??"",credential:bt(l.credential)??""});}let s=wt(i.expires_at),a=wt(i.ttl_seconds);return {iceServers:o,expiresAt:s!==void 0?s*1e3:Date.now()+(a??0)*1e3}}async kick(e,t,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:t},r);}async leave(e,t=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:t});}async telemetry(e,t){await this.reporter.post(e,t);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function bt(n){return typeof n=="string"&&n.length>0?n:void 0}function wt(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var fa=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),k=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="P2pError",this.retryable=fa.has(t);}reason;retryable};var kt=class{listeners=new Map;on(e,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>this.off(e,t)}off(e,t){this.listeners.get(e)?.delete(t);}once(e,t){let r=this.on(e,((...i)=>{r(),t(...i);}));return r}emit(e,...t){let r=this.listeners.get(e);if(r)for(let i of [...r])i(...t);}clear(){this.listeners.clear();}};var ya=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function pe(n){let e=null;for(let t of n.split(/\r\n|\n/)){if(!t.startsWith("a=fingerprint:"))continue;let r=He(t.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function He(n){let[e,...t]=n.trim().split(/\s+/);if(e===void 0||t.length===0)return null;let r=`${e.toLowerCase()} ${t.join("").toUpperCase()}`;return ya.test(r)?r:null}function _e(n,e){if(n.length!==e.length)return false;let t=0;for(let r=0;r<n.length;r++)t|=n.charCodeAt(r)^e.charCodeAt(r);return t===0}var wn=5e3,va=12e4+wn,ba=1024,wa=6e4,ka=1e4,Cr=64*1024,Mr=5;function St(n){let e=new Map,t=-1/0,r=null,i=(()=>{let a;try{a=new URL(`${n.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return a.username!==""||a.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:a.href,shown:`${a.protocol}//${a.host}`}})(),o=()=>{let a=n.subtle??globalThis.crypto?.subtle;if(!a)throw new k("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return a},s=async()=>{if(!i.ok)throw new k("keys_unavailable",i.reason);let a=n.fetch??((h,g)=>globalThis.fetch(h,g)),d;try{d=await a(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(ka)});}catch{throw new k("keys_unavailable",`the JWKS endpoint at ${i.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!d.ok)throw new k("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let l;try{let h=await d.text();if(h.length>Cr)throw new k("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${Cr} characters, which is not a key set this platform publishes.`);l=JSON.parse(h);}catch(h){throw h instanceof k?h:new k("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let p=Array.isArray(l.keys)?l.keys:[];if(p.length>Mr)throw new k("keys_unavailable",`the JWKS endpoint published ${p.length} keys, over the ${Mr} the platform declares. Refusing rather than verifying against a set of unknown size.`);let u=o();for(let h of p){let g=h;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.kid.length===0))try{let f=await u.importKey("jwk",{...h,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,f);}catch{}}};return {async key(a){let d=e.get(a);if(d)return d;if(!i.ok)throw new k("keys_unavailable",i.reason);if(r)return await r,e.get(a)??null;let l=n.now();if(!Number.isFinite(l))throw new k("keys_unavailable","the clock supplied to the SDK returned a non-finite time, so the JWKS throttle cannot be evaluated. This is a configuration fault, not a server failure.");return l<t&&(t=-1/0),l-t<wa?null:(t=l,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var We=class{seen=new Map;admit(e,t){for(let[r,i]of this.seen)i<=t&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=ba){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+va),true}};function Or(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return r}function Lr(n){try{let e=new TextDecoder().decode(Or(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function Rt(n,e,t,r,i){let o=E=>{throw new k("peer_unauthenticated",`the peer's join credential is not usable: ${E}`)},s=n.split(".");s.length!==3&&o("it is not a three-part JWT");let[a,d,l]=s,p=Lr(a);p===null&&o("its header does not decode"),p.alg!=="RS256"&&o(`its alg is ${JSON.stringify(p.alg)}, not RS256`),p.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(p.typ)}, not p2p+jwt`);let u=p.kid;(typeof u!="string"||u.length===0)&&o("it names no key");let h=await t.key(u);h===null&&o("it was signed by a key this build cannot resolve");let g=i.subtle??globalThis.crypto?.subtle;g||o("this environment has no WebCrypto");let f=new TextEncoder().encode(`${a}.${d}`),A;try{A=Or(l);}catch{o("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},h,A,f)||o("its signature does not verify");let O=Lr(d);O===null&&o("its payload does not decode");let M=O,m=E=>typeof M[E]=="string"?M[E]:"",b=E=>typeof M[E]=="number"&&Number.isFinite(M[E])?M[E]:NaN;m("iss")!==i.issuer&&o("it was issued by someone else"),m("aud")!==`${i.issuer}/p2p-match`&&o("its audience is not this platform"),m("match_id")!==e.matchId&&o("it is for another match"),m("game_id")!==e.gameId&&o("it is for another game");let S=b("exp")*1e3,w=b("nbf")*1e3;(!Number.isFinite(S)||e.now>S+wn)&&o("it has expired"),Number.isFinite(w)&&e.now<w-wn&&o("it is not valid yet");let D=m("role");D!=="host"&&D!=="client"&&o("it names no usable role");let I=b("host_epoch");I!==e.hostEpoch&&o("it names a different host epoch");let G=He(m("fingerprint"));G===null&&o("its fingerprint claim is malformed"),_e(G,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let F=He(m("host_fingerprint"));F===null&&o("its host fingerprint claim is malformed"),_e(F,e.hostFingerprint)||o("it was issued against a different host certificate");let $=m("jti");$.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit($,e.now)||o("it has already been used");let V=m("sub");return V.length===0&&o("it names no player"),{playerId:V.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:I,role:D,fingerprint:G,hostFingerprint:F,jti:$,expiresAt:S}}var he=32769;function kn(n){let e=new TextEncoder().encode(n.jwt);if(e.length>8192)throw new Error(`[gem] a join credential of ${e.length} bytes exceeds the wire format's cap`);let t=new ArrayBuffer(3+e.length+4+4),r=new DataView(t);return r.setUint8(0,1),r.setUint16(1,e.length,true),new Uint8Array(t,3,e.length).set(e),r.setUint32(3+e.length,n.protocolVersion,true),r.setUint32(7+e.length,n.assignedPeerId,true),t}function Sn(n){let e=new ArrayBuffer(9),t=new DataView(e);return t.setUint8(0,2),t.setUint32(1,n.protocolVersion,true),t.setUint32(5,n.assignedPeerId,true),e}function Rn(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function _n(n){if(n.byteLength<1)return null;let e=new DataView(n);switch(e.getUint8(0)){case 1:{if(n.byteLength<3)return null;let t=e.getUint16(1,true);return t>8192||n.byteLength<3+t+8?null:{kind:"join",jwt:new TextDecoder().decode(new Uint8Array(n,3,t)),protocolVersion:e.getUint32(3+t,true),assignedPeerId:e.getUint32(7+t,true)}}case 2:return n.byteLength<9?null:{kind:"admit",protocolVersion:e.getUint32(1,true),assignedPeerId:e.getUint32(5,true)};case 3:return n.byteLength<2?null:{kind:"reject",reason:e.getUint8(1)};default:return null}}function Dr(n){switch(n){case 1:return "the host did not accept this credential";case 2:return "the host speaks a different protocol version \u2014 an engine peer refuses a browser peer here, deliberately";case 3:return "the match is full";case 4:return "the host is rate-limiting joins";case 129:return "the host verified this credential but it names a different player than the one who signalled \u2014 the host has its own line saying which";case 130:return "the host has this player on the kicked list for the current host epoch";case 131:return "the host could not fetch the platform's signing keys, so it cannot verify anyone yet \u2014 the host's console says why";default:return `the host refused with an unrecognised code (${n})`}}function Gr(n){switch(n){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var jr=3e4,Ee=class{constructor(e,t,r){this.localPlayerId=e;this.hostPlayerId=t,this.epoch=r;}localPlayerId;state="idle";epoch;hostPlayerId;kicked=new Set;startedAt=0;get currentState(){return this.state}get currentEpoch(){return this.epoch}get currentHostPlayerId(){return this.hostPlayerId}get isLocalHost(){return this.hostPlayerId===this.localPlayerId}isKicked(e){return this.kicked.has(e)}stalled(e){return this.state!=="idle"&&e-this.startedAt>3e4}apply(e,t){return !Number.isInteger(e.hostEpoch)||e.hostEpoch<0?{kind:"refused",why:`host epoch ${String(e.hostEpoch)} is not a whole number`}:e.hostEpoch===this.epoch?e.migrationComplete===true&&this.state!=="idle"?(this.state="idle",{kind:"completed"}):{kind:"duplicate"}:e.hostEpoch<this.epoch?{kind:"refused",why:`host epoch ${e.hostEpoch} is behind the current ${this.epoch}`}:e.hostPlayerId.length===0?{kind:"refused",why:"the migration named no new host"}:(this.kicked=new Set(e.kickedPlayerIds??[]),this.epoch=e.hostEpoch,this.hostPlayerId=e.hostPlayerId,this.startedAt=t,this.state=this.isLocalHost?"preparing":"reconnecting",{kind:"accepted",state:this.state})}complete(){this.state="idle";}};var _t={reliable:{negotiated:true,id:0,ordered:true},ordered:{negotiated:true,id:1,ordered:true,maxRetransmits:0},unreliable:{negotiated:true,id:2,ordered:false,maxRetransmits:0}},Ke=["reliable","ordered","unreliable"];function Et(n){let e=globalThis.RTCPeerConnection;if(!e)throw new Error("[gem] this environment has no RTCPeerConnection. Pass `peerConnectionFactory` to connect against a stand-in, which is how this flow is tested outside a browser.");return new e({iceServers:n.iceServers,...n.certificates===void 0?{}:{certificates:n.certificates}})}async function xt(){let n=globalThis.RTCPeerConnection;return n?.generateCertificate?n.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var Fr=1,xa=3e4,$r=2e3,Ta=5e3,qr=6e4,Aa=8,xn=class{constructor(e=Aa){this.perMinute=e;}perMinute;sent=[];delayUntilAllowed(e){return this.prune(e),this.sent.length<this.perMinute?0:Math.max(0,(this.sent[0]??e)+6e4-e)}record(e){this.prune(e),this.sent.push(e);}prune(e){let t=0;for(let r of this.sent)r<=e&&e-r<6e4&&(this.sent[t++]=r);this.sent.length=t;}},Ia=new xn,Pa=8,Ca=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),xe=class{constructor(e){this.options=e;this.keys=e.keys??St({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new kt;links=new Map;replays=new We;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=Fr+1;ended=null;closed=false;ready=null;helloSeen=false;reportedUnreachableEpoch=-1;reportedStallEpoch=-1;counted=false;pendingOffers=new Map;answeredSessions=new Map;credentialGeneration=0;credentialDeadline=0;get matchId(){return this.options.matchId}get playerId(){return this.localPlayerId}get isHost(){return this.migration?.isLocalHost??false}get hostPlayerId(){return this.migration?.currentHostPlayerId??""}get hostEpoch(){return this.migration?.currentEpoch??0}get peers(){let e=[];for(let t of this.links.values())t.admitted&&e.push(this.expose(t));return e}peer(e){let t=this.links.get(e);return t&&t.admitted?this.expose(t):null}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}async start(e){let t=this.options.connectTimeoutMs??xa;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((a,d)=>{this.ready={resolve:a,reject:d};}),i=U(this.options.clusterTargetId);if(i!==void 0)try{let a=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=a.iceServers,this.mark("turn leased");}catch(a){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${En(a)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let o=this.options.clock.setTimeout(()=>{this.fail(new k("timeout",`no usable P2P connection after ${t}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},t),s=()=>this.fail(new k("aborted","the caller aborted while connecting"));e?.aborted?s():e?.addEventListener("abort",s);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",s),this.ready=null;}}async kick(e){if(!this.isHost)throw new k("misconfigured","only the current host of this match can kick a peer");await this.options.api.kick(this.options.matchId,e);}async leave(){try{await this.options.api.leave(this.options.matchId);}catch{}this.close();}close(){if(!this.closed){this.closed=true,this.pendingOffers.clear();for(let e of [...this.links.values()])this.dropLink(e,"closed",false);this.options.signaling.close(),this.emitter.clear();}}report(e){this.options.api.telemetry(e).catch(()=>{});}notifyCandidatesDropped(e){this.emitter.emit("candidatesDropped",e);}handleSignal(e,t){this.closed||this.route(e,t).catch(r=>this.report_(r));}async route(e,t){switch(e){case "hello":return this.onHello(t);case "offer":return this.onOffer(t);case "answer":return this.onAnswer(t);case "ice":return this.onIce(t);case "peerLeft":return this.onPeerLeft(t);case "migration":return this.onMigration(t);case "matchEnded":return this.onMatchEnded(t);case "error":return this.onSignalingError(t);default:return}}async onHello(e){let t=N(e.playerId),r=N(e.hostPlayerId),i=Tt(e.hostEpoch);if(!(t===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=t,this.migration===null&&(this.migration=new Ee(t,r,i)),!this.helloSeen)){if(this.helloSeen=true,this.isHost){this.mark("host listening"),this.settle(),await this.drainPendingOffers();return}this.pendingOffers.clear(),await this.offerToHost("initial");}}async drainPendingOffers(){if(this.pendingOffers.size===0)return;let e=[...this.pendingOffers.values()];this.pendingOffers.clear(),this.mark("queued offer drained");for(let t of e)try{await this.onOffer(t);}catch(r){this.report_(r);}}async offerToHost(e){let t=this.hostPlayerId,r=this.openLink(t,Fr),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new k("invalid_sdp","the browser produced an offer with no SDP");ie(o,"offer"),this.refuseMedia(o,"offer"),this.options.signaling.offer(o,e),this.mark("offer sent"),this.fetchCredential().catch(s=>this.report_(s));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,i=r===void 0?null:pe(r);if(i===null)throw new k("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let o=this.options.credentialPacing??Ia,s=()=>this.closed||e!==this.credentialGeneration,a=Ta;for(;;){let d=o.delayUntilAllowed(this.options.clock.now());if(d>0&&!await this.waitForCredential(d,s))return;o.record(this.options.clock.now());try{let l=await this.options.api.joinCredential(this.options.matchId,i);if(s())return;this.credential=l,this.mark("credential ready"),this.maybeAuthenticate();return}catch(l){if(s())return;let p=l.status,u;if(p===409)u=$r;else if(p===429){let h=l.retryAfterSeconds;typeof h=="number"&&Number.isFinite(h)&&h>=0?u=h*1e3:(u=a,a=Math.min(a*2,qr)),u=Math.min(Math.max(u,$r),qr);}else throw l;if(!await this.waitForCredential(u,s))return}}}async waitForCredential(e,t){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!t())}async onOffer(e){let t=N(e.fromPlayerId),r=N(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=Pa){let p=this.pendingOffers.keys().next().value;p!==void 0&&this.pendingOffers.delete(p);}this.pendingOffers.set(t,e);return}if(!this.isHost||this.migration.isKicked(t)===true)return;let i=N(e.sessionId);if(i!==null&&this.answeredSessions.get(t)===i)return;ie(r,"offer"),this.refuseMedia(r,"offer");let o=pe(r);if(o===null)throw new k("invalid_sdp",`the offer from ${t} carries no usable fingerprint`);this.mark("offer received"),i!==null&&this.answeredSessions.set(t,i);let s=this.links.get(t);s&&this.dropLink(s,"resignalled",false);let a=this.openLink(t,this.nextPeerId++);a.remoteFingerprint=o,await a.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(a);let d=await a.connection.createAnswer();await a.connection.setLocalDescription(d);let l=a.connection.localDescription?.sdp??d.sdp;if(!l)throw new k("invalid_sdp","the browser produced an answer with no SDP");ie(l,"answer"),this.refuseMedia(l,"answer"),this.options.signaling.answer(t,l,a.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let t=N(e.fromPlayerId),r=N(e.sdp);if(t===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||t!==this.hostPlayerId)return;ie(r,"answer"),this.refuseMedia(r,"answer");let o=pe(r);if(o===null)throw new k("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),i.remoteFingerprint=o,i.pendingAnswer=r,this.hostVerified(i)&&await this.applyAnswer(i,r);}hostVerified(e){let t=this.credential;return t===null||e.remoteFingerprint===null?false:_e(t.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new k("peer_unauthenticated","the host's DTLS certificate is not the one the platform attested for this match. Refusing before the handshake, so no credential is presented.")),this.dropLink(e,"host_fingerprint_mismatch",false),false)}maybeAuthenticate(){if(this.isHost)return;let e=this.links.get(this.hostPlayerId);if(!e||e.remoteFingerprint===null||e.connection.remoteDescription!==null)return;let t=e.pendingAnswer;t!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,t).catch(r=>this.report_(r));}async applyAnswer(e,t){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:t}),this.flushCandidates(e);}async onIce(e){let t=N(e.fromPlayerId),r=N(e.candidate);if(t===null||r===null)return;let i=this.links.get(t);if(!i)return;let o=N(e.sdpMid),s=Tt(e.sdpMLineIndex)??Tt(e.sdpMLineIndexAlt),a={candidate:r,...o===null?{}:{sdpMid:o},...s===null?{}:{sdpMLineIndex:s}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(a);return}await i.connection.addIceCandidate(a);}onPeerLeft(e){let t=N(e.playerId);if(t===null)return;let r=N(e.reason)??"left";if(t===this.localPlayerId){this.fail(new k("kicked",`this player was removed from the match (${r})`)),this.close();return}let i=this.links.get(t);i&&this.dropLink(i,r,true);}async onMigration(e){let t=N(e.hostPlayerId),r=Tt(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:t,hostEpoch:r,...N(e.reason)===null?{}:{reason:N(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(o=>typeof o=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind!=="duplicate"){if(i.kind==="completed"){this.emitter.emit("hostChanged",t,r);return}if(i.kind==="refused"){this.report_(new k("migration_failed",i.why));return}for(let o of [...this.links.values()])this.dropLink(o,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",t,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new k("migration_failed",`host migration to epoch ${e} did not complete. The elected host never acknowledged it, so the platform is still holding the match in migration.`)));},31e3);}onMatchEnded(e){let t=N(e.reason)??"ended";this.ended=t,this.emitter.emit("matchEnded",t),this.ready!==null&&this.fail(new k("match_ended",`the match ended: ${t}`)),this.close();}onSignalingError(e){let t=N(e.code)??"unknown",r=N(e.message)??"the platform refused a signaling message";this.report_(new k("signaling_failed",`${t}: ${r}`));}openLink(e,t){let i=(this.options.peerConnectionFactory??Et)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let h of Ke){let g=i.createDataChannel(h,_t[h]);g.binaryType="arraybuffer",o[h]=g;}let s={playerId:e,assignedPeerId:t,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=h=>{let g=h.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},d=()=>this.onIceState(s),l=()=>this.onConnectionState(s),p=h=>{this.onHandshakeMessage(s,h.data).catch(g=>this.report_(g));},u=()=>{this.onReliableOpen(s).catch(h=>this.report_(h));};return i.addEventListener("icecandidate",a),i.addEventListener("iceconnectionstatechange",d),i.addEventListener("connectionstatechange",l),o.reliable.addEventListener("open",u),o.reliable.addEventListener("message",p),s.detachHandshake=()=>{o.reliable.removeEventListener("open",u),o.reliable.removeEventListener("message",p);},s.detachAll=()=>{s.detachHandshake(),i.removeEventListener("icecandidate",a),i.removeEventListener("iceconnectionstatechange",d),i.removeEventListener("connectionstatechange",l);},this.links.set(e,s),s}flushCandidates(e){let t=e.pendingCandidates;e.pendingCandidates=[];for(let r of t)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let t=this.credential;if(t===null)throw new k("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=t.expiresAt)throw new k("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(kn({jwt:t.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,t){if(!(t instanceof ArrayBuffer))return;let r=_n(t);if(r!==null){if(this.isHost&&r.kind==="join"){await this.admit(e,r.jwt,r.protocolVersion);return}if(!this.isHost&&r.kind==="admit"){e.assignedPeerId=r.assignedPeerId,this.finishAdmission(e),this.migration?.complete();return}!this.isHost&&r.kind==="reject"&&(this.fail(new k(Gr(r.reason),Dr(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,t,r){if(r!==32769){this.refuseLink(e,2,"version_mismatch",`it presented protocol version ${r}, not this SDK's ${32769} \u2014 an engine peer cannot join a browser-hosted match`);return}let i=pe(e.connection.localDescription?.sdp??"");if(i===null||e.remoteFingerprint===null){this.refuseLink(e,1,"fingerprint_unavailable","this connection's DTLS fingerprints could not be read from its SDP, so no credential can be checked against it");return}let o;try{o=await Rt(t,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:i,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(s){let a=s instanceof k&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",En(s)),a&&this.fail(s);return}if(o.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${o.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(o.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(Sn({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,t,r,i){this.warn(`refused to admit ${e.playerId}: ${i}`);try{e.channels.reliable.send(Rn(t));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){let t=e.connection.iceConnectionState;if(!(t!=="failed"&&t!=="disconnected"&&t!=="closed")){if(this.isHost){(t==="failed"||t==="closed")&&this.dropLink(e,t,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,t);}catch(r){this.report_(r);}}}}onConnectionState(e){let t=e.connection.connectionState;t!=="failed"&&t!=="closed"||this.dropLink(e,t,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(t,r="reliable")=>e.channels[r].send(t)}}dropLink(e,t,r){this.links.delete(e.playerId),e.detachAll();for(let i of Ke)Ur(e.channels[i]);Ur(e.connection),r&&e.admitted&&this.emitter.emit("peerLeft",e.playerId,t);}settle(){this.ready?.resolve(),this.ready=null;}fail(e){if(this.count(e.reason),this.ready!==null){let t=this.ready;this.ready=null,t.reject(e);return}this.emitter.emit("error",e);}report_(e){this.fail(e instanceof k?e:new k("connection_failed",En(e),{cause:e}));}count(e){this.counted||!Ca.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(yt(e))throw new k("media_refused",`the ${t} carries an active audio or video section. This path carries data channels only; voice belongs to the platform voice service, and gem-api age-gates relayed SDP that proposes media.`)}mark(e){this.options.boot?.mark(e);}sleep(e){return new Promise(t=>this.options.clock.setTimeout(t,e))}warn(e){let t=this.options.log;t!==null&&(t??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function N(n){return typeof n=="string"&&n.length>0?n:null}function Tt(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function En(n){return n instanceof Error?n.message:String(n)}function Ur(n){try{n.close();}catch{}}var Ma=100,La=50,Te=class{constructor(e){this.options=e;}options;queue=[];drainHandle=null;dropped=0;closed=false;dropListener=null;onDropped(e){this.dropListener=e;}join(){this.assertUsable(),this.options.bridge.signal("join",this.options.matchId,{});}offer(e,t){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:t});}answer(e,t,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:t,assignedPeerId:r});}candidate(e,t,r,i){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??Ma)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:t,...r===void 0?{}:{sdpMid:r},...i===void 0?{}:{sdpMLineIndex:i}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,t){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:t,lastSeenAt:Math.floor(this.options.clock.now()/1e3)}});}discardQueued(){this.queue.length=0;}close(){this.closed=true,this.discardQueued(),this.drainHandle!==null&&(this.options.clock.clearTimeout(this.drainHandle),this.drainHandle=null);}assertUsable(){if(this.closed)throw new k("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new k("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see public-docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId:t,candidate:r,sdpMid:i,sdpMLineIndex:o}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:t,candidate:r,...i===void 0?{}:{sdpMid:i},...o===void 0?{}:{sdpMLineIndex:o}});}if(this.dropped>0&&this.queue.length===0){let t=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(t),this.dropListener?.(t);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??La));}};var Tn="webrtc_p2p";function Oa(n){let e=new Re({client:n.client,gameId:n.gameId}),t=new Map;return {handleSignalEvent(r,i,o){t.get(r)?.handleSignal(i,o);},session(r){return t.get(r)??null},async connect(r={}){if(n.bridge===null)throw new k("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See public-docs/p2p-and-parties.md \xA72.");let i=U(r.clusterTargetId)??U(await n.resolveClusterTarget?.());n.rooms.isHost&&n.rooms.currentMatch===null&&n.rooms.currentRoom?.matchId===void 0&&await n.rooms.startMatch({...i===void 0?{}:{clusterTargetId:i},...r.signal===void 0?{}:{signal:r.signal}});let o=await n.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(o.protocol!==Tn)throw new k("unsupported_protocol",`match ${o.matchId} speaks '${o.protocol}', not '${Tn}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new Te({bridge:n.bridge,matchId:o.matchId,clock:n.clock}),a=new xe({api:e,clock:n.clock,matchId:o.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:s,...i===void 0?{}:{clusterTargetId:i},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await xt(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...n.boot===void 0?{}:{boot:n.boot},...n.log===void 0?{}:{log:n.log}});s.onDropped(d=>a.notifyCandidatesDropped(d)),t.set(o.matchId,a),a.on("matchEnded",()=>t.delete(o.matchId));try{await a.start(r.signal);}catch(d){throw t.delete(o.matchId),a.close(),d}return a}}}function Hr(n){return typeof n=="string"&&n.trim()!==""}function Wr(n,e){return Hr(n)?n.trim():Hr(e)?e:null}function At(n){if(typeof n!="object"||n===null)return;let e={};for(let[t,r]of Object.entries(n)){let i=An(r);i!==void 0&&(e[t]=i);}return e}function It(n){if(Array.isArray(n))return n.map(Da).filter(e=>!!e)}function An(n){if(In(n)||Array.isArray(n)&&n.every(In))return n}function In(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function Da(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=An(e.fixed),r=An(e.default);return {name:e.name,type:typeof e.type=="string"?e.type:"string",list:e.list===true,required:e.required===true,mutable:e.mutable!==false,...t===void 0?{}:{fixed:t},...r===void 0?{}:{default:r},...Ae("description",Ga(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(In)?{allowed:e.allowed}:{},...Ae("min",Ve(e.min)),...Ae("max",Ve(e.max)),...Ae("minItems",Ve(e.min_items)),...Ae("maxItems",Ve(e.max_items)),...Ae("maxLength",Ve(e.max_length))}}function Ga(n){return typeof n=="string"&&n.length>0?n:void 0}function Ve(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ae(n,e){return e===void 0?{}:{[n]:e}}function X(n){let e=n??{},t=T(e.id)??T(e.game_room_id);if(t===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(Pn):[];return {id:t,gameId:T(e.game_id)??"",name:T(e.name)??"",status:T(e.status)??"open",hostPlayerId:T(e.host_player_id)??"",maxPlayers:z(e.max_players)??0,memberCount:z(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...J("joinCode",T(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...J("roomArgs",At(e.room_args)),...J("roomArgsTemplate",It(e.room_args_template)),gameChannel:T(e.game_channel)??"release",...J("region",T(e.region)),...J("matchId",T(e.match_id)),version:z(e.version)??0,...J("templateId",T(e.template_id)),roomType:T(e.game_room_type)??"Standard",...J("transports",Fe(e.transports)??void 0),createdAt:z(e.created_at)??0,updatedAt:z(e.updated_at)??0,...J("startedAt",z(e.started_at))}}function Pn(n){let e=n??{},t=T(e.display_name),r=T(e.display_tag);return {playerId:T(e.player_id)??"",isReady:e.is_ready===true,role:T(e.role)??"member",joinedAt:z(e.joined_at)??0,...J("groupId",T(e.group_id)),...J("platform",T(e.platform)),...t===void 0?{}:{displayName:le(t)},...r===void 0?{}:{displayTag:le(r)},...J("discriminator",T(e.discriminator))}}function Be(n){let e=n??{};return {id:T(e.id)??T(e.game_room_id)??"",gameId:T(e.game_id)??"",name:T(e.name)??"",status:T(e.status)??"open",hostPlayerId:T(e.host_player_id)??"",maxPlayers:z(e.max_players)??0,memberCount:z(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:T(e.game_channel)??"release",roomType:T(e.game_room_type)??"Standard",createdAt:z(e.created_at)??0}}function T(n){return typeof n=="string"&&n.length>0?n:void 0}function z(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function J(n,e){return e===void 0?{}:{[n]:e}}var Ie=class{constructor(e){this.options=e;}options;list(e){let t=new URLSearchParams;e.status&&t.set("status",e.status),e.templateSlug&&t.set("template_slug",e.templateSlug),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);let r=t.size>0?`?${t.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(i=>({rooms:(i.game_rooms??[]).map(Be),...typeof i.next_cursor=="string"?{nextCursor:i.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(t=>({rooms:(t.game_rooms??[]).map(Be)}))}create(e,t){return ja(e.maxPlayers),this.options.client.post(this.baseV2(),{name:e.name,...e.isPublic===void 0?{}:{is_public:e.isPublic},...e.settings===void 0?{}:{settings:e.settings},...e.region===void 0?{}:{region:e.region},...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.partyId===void 0?{}:{party_id:e.partyId},...e.roomArgs===void 0?{}:{room_args:e.roomArgs},...Pt(t)},e.signal).then(X)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(X)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...Pt(r)},t.signal).then(X)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...Pt(r)},t.signal).then(X)}quickJoin(e,t){return this.options.client.post(`${this.baseV2()}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.region===void 0?{}:{region:e.region},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...Pt(t)},e.signal).then(X)}leave(e,t,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:t},r,{keepalive:i}).then(()=>{})}close(e,t){return this.options.client.delete(this.roomV1(e),t).then(()=>{})}update(e,t){return this.options.client.patch(this.roomV2(e),{...t.name===void 0?{}:{name:t.name},...t.maxPlayers===void 0?{}:{max_players:t.maxPlayers},...t.isPublic===void 0?{}:{is_public:t.isPublic},...t.settings===void 0?{}:{settings:t.settings},...t.roomArgs===void 0?{}:{room_args:t.roomArgs}},t.signal).then(X)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(X)}kick(e,t,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(t)}`,{},r).then(()=>this.get(e,r))}transferHost(e,t,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(t)}`,{},r).then(X)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function Pt(n){return {platform:n.platform,game_version:n.gameVersion,engine_version:n.engineVersion}}function ja(n){n!==void 0&&console.warn(`[gem] createRoom: maxPlayers (${n}) is deprecated and was not sent. A room's seats come from the room template published in your game config \u2014 name one with templateSlug \u2014 and a room created without a template seats 8. To change a room that already exists, call update({ maxPlayers }) as its host.`);}var Pe=class{listeners=new Map;retainedMatch=null;on(e,t){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(t),e==="matchReady"&&this.retainedMatch!==null){let i=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(t)&&this.retainedMatch===i&&t(i);});}return ()=>this.off(e,t)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,t){this.listeners.get(e)?.delete(t);}once(e,t){let r=this.on(e,((...i)=>{r(),t(...i);}));return r}emit(e,...t){e==="matchReady"&&(this.retainedMatch=t[0]);let r=this.listeners.get(e);if(r)for(let i of [...r])i(...t);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};function Na(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var Fa=1e3,$a=3e3,qa=6e4,Ua=2,Kr=new Set(["game_room_closed","game_room_gone"]),Ha=12e4,Wa=5e3;function Jr(n){return new Cn(n)}var Cn=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Ie({client:e.client,gameId:()=>this.requireGameId()}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Pe;api;room=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;async create(e){this.assertNotInRoom("create");let t=await this.attachParty(e),r=await this.run("create",()=>this.api.create(t,this.version("create")));return this.enter(r,"created"),r}async join(e,t={}){this.assertNotInRoom("join");let r=await this.attachParty(t),i=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(i,"joined"),i}async joinByCode(e,t={}){this.assertNotInRoom("joinByCode");let r=await this.attachParty(t),i=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(i,"joined"),i}async quickJoin(e){this.assertNotInRoom("quickJoin");let t=await this.attachParty(e),r=await this.run("quickJoin",()=>this.api.quickJoin(t,this.version("quickJoin")).catch(i=>this.retryPastStaleMembership(i,t)));return this.enter(r,"joined"),r}async list(e={}){let t=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",t),t}async myRooms(e){let t=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",t.rooms),t.rooms}async leave(e={}){let t=this.requireRoom("leave"),r=e.keepalive===true,i=()=>this.run("leave",()=>this.api.leave(t.id,e.asGroup!==false,e.signal,r));if(r){let o=i();this.track(this.notifyLeavingMatch({keepalive:true})),await o;}else await this.notifyLeavingMatch(),await i();this.exit(),this.emitter.emit("left");}async leaveAll(e){let t=await this.myRooms(e),r=[];for(let i of t)try{await this.run("leaveAll",()=>this.api.leave(i.id,!0,e)),r.push(i.id),this.room?.id===i.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let t=this.requireRoom("close");await this.run("close",()=>this.api.close(t.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let t=this.room;if(!t)return null;let r;try{r=await this.track(this.api.get(t.id,e));}catch(i){if(i instanceof W&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let s=await this.askWhyEnded(o,e);this.endMatch(o,s??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",i),i}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let t=this.room,r=this.heldMatchId;if(!(t===null||r===null)&&!(t.status==="in_game"&&t.matchId===r)&&!(t.matchId!==void 0&&t.matchId!==r)&&this.settling!==r){this.settling=r;try{let i=await this.askWhyEnded(r,e);i!==null&&this.endMatch(r,i,t.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,t){let r=this.room;if(r===null)return null;let i=this.takeHint(e),o;try{o=await this.track(this.onceGameIdKnown(()=>Vt({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...t===void 0?{}:{signal:t}})));}catch(s){return s instanceof W&&s.reason==="not_found"?i??null:(this.reportError("reconcile",s),null)}return o===null?null:o.status==="ready"?(this.seenMatches.add(e),null):o.status==="failed"?(this.settleFailed(o.matchId,o.reason),null):o.reason==="unknown"&&i!==null?i:o.reason}takeHint(e){let t=this.pendingHint;if(t===null||t.matchId!==void 0&&t.matchId!==e||(this.pendingHint=null,t.reason===void 0))return null;let r=ke(t.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let t=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=t,this.track(t)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,t){let r=this.requireRoom("setReady"),i=await this.run("setReady",()=>this.api.setReady(r.id,e,t));return this.apply(i),i}async kick(e,t){let r=this.requireRoom("kick"),i=await this.run("kick",()=>this.api.kick(r.id,e,t));return this.apply(i),i}async transferHost(e,t){let r=this.requireRoom("transferHost"),i=await this.run("transferHost",()=>this.api.transferHost(r.id,e,t));return this.apply(i),i}async update(e){let t=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(t.id,e));return this.apply(r),r}async startMatch(e={}){let t=this.requireRoom("startMatch");if(!this.isHost)throw new c("misconfigured",`only the host of room ${t.id} can start a match, and this player is not it. Every other member waits for \`matchAllocationStarted\` instead \u2014 that is the whole point of the room carrying the match.`);let r=U(e.clusterTargetId)??U(await this.options.resolveClusterTarget?.());await this.options.ensureLocalServer?.(t.id);let i=await this.run("startMatch",()=>at({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:t.id,...r===void 0?{}:{clusterTargetId:r},retry:{...e.retry,onWaiting:o=>{this.emitter.emit("matchStartWaiting",o),e.retry?.onWaiting?.(o);}},...e.signal===void 0?{}:{signal:e.signal}}));return this.beginMatch(i.matchId),i}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new c("misconfigured","this match is suspended \u2014 the transport dropped and nobody has decided to reconnect yet. Call reconnectToMatch(), or dedicatedServer.connect(), which does it for you.");let t=this.emitter.retained;return t!==null&&this.session.phase==="ready"?t:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let t=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),i=await this.run("pollMatchStatus",()=>this.chase(t.id,r,e));return this.settleOutcome(i)}chase(e,t,r){return st({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:t,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(t),...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.pollIntervalMs===void 0?{}:{pollIntervalMs:r.pollIntervalMs},...r.signal===void 0?{}:{signal:r.signal}})}settleOutcome(e){if(e.status==="failed")throw this.settleFailed(e.matchId,e.reason),new c("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!Kr.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new c("match_ended",`match ${e.matchId} ended: ${e.reason}`);return this.seenMatches.add(e.matchId),this.emitter.retained?.matchId===e.matchId?this.emitter.retain(e):this.emitter.emit("matchReady",e),this.heldMatchId===e.matchId&&this.session.phase!=="connected"&&(this.session={phase:"ready",matchId:e.matchId}),e}settleFailed(e,t){this.heldMatchId===e&&(this.abandonReconnect(e,t),this.emitter.emit("matchFailed",e,t),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,t,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:t,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:t,roomReopened:r}),this.abandonReconnect(e,t));}armReconnect(e,t){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),t==="kicked"){r.abandon(e,t);return}let i={matchId:e,cause:t,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=i,this.track(this.reconnectStep(i));}park(e,t){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),t());}reconnecting(e){return !this.disposed&&!e.done&&this.reconnect===e&&this.session.phase==="suspended"&&this.session.matchId===e.matchId}finishReconnect(){let e=this.reconnect;e!==null&&(e.done=true,e.timer!==null&&(this.options.clock.clearTimeout(e.timer),e.timer=null),e.parked=null,this.reconnect=null);}abandonReconnect(e,t){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,t));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!Ct()){this.park(e,()=>this.reconnectStep(e));return}let t=this.options.autoReconnect;if(t===void 0||e.attempt===0&&(await this.reconcile().catch(()=>{}),!this.reconnecting(e)))return;let r=e.deadlineAt-this.options.clock.now();if(e.attempt>=t.attempts||r<Fa){this.abandonReconnect(e.matchId,e.cause);return}e.attempt+=1,this.emitter.emit("matchReconnecting",{matchId:e.matchId,attempt:e.attempt,attempts:t.attempts,remainingMs:r}),e.timer=this.options.clock.setTimeout(()=>{e.timer=null,this.track(this.reconnectAttempt(e));},Math.min(Na(e.attempt,t.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!Ct()){this.park(e,()=>this.reconnectAttempt(e));return}let t=this.options.autoReconnect,r=this.room;if(t===void 0||r===null)return;let i=null;try{i=await this.track(this.onceGameIdKnown(()=>Vt({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e.matchId,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e.matchId)})));}catch(o){this.reportError("reconcile",o);}if(this.reconnecting(e)){if(i?.status==="ended"){this.endMatch(i.matchId,i.reason,!Kr.has(i.reason)),this.track(this.reconcile().catch(()=>{}));return}if(i?.status==="failed"){this.abandonReconnect(e.matchId,i.reason),this.settleFailed(i.matchId,i.reason);return}if(i?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(i);let o;try{o=await t.redial(e.matchId,e.deadlineAt);}catch(s){this.reportError("reconcile",s),o="failed";}if(e.done||this.reconnect!==e)return;if(o==="closed"){this.finishReconnect();return}if(o==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let t=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):t&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new c("misconfigured",`no match is connected, so there is nothing to suspend (state '${this.matchConnectionState}').`);let t=this.session.matchId;this.session={phase:"suspended",matchId:t,reason:e},this.emitter.emit("matchSuspended",{matchId:t,cause:e}),this.armReconnect(t,e);}async reconnectToMatch(e={}){if(this.session.phase!=="suspended")throw new c("misconfigured",`reconnectToMatch expects a suspended match; this one is '${this.matchConnectionState}'. Call notifyMatchDisconnected() when the transport drops.`);let t=this.heldMatchId;if(t===null)throw new c("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:t},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let t=this.heldMatchId;if(t!==null)try{await this.api.leaveMatch(t,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,t){let r=this.emitter.on(e,t);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}handleRoomEvent(e){if(this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let t=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(t).catch(()=>{}));}handleSeated(e){this.disposed||!this.watchingSeats||this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}async reconcileSeats(){if(this.disposed||!this.watchingSeats)return;let e;try{e=await this.myRooms();}catch{return}let t=new Set;for(let r of e)r.status!=="closed"&&(t.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])t.has(r)||this.reported.delete(r);}async reportSeat(e){let t=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||t===null||!r.members.some(i=>i.playerId===t)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.seatPollMs>0&&Ct())){this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null);return}if(this.seatPollHandle!==null)return;let t=()=>{this.seatPollHandle=null,this.track(this.reconcileSeats().catch(()=>{}).then(()=>this.retuneSeatWatch()));};this.seatPollHandle=this.options.clock.setTimeout(t,this.seatPollMs);}installResumeWatch(){let e=globalThis;if(typeof e.addEventListener!="function")return;this.visibilityListener=()=>{if(!this.disposed&&(this.retuneSeatWatch(),!!Ct())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of Vr)e.addEventListener(r,this.visibilityListener);let t=globalThis.document;typeof t?.addEventListener=="function"&&t.addEventListener("resume",this.visibilityListener);}startPolling(e){this.stopPolling(),!this.disposed&&(this.pinnedIntervalMs=e??null,this.polling=true,this.schedule());}stopPolling(){this.pollHandle!==null&&(this.options.clock.clearTimeout(this.pollHandle),this.pollHandle=null),this.polling=false,this.pollIntervalMs=null;}async settled(){for(let e=0;e<20&&this.inFlight.length>0;e++){let t=this.inFlight;this.inFlight=[],await Promise.allSettled(t);}}dispose(){if(this.disposed=true,this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of Vr)e.removeEventListener?.(r,this.visibilityListener);globalThis.document?.removeEventListener?.("resume",this.visibilityListener),this.visibilityListener=null;}}get watchingSeats(){return this.options.watchSeats!==false&&this.emitter.hasListeners("seated")}get seatPollMs(){return this.options.seatPollIntervalMs??Wa}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new c("misconfigured","the game id is not known yet. It comes from the play token, and this manager was given no way to wait for one \u2014 pass gameId, or awaitGameId so a call made before the first token waits for it the way createGem wires it.")}playerId(){return typeof this.options.playerId=="function"?this.options.playerId():this.options.playerId}version(e){let t=this.options.clientVersion,r=Wr(this.options.platformGameVersion?.(),t?.gameVersion);if(r===null)throw new c("misconfigured",`${e} has no game version to report \u2014 gem-api requires platform, game_version and engine_version together on every room route, and refuses a request carrying two of the three. The arcade normally supplies it with the play token; an embedder that does not, or a build running outside the arcade, leaves nobody to ask. Pass \`clientVersion: { gameVersion }\` to createGem (or to createRoomManager) as the fallback. It has to name a build you actually published, and a wrong one pins the room to the wrong build \u2014 which is why the platform answers it wherever it can.`);return kr({...t,gameVersion:r},e)}async attachParty(e){if(e.partyId!==void 0)return e;let t=this.options.resolveParty;if(t===void 0)return e;let r=await t();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,t){if(!(e instanceof W)||e.reason!=="conflict")throw e;if(this.options.recoverStaleMembership===false)throw new W(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let r;try{r=await this.leaveAll(t.signal);}catch{throw new W(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(r.length===0)throw new W(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery cleared nothing, so the refusal stands. myRooms() shows what is held. A room this player was seated in as a party member cannot be cleared from here at all \u2014 only the leader of a party may take it out of a room \u2014 so a member joins by adopting that room, myRooms() then join(), rather than quick-joining.`,e.retryAfterSeconds,e.code);return this.api.quickJoin(t,this.version("quickJoin"))}assertNotInRoom(e){if(this.room!==null)throw new c("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}requireRoom(e){if(this.room===null)throw new c("misconfigured",`${e} refused: not in a room.`);return this.room}async run(e,t){try{return await this.track(this.onceGameIdKnown(t))}catch(r){throw this.reportError(e,r),r}}onceGameIdKnown(e){return this.gameId!==null||this.options.awaitGameId===void 0?e():this.options.awaitGameId().then(e)}reportError(e,t){let r=t instanceof W?{operation:e,code:t.status,reason:t.reason,message:t.message,retryable:t.retryable}:{operation:e,code:0,reason:t instanceof c?t.reason:"unavailable",message:t instanceof Error?t.message:String(t),retryable:false};this.emitter.emit("error",r);}track(e){return this.inFlight.push(e),e}enter(e,t){this.room=e,this.abortFollow(),this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(t,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let t=this.room;if(t===null||t.id!==e.id)return;let r=new Map(t.members.map(a=>[a.playerId,a])),i=new Map(e.members.map(a=>[a.playerId,a])),o=this.playerId();for(let a of i.keys())r.has(a)||this.emitter.emit("memberJoined",a);for(let a of r.keys())if(!i.has(a)){if(a===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",a);}for(let[a,d]of i){let l=r.get(a);l&&l.isReady!==d.isReady&&this.emitter.emit("readyChanged",a,d.isReady);}t.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let s=Ka(t,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),s&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let t=this.heldMatchId;t!==null&&t!==e&&this.endMatch(t,"replaced",true),this.session={phase:"starting",matchId:e},this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,t=this.heldMatchId;if(e===null||t===null||this.followAbort!==null&&this.followingMatchId===t)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=t,this.track(this.onceGameIdKnown(()=>this.chase(e.id,t,{signal:r.signal})).then(i=>{if(!r.signal.aborted)try{this.settleOutcome(i);}catch{}}).catch(i=>{r.signal.aborted||this.reportError("pollMatchStatus",i);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let t=this.heldMatchId;if(t!==null)return Promise.resolve(t);let r=e.timeoutMs??Ha;return new Promise((i,o)=>{let s=u=>{a(),d(),this.options.clock.clearTimeout(p),e.signal?.removeEventListener("abort",l),u();},a=this.emitter.on("matchAllocationStarted",u=>s(()=>i(u))),d=this.emitter.on("matchFailed",(u,h)=>s(()=>o(new c("allocation_failed",`match ${u} did not come up: ${h}`)))),l=()=>s(()=>o(new c("aborted","the caller aborted while awaiting a match"))),p=this.options.clock.setTimeout(()=>s(()=>o(new c("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?l():e.signal?.addEventListener("abort",l);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??$a}pushedInterval(){return this.options.pushedPollIntervalMs??qa}pushed(){return this.options.clock.now()-this.lastPushAt<Ua*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=t=>{t?.persisted!==true&&this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{}));},e.addEventListener("pagehide",this.unloadListener));}};function Ct(){let n=globalThis.document;return n?.visibilityState===void 0||n.visibilityState==="visible"}var Vr=["visibilitychange","focus","pageshow","online"];function Ka(n,e){return n.version!==e.version||n.status!==e.status||n.matchId!==e.matchId||n.hostPlayerId!==e.hostPlayerId||n.name!==e.name||n.maxPlayers!==e.maxPlayers||n.isPublic!==e.isPublic||Br(n)!==Br(e)}function Br(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function Xr(n){let e=0,t=new Map;return {resolve(){if(!n.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(i=>{let o={},s=d=>{t.delete(r)&&(n.clock.clearTimeout(o.timer),i(d));};t.set(r,s),o.timer=n.clock.setTimeout(()=>s(void 0),n.timeoutMs??2e3);let a=false;try{a=n.bridge.requestParty(r);}catch{}a||s(void 0);})},settle(r,i){t.get(r)?.(i);}}}
|
|
2
|
-
export{
|
|
1
|
+
globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:5.11.0]";var y="gem-web-bridge",Z={min:1,max:1},fe=65536,jn=8,ze=5e3,Fn=1024,jt=1e4;function Ft(n){return Object.freeze(Object.assign(Object.create(null),n))}var Qe=Ft({"gem.handshake":30,"gem.handshake.accept":5,"gem.token":30,"gem.token.denied":30,"gem.player":12,"gem.pause":120,"gem.prefs":60,"gem.cohorts":12,"gem.viewport":60,"gem.deviceSettings":12,"gem.willTerminate":10,"gem.roomEvent":120,"gem.socketState":12,"gem.seatedEvent":60,"gem.autoStartFailedEvent":30,"gem.signalEvent":1800,"gem.dedicatedEvent":120,"gem.partyResult":30,"gem.clusterTarget":12,"gem.devtools":30,"gem.screenshot":6,"gem.screenshot.denied":12,"gem.requestContext":12,"gem.gameContext":12,"gem.signal":1200,"gem.dedicatedOffer":60,"gem.partyRequest":12,"gem.ready":5,"gem.progress":600,"gem.requestToken":12,"gem.requestLocalServer":6,"gem.localServer":30,"gem.localServer.denied":30,"gem.exit":5,"gem.openExternal":6,"gem.requestFullscreen":30,"gem.audioState":120,"gem.rewardCue":60,"gem.frameStats":120,"gem.error":60,"gem.requestPurchase":12,"gem.purchaseResult":30,"gem.deviceSettings.put":30,"gem.deviceSettings.result":30,"gem.requestAd":6,"gem.adResult":12,"gem.requestSignIn":6,"gem.signInResult":12,__malformed:60}),ye="__malformed",cs=["gem.handshake","gem.token","gem.token.denied","gem.player","gem.pause","gem.prefs","gem.cohorts","gem.viewport","gem.deviceSettings","gem.willTerminate","gem.roomEvent","gem.socketState","gem.seatedEvent","gem.autoStartFailedEvent","gem.signalEvent","gem.dedicatedEvent","gem.partyResult","gem.clusterTarget","gem.devtools","gem.screenshot","gem.requestContext","gem.localServer","gem.localServer.denied","gem.error","gem.purchaseResult","gem.deviceSettings.result","gem.adResult","gem.signInResult"],us=["gem.handshake.accept","gem.screenshot.denied","gem.gameContext","gem.signal","gem.dedicatedOffer","gem.partyRequest","gem.ready","gem.progress","gem.requestToken","gem.requestLocalServer","gem.exit","gem.openExternal","gem.requestFullscreen","gem.audioState","gem.rewardCue","gem.frameStats","gem.error","gem.requestPurchase","gem.deviceSettings.put","gem.requestAd","gem.requestSignIn"],ii=Ft({"gem.requestAd":"ads","gem.adResult":"ads","gem.requestSignIn":"signIn","gem.signInResult":"signIn","gem.requestPurchase":"purchases","gem.purchaseResult":"purchases","gem.devtools":"devtools","gem.screenshot":"screenshot","gem.screenshot.denied":"screenshot","gem.requestContext":"feedbackContext","gem.gameContext":"feedbackContext","gem.roomEvent":"rooms","gem.signal":"p2p","gem.signalEvent":"p2p","gem.dedicatedOffer":"dedicated","gem.dedicatedEvent":"dedicated","gem.clusterTarget":"clusterTarget","gem.partyRequest":"parties","gem.partyResult":"parties","gem.autoStartFailedEvent":"autoStartFailure","gem.seatedEvent":"partySeating","gem.socketState":"socketState","gem.audioState":"audioState","gem.rewardCue":"rewardCue","gem.frameStats":"frameStats","gem.viewport":"viewport","gem.requestLocalServer":"localHost","gem.localServer":"localHost","gem.localServer.denied":"localHost","gem.cohorts":"cohorts","gem.deviceSettings":"deviceSettings","gem.deviceSettings.put":"deviceSettings","gem.deviceSettings.result":"deviceSettings"}),oi=Object.freeze([["gem.asyncOpponents.","asyncOpponents"]]);function Ze(n){let e=ii[n];if(e!==void 0)return e;for(let[t,r]of oi)if(n.startsWith(t))return r}function et(n){let e=/^([a-z][a-z0-9+.-]*):\/\/([a-z0-9.-]+|\[[0-9a-f:.]+\])(:([0-9]{1,5}))?$/i.exec(n);return e===null?false:e[4]===void 0||Number(e[4])<=65535}function ai(n){let e;try{e=new URL(n);}catch{return false}return e.username!==""||e.password!==""?false:e.protocol==="https:"?true:e.protocol==="http:"&&(e.hostname==="localhost"||e.hostname==="127.0.0.1")}function si(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function Gt(n,e,t){if(e>jn)return `nesting deeper than ${jn}`;if(++t.nodes>ze)return `more than ${ze} values`;if(t.bytes>fe)return `over the ${fe} byte limit`;if(n==null)return t.bytes+=4,null;let r=typeof n;if(r==="boolean")return t.bytes+=5,null;if(r==="number")return t.bytes+=8,null;if(r==="string")return t.bytes+=n.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let i=n;if(t.seen.has(i))return "a repeated or cyclic object reference";if(t.seen.add(i),Array.isArray(n)){if(n.length>Fn)return `an array of ${n.length} entries, over the ${Fn} limit`;t.bytes+=2;for(let a of n){let d=Gt(a,e+1,t);if(d)return d}return null}let o=Object.getPrototypeOf(n);if(o!==Object.prototype&&o!==null)return "a value that is not a plain object";t.bytes+=2;let s=n;for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;if(++t.nodes>ze)return `more than ${ze} values`;if(t.bytes+=a.length*3+4,t.bytes>fe)return `over the ${fe} byte limit`;let d=Gt(s[a],e+1,t);if(d)return d}return null}function di(n){let e={nodes:0,bytes:0,seen:new Set},t=Gt(n,0,e);return t?`message contains ${t}`:e.bytes>fe?`message is over the ${fe} byte limit`:null}var li={origin:[et,"not a well-formed origin"],url:[ai,"not a safe absolute http(s) URL"],bcp47:[si,"not a well-formed BCP 47 tag"]};function Nn(n,e,t){for(let r of e){let i=t===""?r.n:`${t}.${r.n}`,o=n[r.n];if(o==null){if(r.o)continue;return `${i}: required`}let s=$n(o,r,i);if(s)return s}return null}function $n(n,e,t){switch(e.k){case "string":{if(typeof n!="string")return `${t}: expected string`;if(n.length>e.max)return `${t}: exceeds ${e.max} characters`;if(e.f){let[r,i]=li[e.f];if(!r(n))return `${t}: ${i}`}return null}case "int":return typeof n!="number"||!Number.isInteger(n)?`${t}: expected integer`:n<e.lo||n>e.hi?`${t}: out of range ${e.lo}..${e.hi}`:null;case "boolean":return typeof n=="boolean"?null:`${t}: expected boolean`;case "enum":{let r=e.v;return r.includes(n)?null:`${t}: not one of ${r.join("|")}`}case "object":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected object`:Nn(n,e.fs,t);case "json":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected a plain object`:null;case "array":{if(!Array.isArray(n))return `${t}: expected array`;if(n.length>e.max)return `${t}: exceeds ${e.max} items`;let r=e.it,i=`${t}[]`;for(let o of n){if(o==null){if(r.o)continue;return `${i}: required`}let s=$n(o,r,i);if(s)return s}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}function v(n,e){return t=>{let r=di(t);if(r)return r;if(typeof t!="object"||t===null||Array.isArray(t))return "message: expected object";let i=t;return i.gem!==y?"gem: wrong protocol marker":i.type!==n?`type: expected ${n}`:Nn(i,e,"")}}var ci=v("gem.handshake",[{n:"versions",k:"object",fs:[{n:"min",k:"int",lo:1,hi:1e3},{n:"max",k:"int",lo:1,hi:1e3}]},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}},{n:"embedder",k:"string",max:2048,f:"origin"}]),ui=v("gem.handshake.accept",[{n:"v",k:"int",lo:1,hi:1e3},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}}]),mi=v("gem.token",[{n:"token",k:"string",max:4096},{n:"requestId",k:"string",o:1,max:64},{n:"generation",k:"int",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"string",o:1,max:512,f:"url"},{n:"playerId",k:"string",max:64},{n:"gameId",k:"string",max:64},{n:"channel",k:"enum",v:["dev","test","release"]},{n:"gameVersion",k:"string",o:1,max:64},{n:"expiresAt",k:"int",lo:0,hi:4102444800},{n:"chainEndsAt",k:"int",lo:0,hi:4102444800},{n:"allowDevTools",k:"boolean",o:1}]),pi=v("gem.token.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:36e5},{n:"reason",k:"enum",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"string",max:64}]),hi=v("gem.player",[{n:"untrusted",k:"object",fs:[{n:"displayName",k:"string",max:64},{n:"displayTag",k:"string",o:1,max:80},{n:"displayHandle",k:"string",max:80}]},{n:"playerId",k:"string",o:1,max:64},{n:"discriminator",k:"string",o:1,max:8},{n:"avatarIconUrl",k:"string",o:1,max:2048,f:"url"},{n:"badges",k:"array",o:1,max:2,it:{n:"",k:"object",fs:[{n:"itemId",k:"string",max:64},{n:"iconUrl",k:"string",max:2048,f:"url"}]}},{n:"displayTag",k:"string",max:8},{n:"avatarUrl",k:"string",o:1,max:2048,f:"url"}]),gi=v("gem.pause",[{n:"paused",k:"boolean"}]),fi=v("gem.prefs",[{n:"reducedMotion",k:"boolean"},{n:"muted",k:"boolean"},{n:"showFrameStats",k:"boolean",o:1},{n:"locale",k:"string",max:35,f:"bcp47"}]),yi=v("gem.cohorts",[{n:"cohorts",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"experimentId",k:"string",max:36},{n:"variantKey",k:"string",max:32}]}}]),vi=v("gem.viewport",[{n:"insets",k:"object",fs:[{n:"top",k:"int",lo:0,hi:4096},{n:"right",k:"int",lo:0,hi:4096},{n:"bottom",k:"int",lo:0,hi:4096},{n:"left",k:"int",lo:0,hi:4096}]}]),bi=v("gem.deviceSettings",[{n:"settings",k:"json",o:1}]),wi=v("gem.willTerminate",[{n:"reason",k:"enum",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"int",lo:0,hi:6e4}]),ki=v("gem.roomEvent",[{n:"event",k:"enum",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"string",max:64},{n:"matchId",k:"string",o:1,max:64},{n:"version",k:"int",o:1,lo:0,hi:2147483647},{n:"reason",k:"string",o:1,max:64},{n:"platform",k:"enum",o:1,v:["universal","mobile"]}]),Si=v("gem.socketState",[{n:"connected",k:"boolean"},{n:"reason",k:"enum",o:1,v:["connecting","dropped","watchdog","terminal"]}]),Ri=v("gem.seatedEvent",[{n:"roomId",k:"string",max:64}]),_i=v("gem.autoStartFailedEvent",[{n:"roomId",k:"string",max:64},{n:"code",k:"string",max:64}]),Ei=v("gem.signalEvent",[{n:"event",k:"enum",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Ti=v("gem.dedicatedEvent",[{n:"event",k:"enum",v:["answer","error","matchEnded"]},{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",o:1,max:10240},{n:"sessionId",k:"string",o:1,max:64},{n:"code",k:"string",o:1,max:64},{n:"message",k:"string",o:1,max:256},{n:"reason",k:"string",o:1,max:64}]),xi=v("gem.partyResult",[{n:"requestId",k:"string",max:64},{n:"partyId",k:"string",o:1,max:64}]),Ii=v("gem.clusterTarget",[{n:"clusterTargetId",k:"string",max:64},{n:"clusterTargetIds",k:"array",o:1,max:3,it:{n:"",k:"string",max:64}}]),Ai=v("gem.devtools",[{n:"action",k:"enum",v:["open","close","toggle"]}]),Ci=v("gem.screenshot",[{n:"maxWidth",k:"int",lo:1,hi:7680},{n:"maxHeight",k:"int",lo:1,hi:4320}]),Pi=v("gem.screenshot.denied",[{n:"reason",k:"enum",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"boolean"}]),Mi=v("gem.requestContext",[]),Li=v("gem.gameContext",[{n:"context",k:"json"}]),Oi=v("gem.signal",[{n:"signal",k:"enum",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Di=v("gem.dedicatedOffer",[{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",max:10240},{n:"intent",k:"enum",v:["initial","ice_restart","full_reconnect"]}]),Gi=v("gem.partyRequest",[{n:"requestId",k:"string",max:64}]),ji=v("gem.ready",[]),Fi=v("gem.progress",[{n:"loaded",k:"int",lo:0,hi:1099511627776},{n:"total",k:"int",lo:0,hi:1099511627776}]),Ni=v("gem.requestToken",[{n:"requestId",k:"string",max:64},{n:"reason",k:"enum",v:["initial","expiring","rejected"]}]),$i=v("gem.requestLocalServer",[{n:"requestId",k:"string",max:64},{n:"gameRoomId",k:"string",max:64}]),Ui=v("gem.localServer",[{n:"requestId",k:"string",max:64},{n:"serverId",k:"string",o:1,max:128}]),qi=v("gem.localServer.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"reason",k:"enum",v:["refused","unavailable"]}]),Hi=v("gem.exit",[{n:"reason",k:"string",o:1,max:64}]),Wi=v("gem.openExternal",[{n:"url",k:"string",max:2048,f:"url"}]),Ki=v("gem.requestFullscreen",[{n:"enabled",k:"boolean"}]),Vi=v("gem.audioState",[{n:"muted",k:"boolean"}]),Bi=v("gem.rewardCue",[{n:"currencySlug",k:"string",max:32},{n:"expected",k:"int",o:1,lo:1,hi:1e9},{n:"origin",k:"object",o:1,fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384}]}]),Ji=v("gem.frameStats",[{n:"fps",k:"int",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"int",lo:0,hi:1e5}]),Xi=v("gem.error",[{n:"code",k:"enum",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"string",o:1,max:256}]),Yi=v("gem.requestPurchase",[{n:"requestId",k:"string",max:64},{n:"purchaseKind",k:"enum",v:["item","recipe"]},{n:"targetId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"quantity",k:"int",o:1,lo:1,hi:10},{n:"catalogId",k:"string",o:1,max:64}]),zi=v("gem.purchaseResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["ok","declined","unavailable"]},{n:"purchaseId",k:"string",o:1,max:64}]),Qi=v("gem.deviceSettings.put",[{n:"requestId",k:"string",max:64},{n:"settings",k:"json"}]),Zi=v("gem.deviceSettings.result",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["stored","too_large","unavailable"]}]),eo=v("gem.requestAd",[{n:"requestId",k:"string",max:64},{n:"placement",k:"string",max:32},{n:"format",k:"enum",v:["interstitial","rewarded"]}]),to=v("gem.adResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["shown","no_ad","unavailable"]}]),no=v("gem.requestSignIn",[{n:"requestId",k:"string",max:64}]),ro=v("gem.signInResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["signed_in","declined","unavailable"]}]),se=Ft({"gem.handshake":ci,"gem.handshake.accept":ui,"gem.token":mi,"gem.token.denied":pi,"gem.player":hi,"gem.pause":gi,"gem.prefs":fi,"gem.cohorts":yi,"gem.viewport":vi,"gem.deviceSettings":bi,"gem.willTerminate":wi,"gem.roomEvent":ki,"gem.socketState":Si,"gem.seatedEvent":Ri,"gem.autoStartFailedEvent":_i,"gem.signalEvent":Ei,"gem.dedicatedEvent":Ti,"gem.partyResult":xi,"gem.clusterTarget":Ii,"gem.devtools":Ai,"gem.screenshot":Ci,"gem.screenshot.denied":Pi,"gem.requestContext":Mi,"gem.gameContext":Li,"gem.signal":Oi,"gem.dedicatedOffer":Di,"gem.partyRequest":Gi,"gem.ready":ji,"gem.progress":Fi,"gem.requestToken":Ni,"gem.requestLocalServer":$i,"gem.localServer":Ui,"gem.localServer.denied":qi,"gem.exit":Hi,"gem.openExternal":Wi,"gem.requestFullscreen":Ki,"gem.audioState":Vi,"gem.rewardCue":Bi,"gem.frameStats":Ji,"gem.error":Xi,"gem.requestPurchase":Yi,"gem.purchaseResult":zi,"gem.deviceSettings.put":Qi,"gem.deviceSettings.result":Zi,"gem.requestAd":eo,"gem.adResult":to,"gem.requestSignIn":no,"gem.signInResult":ro});var tt=3;function q(n){if(typeof n!="string")return;let e=n.trim();return e.length===0?void 0:e}function ve(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=q(t);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var io=2e3,oo=5e3;function ao(n){let e=[],t=false,r=null,i=new Map,o=()=>{if(e.length>0)return Promise.resolve(e);if(t)return Promise.resolve([]);if(!n.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let s,a=new Promise(d=>{let l=false,p=null;s=u=>{l||(l=true,r=null,n.clock.clearTimeout(p),d(u));},p=n.clock.setTimeout(()=>{t=true,s([]);},n.timeoutMs??io);});return r={promise:a,settle:s},a};return {resolveList:o,resolve(){return e.length>0||t||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(s=>s[0])},refresh(s){return !Un(e,s)||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let d=null,l=p=>{i.delete(l)&&(n.clock.clearTimeout(d),a(p));};i.set(l,s),d=n.clock.setTimeout(()=>l(e),n.refreshTimeoutMs??oo);})},accept(s,a){let d=ve(a),l=q(s),p=d.length>0?d:l===void 0?[]:[l];if(p.length!==0){e=p,r?.settle(p);for(let[u,h]of [...i])Un(p,h)||u(p);}}}}function Un(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Le=16384,nt=24;function R(n){return e=>typeof e=="string"&&e.length>0&&e.length<=n?e:void 0}function ee(n,e){return t=>typeof t=="number"&&Number.isInteger(t)&&t>=n&&t<=e?t:void 0}function be(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function qn(n){return typeof n=="boolean"?n:void 0}var O=R(64),Oe=ee(0,2147483647);function Nt(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(e.length>=64)break;let r=O(t);typeof r=="string"&&e.push(r);}return e}function T(n,e,t){return {to:n,from:e,read:t,required:true}}function _(n,e,t){return {to:n,from:e,read:t,required:false}}function we(n,e){let t={};for(let r of e){let i=r.read(n[r.from]);if(i===void 0){if(r.required)return null;continue}t[r.to]=i;}return t}function De(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e=n;return typeof e.type!="string"||typeof e.data!="object"||e.data===null||Array.isArray(e.data)?null:{type:e.type,data:e.data}}var Hn=[T("sdp","sdp",R(10240)),T("signaling_intent","intent",be("initial","ice_restart","full_reconnect"))];function rt(n,e,t){if(typeof t!="object"||t===null||Array.isArray(t))return {reason:"offer: data must be an object"};let r=t,i=we(r,Hn);return i===null?{reason:`offer: '${Hn.find(s=>s.read(r[s.from])===void 0)?.from??"?"}' is missing or out of bounds`}:{frame:{type:"webrtc_offer",match_id:n,game_id:e,...i}}}var $t=Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"})),so=new Set(["error"]),lo=Object.freeze(Object.assign(Object.create(null),{answer:[T("sdp","sdp",R(10240)),_("sessionId","session_id",R(64))],error:[_("code","code",R(64)),_("message","message",R(256))],matchEnded:[_("reason","reason",R(64))]}));function it(n,e,t){let r=De(n);if(r===null)return null;let i=$t[r.type];if(i===void 0)return null;let o=O(r.data.match_id);if(typeof o!="string"||!(so.has(i)?t(o):r.data.game_id===e))return null;let a=we(r.data,lo[i]??[]);return a===null?null:{event:i,matchId:o,...a}}var co=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=be("disconnected","failed","closed")(e.iceState),r=ee(0,4102444800)(e.lastSeenAt);if(!(t===void 0&&r===void 0))return {...t===void 0?{}:{ice_state:t},...r===void 0?{}:{last_seen_timestamp:r}}},uo=Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[T("sdp","sdp",R(10240)),T("signaling_intent","intent",be("initial","ice_restart","full_reconnect")),_("sdp_hash","sdpHash",R(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[T("peer_id","peerId",O),T("sdp","sdp",R(10240)),T("assigned_peer_id","assignedPeerId",ee(0,4294967295)),_("sdp_hash","sdpHash",R(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[T("peer_id","peerId",O),T("candidate","candidate",R(512)),_("sdp_mid","sdpMid",R(64)),_("sdp_mline_index","sdpMLineIndex",ee(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[T("host_epoch","hostEpoch",Oe)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[T("host_epoch","hostEpoch",Oe),_("evidence","evidence",co)]}}));function ot(n,e,t,r){let i=uo[n];if(i===void 0)return {reason:`unknown signal '${n}'`};if(typeof r!="object"||r===null||Array.isArray(r))return {reason:`${n}: data must be an object`};let o=r,s=we(o,i.args);if(s===null){let a=i.args.find(d=>d.required&&d.read(o[d.from])===void 0);return {reason:`${n}: '${a?.from??"?"}' is missing or out of bounds`}}return {frame:{type:i.type,match_id:e,...i.gameScoped?{game_id:t}:{},...s}}}var mo=Object.freeze(Object.assign(Object.create(null),{p2p_hello:"hello",p2p_sdp_offer:"offer",p2p_sdp_answer:"answer",p2p_ice_candidate:"ice",p2p_peer_joined:"peerJoined",p2p_peer_left:"peerLeft",p2p_host_migration:"migration",p2p_match_ended:"matchEnded",p2p_error:"error"})),po=new Set(["error"]),ho=Object.freeze(Object.assign(Object.create(null),{hello:[T("playerId","player_id",O),T("hostPlayerId","host_player_id",O),T("hostEpoch","host_epoch",Oe),_("members","members",Nt)],offer:[T("fromPlayerId","from_player_id",O),T("sdp","sdp",R(10240)),_("sessionId","signaling_session_id",R(128)),_("sdpHash","sdp_hash",R(128)),_("iceUfrag","ice_ufrag",R(64)),_("intent","signaling_intent",be("initial","ice_restart","full_reconnect"))],answer:[T("fromPlayerId","from_player_id",O),T("sdp","sdp",R(10240)),_("sessionId","signaling_session_id",R(128)),_("sdpHash","sdp_hash",R(128)),_("iceUfrag","ice_ufrag",R(64)),_("assignedPeerId","assigned_peer_id",ee(0,4294967295))],ice:[T("fromPlayerId","from_player_id",O),T("candidate","candidate",R(512)),_("sdpMid","sdp_mid",R(64)),_("sdpMLineIndex","sdp_m_line_index",ee(0,255)),_("sdpMLineIndexAlt","sdp_mline_index",ee(0,255))],peerJoined:[T("playerId","player_id",O)],peerLeft:[T("playerId","player_id",O),_("reason","reason",R(64))],migration:[T("hostPlayerId","new_host_player_id",O),T("hostEpoch","host_epoch",Oe),_("reason","reason",R(64)),_("kickedPlayerIds","kicked_player_ids",Nt),_("migrationComplete","migration_complete",qn)],matchEnded:[_("reason","reason",R(64))],error:[_("code","code",R(64)),_("message","message",R(256))]}));function at(n,e,t){let r=De(n);if(r===null)return null;let i=mo[r.type];if(i===void 0)return null;let o=O(r.data.match_id);if(typeof o!="string"||!(po.has(i)?t(o):r.data.game_id===e))return null;let a=we(r.data,ho[i]??[]);return a===null?null:{event:i,matchId:o,data:a}}var go=Object.freeze(Object.assign(Object.create(null),{party_invite_received:"inviteReceived",party_member_joined:"memberJoined",party_member_left:"memberLeft",party_member_kicked:"memberKicked",party_leader_transferred:"leaderTransferred",party_updated:"updated",party_disbanded:"disbanded",party_game_room_joined:"gameRoomJoined",party_game_room_left:"gameRoomLeft"}));function Ge(n){let e=De(n);if(e===null)return null;let t=go[e.type];if(t===void 0)return null;let r=e.data,i=O(r.party_id);if(typeof i!="string")return null;let o=ee(0,Number.MAX_SAFE_INTEGER)(r.version),s=O(r.game_room_id),a=O(r.game_id),d=O(r.inviter_player_id),l=R(80)(r.inviter_display_tag),p=R(64)(r.party_name);return {event:t,partyId:i,...o===void 0?{}:{version:o},...s===void 0?{}:{gameRoomId:s},...a===void 0?{}:{gameId:a},...d===void 0?{}:{inviterPlayerId:d},...l===void 0?{}:{inviterDisplayTag:l},...p===void 0?{}:{partyName:p}}}var re={now:()=>Date.now(),setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n)},te=class{constructor(e=re){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let t=Qe[e];if(t===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??t,s=Math.max(0,r-i),a=Math.min(t,o+s*t/6e4);return a<1?(this.tokens.set(e,a),this.lastRefill.set(e,r),false):(this.tokens.set(e,a-1),this.lastRefill.set(e,r),true)}};function Se(n,e){return n.toLowerCase()===e.toLowerCase()}function st(n){let e=n.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function Kn(n,e){if(typeof e!="string"||e==="")return false;let t,r;try{t=new URL(n),r=new URL(e);}catch{return false}return t.protocol!=="http:"&&t.protocol!=="https:"||r.protocol!=="http:"&&r.protocol!=="https:"||t.username!==""||t.password!==""||t.pathname!=="/"||t.search!==""||t.hash!==""||t.port===""?false:st(t.hostname)&&st(r.hostname)}function Ut(n,e){if(n.min>n.max||e.min>e.max)return null;let t=Math.min(n.max,e.max),r=Math.max(n.min,e.min);return t>=r?t:null}var fo=["universal","mobile"],yo={game_room_updated:"updated",game_room_match_started:"match_started",game_room_match_ready:"match_ready",game_room_match_failed:"match_failed",game_room_version_stale:"version_stale",match_ended:"updated",p2p_match_ended:"updated"},vo=new Set(["match_ended","p2p_match_ended"]),bo="game_room_auto_start_failed",wo=/^[a-z][a-z0-9_]{0,63}$/,je=64,ko=8,Ht=class{constructor(e,t){this.clock=e;this.limit=t;}clock;limit;windowStart=0;used=0;allow(){let e=this.clock.now();return e-this.windowStart>=1e3&&(this.windowStart=e,this.used=0),this.used>=this.limit?false:(this.used+=1,true)}};function dt(n){if(!(typeof n!="string"||n.length===0||n.length>je))return n}function So(n){return n instanceof Error?n.message:String(n)}function Vn(n,e){if(!n.has(e)){if(n.size>=ko){let t=n.values().next().value;t!==void 0&&n.delete(t);}n.add(e);}}function qt(){return new MessageChannel}var Ro=6e4/(Qe["gem.handshake"]??1),_o=6e4,Wt=class{constructor(e){this.options=e;if(!et(e.frameOrigin))throw new Error(`GemHost: frameOrigin must be a concrete origin, got '${e.frameOrigin}'. '*' and 'null' are refused \u2014 the handshake transfers the MessagePort, so an imprecise targetOrigin gives the session away.`);if(!et(e.embedderOrigin))throw new Error(`GemHost: embedderOrigin must be a concrete origin, got '${e.embedderOrigin}'.`);this.clock=e.clock??re,this.inbound=new te(this.clock),this.outbound=new te(this.clock),this.socketWindow=new Ht(this.clock,24);}options;state="idle";port=null;version=null;timeoutHandle=null;reofferHandle=null;makeChannel=qt;offered=[];offersMade=0;localDenials=0;chainEndsAt=null;gameId=null;peerCapabilities=[];knownMatches=new Set;askedMatches=new Set;clock;inbound;outbound;socketWindow;get currentState(){return this.state}get frameCapabilities(){return this.peerCapabilities}frameSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}start(e=qt){if(this.state!=="idle"){this.fail("handshake_duplicate",`cannot start from state '${this.state}'`);return}if(typeof e=="function")this.makeChannel=e;else if(e&&e.port1&&e.port2){let t=e,r=false;this.makeChannel=()=>r?qt():(r=true,t);}else throw new Error("GemHost.start: pass a function returning { port1, port2 } \u2014 omit it entirely to get a fresh MessageChannel per offer, which is what an embedder normally wants.");this.transition("handshaking"),this.offer(),this.scheduleReoffer(),this.timeoutHandle=this.clock.setTimeout(()=>{this.timeoutHandle=null,this.state==="handshaking"&&this.fail("handshake_timeout",`no answer from ${this.options.frameOrigin} to ${this.offersMade} handshake ${this.offersMade===1?"offer":"offers"} in the first ${jt}ms; the offers continue for as long as this page holds the frame. This page presented embedder origin ${this.options.embedderOrigin}. A frame answers none of them if it carries no bridge at all, if it has not started listening yet, or if that origin is missing from the embedders it will accept \u2014 this side cannot tell which, and does not try.`);},jt);}offer(){if(!this.outbound.allow("gem.handshake"))return false;let e=this.makeChannel(),t=e.port1;return t.onmessage=r=>this.receive(r.data,t),t.start?.(),this.offered.push({port:t,at:this.clock.now()}),this.offersMade+=1,this.options.frame.postMessage({gem:y,type:"gem.handshake",versions:{min:Z.min,max:Z.max},embedder:this.options.embedderOrigin,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}},this.options.frameOrigin,[e.port2]),true}scheduleReoffer(){this.reofferHandle=this.clock.setTimeout(()=>{this.reofferHandle=null,this.state==="handshaking"&&(this.offer(),this.pruneStaleOffers(),this.scheduleReoffer());},Ro);}pruneStaleOffers(){let e=this.clock.now()-_o;for(;this.offered.length>0&&(this.offered[0]?.at??e)<e;){let t=this.offered.shift();if(t===void 0)break;t.port.onmessage=null,t.port.close();}}adopt(e){for(let t of this.offered)t.port!==e&&(t.port.onmessage=null,t.port.close());this.offered.length=0,this.port=e;}static checkHandshakeOrigin(e,t,r){return Se(e.origin,t)?e.source!==r?"source is not the mounted frame":null:`origin '${e.origin}' is not the expected frame origin`}sendToken(e){if(!Number.isInteger(e.chainEndsAt)||e.chainEndsAt<0){this.fail("internal","refusing a grant whose chainEndsAt is not a whole number of seconds >= 0");return}let t=this.chainEndsAt??e.chainEndsAt;if(this.chainExpired()){this.fail("token_unavailable","token chain ceiling reached");return}this.send({gem:y,type:"gem.token",token:e.token,expiresAt:e.expiresAt,chainEndsAt:t,generation:e.generation,playerId:e.playerId,gameId:e.gameId,channel:e.channel,...e.gameVersion===void 0?{}:{gameVersion:e.gameVersion},...e.requestId===void 0?{}:{requestId:e.requestId},...e.apiBaseUrl===void 0?{}:{apiBaseUrl:e.apiBaseUrl},...e.allowDevTools===true?{allowDevTools:true}:{},...e.garden===void 0?{}:{garden:e.garden}})&&(this.chainEndsAt=t,this.gameId??=e.gameId);}relayRoomEvent(e){if(this.gameId===null||typeof e!="object"||e===null||Array.isArray(e))return false;let t=e;if(typeof t.type!="string")return false;let r=yo[t.type];if(r===void 0||typeof t.data!="object"||t.data===null||Array.isArray(t.data))return false;let i=t.data;if(i.game_id!==this.gameId)return false;let o=dt(i.game_room_id);if(o===void 0)return false;let s=vo.has(t.type)?void 0:dt(i.match_id);s!==void 0&&this.rememberMatch(s);let a=typeof i.version=="number"?i.version:void 0,d=typeof i.reason=="string"?i.reason.slice(0,je):void 0,l=r==="version_stale"&&fo.includes(i.platform)?i.platform:void 0;return this.sendRoomEvent({event:r,roomId:o,...s===void 0?{}:{matchId:s},...a===void 0?{}:{version:a},...d===void 0?{}:{reason:d},...l===void 0?{}:{platform:l}})}sendRoomEvent(e){return this.frameSupports("rooms")?this.send({gem:y,type:"gem.roomEvent",event:e.event,roomId:e.roomId,...e.matchId===void 0?{}:{matchId:e.matchId},...e.version===void 0?{}:{version:e.version},...e.reason===void 0?{}:{reason:e.reason},...e.platform===void 0?{}:{platform:e.platform}}):false}sendSocketState(e){return this.frameSupports("socketState")?this.send({gem:y,type:"gem.socketState",connected:e.connected,...e.connected?{}:{reason:e.reason}}):false}sendSeatedEvent(e){return this.frameSupports("partySeating")?this.send({gem:y,type:"gem.seatedEvent",roomId:e}):false}relaySeatedEvent(e){if(this.gameId===null)return false;let t=Ge(e);if(t===null||t.event!=="gameRoomJoined"||t.gameId!==this.gameId)return false;let r=dt(t.gameRoomId);return r===void 0?false:this.sendSeatedEvent(r)}sendAutoStartFailedEvent(e){return this.frameSupports("autoStartFailure")?this.send({gem:y,type:"gem.autoStartFailedEvent",roomId:e.roomId,code:e.code}):false}relayAutoStartFailedEvent(e){if(this.gameId===null||typeof e!="object"||e===null||Array.isArray(e))return false;let t=e;if(t.type!==bo||typeof t.data!="object"||t.data===null||Array.isArray(t.data))return false;let r=t.data;if(r.game_id!==this.gameId)return false;let i=dt(r.game_room_id),o=typeof r.code=="string"&&wo.test(r.code)?r.code:void 0;return i===void 0||o===void 0?false:this.sendAutoStartFailedEvent({roomId:i,code:o})}relaySocketEvent(e){let t=[];(this.relayRoomEvent(e)||this.relayAutoStartFailedEvent(e))&&t.push("room"),this.relaySignalEvent(e)&&t.push("signal"),this.relayDedicatedEvent(e)&&t.push("dedicated");let r=Ge(e);return r!==null&&(this.options.onPartyEvent?.(r),this.relaySeatedEvent(e),t.push("party")),t}relaySignalEvent(e){if(this.gameId===null)return false;let t=at(e,this.gameId,r=>this.knowsMatch(r));return t===null?false:(t.event==="hello"&&this.rememberMatch(t.matchId),this.sendSignalEvent(t))}sendSignalEvent(e){return this.frameSupports("p2p")?this.send({gem:y,type:"gem.signalEvent",event:e.event,matchId:e.matchId,data:e.data}):false}relayDedicatedEvent(e){if(this.gameId===null)return false;let t=it(e,this.gameId,r=>this.knowsMatch(r));return t===null?false:this.sendDedicatedEvent(t)}sendDedicatedEvent(e){return this.frameSupports("dedicated")?this.send({gem:y,type:"gem.dedicatedEvent",event:e.event,matchId:e.matchId,...e.sdp===void 0?{}:{sdp:e.sdp},...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.code===void 0?{}:{code:e.code},...e.message===void 0?{}:{message:e.message},...e.reason===void 0?{}:{reason:e.reason}}):false}knowsMatch(e){return this.knownMatches.has(e)||this.askedMatches.has(e)}rememberMatch(e){Vn(this.knownMatches,e);}rememberAsked(e){Vn(this.askedMatches,e);}answerPartyRequest(e,t){return this.send({gem:y,type:"gem.partyResult",requestId:e,...t===void 0?{}:{partyId:t}})}answerPurchase(e,t,r){return this.send({gem:y,type:"gem.purchaseResult",requestId:e,outcome:t,...r===void 0||t!=="ok"?{}:{purchaseId:r}})}answerDeviceSettingsPut(e,t){return this.send({gem:y,type:"gem.deviceSettings.result",requestId:e,outcome:t})}sendDeviceSettings(e){return this.frameSupports("deviceSettings")?this.send({gem:y,type:"gem.deviceSettings",...e===void 0?{}:{settings:e}}):false}answerAd(e,t){return this.send({gem:y,type:"gem.adResult",requestId:e,outcome:t})}answerSignIn(e,t){return this.send({gem:y,type:"gem.signInResult",requestId:e,outcome:t})}denyToken(e){this.send({gem:y,type:"gem.token.denied",requestId:e.requestId,retryable:e.retryable,reason:e.reason,correlationId:e.correlationId,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}});}grantLocalServer(e){return this.frameSupports("localHost")?this.send({gem:y,type:"gem.localServer",requestId:e.requestId,...e.serverId===void 0?{}:{serverId:e.serverId}}):false}denyLocalServer(e){return this.frameSupports("localHost")?this.send({gem:y,type:"gem.localServer.denied",requestId:e.requestId,retryable:e.retryable,reason:e.reason}):false}sendClusterTarget(e){let t=typeof e=="string"?[e]:e,r=Array.isArray(t)?t.length===0?"[]":t.find(o=>typeof o!="string"||o.trim().length===0||o.length>je):String(t);if(r!==void 0)return this.fail("internal",`refusing to send '${String(r)}' as a cluster target \u2014 each id must be a non-blank string of at most ${je} characters, and a list must name at least one. Omit the message entirely when there is no answer: the frame then names no cluster and gem-api chooses.`),false;if(t.length>3)return this.fail("internal",`refusing to send ${t.length} cluster targets \u2014 at most ${3} acceptable clusters cross, best first.`),false;if(!this.frameSupports("clusterTarget"))return false;let[i]=t;return this.send({gem:y,type:"gem.clusterTarget",clusterTargetId:i,...typeof e=="string"?{}:{clusterTargetIds:[...t]}})}sendPlayer(e){let{displayName:t,displayTag:r}=e.untrusted,i=e.badges?.map(({itemId:s,iconUrl:a})=>({itemId:s,iconUrl:a})),o=e.discriminator!==void 0&&/^[0-9]{1,8}$/.test(e.discriminator)?e.discriminator:void 0;this.send({gem:y,type:"gem.player",untrusted:{displayName:t,...r===void 0?{}:{displayTag:r},displayHandle:r??t},...e.playerId===void 0?{}:{playerId:e.playerId},...o===void 0?{}:{discriminator:o},...e.avatarIconUrl===void 0?{}:{avatarIconUrl:e.avatarIconUrl},...i===void 0?{}:{badges:i},displayTag:o??"",...e.avatarIconUrl===void 0?{}:{avatarUrl:e.avatarIconUrl}});}chainExpired(){return this.chainEndsAt!==null&&this.clock.now()/1e3>=this.chainEndsAt}localCorrelationId(){return `local-${++this.localDenials}`}sendPause(e){this.send({gem:y,type:"gem.pause",paused:e});}sendDevtools(e){this.send({gem:y,type:"gem.devtools",action:e});}requestScreenshot(e,t){return this.frameSupports("screenshot")?this.send({gem:y,type:"gem.screenshot",maxWidth:t.maxWidth,maxHeight:t.maxHeight},[e]):false}requestContext(){return this.frameSupports("feedbackContext")?this.send({gem:y,type:"gem.requestContext"}):false}sendPrefs(e){this.send({gem:y,type:"gem.prefs",...e});}sendCohorts(e){return this.frameSupports("cohorts")?this.send({gem:y,type:"gem.cohorts",cohorts:e.map(t=>({experimentId:t.experimentId,variantKey:t.variantKey}))}):false}sendViewport(e){return this.frameSupports("viewport")?this.send({gem:y,type:"gem.viewport",insets:{top:e.insets.top,right:e.insets.right,bottom:e.insets.bottom,left:e.insets.left}}):false}sendWillTerminate(e,t){this.send({gem:y,type:"gem.willTerminate",reason:e,graceMs:t});}close(){this.timeoutHandle!==null&&(this.clock.clearTimeout(this.timeoutHandle),this.timeoutHandle=null),this.reofferHandle!==null&&(this.clock.clearTimeout(this.reofferHandle),this.reofferHandle=null);for(let e of this.offered)e.port.onmessage=null,e.port.close();this.offered.length=0,this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="unsupported"&&this.transition("closed");}transition(e){this.state!==e&&(this.state=e,this.options.onStateChange?.(e));}fail(e,t){this.options.onError?.(e,t);}send(e,t){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let r=e.type;if(!this.outbound.allow(r))return this.fail("rate_limited",`parent exceeded its own limit for ${r}`),false;let i=se[r]?.(e);return i?(this.fail("internal",`refusing to send malformed ${r}: ${i}`),false):(t===void 0?this.port.postMessage({...e,v:this.version}):this.port.postMessage({...e,v:this.version},t),true)}receive(e,t){if(this.state==="closed"||this.state==="unsupported")return;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string"){this.refuseMalformed("invalid_message","message has no type");return}let i=se[r];if(!i){this.refuseMalformed("unsupported",`unknown message type ${JSON.stringify(r.slice(0,je))}`);return}if(!this.inbound.allow(r)){this.fail("rate_limited",`frame exceeded the limit for ${r}`);return}let o=Ze(r);if(o!==void 0&&!this.options.capabilities?.includes(o)){this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this parent did not advertise`);return}let s=i(e);if(s){this.fail("invalid_message",`${r}: ${s}`);return}let a=e;r!=="gem.handshake.accept"&&!this.versionMatches(a,r)||this.dispatch(r,a,t);}refuseMalformed(e,t){if(!this.inbound.allow(ye)){this.options.onDropped?.(e,t);return}this.fail(e,t);}versionMatches(e,t){return e.v===this.version?true:(this.fail("invalid_message",`${t}: expected v ${String(this.version)}, got ${String(e.v)}`),false)}forwardSignal(e){let t=this.options.onSendSignal;if(t===void 0){this.fail("unsupported","this parent advertised `p2p` but wired no onSendSignal, so signaling has nowhere to go");return}if(this.gameId===null){this.options.onDropped?.("internal","gem.signal before any token was issued");return}if(e.signal!=="join"&&!this.knownMatches.has(e.matchId)){this.fail("unsupported",`gem.signal names match '${e.matchId}', which this player's socket has not mentioned`);return}if(!this.socketWindow.allow()){this.fail("rate_limited","signaling exceeded this parent per-second socket budget");return}let r=ot(e.signal,e.matchId,this.gameId,e.data);if("reason"in r){this.fail("invalid_message",`gem.signal: ${r.reason}`);return}this.withinFrameSize("gem.signal",r.frame,"Trickle ICE candidates rather than gathering them into the offer.")&&(this.rememberAsked(e.matchId),t(r.frame));}forwardDedicatedOffer(e){let t=this.options.onSendSignal;if(t===void 0){this.fail("unsupported","this parent advertised `dedicated` but wired no onSendSignal, so the offer has nowhere to go");return}if(this.gameId===null){this.options.onDropped?.("internal","gem.dedicatedOffer before any token was issued");return}if(!this.socketWindow.allow()){this.fail("rate_limited","signaling exceeded this parent per-second socket budget");return}let r=rt(e.matchId,this.gameId,{sdp:e.sdp,intent:e.intent});if("reason"in r){this.fail("invalid_message",`gem.dedicatedOffer: ${r.reason}`);return}if(this.withinFrameSize("gem.dedicatedOffer",r.frame,"A complete gathered offer fits; one that does not is carrying media sections this path does not permit, or candidates from ICE servers this path does not use.")){this.rememberAsked(e.matchId);try{t(r.frame);}catch(i){this.sendDedicatedEvent({event:"error",matchId:e.matchId,code:"embedder_relay_unavailable",message:"the page could not put the offer on the player socket"}),this.fail("internal",`gem.dedicatedOffer: the socket refused the send: ${So(i)}`);}}}withinFrameSize(e,t,r){let i=JSON.stringify(t).length;return i<=16384?true:(this.fail("invalid_message",`${e} builds a ${i}-byte socket frame, over the ${16384}-byte limit gem-api enforces, so the socket would drop it and then fail to establish. ${r}`),false)}dispatch(e,t,r){if(e==="gem.handshake.accept"){if(this.state!=="handshaking"){this.fail("handshake_duplicate","handshake already settled");return}let i=t.v;if(i<Z.min||i>Z.max){this.transition("unsupported"),this.fail("version_mismatch",`frame chose v${i}, outside our supported range`),this.close();return}this.adopt(r),this.version=i,this.peerCapabilities=t.capabilities??[],this.timeoutHandle!==null&&(this.clock.clearTimeout(this.timeoutHandle),this.timeoutHandle=null),this.reofferHandle!==null&&(this.clock.clearTimeout(this.reofferHandle),this.reofferHandle=null),this.transition("connected");return}if(this.state!=="connected"){this.fail("invalid_message",`${e} received before the handshake completed`);return}switch(e){case "gem.ready":this.options.onReady?.();break;case "gem.progress":this.options.onProgress?.(t);break;case "gem.requestToken":{let i=t;if(this.chainExpired()){this.denyToken({requestId:i.requestId,retryable:false,reason:"chain_exhausted",correlationId:this.localCorrelationId()});break}this.options.onRequestToken?.(i);break}case "gem.requestLocalServer":{this.options.onRequestLocalServer?.(t);break}case "gem.exit":this.options.onExit?.(t),this.close();break;case "gem.openExternal":this.options.onOpenExternal?.(t);break;case "gem.requestFullscreen":this.options.onRequestFullscreen?.(t);break;case "gem.audioState":this.options.onAudioState?.(t);break;case "gem.rewardCue":this.options.onRewardCue?.(t);break;case "gem.frameStats":this.options.onFrameStats?.(t);break;case "gem.screenshot.denied":this.options.onScreenshotDenied?.(t);break;case "gem.gameContext":this.options.onGameContext?.(t);break;case "gem.signal":this.forwardSignal(t);break;case "gem.dedicatedOffer":this.forwardDedicatedOffer(t);break;case "gem.partyRequest":{let i=t;if(this.options.onPartyRequest===void 0){this.answerPartyRequest(i.requestId);break}this.options.onPartyRequest(i);break}case "gem.requestPurchase":{let i=t;if(!this.frameSupports("purchases")){this.fail("unsupported_capability","refusing gem.requestPurchase: the frame did not advertise 'purchases', so it cannot receive gem.purchaseResult. Nothing was prompted and nothing was spent.");break}if(this.options.onRequestPurchase===void 0){this.answerPurchase(i.requestId,"unavailable");break}this.options.onRequestPurchase(i);break}case "gem.deviceSettings.put":{let i=t;if(!this.frameSupports("deviceSettings")){this.fail("unsupported_capability","refusing gem.deviceSettings.put: the frame did not advertise 'deviceSettings', so it cannot receive gem.deviceSettings.result. Nothing was stored.");break}if(this.options.onDeviceSettingsPut===void 0){this.answerDeviceSettingsPut(i.requestId,"unavailable");break}this.options.onDeviceSettingsPut(i);break}case "gem.requestAd":{let i=t;if(!this.frameSupports("ads")){this.fail("unsupported_capability","refusing gem.requestAd: the frame did not advertise 'ads', so it cannot receive gem.adResult. Nothing was rendered.");break}if(this.options.onRequestAd===void 0){this.answerAd(i.requestId,"no_ad");break}this.options.onRequestAd(i);break}case "gem.requestSignIn":{let i=t;if(!this.frameSupports("signIn")){this.fail("unsupported_capability","refusing gem.requestSignIn: the frame did not advertise 'signIn', so it cannot receive gem.signInResult. Nothing was rendered.");break}if(this.options.onRequestSignIn===void 0){this.answerSignIn(i.requestId,"unavailable");break}this.options.onRequestSignIn(i);break}case "gem.error":this.fail(t.code,t.message);break;default:this.fail("unsupported",`no parent handler for '${e}'`);}}};var W=class{#e;constructor(e){this.#e=e,Object.freeze(this);}toString(){return "[gem: use gem.text.toPlain()]"}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function le(n){return new W(n)}var Eo={toPlain(n){return W.unwrap(n)},compare(n,e,t){let r=n instanceof W?W.unwrap(n):n,i=e instanceof W?W.unwrap(e):e,o;try{o=new Intl.Collator(t);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(n,e){let t=n instanceof W?W.unwrap(n):n,r=e instanceof W?W.unwrap(e):e;return t.normalize("NFC")===r.normalize("NFC")}};function Bn(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function Jn(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function To(n){let e=n.untrusted,t=le(e.displayName),r=e.displayTag||e.displayHandle,i=r?le(r):void 0,o=n.discriminator||n.displayTag,s=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,a=n.avatarIconUrl||n.avatarUrl,d={displayName:t,displayHandle:i??t,badges:(n.badges??[]).map(l=>({itemId:l.itemId,iconUrl:l.iconUrl}))};return n.playerId&&(d.playerId=n.playerId),s&&(d.discriminator=s),i&&(d.displayTag=i),a&&(d.avatarIconUrl=d.avatarUrl=a),d}var xo=1e4,Kt=class{constructor(e){this.options=e;if(e.expectedSource===void 0||e.expectedSource===null)throw new Error("GemFrame: expectedSource is required and must not be null \u2014 pass window.parent. The handshake transfers the MessagePort, and origin alone does not say WHICH document on that origin sent it.");this.expectedSource=e.expectedSource,this.clock=e.clock??re,this.inbound=new te(this.clock),this.outbound=new te(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(a=>Se(a,e.origin))||Kn(e.origin,this.options.selfOrigin)))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=se["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!Se(i.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${i.embedder}' but arrived from '${e.origin}'`),false;let o=e.ports?.[0];if(!o)return this.refuse(e,"handshake transferred no MessagePort"),false;let s=Ut(Z,i.versions);return s===null?(o.onmessage=null,o.postMessage({gem:y,type:"gem.error",code:"version_mismatch",message:`frame supports v${Z.min}..v${Z.max}`}),o.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=o,this.version=s,o.onmessage=a=>this.receive(a.data,a.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],o.postMessage({gem:y,type:"gem.handshake.accept",v:s,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:y,type:"gem.ready"});}settled(e=xo){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(t=>{let r=o=>{this.clock.clearTimeout(i),t(o);},i=this.clock.setTimeout(()=>{let o=this.settleWaiters.indexOf(r);o>=0&&this.settleWaiters.splice(o,1),t(this.state);},e);this.settleWaiters.push(r);})}progress(e,t){this.send({gem:y,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:y,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:y,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),true):false}exit(e){this.send(e===void 0?{gem:y,type:"gem.exit"}:{gem:y,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:y,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:y,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:y,type:"gem.audioState",muted:e}),true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let t={gem:y,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(t.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(t.origin={x:Bn(e.origin.x),y:Bn(e.origin.y)}),this.send(t),true}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:y,type:"gem.frameStats",fps:Jn(e.fps,1e3),frameTimeP95Ms:Jn(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:y,type:"gem.gameContext",context:e}),true)}signal(e,t,r){this.send({gem:y,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:y,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:y,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,i,o,s){return this.send({gem:y,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...s===void 0?{}:{catalogId:s}})}putDeviceSettings(e,t){return this.send({gem:y,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:y,type:"gem.requestAd",requestId:e,placement:t,format:r})}requestSignIn(e){return this.send({gem:y,type:"gem.requestSignIn",requestId:e})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let t of this.settleWaiters.splice(0))t(e);this.options.onStateChange?.(e);}}refuseMalformed(e,t){if(!this.inbound.allow(ye)){this.options.onDropped?.(e,t);return}this.fail(e,t);}dropUnknownType(e){this.inbound.allow(ye)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,t){e.ports?.[0]?.close?.(),this.inbound.allow(ye)&&this.options.onRefused?.(t);}fail(e,t){this.options.onError?.(e,t),this.state==="connected"&&this.port&&this.send({gem:y,type:"gem.error",code:e,...t===void 0?{}:{message:t}});}send(e){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let t=e.type;if(!this.outbound.allow(t))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${t}`),false;let r=se[t]?.(e);return r?(this.options.onError?.("internal",`refusing to send malformed ${t}: ${r}`),false):(this.port.postMessage(this.version===null?e:{...e,v:this.version}),true)}receive(e,t=[]){let r=false;try{r=this.dispatchInbound(e,t);}finally{r||Xn(t);}}dispatchInbound(e,t){if(this.state!=="connected")return false;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string")return this.refuseMalformed("invalid_message","message has no type"),false;let i=se[r];if(!i)return this.dropUnknownType(r),false;if(!this.inbound.allow(r))return this.fail("rate_limited",`parent exceeded the limit for ${r}`),false;let o=Ze(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let s=i(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(a);break;case "gem.pause":this.options.onPause?.(a);break;case "gem.prefs":this.options.onPrefs?.(a);break;case "gem.cohorts":this.options.onCohorts?.(a);break;case "gem.viewport":this.options.onViewport?.(a);break;case "gem.willTerminate":this.options.onWillTerminate?.(a);break;case "gem.devtools":this.options.onDevtools?.(a.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let d=t[0];if(!d){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let l={maxWidth:a.maxWidth,maxHeight:a.maxHeight};if(!this.options.onScreenshot){d.close(),this.screenshotDenied("not_wired",false);break}return Xn(t.slice(1)),this.options.onScreenshot(l,d,(p,u)=>this.screenshotDenied(p,u)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer":this.options.onLocalServer?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{this.options.onPlayer?.(To(a));break}case "gem.roomEvent":this.options.onRoomEvent?.(a);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(a);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(a);break;case "gem.socketState":this.options.onSocketState?.(a);break;case "gem.signalEvent":this.options.onSignalEvent?.(a);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(a);break;case "gem.clusterTarget":this.options.onClusterTarget?.(a);break;case "gem.partyResult":this.options.onPartyResult?.(a);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(a);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(a);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(a);break;case "gem.adResult":this.options.onAdResult?.(a);break;case "gem.signInResult":this.options.onSignInResult?.(a);break;case "gem.error":this.options.onError?.(a.code,a.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,t){this.send({gem:y,type:"gem.screenshot.denied",reason:e,retryable:t});}};function Xn(n){for(let e of n)try{e?.close?.();}catch{}}var Io=16384;function Ao(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e;try{e=JSON.stringify(n);}catch{return null}return typeof e!="string"?null:Co(e)}function Co(n){let e=0;for(let t=0;t<n.length;t+=1){let r=n.charCodeAt(t);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let i=n.charCodeAt(t+1);i>=56320&&i<=57343?(e+=4,t+=1):e+=3;}else e+=3;}return e}var Yn=["p2p","dedicated","unknown"],lt=["connection_setup_duration_seconds","reconnect_latency_seconds","datachannel_rtt_seconds","p2p_join_to_play_latency_seconds","ice_restart_outcome_total","connection_failures_total","transport_permanent_failures_total","transport_quality_score","host_migration_outcome_total","turn_relay_usage_ratio"];var ce=class{constructor(e){this.options=e;}options;async post(e,t){let r=this.options.gameId();if(r===null||r==="")return;let i=Po(e,this.options.transport,(this.options.now??Date.now)());i.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:i},t);}report(e){this.post(e).catch(()=>{});}};function Po(n,e,t){let r=Math.floor(t/1e3);return n.filter(i=>lt.includes(i.type)).slice(0,100).map(i=>{let o=Mo(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function Mo(n){if(n!==void 0)return Yn.includes(n)?n:"unknown"}function Vt(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}var H=class extends Error{constructor(t,r,i,o,s){super(`${t} (${r}): ${i}`);this.reason=t;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=s;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}};var Oo=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),c=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="DedicatedServerError",this.retryable=Oo.has(t),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var zn=["explicit","stale_cleanup","game_room_closed","replaced","migration_failed","host_left","insufficient_players","all_left","expired","migration_rate_exceeded","game_room_gone","failed","idle","reclaimed"],Do=new Set(zn);function Re(n){return typeof n=="string"&&Do.has(n)?n:"unknown"}var Fe="webrtc_dedicated",Jt=["universal","mobile","web"];var Go="p2p_unavailable",jo="capacity_unavailable",Fo=2,Qn=3e4,Zn=1e3,er=2e4;async function ct(n){let e=q(n.clusterTargetId),t=n.nextClusterTarget,r=0,i=n.clock??re,o=n.retry??{},s=o.budgetMs??Qn,a=o.maxDelayMs??er,d=o.initialDelayMs??Zn,l=i.now(),p=l+s,u=0;for(;;){u++;try{let h=await Yt(n.signal,"while allocating",()=>n.client.post(`${rr(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:h.match_id,status:h.status}}catch(h){if(!No(h)||s<=0)throw h;if(h.status===503&&h.code===Go)throw new c("p2p_unavailable",`room ${n.roomId} starts a peer-to-peer match, which allocates no server \u2014 so this refusal is not capacity and waiting cannot help: ${h.message}`,{cause:h});if(r=h.code===jo?r+1:0,t!==void 0&&r>=Fo){let M=t;t=void 0;let C=q(await M());C!==void 0&&(e=C,r=0);}let g=Math.min(a,d*2**(u-1)),f=Math.min(a,(h.retryAfterSeconds??0)*1e3),I=Math.max(g/2,f)+Math.random()*(g/2);if(i.now()+I>p)throw $o(n,h,u,i.now()-l,s);if(o.onWaiting?.({attempt:u,elapsedMs:i.now()-l,budgetMs:s,nextAttemptInMs:I,status:h.status,message:h.message}),await pt(i,I,n.signal),n.signal?.aborted)throw Bt("while waiting to allocate")}}}function No(n){return n instanceof H?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function $o(n,e,t,r,i){let o=`${t} attempt${t===1?"":"s"} over ${r}ms of a ${i}ms budget`;return e.status===429?new c("start_rate_limited",`the platform was still limiting match starts for room ${n.roomId} after ${o}: ${e.message}`,{cause:e}):new c("no_server_ready",`the platform had no server ready for room ${n.roomId} after ${o}: ${e.message}`,{cause:e})}var Uo=12e4,qo=1e3;async function ut(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??qo,i=n.timeoutMs??Uo,o=e.now()+i,s=tr(n),a={seen:n.knownToExist===true};for(;;){let d=await nr(n,s,a);if(d.outcome!==null)return d.outcome;if(e.now()+r>o)throw new c("timeout",`match ${t} was still ${d.status} after ${i}ms`);await pt(e,r,n.signal);}}async function Xt(n){return (await nr(n,tr(n),{seen:n.knownToExist===true})).outcome}function tr(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${rr(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function nr(n,e,t){let{matchId:r}=n,i=n.clock.now(),o;try{o=await Yt(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(s){if(s instanceof H&&s.reason==="not_found")return {status:"not_found",outcome:t.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(t.seen=true,o.status==="ready")return {status:"ready",outcome:Ho(r,o,i)};if(o.status==="failed"){let s=o.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Re(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function mt(n){let e=await Yt(n.signal,"while listing cluster targets",()=>n.client.get("/v1/ping/targets",n.signal)),t=[];for(let r of e.targets??[]){let i=r?.cluster_target_id;typeof i!="string"||i.length===0||t.push({id:i,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return t}async function Yt(n,e,t){if(n?.aborted)throw Bt(e);try{return await t()}catch(r){throw n?.aborted?Bt(e,r):r}}function Bt(n,e){return new c("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function Ho(n,e,t){let r=e.join_credential,i=e.expires_in_seconds,o=typeof r=="string"&&typeof i=="number";return {status:"ready",matchId:n,protocol:e.protocol??"unknown",...o?{joinCredential:r,credentialExpiresAt:t+i*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function rr(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function pt(n,e,t){return t?.aborted?Promise.resolve():new Promise(r=>{let i=()=>{n.clearTimeout(o),t?.removeEventListener("abort",i),r();},o=n.setTimeout(i,e);t?.addEventListener("abort",i);})}var Wo=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),Qt="embedder_relay_unavailable",Ko="embedder_no_relay",Vo=new Set([Qt]),Zt=new Set([Ko]),ht=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new zt(this)}handleEvent(e){let t=this.pending.get(e.matchId);if(t!==void 0){if(e.event==="matchEnded"){t.refuse(new c("match_ended",`the match ended while the offer was in flight (${e.reason??"no reason given"}), so no server is left to answer it`));return}if(e.event==="answer"){if(typeof e.sdp!="string"||e.sdp.length===0){t.refuse(new c("signaling_failed","the parent relayed an answer with no SDP in it"));return}t.settle({sdp:e.sdp});return}t.refuse(Bo(e.code,e.message));}}register(e,t){this.pending.get(e)?.refuse(new c("signaling_failed","a newer offer for this match superseded the one in flight")),this.pending.set(e,t);}release(e,t){this.pending.get(e)===t&&this.pending.delete(e);}transport(){let e=this.options.bridge;if(e===null)throw new c("signaling_unavailable","this game is not running inside a page that holds the player's notification socket, so there is nothing to carry an offer. Dedicated signaling needs that socket and only the page can hold one \u2014 see public-docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new c("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See public-docs/dedicated-server-flow.md \xA72.");return e}};function Bo(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new c(Jo(n),r,{platformCode:n})}function Jo(n){return n===void 0||Vo.has(n)?"signaling_failed":Zt.has(n)?"offer_refused":Wo.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var zt=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,t){if(this.closed)return Promise.reject(new c("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(i){return Promise.reject(i)}return t?.aborted?Promise.reject(new c("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let s=()=>{a(),o(new c("aborted","the caller aborted the signaling exchange"));},a=()=>{t?.removeEventListener("abort",s),this.hub.release(e.matchId,d),this.teardown===a&&(this.teardown=null);},d={settle:l=>{a(),i(l);},refuse:l=>{a(),o(l);}};this.teardown=a,t?.addEventListener("abort",s),this.hub.register(e.matchId,d);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(l){d.refuse(l instanceof c?l:new c("signaling_failed",l instanceof Error?l.message:String(l),{cause:l}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var ir="match_ended:",or="server_shutdown:",ar="kicked:",Xo=123;function Yo(n){if(typeof n!="string"||n.length===0||n.length>Xo)return {kind:"other"};if(n.startsWith(ir)){let e=Re(n.slice(ir.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(or)?{kind:"server_shutdown",cause:n.slice(or.length)}:n.startsWith(ar)?{kind:"kicked",detail:n.slice(ar.length)}:{kind:"other"}}function en(n,e,t){let r=Yo(t),i=r.kind==="kicked"?"kicked":"link_closed";n.notifyMatchDisconnected(i).catch(()=>{}),r.kind==="match_ended"&&n.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}var zo="join",Qo="welcome",Zo="rejected",tn=25e3,ea=1e3,nn=1;function rn(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var ta={credential_expired:"credential_expired",credential_reused:"credential_reused",credential_timeout:"timeout",join_rate_limited:"join_rate_limited",expected_join:"join_refused",invalid_credential:"join_refused",credential_not_for_this_channel:"join_refused"};function on(n){let e=typeof n=="string"?n:"unknown";return new c(ta[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function Ne(n){let{channel:e,clock:t}=n;return new Promise((r,i)=>{let o=false,s=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??tn),a=t.setTimeout(()=>x(new c("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(s,ea)),d=I=>{let M=I.data;if(typeof M!="string"){u(M);return}let C;try{C=JSON.parse(M);}catch{u(M);return}if(o){u(M);return}if(C.t===Qo){let m=rn(C.heartbeat_interval);f({...typeof C.player_id=="string"?{playerId:C.player_id}:{},...typeof C.match_id=="string"?{matchId:C.match_id}:{},...m===void 0?{}:{heartbeatIntervalMs:m}});return}if(C.t===Zo){x(on(C.reason));return}u(M);},l=()=>{x(new c("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},p=()=>{x(new c("aborted","the caller aborted during the join exchange"));},u=I=>{o&&n.onMessage?.(I);},h=()=>{t.clearTimeout(a),e.removeEventListener("close",l),n.signal?.removeEventListener("abort",p);},g=()=>{e.removeEventListener("message",d);},f=I=>{o=true,h(),n.onMessage===void 0&&g(),r({welcome:I,detach:g});},x=I=>{o||(o=true,h(),g(),i(I));};if(e.addEventListener("message",d),e.addEventListener("close",l),n.signal?.aborted){p();return}n.signal?.addEventListener("abort",p);try{e.send(JSON.stringify({t:zo,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:nn}:{}}));}catch(I){x(new c("connection_failed",`the join frame could not be sent on the open channel: ${String(I)}`,{cause:I}));}})}function gt(){return {exchange(){return Promise.reject(new c("signaling_unavailable","no signaling channel is wired. The exchange rides the notification WebSocket, and POST /v1/ws/ticket accepts only account credentials \u2014 a game frame holds a game-scoped token and cannot mint one \u2014 so it has to be relayed by the page embedding this game. Run inside a parent that advertises `dedicated`, or pass your own `signaling` implementation. See public-docs/dedicated-server-flow.md \xA72."))},close(){}}}var ue=1,$e=2,an=4,ln=8,na=2,ra=1e3,cn="heartbeat timeout",ft="gem-uu",yt=2,dr="gem_transports";function Ue(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!ia(r)||e.includes(r)||e.push(r);}return e}function ia(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function vt(n,e){if(typeof n!="object"||n===null)return null;let t=n[dr];if(typeof t!="object"||t===null)return null;let r=t;return typeof r.v!="number"||r.v<1||typeof r.host!="string"||typeof r.port!="number"||e!==void 0&&r.match_id!==e?null:r}function bt(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var lr=new TextEncoder,cr=new TextDecoder;function un(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function mn(n){let e=0;return n?.reliable===false&&(e|=ue),n?.ordered===false&&(e|=$e),e}function pn(n){return {reliable:(n&ue)===0,ordered:(n&$e)===0}}var hn={reliable:true,ordered:true};function ur(n){return JSON.stringify({t:"join",credential:n,wire:yt,heartbeat:nn})}function mr(n){let e;try{e=JSON.parse(n);}catch{throw new c("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let t=rn(e.heartbeat_interval);return {...e.player_id===void 0?{}:{playerId:e.player_id},...e.match_id===void 0?{}:{matchId:e.match_id},...t===void 0?{}:{heartbeatIntervalMs:t}}}throw e.t==="rejected"?on(e.reason):new c("join_refused","the server answered the join out of protocol")}function gn(){return typeof globalThis.WebTransport=="function"&&fn===null}function wt(){return fn}var fn=null;var sr="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function oa(n){let e=Vt(n);if(e.byteLength!==32)throw new c("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var sn=class{buffered=new Uint8Array(0);push(e){let t=new Uint8Array(this.buffered.byteLength+e.byteLength);t.set(this.buffered,0),t.set(e,this.buffered.byteLength),this.buffered=t;let r=[];for(;!(this.buffered.byteLength<4);){let o=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(o===0||o>1<<20)throw new c("connection_failed",`a control-stream record claims ${o} bytes`);if(this.buffered.byteLength<4+o)break;let s=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:s[0]??0,payload:s.slice(1)});}return r}};function dn(n,e){let t=new Uint8Array(5+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength+1,true),t[4]=n,t.set(e,5),t}async function qe(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webTransport;if(t===void 0){let a=globalThis.WebTransport;if(a===void 0)throw new c("connection_failed","this environment has no WebTransport");t=n.certHashBase64===void 0?new a(n.url):new a(n.url,{serverCertificateHashes:[{algorithm:"sha-256",value:oa(n.certHashBase64)}]});}let r=t,i=a=>{try{r.close();}catch{}throw a},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(fn=sr,i(new c("connection_failed",`${sr}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,d)=>{setTimeout(()=>d(new c("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,s]);let a=r.incomingBidirectionalStreams.getReader(),d=await Promise.race([a.read(),s]);if(a.releaseLock(),d.done||d.value===void 0)return i(new c("connection_failed","the session ended before the control stream arrived"));let l=d.value,p=l.writable.getWriter();await p.write(dn(an,lr.encode(ur(n.credential))));let u=new sn,h=l.readable.getReader(),g;for(;g===void 0;){let f=await Promise.race([h.read(),s]);if(f.done||f.value===void 0)return i(new c("connection_failed","the control stream closed before the join was answered"));for(let x of u.push(f.value)){g=mr(cr.decode(x.payload));break}}return {link:aa(r,p,h,u,n.log??(f=>console.warn(f)),hr(g,n.clock)),welcome:g}}catch(a){return i(a)}}function aa(n,e,t,r,i,o){let s,a,d=false,l=f=>{if(!d){d=true,p.stop();try{n.close();}catch{}a?.(f);}},p=vn(o,()=>l(cn)),u=(f,x)=>{p.heard(),(f&ln)===0&&s!==void 0&&((f&an)!==0?s(cr.decode(x),hn):s(x,pn(f)));};(async()=>{try{for(;;){let f=await t.read();if(f.done||f.value===void 0)break;for(let x of r.push(f.value))u(x.flags,x.payload);}}catch{}l("stream closed");})();let h,g;try{let f=n.datagrams;if(f?.readable!==void 0&&f.writable!==void 0){let x=f.readable.getReader();g=f.writable.getWriter(),h=f,(async()=>{try{for(;;){let I=await x.read();if(I.done||I.value===void 0)break;let M=I.value;M.byteLength!==0&&u((M[0]??0)|ue|$e,M.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(f){h=void 0,g=void 0,i(`[gem] webtransport datagram lane unusable (${bt(f)}); unreliable sends ride the stream`);}return n.closed.then(f=>l(pr(f?.reason)??"session closed"),()=>l("session failed")),{transport:"webtransport",send(f,x){if(d)return;if(typeof f=="string"){e.write(dn(an,lr.encode(f))).catch(()=>l("write failed"));return}let I=mn(x);if((I&ue)!==0&&g!==void 0){let M=un(I,f),C=h?.maxDatagramSize;if(C===void 0||M.byteLength<=C){g.write(M).catch(()=>{});return}}e.write(dn(I,f)).catch(()=>l("write failed"));},onMessage(f){s=f;},onClose(f){a=f;},close(){l("closed");}}}function yn(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webSocket;if(t===void 0){let i=globalThis.WebSocket;if(i===void 0)return Promise.reject(new c("connection_failed","this environment has no WebSocket"));t=new i(n.url);}let r=t;return r.binaryType="arraybuffer",new Promise((i,o)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),o(new c("timeout","websocket did not come up in time")));},e),d=g=>{s||(s=true,clearTimeout(a),r.close(),o(g));},l=()=>{r.send(ur(n.credential));},p=g=>{if(s)return;if(typeof g.data!="string"){d(new c("join_refused","the server sent binary before answering the join"));return}let f;try{f=mr(g.data);}catch(x){d(x);return}s=true,clearTimeout(a),r.removeEventListener("open",l),r.removeEventListener("message",p),r.removeEventListener("close",u),r.removeEventListener("error",h),i({link:sa(r,hr(f,n.clock)),welcome:f});},u=()=>{d(new c("connection_failed","the websocket closed before the join was answered"));},h=()=>{d(new c("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",l),r.addEventListener("message",p),r.addEventListener("close",u),r.addEventListener("error",h),r.readyState===1&&l();})}function pr(n){return typeof n=="string"&&n.length>0?n:void 0}function hr(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function vn(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,ra)*na,i=t.now(),o=null,s=()=>{o=null;let a=t.now()-i;if(a>=r){e();return}o=t.setTimeout(s,r-a);};return o=t.setTimeout(s,r),{heard:()=>{i=t.now();},stop:()=>{o!==null&&(t.clearTimeout(o),o=null);}}}function sa(n,e){let t,r,i=false,o=a=>{if(!i){i=true,s.stop();try{n.close();}catch{}r?.(a);}},s=vn(e,()=>o(cn));return n.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){t?.(a.data,hn);return}let d=new Uint8Array(a.data);if(d.byteLength===0)return;let l=d[0]??0;(l&ln)===0&&t?.(d.slice(1),pn(l));})),n.addEventListener("close",(a=>o(pr(a?.reason)??"socket closed"))),{transport:"websocket",send(a,d){if(!i){if(typeof a=="string"){n.send(a);return}n.send(un(mn(d),a));}},onMessage(a){t=a;},onClose(a){r=a;},close(){o("closed");}}}function bn(n,e,t,r){let i,o,s=false,a=t,d=u=>{if(!s){s=true,l.stop();try{n.close();}catch{}try{e.close();}catch{}o?.(u);}},l=vn(r,()=>d(cn)),p=(u,h)=>{if(l.heard(),typeof u=="string"){i?.(u,hn);return}let g=new Uint8Array(u);if(g.byteLength===0)return;let f=g[0]??0;(f&ln)===0&&i?.(g.slice(1),pn(f|h));};if(n.addEventListener("message",(u=>p(u.data,0))),n.addEventListener("close",(()=>d("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let u=e.connectionState;(u==="failed"||u==="closed")&&d(`connection ${u}`);})),a!==void 0){let u=a;u.addEventListener("message",(h=>p(h.data,ue|$e))),u.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(u,h){if(s)return;if(typeof u=="string"){n.send(u);return}let g=mn(h),f=un(g,u);if((g&ue)!==0&&a!==void 0&&a.readyState==="open"){a.send(f);return}n.send(f);},onMessage(u){i=u;},onClose(u){o=u;},close(){d("closed");}}}var gr=10240,fr=2048,da=new TextEncoder;function yr(n){return da.encode(n).length}function ie(n,e){let t=i=>{throw new c("invalid_sdp",`the ${e} ${i}`)},r=yr(n);r>=gr&&t(`is ${r} bytes, over the ${gr} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),n.startsWith("v=")||t("does not start with 'v=', so it is not SDP"),n.includes("\0")&&t("contains a null byte"),/\r(?!\n)/.test(n)&&t("contains a bare carriage return");for(let i of n.split(/\r\n|\n/)){let o=yr(i);o>fr&&t(`has a ${o}-byte line, over the ${fr} limit`);}}function kt(n){for(let e of n.split(/\r\n|\n/)){if(!e.startsWith("m="))continue;let[t,r="0"]=e.slice(2).trim().split(/\s+/);if(!(t!=="audio"&&t!=="video")&&r.split("/")[0]!=="0")return true}return false}var la=3e3,ca=1e4,ua=15e3;async function He(n){let e=n.peerConnection;try{br(n,"before the handshake started"),wn(n);let t=e.createDataChannel(n.channelLabel??"gem",{ordered:!0});for(let s of n.extraChannels??[]){let a=e.createDataChannel(s.label,{...s.ordered===void 0?{}:{ordered:s.ordered},...s.maxRetransmits===void 0?{}:{maxRetransmits:s.maxRetransmits}});n.onExtraChannel?.(s.label,a);}let r=await e.createOffer();await e.setLocalDescription(r),await ha(e,n),wn(n);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new c("invalid_sdp","the offer carried no SDP");ie(i,"offer"),vr(i,"offer");let o=await pa(n,i);if(wn(n),typeof o?.sdp!="string")throw new c("invalid_sdp","the signaling channel answered without an SDP");return ie(o.sdp,"answer"),vr(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await ga(t,n),br(n,"before the channel opened"),t}catch(t){throw e.close(),ma(t)}}function ma(n){return n instanceof c?n:Sr(n)?me():new c("connection_failed",Rr(n),{cause:n})}function vr(n,e){if(kt(n))throw new c("media_refused",`the ${e} carries an active audio or video section. This path carries a data channel only; voice belongs to the platform voice service.`)}async function pa(n,e){let t=n.exchangeTimeoutMs??ca,r=kr(n,t),i=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(o=>{throw o instanceof c?o:Sr(o)?me():new c("signaling_failed",Rr(o),{cause:o})});return fa(i,n,r,()=>r.exhausted?kn("while the offer was in flight"):new c("timeout",`no answer arrived within ${t}ms`))}function ha(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let i=()=>{t.clearTimeout(s),n.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{n.iceGatheringState==="complete"&&i();},s=t.setTimeout(i,e.gatherTimeoutMs??la);n.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function ga(n,e){if(e.signal?.aborted)return Promise.reject(me());if(n.readyState==="open")return Promise.resolve();if(n.readyState!=="connecting")return Promise.reject(new c("connection_failed",`the data channel was already '${n.readyState}' when the answer was applied`));let{clock:t}=e,r=e.openTimeoutMs??ua,i=kr(e,r);return new Promise((o,s)=>{let a=()=>{t.clearTimeout(h),n.removeEventListener("open",d),n.removeEventListener("close",l),n.removeEventListener("error",l),e.signal?.removeEventListener("abort",p);},d=()=>{a(),o();},l=g=>{a(),s(new c("connection_failed","the data channel failed before it opened",wr(g)===void 0?void 0:{cause:wr(g)}));},p=()=>{a(),s(me());},u=()=>{a(),s(i.exhausted?kn("while the channel was still opening"):new c("timeout",`the data channel did not open within ${r}ms`));},h=t.setTimeout(u,i.ms);n.addEventListener("open",d),n.addEventListener("close",l),n.addEventListener("error",l),e.signal?.addEventListener("abort",p);})}function kr(n,e){if(n.credentialExpiresAt===void 0)return {ms:e,exhausted:false};let t=n.credentialExpiresAt-n.clock.now();return t<=e?{ms:Math.max(0,t),exhausted:true}:{ms:e,exhausted:false}}function fa(n,e,t,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(me()):new Promise((s,a)=>{let d=u=>{i.clearTimeout(p),o?.removeEventListener("abort",l),u();},l=()=>d(()=>a(me())),p=i.setTimeout(()=>d(()=>a(r())),t.ms);o?.addEventListener("abort",l),n.then(u=>d(()=>s(u)),u=>d(()=>a(u)));})}function br(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw kn(`already ${e}`)}function kn(n){return new c("credential_expired",`the join credential ran out ${n} \u2014 poll match status again for a fresh one`)}function wn(n){if(n.signal?.aborted)throw me()}function me(){return new c("aborted","the caller aborted the connection attempt")}function Sr(n){return n?.name==="AbortError"}function wr(n){return n?.error}function Rr(n){return n instanceof Error?n.message:String(n)}var We="0.1.0-beta",_r="0-beta",_e="web",ya=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;function va(n){let e=ya.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function Er(n,e){let t=ba(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:We};let i=va(r);if(i===null)throw new c("misconfigured",`${e} refused: engineVersion '${r}' is not semver, so no engine line can be derived from it and gem-api answers 400. Omit it \u2014 a browser game has no engine version of its own, and the SDK reports '${We}' for it.`);if(i!==_r)throw new c("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${_r}' is the only line a web dedicated-server fleet runs. gem-api uses the line \u2014 the semver major plus any prerelease tag \u2014 verbatim as the fleet's label selector, so a match on '${i}' would match nothing and be reported as a capacity shortfall rather than as this. Omit engineVersion: a browser game has no engine version of its own, and the SDK reports '${We}' for it.`);return {...n,platform:t,engineVersion:r}}function ba(n,e){if(n===void 0||n===_e)return _e;if(!Jt.includes(n))throw new c("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${Jt.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${_e}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${_e}' and is deprecated \u2014 remove the field. A browser game publishes its bundle in the web package dimension, so a client reporting anything else is version-checked against a dimension it has nothing in, and every blacklist, release and expiry check passes without looking at this build.`),_e}function wa(n){let{client:e,clock:t,rooms:r}=n,i=n.signaling??gt,o=n.log??(m=>console.warn(m)),s=new ce({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,d=(m,b)=>{let S=a.get(m)??new Set;S.add(b),a.set(m,S);},l=(m,b)=>{let S=a.get(m);S!==void 0&&(S.delete(b),S.size===0&&a.delete(m));},p=async m=>{if(r.isHost&&!Aa(r)&&r.currentRoom?.matchId===void 0){let b=q(m.clusterTargetId);await r.startMatch({...b===void 0?{}:{clusterTargetId:b},...m.retry===void 0?{}:{retry:m.retry},...m.signal===void 0?{}:{signal:m.signal}});}return Pr(r.matchConnectionState==="suspended"?await r.reconnectToMatch(Sn(m)):await r.awaitMatch(Sn(m)))},u=async m=>Pr(await r.pollMatchStatus(Sn(m))),h=async(m,b)=>{let S=false;try{let w=await p(m),D=r.currentRoom?.transports;if(D!==void 0&&!D.includes("webrtc"))throw new c("misconfigured",`the room template offers (${D.join(", ")||"no transports"}), not webrtc, which is all this path dials. Connect through gem.match.connect(), or pass \`transports: []\` here to negotiate across the template's list.`);let P=m.peerConnection??Mr();S=!0;let G=await He({peerConnection:P,signaling:b,clock:t,matchId:w.matchId,credentialExpiresAt:w.credentialExpiresAt,...St(m,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),N=null;if(m.presentCredential!==!1)try{N=await Ne({channel:G,clock:t,credential:w.joinCredential,credentialExpiresAt:w.credentialExpiresAt,...St(m,"onMessage","signal"),...m.welcomeTimeoutMs===void 0?{}:{ceilingMs:m.welcomeTimeoutMs}});}catch($){throw B(G),B(P),$}return Ia(r,w,G,P,b,m.reportDisconnect!==!1,m.reportConnected!==!1,N,{remember:d,forget:l},m.onMatchEnded)}catch(w){throw S&&Cr(s,w),B(b),w}},g=async(m,b,S,w,D,P)=>{if(m==="webtransport"){let L=w?.webtransport;if(L===void 0)throw new c("misconfigured","webtransport is not advertised");let Y={credential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,clock:t};if(typeof L.named_url=="string"&&L.named_url!==""){let ne=Math.max(Math.floor(P/2),1e3);try{return await qe({url:L.named_url,timeoutMs:ne,log:o,...Y})}catch(oe){if(wt()!==null)throw oe;return o(`[gem] webtransport named dial failed (${bt(oe)}); retrying the pinned dial`),qe({url:L.url,certHashBase64:L.cert_sha256_b64,timeoutMs:ne,log:o,...Y})}}return qe({url:L.url,certHashBase64:L.cert_sha256_b64,timeoutMs:P,...Y})}if(m==="websocket"){let L=w?.websocket;if(L===void 0)throw new c("misconfigured","websocket is not advertised");return yn({url:L.url,credential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,clock:t,timeoutMs:P})}let G=b.peerConnection??Mr(),N,$=await He({peerConnection:G,signaling:D,clock:t,matchId:S.matchId,credentialExpiresAt:S.credentialExpiresAt,extraChannels:[{label:ft,ordered:false,maxRetransmits:0}],onExtraChannel:(L,Y)=>{L===ft&&(N=Y);},...St(b,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...b.exchangeTimeoutMs===void 0&&b.redial===true?{exchangeTimeoutMs:Sa}:{}}),V;try{V=await Ne({channel:$,clock:t,credential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,wire:yt,heartbeat:!0,...St(b,"signal"),...b.welcomeTimeoutMs===void 0?{}:{ceilingMs:b.welcomeTimeoutMs}});}catch(L){throw B($),B(G),L}let E=V.welcome.heartbeatIntervalMs;return {link:bn($,G,N,E===void 0?void 0:{clock:t,intervalMs:E}),welcome:V.welcome,channel:$,peerConnection:G}},f=(m,b,S,w,D)=>{let P=false,G;w.link.onClose(E=>{!P&&m.reportDisconnect!==false&&en(r,b.matchId,E),G?.(E);}),m.reportDisconnect!==false&&m.reportConnected!==false&&r.notifyMatchConnected(b.matchId);let N={transport:w.link.transport,send:(E,L)=>w.link.send(E,L),onMessage:E=>w.link.onMessage(E),onClose:E=>{G=E;},close:()=>w.link.close()},$=()=>{P||(P=true,B(w.link),B(D));},V=E=>{if(!P){try{m.onMatchEnded?.(E);}catch{}$();}};return d(b.matchId,V),{matchId:b.matchId,transport:S,link:N,joinCredential:b.joinCredential,credentialExpiresAt:b.credentialExpiresAt,welcome:w.welcome,...w.channel===void 0?{}:{channel:w.channel},...w.peerConnection===void 0?{}:{peerConnection:w.peerConnection},close(){l(b.matchId,V),$();}}},x=async(m,b)=>{let S=r.currentRoom?.id,w=r.gameId,D=()=>({advert:vt(r.currentRoom?.settings,m),template:r.currentRoom?.transports??null});if(S===void 0||w===null)return D();try{let P=await e.get(`/v2/games/${encodeURIComponent(w)}/game-rooms/${encodeURIComponent(S)}`,b);return {advert:vt(P.settings,m),template:Ue(P.transports)??r.currentRoom?.transports??null}}catch{return D()}},I=(m,b)=>{let S=m??Tr;return b.length===0?S:S.filter(w=>b.includes(w))},M=async(m,b,S)=>{try{let w=await p(m),{advert:D,template:P}=await x(w.matchId,m.signal),G=I(P,b),N=G.filter(j=>Ea(j,D)),$=wt();if($!==null&&G.includes("webtransport")&&D?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${$} (learned on an earlier dial in this page)`),N.length===0){let j=P===null?`the default order (${Tr.join(", ")})`:`the room template's transports (${P.join(", ")||"none"})`;throw new c("misconfigured",`none of ${j}`+(b.length>0?`, narrowed to (${b.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let V=m.transportAttemptTimeoutMs??ka,E=()=>m.deadlineAt===void 0?1/0:m.deadlineAt-t.now(),L=j=>n.signalingReady===void 0||j<=0?Promise.resolve(!0):n.signalingReady(j),Y=[],ne=[];for(let j of N){if(E()<Ir){o(`[gem] ${j} rung not tried: the reconnect budget is spent`);break}ne.length>0&&w.credentialExpiresAt-t.now()<Ar&&(w=await u(m)),ne.push(j);let Dn=!1,Gn=!1,Ye={attempts:0,waitedMs:0};for(;;){if(j==="webrtc"&&m.redial===!0){let Q=Math.min(xr,E());await L(Q)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(Q)}ms; offering anyway`);}let ri=Math.max(Math.min(V,E()),Ir);try{return f(m,w,j,await g(j,m,w,D,S,ri),S)}catch(Q){let U=Q instanceof c?Q:new c("connection_failed",Q instanceof Error?Q.message:String(Q),{cause:Q});if(j==="webrtc"&&Cr(s,U),(U.reason==="credential_expired"||U.reason==="credential_reused")&&!Dn){Dn=!0,w=await u(m);continue}if(j==="webrtc"&&U.reason==="signaling_failed"&&U.platformCode===Qt&&!Gn){Gn=!0;let ae=Math.min(xr,E());if(o(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(ae)}ms for the socket before offering again`),await L(ae))continue}if(U.reason==="join_rate_limited"){let ae=_a(Ye,Math.random,E());if(ae!==null){if(Ye.attempts+=1,Ye.waitedMs+=ae,o(`[gem] ${j} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ae)}ms before presenting again (retry ${Ye.attempts} of ${Or.maxAttempts})`),await pt(t,ae,m.signal),m.signal?.aborted)throw new c("aborted","the caller aborted while waiting out a join rate limit");w.credentialExpiresAt-t.now()<Ar&&(w=await u(m));continue}}if(Ra.has(U.reason)||U.reason==="credential_expired"||j==="webrtc"&&Lr(U)){o(`[gem] ${j} rung failed (${U.reason}): ${bt(U.cause??U)} \u2014 `+(ne.length<N.length?`falling through to ${N[ne.length]}`:"no rungs left")),Y.push(U);break}throw o(`[gem] ${j} rung refused the session (${U.reason}): ${U.message}`),U}}}let oe=Y[Y.length-1];throw oe===void 0?new c("timeout",`the reconnect budget ran out before any transport (${N.join(", ")}) could be tried`):new c(oe.reason,`every transport tried (${ne.join(", ")}) failed; the last said: ${oe.message}`,{cause:Y,platformCode:oe.platformCode})}catch(w){throw B(S),w}};return {listClusterTargets:async(m={})=>mt({client:e,...m}),handleMatchEnded(m,b){let S=a.get(m);if(S!==void 0){a.delete(m);for(let w of S)w(b);}},connect:(async(m={})=>{let b=m.signaling??i();return m.transports===void 0?h(m,b):M(m,m.transports,b)})}}var Tr=["webtransport","webrtc","websocket"],ka=1e4,Sa=5e3,xr=3e3,Ir=1e3,Ar=1e4,Ra=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Lr(n){return n.platformCode!==void 0&&Zt.has(n.platformCode)}var Or={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function _a(n,e=Math.random,t=1/0){let r=Or;if(n.attempts>=r.maxAttempts)return null;let i=Math.min(r.budgetMs-n.waitedMs,t);if(i<r.initialDelayMs)return null;let o=r.initialDelayMs*r.factor**n.attempts;return Math.min(o+e()*r.jitterMs,i)}function Ea(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&gn():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||Ta(e.websocket.url)}function Ta(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return st(e)}function Sn(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var xa=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Cr(n,e){e instanceof c&&(!xa.has(e.reason)&&!Lr(e)||n.report([{type:"connection_failures_total",value:1}]));}function Ia(n,e,t,r,i,o,s,a,d,l){let p=false,u=()=>{p||en(n,e.matchId,void 0);};o&&(t.addEventListener("close",u),s&&n.notifyMatchConnected(e.matchId));let h=()=>{p||(p=true,t.removeEventListener("close",u),a?.detach(),B(t),B(r),B(i));},g=f=>{if(!p){try{l?.(f);}catch{}h();}};return d.remember(e.matchId,g),{matchId:e.matchId,channel:t,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){d.forget(e.matchId,g),h();}}}function Aa(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function Pr(n){if(n.status==="failed")throw new c("allocation_failed",`match ${n.matchId} did not come up: ${n.reason}`);if(n.status==="ended")throw new c("match_ended",`match ${n.matchId} ended (${n.reason}) before this side connected.`);if(n.protocol!==Fe)throw new c("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${Fe}' is reachable from a frame; host and port on this response are advisory and must not be dialled.`);let{joinCredential:e,credentialExpiresAt:t}=n;if(e===void 0||t===void 0)throw new c("connection_failed",`match ${n.matchId} is ready but issued no join credential, so the server would refuse the channel once it opened \u2014 poll match status again.`);return {...n,joinCredential:e,credentialExpiresAt:t}}function Mr(){let n=globalThis.RTCPeerConnection;if(!n)throw new c("misconfigured","this environment has no RTCPeerConnection. Pass `peerConnection` to connect against a stand-in, which is how the flow is tested outside a browser.");return new n({iceServers:[]})}function B(n){try{n.close();}catch{}}function St(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var Ee=class{constructor(e){this.options=e;this.reporter=new ce({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,t,r){let i=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:t},r);return {credential:Rt(i.credential)??"",hostFingerprint:Rt(i.host_fingerprint)??"",hostEpoch:_t(i.host_epoch)??0,expiresAt:(_t(i.expires_at)??0)*1e3}}async turnLease(e,t,r){let i=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:t},r),o=[];for(let d of Array.isArray(i.ice_servers)?i.ice_servers:[]){let l=d,p=(Array.isArray(l.urls)?l.urls:[]).filter(u=>typeof u=="string"&&u.length>0);p.length!==0&&o.push({urls:p,username:Rt(l.username)??"",credential:Rt(l.credential)??""});}let s=_t(i.expires_at),a=_t(i.ttl_seconds);return {iceServers:o,expiresAt:s!==void 0?s*1e3:Date.now()+(a??0)*1e3}}async kick(e,t,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:t},r);}async leave(e,t=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:t});}async telemetry(e,t){await this.reporter.post(e,t);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function Rt(n){return typeof n=="string"&&n.length>0?n:void 0}function _t(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var Ca=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),k=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="P2pError",this.retryable=Ca.has(t);}reason;retryable};var Et=class{listeners=new Map;on(e,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>this.off(e,t)}off(e,t){this.listeners.get(e)?.delete(t);}once(e,t){let r=this.on(e,((...i)=>{r(),t(...i);}));return r}emit(e,...t){let r=this.listeners.get(e);if(r)for(let i of [...r])i(...t);}clear(){this.listeners.clear();}};var Pa=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function pe(n){let e=null;for(let t of n.split(/\r\n|\n/)){if(!t.startsWith("a=fingerprint:"))continue;let r=Ke(t.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function Ke(n){let[e,...t]=n.trim().split(/\s+/);if(e===void 0||t.length===0)return null;let r=`${e.toLowerCase()} ${t.join("").toUpperCase()}`;return Pa.test(r)?r:null}function Te(n,e){if(n.length!==e.length)return false;let t=0;for(let r=0;r<n.length;r++)t|=n.charCodeAt(r)^e.charCodeAt(r);return t===0}var Rn=5e3,Ma=12e4+Rn,La=1024,Oa=6e4,Da=1e4,Dr=64*1024,Gr=5;function Tt(n){let e=new Map,t=-1/0,r=null,i=(()=>{let a;try{a=new URL(`${n.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return a.username!==""||a.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:a.href,shown:`${a.protocol}//${a.host}`}})(),o=()=>{let a=n.subtle??globalThis.crypto?.subtle;if(!a)throw new k("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return a},s=async()=>{if(!i.ok)throw new k("keys_unavailable",i.reason);let a=n.fetch??((h,g)=>globalThis.fetch(h,g)),d;try{d=await a(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(Da)});}catch{throw new k("keys_unavailable",`the JWKS endpoint at ${i.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!d.ok)throw new k("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let l;try{let h=await d.text();if(h.length>Dr)throw new k("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${Dr} characters, which is not a key set this platform publishes.`);l=JSON.parse(h);}catch(h){throw h instanceof k?h:new k("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let p=Array.isArray(l.keys)?l.keys:[];if(p.length>Gr)throw new k("keys_unavailable",`the JWKS endpoint published ${p.length} keys, over the ${Gr} the platform declares. Refusing rather than verifying against a set of unknown size.`);let u=o();for(let h of p){let g=h;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.kid.length===0))try{let f=await u.importKey("jwk",{...h,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,f);}catch{}}};return {async key(a){let d=e.get(a);if(d)return d;if(!i.ok)throw new k("keys_unavailable",i.reason);if(r)return await r,e.get(a)??null;let l=n.now();if(!Number.isFinite(l))throw new k("keys_unavailable","the clock supplied to the SDK returned a non-finite time, so the JWKS throttle cannot be evaluated. This is a configuration fault, not a server failure.");return l<t&&(t=-1/0),l-t<Oa?null:(t=l,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var Ve=class{seen=new Map;admit(e,t){for(let[r,i]of this.seen)i<=t&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=La){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+Ma),true}};function Fr(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return r}function jr(n){try{let e=new TextDecoder().decode(Fr(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function xt(n,e,t,r,i){let o=E=>{throw new k("peer_unauthenticated",`the peer's join credential is not usable: ${E}`)},s=n.split(".");s.length!==3&&o("it is not a three-part JWT");let[a,d,l]=s,p=jr(a);p===null&&o("its header does not decode"),p.alg!=="RS256"&&o(`its alg is ${JSON.stringify(p.alg)}, not RS256`),p.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(p.typ)}, not p2p+jwt`);let u=p.kid;(typeof u!="string"||u.length===0)&&o("it names no key");let h=await t.key(u);h===null&&o("it was signed by a key this build cannot resolve");let g=i.subtle??globalThis.crypto?.subtle;g||o("this environment has no WebCrypto");let f=new TextEncoder().encode(`${a}.${d}`),x;try{x=Fr(l);}catch{o("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},h,x,f)||o("its signature does not verify");let M=jr(d);M===null&&o("its payload does not decode");let C=M,m=E=>typeof C[E]=="string"?C[E]:"",b=E=>typeof C[E]=="number"&&Number.isFinite(C[E])?C[E]:NaN;m("iss")!==i.issuer&&o("it was issued by someone else"),m("aud")!==`${i.issuer}/p2p-match`&&o("its audience is not this platform"),m("match_id")!==e.matchId&&o("it is for another match"),m("game_id")!==e.gameId&&o("it is for another game");let S=b("exp")*1e3,w=b("nbf")*1e3;(!Number.isFinite(S)||e.now>S+Rn)&&o("it has expired"),Number.isFinite(w)&&e.now<w-Rn&&o("it is not valid yet");let D=m("role");D!=="host"&&D!=="client"&&o("it names no usable role");let P=b("host_epoch");P!==e.hostEpoch&&o("it names a different host epoch");let G=Ke(m("fingerprint"));G===null&&o("its fingerprint claim is malformed"),Te(G,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let N=Ke(m("host_fingerprint"));N===null&&o("its host fingerprint claim is malformed"),Te(N,e.hostFingerprint)||o("it was issued against a different host certificate");let $=m("jti");$.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit($,e.now)||o("it has already been used");let V=m("sub");return V.length===0&&o("it names no player"),{playerId:V.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:P,role:D,fingerprint:G,hostFingerprint:N,jti:$,expiresAt:S}}var he=32769;function _n(n){let e=new TextEncoder().encode(n.jwt);if(e.length>8192)throw new Error(`[gem] a join credential of ${e.length} bytes exceeds the wire format's cap`);let t=new ArrayBuffer(3+e.length+4+4),r=new DataView(t);return r.setUint8(0,1),r.setUint16(1,e.length,true),new Uint8Array(t,3,e.length).set(e),r.setUint32(3+e.length,n.protocolVersion,true),r.setUint32(7+e.length,n.assignedPeerId,true),t}function En(n){let e=new ArrayBuffer(9),t=new DataView(e);return t.setUint8(0,2),t.setUint32(1,n.protocolVersion,true),t.setUint32(5,n.assignedPeerId,true),e}function Tn(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function xn(n){if(n.byteLength<1)return null;let e=new DataView(n);switch(e.getUint8(0)){case 1:{if(n.byteLength<3)return null;let t=e.getUint16(1,true);return t>8192||n.byteLength<3+t+8?null:{kind:"join",jwt:new TextDecoder().decode(new Uint8Array(n,3,t)),protocolVersion:e.getUint32(3+t,true),assignedPeerId:e.getUint32(7+t,true)}}case 2:return n.byteLength<9?null:{kind:"admit",protocolVersion:e.getUint32(1,true),assignedPeerId:e.getUint32(5,true)};case 3:return n.byteLength<2?null:{kind:"reject",reason:e.getUint8(1)};default:return null}}function Nr(n){switch(n){case 1:return "the host did not accept this credential";case 2:return "the host speaks a different protocol version \u2014 an engine peer refuses a browser peer here, deliberately";case 3:return "the match is full";case 4:return "the host is rate-limiting joins";case 129:return "the host verified this credential but it names a different player than the one who signalled \u2014 the host has its own line saying which";case 130:return "the host has this player on the kicked list for the current host epoch";case 131:return "the host could not fetch the platform's signing keys, so it cannot verify anyone yet \u2014 the host's console says why";default:return `the host refused with an unrecognised code (${n})`}}function $r(n){switch(n){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var Ur=3e4,xe=class{constructor(e,t,r){this.localPlayerId=e;this.hostPlayerId=t,this.epoch=r;}localPlayerId;state="idle";epoch;hostPlayerId;kicked=new Set;startedAt=0;get currentState(){return this.state}get currentEpoch(){return this.epoch}get currentHostPlayerId(){return this.hostPlayerId}get isLocalHost(){return this.hostPlayerId===this.localPlayerId}isKicked(e){return this.kicked.has(e)}stalled(e){return this.state!=="idle"&&e-this.startedAt>3e4}apply(e,t){return !Number.isInteger(e.hostEpoch)||e.hostEpoch<0?{kind:"refused",why:`host epoch ${String(e.hostEpoch)} is not a whole number`}:e.hostEpoch===this.epoch?e.migrationComplete===true&&this.state!=="idle"?(this.state="idle",{kind:"completed"}):{kind:"duplicate"}:e.hostEpoch<this.epoch?{kind:"refused",why:`host epoch ${e.hostEpoch} is behind the current ${this.epoch}`}:e.hostPlayerId.length===0?{kind:"refused",why:"the migration named no new host"}:(this.kicked=new Set(e.kickedPlayerIds??[]),this.epoch=e.hostEpoch,this.hostPlayerId=e.hostPlayerId,this.startedAt=t,this.state=this.isLocalHost?"preparing":"reconnecting",{kind:"accepted",state:this.state})}complete(){this.state="idle";}};var It={reliable:{negotiated:true,id:0,ordered:true},ordered:{negotiated:true,id:1,ordered:true,maxRetransmits:0},unreliable:{negotiated:true,id:2,ordered:false,maxRetransmits:0}},Be=["reliable","ordered","unreliable"];function At(n){let e=globalThis.RTCPeerConnection;if(!e)throw new Error("[gem] this environment has no RTCPeerConnection. Pass `peerConnectionFactory` to connect against a stand-in, which is how this flow is tested outside a browser.");return new e({iceServers:n.iceServers,...n.certificates===void 0?{}:{certificates:n.certificates}})}async function Ct(){let n=globalThis.RTCPeerConnection;return n?.generateCertificate?n.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var Hr=1,$a=3e4,Wr=2e3,Ua=5e3,Kr=6e4,qa=8,An=class{constructor(e=qa){this.perMinute=e;}perMinute;sent=[];delayUntilAllowed(e){return this.prune(e),this.sent.length<this.perMinute?0:Math.max(0,(this.sent[0]??e)+6e4-e)}record(e){this.prune(e),this.sent.push(e);}prune(e){let t=0;for(let r of this.sent)r<=e&&e-r<6e4&&(this.sent[t++]=r);this.sent.length=t;}},Ha=new An,Wa=8,Ka=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),Ie=class{constructor(e){this.options=e;this.keys=e.keys??Tt({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Et;links=new Map;replays=new Ve;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=Hr+1;ended=null;closed=false;ready=null;helloSeen=false;reportedUnreachableEpoch=-1;reportedStallEpoch=-1;counted=false;pendingOffers=new Map;answeredSessions=new Map;credentialGeneration=0;credentialDeadline=0;get matchId(){return this.options.matchId}get playerId(){return this.localPlayerId}get isHost(){return this.migration?.isLocalHost??false}get hostPlayerId(){return this.migration?.currentHostPlayerId??""}get hostEpoch(){return this.migration?.currentEpoch??0}get peers(){let e=[];for(let t of this.links.values())t.admitted&&e.push(this.expose(t));return e}peer(e){let t=this.links.get(e);return t&&t.admitted?this.expose(t):null}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}async start(e){let t=this.options.connectTimeoutMs??$a;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((a,d)=>{this.ready={resolve:a,reject:d};}),i=q(this.options.clusterTargetId);if(i!==void 0)try{let a=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=a.iceServers,this.mark("turn leased");}catch(a){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${In(a)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let o=this.options.clock.setTimeout(()=>{this.fail(new k("timeout",`no usable P2P connection after ${t}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},t),s=()=>this.fail(new k("aborted","the caller aborted while connecting"));e?.aborted?s():e?.addEventListener("abort",s);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",s),this.ready=null;}}async kick(e){if(!this.isHost)throw new k("misconfigured","only the current host of this match can kick a peer");await this.options.api.kick(this.options.matchId,e);}async leave(){try{await this.options.api.leave(this.options.matchId);}catch{}this.close();}close(){if(!this.closed){this.closed=true,this.pendingOffers.clear();for(let e of [...this.links.values()])this.dropLink(e,"closed",false);this.options.signaling.close(),this.emitter.clear();}}report(e){this.options.api.telemetry(e).catch(()=>{});}notifyCandidatesDropped(e){this.emitter.emit("candidatesDropped",e);}handleSignal(e,t){this.closed||this.route(e,t).catch(r=>this.report_(r));}async route(e,t){switch(e){case "hello":return this.onHello(t);case "offer":return this.onOffer(t);case "answer":return this.onAnswer(t);case "ice":return this.onIce(t);case "peerLeft":return this.onPeerLeft(t);case "migration":return this.onMigration(t);case "matchEnded":return this.onMatchEnded(t);case "error":return this.onSignalingError(t);default:return}}async onHello(e){let t=F(e.playerId),r=F(e.hostPlayerId),i=Pt(e.hostEpoch);if(!(t===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=t,this.migration===null&&(this.migration=new xe(t,r,i)),!this.helloSeen)){if(this.helloSeen=true,this.isHost){this.mark("host listening"),this.settle(),await this.drainPendingOffers();return}this.pendingOffers.clear(),await this.offerToHost("initial");}}async drainPendingOffers(){if(this.pendingOffers.size===0)return;let e=[...this.pendingOffers.values()];this.pendingOffers.clear(),this.mark("queued offer drained");for(let t of e)try{await this.onOffer(t);}catch(r){this.report_(r);}}async offerToHost(e){let t=this.hostPlayerId,r=this.openLink(t,Hr),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new k("invalid_sdp","the browser produced an offer with no SDP");ie(o,"offer"),this.refuseMedia(o,"offer"),this.options.signaling.offer(o,e),this.mark("offer sent"),this.fetchCredential().catch(s=>this.report_(s));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,i=r===void 0?null:pe(r);if(i===null)throw new k("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let o=this.options.credentialPacing??Ha,s=()=>this.closed||e!==this.credentialGeneration,a=Ua;for(;;){let d=o.delayUntilAllowed(this.options.clock.now());if(d>0&&!await this.waitForCredential(d,s))return;o.record(this.options.clock.now());try{let l=await this.options.api.joinCredential(this.options.matchId,i);if(s())return;this.credential=l,this.mark("credential ready"),this.maybeAuthenticate();return}catch(l){if(s())return;let p=l.status,u;if(p===409)u=Wr;else if(p===429){let h=l.retryAfterSeconds;typeof h=="number"&&Number.isFinite(h)&&h>=0?u=h*1e3:(u=a,a=Math.min(a*2,Kr)),u=Math.min(Math.max(u,Wr),Kr);}else throw l;if(!await this.waitForCredential(u,s))return}}}async waitForCredential(e,t){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!t())}async onOffer(e){let t=F(e.fromPlayerId),r=F(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=Wa){let p=this.pendingOffers.keys().next().value;p!==void 0&&this.pendingOffers.delete(p);}this.pendingOffers.set(t,e);return}if(!this.isHost||this.migration.isKicked(t)===true)return;let i=F(e.sessionId);if(i!==null&&this.answeredSessions.get(t)===i)return;ie(r,"offer"),this.refuseMedia(r,"offer");let o=pe(r);if(o===null)throw new k("invalid_sdp",`the offer from ${t} carries no usable fingerprint`);this.mark("offer received"),i!==null&&this.answeredSessions.set(t,i);let s=this.links.get(t);s&&this.dropLink(s,"resignalled",false);let a=this.openLink(t,this.nextPeerId++);a.remoteFingerprint=o,await a.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(a);let d=await a.connection.createAnswer();await a.connection.setLocalDescription(d);let l=a.connection.localDescription?.sdp??d.sdp;if(!l)throw new k("invalid_sdp","the browser produced an answer with no SDP");ie(l,"answer"),this.refuseMedia(l,"answer"),this.options.signaling.answer(t,l,a.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let t=F(e.fromPlayerId),r=F(e.sdp);if(t===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||t!==this.hostPlayerId)return;ie(r,"answer"),this.refuseMedia(r,"answer");let o=pe(r);if(o===null)throw new k("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),i.remoteFingerprint=o,i.pendingAnswer=r,this.hostVerified(i)&&await this.applyAnswer(i,r);}hostVerified(e){let t=this.credential;return t===null||e.remoteFingerprint===null?false:Te(t.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new k("peer_unauthenticated","the host's DTLS certificate is not the one the platform attested for this match. Refusing before the handshake, so no credential is presented.")),this.dropLink(e,"host_fingerprint_mismatch",false),false)}maybeAuthenticate(){if(this.isHost)return;let e=this.links.get(this.hostPlayerId);if(!e||e.remoteFingerprint===null||e.connection.remoteDescription!==null)return;let t=e.pendingAnswer;t!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,t).catch(r=>this.report_(r));}async applyAnswer(e,t){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:t}),this.flushCandidates(e);}async onIce(e){let t=F(e.fromPlayerId),r=F(e.candidate);if(t===null||r===null)return;let i=this.links.get(t);if(!i)return;let o=F(e.sdpMid),s=Pt(e.sdpMLineIndex)??Pt(e.sdpMLineIndexAlt),a={candidate:r,...o===null?{}:{sdpMid:o},...s===null?{}:{sdpMLineIndex:s}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(a);return}await i.connection.addIceCandidate(a);}onPeerLeft(e){let t=F(e.playerId);if(t===null)return;let r=F(e.reason)??"left";if(t===this.localPlayerId){this.fail(new k("kicked",`this player was removed from the match (${r})`)),this.close();return}let i=this.links.get(t);i&&this.dropLink(i,r,true);}async onMigration(e){let t=F(e.hostPlayerId),r=Pt(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:t,hostEpoch:r,...F(e.reason)===null?{}:{reason:F(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(o=>typeof o=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind!=="duplicate"){if(i.kind==="completed"){this.emitter.emit("hostChanged",t,r);return}if(i.kind==="refused"){this.report_(new k("migration_failed",i.why));return}for(let o of [...this.links.values()])this.dropLink(o,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",t,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new k("migration_failed",`host migration to epoch ${e} did not complete. The elected host never acknowledged it, so the platform is still holding the match in migration.`)));},31e3);}onMatchEnded(e){let t=F(e.reason)??"ended";this.ended=t,this.emitter.emit("matchEnded",t),this.ready!==null&&this.fail(new k("match_ended",`the match ended: ${t}`)),this.close();}onSignalingError(e){let t=F(e.code)??"unknown",r=F(e.message)??"the platform refused a signaling message";this.report_(new k("signaling_failed",`${t}: ${r}`));}openLink(e,t){let i=(this.options.peerConnectionFactory??At)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let h of Be){let g=i.createDataChannel(h,It[h]);g.binaryType="arraybuffer",o[h]=g;}let s={playerId:e,assignedPeerId:t,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=h=>{let g=h.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},d=()=>this.onIceState(s),l=()=>this.onConnectionState(s),p=h=>{this.onHandshakeMessage(s,h.data).catch(g=>this.report_(g));},u=()=>{this.onReliableOpen(s).catch(h=>this.report_(h));};return i.addEventListener("icecandidate",a),i.addEventListener("iceconnectionstatechange",d),i.addEventListener("connectionstatechange",l),o.reliable.addEventListener("open",u),o.reliable.addEventListener("message",p),s.detachHandshake=()=>{o.reliable.removeEventListener("open",u),o.reliable.removeEventListener("message",p);},s.detachAll=()=>{s.detachHandshake(),i.removeEventListener("icecandidate",a),i.removeEventListener("iceconnectionstatechange",d),i.removeEventListener("connectionstatechange",l);},this.links.set(e,s),s}flushCandidates(e){let t=e.pendingCandidates;e.pendingCandidates=[];for(let r of t)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let t=this.credential;if(t===null)throw new k("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=t.expiresAt)throw new k("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(_n({jwt:t.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,t){if(!(t instanceof ArrayBuffer))return;let r=xn(t);if(r!==null){if(this.isHost&&r.kind==="join"){await this.admit(e,r.jwt,r.protocolVersion);return}if(!this.isHost&&r.kind==="admit"){e.assignedPeerId=r.assignedPeerId,this.finishAdmission(e),this.migration?.complete();return}!this.isHost&&r.kind==="reject"&&(this.fail(new k($r(r.reason),Nr(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,t,r){if(r!==32769){this.refuseLink(e,2,"version_mismatch",`it presented protocol version ${r}, not this SDK's ${32769} \u2014 an engine peer cannot join a browser-hosted match`);return}let i=pe(e.connection.localDescription?.sdp??"");if(i===null||e.remoteFingerprint===null){this.refuseLink(e,1,"fingerprint_unavailable","this connection's DTLS fingerprints could not be read from its SDP, so no credential can be checked against it");return}let o;try{o=await xt(t,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:i,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(s){let a=s instanceof k&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",In(s)),a&&this.fail(s);return}if(o.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${o.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(o.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(En({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,t,r,i){this.warn(`refused to admit ${e.playerId}: ${i}`);try{e.channels.reliable.send(Tn(t));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){let t=e.connection.iceConnectionState;if(!(t!=="failed"&&t!=="disconnected"&&t!=="closed")){if(this.isHost){(t==="failed"||t==="closed")&&this.dropLink(e,t,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,t);}catch(r){this.report_(r);}}}}onConnectionState(e){let t=e.connection.connectionState;t!=="failed"&&t!=="closed"||this.dropLink(e,t,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(t,r="reliable")=>e.channels[r].send(t)}}dropLink(e,t,r){this.links.delete(e.playerId),e.detachAll();for(let i of Be)Vr(e.channels[i]);Vr(e.connection),r&&e.admitted&&this.emitter.emit("peerLeft",e.playerId,t);}settle(){this.ready?.resolve(),this.ready=null;}fail(e){if(this.count(e.reason),this.ready!==null){let t=this.ready;this.ready=null,t.reject(e);return}this.emitter.emit("error",e);}report_(e){this.fail(e instanceof k?e:new k("connection_failed",In(e),{cause:e}));}count(e){this.counted||!Ka.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(kt(e))throw new k("media_refused",`the ${t} carries an active audio or video section. This path carries data channels only; voice belongs to the platform voice service, and gem-api age-gates relayed SDP that proposes media.`)}mark(e){this.options.boot?.mark(e);}sleep(e){return new Promise(t=>this.options.clock.setTimeout(t,e))}warn(e){let t=this.options.log;t!==null&&(t??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function F(n){return typeof n=="string"&&n.length>0?n:null}function Pt(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function In(n){return n instanceof Error?n.message:String(n)}function Vr(n){try{n.close();}catch{}}var Va=100,Ba=50,Ae=class{constructor(e){this.options=e;}options;queue=[];drainHandle=null;dropped=0;closed=false;dropListener=null;onDropped(e){this.dropListener=e;}join(){this.assertUsable(),this.options.bridge.signal("join",this.options.matchId,{});}offer(e,t){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:t});}answer(e,t,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:t,assignedPeerId:r});}candidate(e,t,r,i){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??Va)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:t,...r===void 0?{}:{sdpMid:r},...i===void 0?{}:{sdpMLineIndex:i}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,t){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:t,lastSeenAt:Math.floor(this.options.clock.now()/1e3)}});}discardQueued(){this.queue.length=0;}close(){this.closed=true,this.discardQueued(),this.drainHandle!==null&&(this.options.clock.clearTimeout(this.drainHandle),this.drainHandle=null);}assertUsable(){if(this.closed)throw new k("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new k("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see public-docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId:t,candidate:r,sdpMid:i,sdpMLineIndex:o}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:t,candidate:r,...i===void 0?{}:{sdpMid:i},...o===void 0?{}:{sdpMLineIndex:o}});}if(this.dropped>0&&this.queue.length===0){let t=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(t),this.dropListener?.(t);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??Ba));}};var Cn="webrtc_p2p";function Ja(n){let e=new Ee({client:n.client,gameId:n.gameId}),t=new Map;return {handleSignalEvent(r,i,o){t.get(r)?.handleSignal(i,o);},session(r){return t.get(r)??null},async connect(r={}){if(n.bridge===null)throw new k("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See public-docs/p2p-and-parties.md \xA72.");let i=q(r.clusterTargetId),o=i??q(await n.resolveClusterTarget?.());n.rooms.isHost&&n.rooms.currentMatch===null&&n.rooms.currentRoom?.matchId===void 0&&await n.rooms.startMatch({...i===void 0?{}:{clusterTargetId:i},...r.signal===void 0?{}:{signal:r.signal}});let s=await n.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(s.protocol!==Cn)throw new k("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${Cn}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new Ae({bridge:n.bridge,matchId:s.matchId,clock:n.clock}),d=new Ie({api:e,clock:n.clock,matchId:s.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:a,...o===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Ct(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...n.boot===void 0?{}:{boot:n.boot},...n.log===void 0?{}:{log:n.log}});a.onDropped(l=>d.notifyCandidatesDropped(l)),t.set(s.matchId,d),d.on("matchEnded",()=>t.delete(s.matchId));try{await d.start(r.signal);}catch(l){throw t.delete(s.matchId),d.close(),l}return d}}}function Br(n){return typeof n=="string"&&n.trim()!==""}function Jr(n,e){return Br(n)?n.trim():Br(e)?e:null}function ge(n){return typeof n=="string"&&n!==""?n:void 0}var Xa=new Set(["localhost","127.0.0.1","[::1]"]);function Xr(n){let e=ge(n);if(e===void 0)return;let t;try{t=new URL(e);}catch{return}if(!(t.username!==""||t.password!=="")&&(t.protocol==="https:"||t.protocol==="http:"&&Xa.has(t.hostname)))return e}function Ya(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=t??{},i=ge(r.item_id),o=Xr(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function Yr(n){let e=n??{},t=ge(e.player_id),r=ge(e.display_name),i=ge(e.discriminator),o=ge(e.display_tag),s=ge(e.avatar_icon_id),a=Xr(e.avatar_icon_url);return {...t===void 0?{}:{playerId:t},...r===void 0?{}:{displayName:le(r)},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:le(o)},...s===void 0?{}:{avatarIconId:s},...a===void 0?{}:{avatarIconUrl:a},badges:Ya(e.badges)}}function Mt(n){if(typeof n!="object"||n===null)return;let e={};for(let[t,r]of Object.entries(n)){let i=Pn(r);i!==void 0&&(e[t]=i);}return e}function Lt(n){if(Array.isArray(n))return n.map(za).filter(e=>!!e)}function Pn(n){if(Mn(n)||Array.isArray(n)&&n.every(Mn))return n}function Mn(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function za(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=Pn(e.fixed),r=Pn(e.default);return {name:e.name,type:typeof e.type=="string"?e.type:"string",list:e.list===true,required:e.required===true,mutable:e.mutable!==false,...t===void 0?{}:{fixed:t},...r===void 0?{}:{default:r},...Ce("description",Qa(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Mn)?{allowed:e.allowed}:{},...Ce("min",Je(e.min)),...Ce("max",Je(e.max)),...Ce("minItems",Je(e.min_items)),...Ce("maxItems",Je(e.max_items)),...Ce("maxLength",Je(e.max_length))}}function Qa(n){return typeof n=="string"&&n.length>0?n:void 0}function Je(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ce(n,e){return e===void 0?{}:{[n]:e}}function X(n){let e=n??{},t=A(e.id)??A(e.game_room_id);if(t===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(Ln):[];return {id:t,gameId:A(e.game_id)??"",name:A(e.name)??"",status:A(e.status)??"open",hostPlayerId:A(e.host_player_id)??"",maxPlayers:z(e.max_players)??0,memberCount:z(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...J("joinCode",A(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...J("roomArgs",Mt(e.room_args)),...J("roomArgsTemplate",Lt(e.room_args_template)),gameChannel:A(e.game_channel)??"release",...J("region",A(e.region)),...J("clusterTargetId",A(e.cluster_target_id)),...J("matchId",A(e.match_id)),version:z(e.version)??0,...J("templateId",A(e.template_id)),roomType:A(e.game_room_type)??"Standard",...J("transports",Ue(e.transports)??void 0),createdAt:z(e.created_at)??0,updatedAt:z(e.updated_at)??0,...J("startedAt",z(e.started_at))}}function Ln(n){let e=n??{};return {...Yr(e),playerId:A(e.player_id)??"",isReady:e.is_ready===true,role:A(e.role)??"member",joinedAt:z(e.joined_at)??0,...J("groupId",A(e.group_id)),...J("platform",A(e.platform))}}function Xe(n){let e=n??{};return {id:A(e.id)??A(e.game_room_id)??"",gameId:A(e.game_id)??"",name:A(e.name)??"",status:A(e.status)??"open",hostPlayerId:A(e.host_player_id)??"",maxPlayers:z(e.max_players)??0,memberCount:z(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:A(e.game_channel)??"release",roomType:A(e.game_room_type)??"Standard",createdAt:z(e.created_at)??0}}function A(n){return typeof n=="string"&&n.length>0?n:void 0}function z(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function J(n,e){return e===void 0?{}:{[n]:e}}var Pe=class{constructor(e){this.options=e;}options;list(e){let t=new URLSearchParams;e.status&&t.set("status",e.status),e.templateSlug&&t.set("template_slug",e.templateSlug),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);let r=t.size>0?`?${t.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(i=>({rooms:(i.game_rooms??[]).map(Xe),...typeof i.next_cursor=="string"?{nextCursor:i.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(t=>({rooms:(t.game_rooms??[]).map(Xe)}))}create(e,t,r){return Za(e.maxPlayers),this.options.client.post(this.baseV2(),{name:e.name,...e.isPublic===void 0?{}:{is_public:e.isPublic},...e.settings===void 0?{}:{settings:e.settings},...e.region===void 0?{}:{region:e.region},...r===void 0?{}:{cluster_target_id:r},...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.partyId===void 0?{}:{party_id:e.partyId},...e.roomArgs===void 0?{}:{room_args:e.roomArgs},...Ot(t)},e.signal).then(X)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(X)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...Ot(r)},t.signal).then(X)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...Ot(r)},t.signal).then(X)}quickJoin(e,t,r=[]){return this.options.client.post(`${this.baseV2()}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...Ot(t)},e.signal).then(X)}leave(e,t,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:t},r,{keepalive:i}).then(()=>{})}close(e,t){return this.options.client.delete(this.roomV1(e),t).then(()=>{})}update(e,t){return this.options.client.patch(this.roomV2(e),{...t.name===void 0?{}:{name:t.name},...t.maxPlayers===void 0?{}:{max_players:t.maxPlayers},...t.isPublic===void 0?{}:{is_public:t.isPublic},...t.settings===void 0?{}:{settings:t.settings},...t.roomArgs===void 0?{}:{room_args:t.roomArgs}},t.signal).then(X)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(X)}kick(e,t,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(t)}`,{},r).then(()=>this.get(e,r))}transferHost(e,t,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(t)}`,{},r).then(X)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function Ot(n){return {platform:n.platform,game_version:n.gameVersion,engine_version:n.engineVersion}}function Za(n){n!==void 0&&console.warn(`[gem] createRoom: maxPlayers (${n}) is deprecated and was not sent. A room's seats come from the room template published in your game config \u2014 name one with templateSlug \u2014 and a room created without a template seats 8. To change a room that already exists, call update({ maxPlayers }) as its host.`);}var Me=class{listeners=new Map;retainedMatch=null;on(e,t){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(t),e==="matchReady"&&this.retainedMatch!==null){let i=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(t)&&this.retainedMatch===i&&t(i);});}return ()=>this.off(e,t)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,t){this.listeners.get(e)?.delete(t);}once(e,t){let r=this.on(e,((...i)=>{r(),t(...i);}));return r}emit(e,...t){e==="matchReady"&&(this.retainedMatch=t[0]);let r=this.listeners.get(e);if(r)for(let i of [...r])i(...t);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};function es(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var ts=1e3,ns=3e3,rs=6e4,is=2,zr=new Set(["game_room_closed","game_room_gone"]),os=12e4,as=5e3;function ti(n){return new On(n)}var On=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Pe({client:e.client,gameId:()=>this.requireGameId()}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Me;api;room=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;async create(e){this.assertNotInRoom("create");let t=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("create",async()=>{let o=await t;return this.api.create(r,this.version("create"),o[0]).catch(async s=>{let a=await this.afterRefusedClusters(s,o);if(a[0]===void 0||a[0]===o[0])throw s;return this.api.create(r,this.version("create"),a[0])})});return this.enter(i,"created"),i}async join(e,t={}){this.assertNotInRoom("join");let r=await this.attachParty(t),i=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(i,"joined"),i}async joinByCode(e,t={}){this.assertNotInRoom("joinByCode");let r=await this.attachParty(t),i=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(i,"joined"),i}async quickJoin(e){this.assertNotInRoom("quickJoin");let t=this.clusterTargets(),r=await this.attachParty(e),i=s=>this.api.quickJoin(r,this.version("quickJoin"),s).catch(a=>this.retryPastStaleMembership(a,r,s)),o=await this.run("quickJoin",async()=>{let s=await t;return i(s).catch(async a=>{let d=await this.afterRefusedClusters(a,s);if(d.length===0||ds(d,s))throw a;return i(d)})});return this.enter(o,"joined"),o}async list(e={}){let t=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",t),t}async myRooms(e){let t=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",t.rooms),t.rooms}async leave(e={}){let t=this.requireRoom("leave"),r=e.keepalive===true,i=()=>this.run("leave",()=>this.api.leave(t.id,e.asGroup!==false,e.signal,r));if(r){let o=i();this.track(this.notifyLeavingMatch({keepalive:true})),await o;}else await this.notifyLeavingMatch(),await i();this.exit(),this.emitter.emit("left");}async leaveAll(e){let t=await this.myRooms(e),r=[];for(let i of t)try{await this.run("leaveAll",()=>this.api.leave(i.id,!0,e)),r.push(i.id),this.room?.id===i.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let t=this.requireRoom("close");await this.run("close",()=>this.api.close(t.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let t=this.room;if(!t)return null;let r;try{r=await this.track(this.api.get(t.id,e));}catch(i){if(i instanceof H&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let s=await this.askWhyEnded(o,e);this.endMatch(o,s??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",i),i}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let t=this.room,r=this.heldMatchId;if(!(t===null||r===null)&&!(t.status==="in_game"&&t.matchId===r)&&!(t.matchId!==void 0&&t.matchId!==r)&&this.settling!==r){this.settling=r;try{let i=await this.askWhyEnded(r,e);i!==null&&this.endMatch(r,i,t.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,t){let r=this.room;if(r===null)return null;let i=this.takeHint(e),o;try{o=await this.track(this.onceGameIdKnown(()=>Xt({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...t===void 0?{}:{signal:t}})));}catch(s){return s instanceof H&&s.reason==="not_found"?i??null:(this.reportError("reconcile",s),null)}return o===null?null:o.status==="ready"?(this.seenMatches.add(e),null):o.status==="failed"?(this.settleFailed(o.matchId,o.reason),null):o.reason==="unknown"&&i!==null?i:o.reason}takeHint(e){let t=this.pendingHint;if(t===null||t.matchId!==void 0&&t.matchId!==e||(this.pendingHint=null,t.reason===void 0))return null;let r=Re(t.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let t=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=t,this.track(t)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,t){let r=this.requireRoom("setReady"),i=await this.run("setReady",()=>this.api.setReady(r.id,e,t));return this.apply(i),i}async kick(e,t){let r=this.requireRoom("kick"),i=await this.run("kick",()=>this.api.kick(r.id,e,t));return this.apply(i),i}async transferHost(e,t){let r=this.requireRoom("transferHost"),i=await this.run("transferHost",()=>this.api.transferHost(r.id,e,t));return this.apply(i),i}async update(e){let t=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(t.id,e));return this.apply(r),r}async startMatch(e={}){let t=this.requireRoom("startMatch");if(!this.isHost)throw new c("misconfigured",`only the host of room ${t.id} can start a match, and this player is not it. Every other member waits for \`matchAllocationStarted\` instead \u2014 that is the whole point of the room carrying the match.`);let r=q(e.clusterTargetId),i=r??(t.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),o=i??t.clusterTargetId;await this.options.ensureLocalServer?.(t.id);let s=(d,l)=>ct({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:t.id,...d===void 0?{}:{clusterTargetId:d},...r===void 0?{nextClusterTarget:()=>this.nextCluster(l)}:{},retry:{...e.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),e.retry?.onWaiting?.(p);}},...e.signal===void 0?{}:{signal:e.signal}}),a=await this.run("startMatch",()=>s(i,[o]).catch(async d=>{if(r!==void 0||!ei(d))throw d;let l=await this.nextCluster([o],true);if(l===void 0)throw d;return s(l,[o,l])}));return this.beginMatch(a.matchId),a}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new c("misconfigured","this match is suspended \u2014 the transport dropped and nobody has decided to reconnect yet. Call reconnectToMatch(), or dedicatedServer.connect(), which does it for you.");let t=this.emitter.retained;return t!==null&&this.session.phase==="ready"?t:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let t=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),i=await this.run("pollMatchStatus",()=>this.chase(t.id,r,e));return this.settleOutcome(i)}chase(e,t,r){return ut({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:t,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(t),...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.pollIntervalMs===void 0?{}:{pollIntervalMs:r.pollIntervalMs},...r.signal===void 0?{}:{signal:r.signal}})}settleOutcome(e){if(e.status==="failed")throw this.settleFailed(e.matchId,e.reason),new c("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!zr.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new c("match_ended",`match ${e.matchId} ended: ${e.reason}`);return this.seenMatches.add(e.matchId),this.emitter.retained?.matchId===e.matchId?this.emitter.retain(e):this.emitter.emit("matchReady",e),this.heldMatchId===e.matchId&&this.session.phase!=="connected"&&(this.session={phase:"ready",matchId:e.matchId}),e}settleFailed(e,t){this.heldMatchId===e&&(this.abandonReconnect(e,t),this.emitter.emit("matchFailed",e,t),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,t,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:t,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:t,roomReopened:r}),this.abandonReconnect(e,t));}armReconnect(e,t){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),t==="kicked"){r.abandon(e,t);return}let i={matchId:e,cause:t,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=i,this.track(this.reconnectStep(i));}park(e,t){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),t());}reconnecting(e){return !this.disposed&&!e.done&&this.reconnect===e&&this.session.phase==="suspended"&&this.session.matchId===e.matchId}finishReconnect(){let e=this.reconnect;e!==null&&(e.done=true,e.timer!==null&&(this.options.clock.clearTimeout(e.timer),e.timer=null),e.parked=null,this.reconnect=null);}abandonReconnect(e,t){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,t));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!Dt()){this.park(e,()=>this.reconnectStep(e));return}let t=this.options.autoReconnect;if(t===void 0||e.attempt===0&&(await this.reconcile().catch(()=>{}),!this.reconnecting(e)))return;let r=e.deadlineAt-this.options.clock.now();if(e.attempt>=t.attempts||r<ts){this.abandonReconnect(e.matchId,e.cause);return}e.attempt+=1,this.emitter.emit("matchReconnecting",{matchId:e.matchId,attempt:e.attempt,attempts:t.attempts,remainingMs:r}),e.timer=this.options.clock.setTimeout(()=>{e.timer=null,this.track(this.reconnectAttempt(e));},Math.min(es(e.attempt,t.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!Dt()){this.park(e,()=>this.reconnectAttempt(e));return}let t=this.options.autoReconnect,r=this.room;if(t===void 0||r===null)return;let i=null;try{i=await this.track(this.onceGameIdKnown(()=>Xt({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e.matchId,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e.matchId)})));}catch(o){this.reportError("reconcile",o);}if(this.reconnecting(e)){if(i?.status==="ended"){this.endMatch(i.matchId,i.reason,!zr.has(i.reason)),this.track(this.reconcile().catch(()=>{}));return}if(i?.status==="failed"){this.abandonReconnect(e.matchId,i.reason),this.settleFailed(i.matchId,i.reason);return}if(i?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(i);let o;try{o=await t.redial(e.matchId,e.deadlineAt);}catch(s){this.reportError("reconcile",s),o="failed";}if(e.done||this.reconnect!==e)return;if(o==="closed"){this.finishReconnect();return}if(o==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let t=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):t&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new c("misconfigured",`no match is connected, so there is nothing to suspend (state '${this.matchConnectionState}').`);let t=this.session.matchId;this.session={phase:"suspended",matchId:t,reason:e},this.emitter.emit("matchSuspended",{matchId:t,cause:e}),this.armReconnect(t,e);}async reconnectToMatch(e={}){if(this.session.phase!=="suspended")throw new c("misconfigured",`reconnectToMatch expects a suspended match; this one is '${this.matchConnectionState}'. Call notifyMatchDisconnected() when the transport drops.`);let t=this.heldMatchId;if(t===null)throw new c("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:t},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let t=this.heldMatchId;if(t!==null)try{await this.api.leaveMatch(t,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,t){let r=this.emitter.on(e,t);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}handleRoomEvent(e){if(this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let t=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(t).catch(()=>{}));}handleAutoStartFailed(e,t){this.room?.id===e&&this.emitter.emit("matchAutoStartFailed",{roomId:e,code:t});}handleSeated(e){this.disposed||!this.watchingSeats||this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}async reconcileSeats(){if(this.disposed||!this.watchingSeats)return;let e;try{e=await this.myRooms();}catch{return}let t=new Set;for(let r of e)r.status!=="closed"&&(t.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])t.has(r)||this.reported.delete(r);}async reportSeat(e){let t=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||t===null||!r.members.some(i=>i.playerId===t)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.seatPollMs>0&&Dt())){this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null);return}if(this.seatPollHandle!==null)return;let t=()=>{this.seatPollHandle=null,this.track(this.reconcileSeats().catch(()=>{}).then(()=>this.retuneSeatWatch()));};this.seatPollHandle=this.options.clock.setTimeout(t,this.seatPollMs);}installResumeWatch(){let e=globalThis;if(typeof e.addEventListener!="function")return;this.visibilityListener=()=>{if(!this.disposed&&(this.retuneSeatWatch(),!!Dt())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of Qr)e.addEventListener(r,this.visibilityListener);let t=globalThis.document;typeof t?.addEventListener=="function"&&t.addEventListener("resume",this.visibilityListener);}startPolling(e){this.stopPolling(),!this.disposed&&(this.pinnedIntervalMs=e??null,this.polling=true,this.schedule());}stopPolling(){this.pollHandle!==null&&(this.options.clock.clearTimeout(this.pollHandle),this.pollHandle=null),this.polling=false,this.pollIntervalMs=null;}async settled(){for(let e=0;e<20&&this.inFlight.length>0;e++){let t=this.inFlight;this.inFlight=[],await Promise.allSettled(t);}}dispose(){if(this.disposed=true,this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of Qr)e.removeEventListener?.(r,this.visibilityListener);globalThis.document?.removeEventListener?.("resume",this.visibilityListener),this.visibilityListener=null;}}get watchingSeats(){return this.options.watchSeats!==false&&this.emitter.hasListeners("seated")}get seatPollMs(){return this.options.seatPollIntervalMs??as}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new c("misconfigured","the game id is not known yet. It comes from the play token, and this manager was given no way to wait for one \u2014 pass gameId, or awaitGameId so a call made before the first token waits for it the way createGem wires it.")}playerId(){return typeof this.options.playerId=="function"?this.options.playerId():this.options.playerId}version(e){let t=this.options.clientVersion,r=Jr(this.options.platformGameVersion?.(),t?.gameVersion);if(r===null)throw new c("misconfigured",`${e} has no game version to report \u2014 gem-api requires platform, game_version and engine_version together on every room route, and refuses a request carrying two of the three. The arcade normally supplies it with the play token; an embedder that does not, or a build running outside the arcade, leaves nobody to ask. Pass \`clientVersion: { gameVersion }\` to createGem (or to createRoomManager) as the fallback. It has to name a build you actually published, and a wrong one pins the room to the wrong build \u2014 which is why the platform answers it wherever it can.`);return Er({...t,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return ve(await this.options.resolveClusterTargets());let e=q(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,t){return !ei(e)||t.length===0?[]:ve(await this.options.refreshClusterTargets?.(t)??[])}async nextCluster(e,t=false){let r=s=>s.find(a=>!e.includes(a)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!t?o:r(ve(await this.options.refreshClusterTargets?.(i)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let t=this.options.resolveParty;if(t===void 0)return e;let r=await t();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,t,r){if(!(e instanceof H)||e.reason!=="conflict")throw e;if(this.options.recoverStaleMembership===false)throw new H(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let i;try{i=await this.leaveAll(t.signal);}catch{throw new H(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(i.length===0)throw new H(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery cleared nothing, so the refusal stands. myRooms() shows what is held. A room this player was seated in as a party member cannot be cleared from here at all \u2014 only the leader of a party may take it out of a room \u2014 so a member joins by adopting that room, myRooms() then join(), rather than quick-joining.`,e.retryAfterSeconds,e.code);return this.api.quickJoin(t,this.version("quickJoin"),r)}assertNotInRoom(e){if(this.room!==null)throw new c("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}requireRoom(e){if(this.room===null)throw new c("misconfigured",`${e} refused: not in a room.`);return this.room}async run(e,t){try{return await this.track(this.onceGameIdKnown(t))}catch(r){throw this.reportError(e,r),r}}onceGameIdKnown(e){return this.gameId!==null||this.options.awaitGameId===void 0?e():this.options.awaitGameId().then(e)}reportError(e,t){let r=t instanceof H?{operation:e,code:t.status,reason:t.reason,message:t.message,retryable:t.retryable}:{operation:e,code:0,reason:t instanceof c?t.reason:"unavailable",message:t instanceof Error?t.message:String(t),retryable:false};this.emitter.emit("error",r);}track(e){return this.inFlight.push(e),e}enter(e,t){this.room=e,this.abortFollow(),this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(t,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let t=this.room;if(t===null||t.id!==e.id)return;let r=new Map(t.members.map(a=>[a.playerId,a])),i=new Map(e.members.map(a=>[a.playerId,a])),o=this.playerId();for(let a of i.keys())r.has(a)||this.emitter.emit("memberJoined",a);for(let a of r.keys())if(!i.has(a)){if(a===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",a);}for(let[a,d]of i){let l=r.get(a);l&&l.isReady!==d.isReady&&this.emitter.emit("readyChanged",a,d.isReady);}t.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let s=ss(t,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),s&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let t=this.heldMatchId;t!==null&&t!==e&&this.endMatch(t,"replaced",true),this.session={phase:"starting",matchId:e},this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,t=this.heldMatchId;if(e===null||t===null||this.followAbort!==null&&this.followingMatchId===t)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=t,this.track(this.onceGameIdKnown(()=>this.chase(e.id,t,{signal:r.signal})).then(i=>{if(!r.signal.aborted)try{this.settleOutcome(i);}catch{}}).catch(i=>{r.signal.aborted||this.reportError("pollMatchStatus",i);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let t=this.heldMatchId;if(t!==null)return Promise.resolve(t);let r=e.timeoutMs??os;return new Promise((i,o)=>{let s=u=>{a(),d(),this.options.clock.clearTimeout(p),e.signal?.removeEventListener("abort",l),u();},a=this.emitter.on("matchAllocationStarted",u=>s(()=>i(u))),d=this.emitter.on("matchFailed",(u,h)=>s(()=>o(new c("allocation_failed",`match ${u} did not come up: ${h}`)))),l=()=>s(()=>o(new c("aborted","the caller aborted while awaiting a match"))),p=this.options.clock.setTimeout(()=>s(()=>o(new c("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?l():e.signal?.addEventListener("abort",l);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??ns}pushedInterval(){return this.options.pushedPollIntervalMs??rs}pushed(){return this.options.clock.now()-this.lastPushAt<is*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=t=>{t?.persisted!==true&&this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{}));},e.addEventListener("pagehide",this.unloadListener));}};function Dt(){let n=globalThis.document;return n?.visibilityState===void 0||n.visibilityState==="visible"}var Qr=["visibilitychange","focus","pageshow","online"];function ss(n,e){return n.version!==e.version||n.status!==e.status||n.matchId!==e.matchId||n.hostPlayerId!==e.hostPlayerId||n.name!==e.name||n.maxPlayers!==e.maxPlayers||n.isPublic!==e.isPublic||Zr(n)!==Zr(e)}function Zr(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function ei(n){return n instanceof H&&n.code==="invalid_cluster_target"}function ds(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}function ni(n){let e=0,t=new Map;return {resolve(){if(!n.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(i=>{let o={},s=d=>{t.delete(r)&&(n.clock.clearTimeout(o.timer),i(d));};t.set(r,s),o.timer=n.clock.setTimeout(()=>s(void 0),n.timeoutMs??2e3);let a=false;try{a=n.bridge.requestParty(r);}catch{}a||s(void 0);})},settle(r,i){t.get(r)?.(i);}}}
|
|
2
|
+
export{ii as CAPABILITY_GATES,oi as CAPABILITY_NAMESPACE_GATES,It as CHANNELS,Be as CHANNEL_KINDS,ce as ClientTelemetry,$t as DEDICATED_INBOUND_EVENTS,tn as DEFAULT_WELCOME_CEILING_MS,Io as DEVICE_SETTINGS_MAX_BYTES,c as DedicatedServerError,ht as DedicatedSignalingHub,us as FRAME_TO_PARENT,Kt as GemFrame,Wt as GemHost,jt as HANDSHAKE_TIMEOUT_MS,xe as HostMigration,ye as MALFORMED_INBOUND_KEY,Fn as MAX_ARRAY_LENGTH,tt as MAX_CLUSTER_TARGETS,fe as MAX_MESSAGE_BYTES,jn as MAX_MESSAGE_DEPTH,ze as MAX_MESSAGE_NODES,nt as MAX_SIGNALS_PER_SECOND,Le as MAX_SOCKET_FRAME_BYTES,Ur as MIGRATION_TIMEOUT_MS,Ee as P2pApi,k as P2pError,Ie as P2pSession,cs as PARENT_TO_FRAME,y as PROTOCOL,W as PlayerText,Qe as RATE_LIMITS,te as RateLimiter,Me as RoomEmitter,Pe as RoomsApi,Z as SUPPORTED_VERSIONS,Ae as SignalingClient,lt as TELEMETRY_EVENTS,Yn as TRANSPORT_LABELS,se as VALIDATORS,Fe as WEBRTC_DEDICATED,Cn as WEBRTC_P2P,We as WEB_ENGINE_VERSION,he as WEB_PROTOCOL_VERSION,le as asPlayerText,ut as awaitMatchOutcome,At as browserPeerConnection,rt as buildDedicatedOfferFrame,ot as buildSocketFrame,Ze as capabilityFor,ao as createClusterTargetSource,wa as createDedicatedServerApi,Tt as createKeySource,Ja as createP2pApi,ni as createPartyResolver,ti as createRoomManager,Ao as deviceSettingsByteLength,He as establishDataChannel,pe as fingerprintOf,Te as fingerprintsMatch,Ct as generateCertificate,et as isOrigin,mt as listClusterTargets,Ln as memberFromWire,Ut as negotiateVersion,q as normaliseClusterTarget,ve as normaliseClusterTargets,Ke as normaliseFingerprint,Se as originsEqual,Ne as presentJoinCredential,it as projectDedicatedEvent,Ge as projectPartyEvent,at as projectSignal,Mt as roomArgValuesFromWire,Lt as roomArgsTemplateFromWire,X as roomFromWire,ct as startMatch,Xe as summaryFromWire,re as systemClock,Eo as text,gt as unavailableSignaling,to as validateGemAdResult,Vi as validateGemAudioState,_i as validateGemAutoStartFailedEvent,Ii as validateGemClusterTarget,yi as validateGemCohorts,Ti as validateGemDedicatedEvent,Di as validateGemDedicatedOffer,bi as validateGemDeviceSettings,Qi as validateGemDeviceSettingsPut,Zi as validateGemDeviceSettingsResult,Ai as validateGemDevtools,Xi as validateGemError,Hi as validateGemExit,Ji as validateGemFrameStats,Li as validateGemGameContext,ci as validateGemHandshake,ui as validateGemHandshakeAccept,Ui as validateGemLocalServer,qi as validateGemLocalServerDenied,Wi as validateGemOpenExternal,Gi as validateGemPartyRequest,xi as validateGemPartyResult,gi as validateGemPause,hi as validateGemPlayer,fi as validateGemPrefs,Fi as validateGemProgress,zi as validateGemPurchaseResult,ji as validateGemReady,eo as validateGemRequestAd,Mi as validateGemRequestContext,Ki as validateGemRequestFullscreen,$i as validateGemRequestLocalServer,Yi as validateGemRequestPurchase,no as validateGemRequestSignIn,Ni as validateGemRequestToken,Bi as validateGemRewardCue,ki as validateGemRoomEvent,Ci as validateGemScreenshot,Pi as validateGemScreenshotDenied,Ri as validateGemSeatedEvent,ro as validateGemSignInResult,Oi as validateGemSignal,Ei as validateGemSignalEvent,Si as validateGemSocketState,mi as validateGemToken,pi as validateGemTokenDenied,vi as validateGemViewport,wi as validateGemWillTerminate,di as validateSize,xt as verifyCredential};//# sourceMappingURL=gem-web-sdk.esm.js.map
|
|
3
3
|
//# sourceMappingURL=gem-web-sdk.esm.js.map
|