@indiegems/gem-web-sdk 13.2.0 → 13.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/gem-web-sdk.esm.js +1 -1
- package/dist/gem-web-sdk.function.js +1 -1
- 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 +1 -1
- package/docs/api/api-reference-function.md +1 -1
- package/docs/api/api-reference-game.md +4 -5
- package/docs/api/api-reference-server.md +1 -1
- package/docs/api/reference.json +3 -3
- package/docs/changelog.md +12 -0
- package/docs/getting-started.md +1 -1
- package/docs/manifest.json +10 -10
- package/docs/server-bundles.md +2 -2
- package/docs/serverless-functions.md +54 -0
- package/docs/what-a-game-must-do.md +2 -3
- package/package.json +1 -1
package/dist/gem-web-sdk.esm.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:13.2.0]";var h="gem-web-bridge",ee={min:1,max:1},ye=65536,Vn=8,rt=5e3,Hn=1024,Wt=1e4,le=Object.create(null),be="__malformed",Ys=["gem.handshake","gem.token","gem.token.denied","gem.player","gem.pause","gem.prefs","gem.cohorts","gem.earnAllowanceChanged","gem.viewport","gem.deviceSettings","gem.willTerminate","gem.roomEvent","gem.socketState","gem.seatedEvent","gem.autoStartFailedEvent","gem.ticketEvent","gem.signalEvent","gem.dedicatedEvent","gem.partyResult","gem.clusterTarget","gem.devtools","gem.screenshot","gem.requestContext","gem.localServer","gem.localServer.denied","gem.menuSelect","gem.error","gem.purchaseResult","gem.deviceSettings.result","gem.adResult","gem.momentResult","gem.signInResult","gem.friendChallengeResult"],Qs=["gem.handshake.accept","gem.screenshot.denied","gem.gameContext","gem.signal","gem.dedicatedOffer","gem.partyRequest","gem.ready","gem.engaged","gem.progress","gem.requestToken","gem.requestLocalServer","gem.exit","gem.openExternal","gem.requestFullscreen","gem.audioState","gem.rewardCue","gem.walletDisplay","gem.controlsDeclare","gem.menu","gem.gemCorner","gem.requestShare","gem.requestAvatarPicker","gem.vibrate","gem.frameStats","gem.portraitBorders","gem.error","gem.requestPurchase","gem.requestAvatar3dPurchase","gem.deviceSettings.put","gem.requestAd","gem.signalMoment","gem.requestSignIn","gem.requestFriendChallenge"],Bt=Object.create(null),Si=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"]]);function it(n){let e=Bt[n];if(e!==void 0)return e;for(let[t,r]of Si)if(n.startsWith(t))return r}function ot(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 xi(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 Ai(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function Pi(n){return /^[a-z_]+$/.test(n)}function Ut(n,e,t){if(e>Vn)return `nesting deeper than ${Vn}`;if(++t.nodes>rt)return `more than ${rt} values`;if(t.bytes>ye)return `over the ${ye} 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>Hn)return `an array of ${n.length} entries, over the ${Hn} limit`;t.bytes+=2;for(let s of n){let l=Ut(s,e+1,t);if(l)return l}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 a=n;for(let s in a){if(!Object.prototype.hasOwnProperty.call(a,s))continue;if(++t.nodes>rt)return `more than ${rt} values`;if(t.bytes+=s.length*3+4,t.bytes>ye)return `over the ${ye} byte limit`;let l=Ut(a[s],e+1,t);if(l)return l}return null}function Ti(n){let e={nodes:0,bytes:0,seen:new Set},t=Ut(n,0,e);return t?`message contains ${t}`:e.bytes>ye?`message is over the ${ye} byte limit`:null}var Ei={origin:[ot,"not a well-formed origin"],url:[xi,"not a safe absolute http(s) URL"],bcp47:[Ai,"not a well-formed BCP 47 tag"],code:[Pi,"not a code of lower-case letters and underscores"]};function Kn(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 a=Jn(o,r,i);if(a)return a}return null}function Jn(n,e,t){switch(e.k){case "s":{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]=Ei[e.f];if(!r(n))return `${t}: ${i}`}return null}case "i":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 "b":return typeof n=="boolean"?null:`${t}: expected boolean`;case "e":{let r=e.v;return r.includes(n)?null:`${t}: not one of ${r.join("|")}`}case "o":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected object`:Kn(n,e.fs,t);case "j":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected a plain object`:null;case "a":{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 a=Jn(o,r,i);if(a)return a}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}var zn=Object.create(null);function y(n,e,t,r){return le[n]=t,r&&(Bt[n]=r),zn[n]=i=>{let o=Ti(i);if(o)return o;if(typeof i!="object"||i===null||Array.isArray(i))return "message: expected object";let a=i;return a.gem!==h?"gem: wrong protocol marker":a.type!==n?`type: expected ${n}`:Kn(a,e,"")}}var Zs=y("gem.handshake",[{n:"versions",k:"o",fs:[{n:"min",k:"i",lo:1,hi:1e3},{n:"max",k:"i",lo:1,hi:1e3}]},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}},{n:"embedder",k:"s",max:2048,f:"origin"},{n:"unbidden",k:"b",o:1}],30),ea=y("gem.handshake.accept",[{n:"v",k:"i",lo:1,hi:1e3},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}}],5),ta=y("gem.token",[{n:"token",k:"s",max:4096},{n:"requestId",k:"s",o:1,max:64},{n:"generation",k:"i",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"s",o:1,max:512,f:"url"},{n:"playerId",k:"s",max:64},{n:"gameId",k:"s",max:64},{n:"channel",k:"e",v:["dev","test","release"]},{n:"gameVersion",k:"s",o:1,max:64},{n:"expiresAt",k:"i",lo:0,hi:4102444800},{n:"chainEndsAt",k:"i",lo:0,hi:4102444800},{n:"allowDevTools",k:"b",o:1}],30),na=y("gem.token.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:36e5},{n:"reason",k:"e",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"s",max:64}],30),ra=y("gem.player",[{n:"untrusted",k:"o",fs:[{n:"displayName",k:"s",max:64},{n:"displayTag",k:"s",o:1,max:80},{n:"displayHandle",k:"s",max:80}]},{n:"playerId",k:"s",o:1,max:64},{n:"discriminator",k:"s",o:1,max:8},{n:"avatarIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatarIconId",k:"s",o:1,max:64},{n:"avatar3dId",k:"s",o:1,max:64},{n:"avatar3dModelUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatar3dIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatars3d",k:"a",o:1,max:8,it:{n:"",k:"o",fs:[{n:"family",k:"s",max:32},{n:"id",k:"s",max:64},{n:"modelUrl",k:"s",max:256,f:"url"},{n:"iconUrl",k:"s",max:256,f:"url"}]}},{n:"badges",k:"a",o:1,max:2,it:{n:"",k:"o",fs:[{n:"itemId",k:"s",max:64},{n:"iconUrl",k:"s",max:2048,f:"url"}]}},{n:"displayTag",k:"s",max:8},{n:"avatarUrl",k:"s",o:1,max:2048,f:"url"},{n:"boost",k:"o",o:1,fs:[{n:"multipliers",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"currencyId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"multiplierBp",k:"i",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"i",o:1,lo:1,hi:7}]}],12),ia=y("gem.pause",[{n:"paused",k:"b"}],120),oa=y("gem.prefs",[{n:"reducedMotion",k:"b"},{n:"muted",k:"b"},{n:"showFrameStats",k:"b",o:1},{n:"locale",k:"s",max:35,f:"bcp47"},{n:"recommended",k:"o",o:1,fs:[{n:"volume",k:"i",lo:0,hi:100},{n:"batterySaver",k:"b"},{n:"keyboardLayout",k:"e",v:["wasd","arrows"]},{n:"gamepadConfirm",k:"e",v:["south","east"]},{n:"vibration",k:"b"},{n:"lookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"gamepadLookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"invertLookY",k:"b",o:1},{n:"touchMovement",k:"s",o:1,max:16,f:"code"},{n:"graphicsQuality",k:"s",o:1,max:16,f:"code"},{n:"graphicsQualityAuto",k:"b",o:1}]}],60),sa=y("gem.cohorts",[{n:"cohorts",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"experimentId",k:"s",max:36},{n:"variantKey",k:"s",max:32}]}}],12,"cohorts"),aa=y("gem.earnAllowanceChanged",[],30,"earnAllowance"),la=y("gem.viewport",[{n:"insets",k:"o",fs:[{n:"top",k:"i",lo:0,hi:4096},{n:"right",k:"i",lo:0,hi:4096},{n:"bottom",k:"i",lo:0,hi:4096},{n:"left",k:"i",lo:0,hi:4096}]},{n:"reserved",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384},{n:"width",k:"i",lo:0,hi:16384},{n:"height",k:"i",lo:0,hi:16384}]}}],60,"viewport"),da=y("gem.deviceSettings",[{n:"settings",k:"j",o:1}],12,"deviceSettings"),ca=y("gem.willTerminate",[{n:"reason",k:"e",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"i",lo:0,hi:6e4}],10),ua=y("gem.roomEvent",[{n:"event",k:"e",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"s",max:64},{n:"matchId",k:"s",o:1,max:64},{n:"version",k:"i",o:1,lo:0,hi:2147483647},{n:"reason",k:"s",o:1,max:64},{n:"platform",k:"e",o:1,v:["universal","mobile"]}],120,"rooms"),ma=y("gem.socketState",[{n:"connected",k:"b"},{n:"reason",k:"e",o:1,v:["connecting","dropped","watchdog","terminal"]}],12,"socketState"),pa=y("gem.seatedEvent",[{n:"roomId",k:"s",max:64}],60,"partySeating"),ga=y("gem.autoStartFailedEvent",[{n:"roomId",k:"s",max:64},{n:"code",k:"s",max:64}],30,"autoStartFailure"),ha=y("gem.ticketEvent",[{n:"event",k:"e",v:["queued","matched","expired","cancelled","failed"]},{n:"ticketId",k:"s",max:64},{n:"partySize",k:"i",o:1,lo:1,hi:64},{n:"queuedAt",k:"i",o:1,lo:0,hi:4102444800},{n:"expiresAt",k:"i",o:1,lo:0,hi:4102444800},{n:"reason",k:"s",o:1,max:64},{n:"roomId",k:"s",o:1,max:64}],60,"ticketEvents"),fa=y("gem.signalEvent",[{n:"event",k:"e",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}],1800,"p2p"),ya=y("gem.dedicatedEvent",[{n:"event",k:"e",v:["answer","error","matchEnded"]},{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",o:1,max:10240},{n:"sessionId",k:"s",o:1,max:64},{n:"code",k:"s",o:1,max:64},{n:"message",k:"s",o:1,max:256},{n:"reason",k:"s",o:1,max:64}],120,"dedicated"),ba=y("gem.partyResult",[{n:"requestId",k:"s",max:64},{n:"partyId",k:"s",o:1,max:64}],30,"parties"),va=y("gem.clusterTarget",[{n:"clusterTargetId",k:"s",max:64},{n:"clusterTargetIds",k:"a",o:1,max:3,it:{n:"",k:"s",max:64}}],12,"clusterTarget"),_a=y("gem.devtools",[{n:"action",k:"e",v:["open","close","toggle"]}],30,"devtools"),ka=y("gem.screenshot",[{n:"maxWidth",k:"i",lo:1,hi:7680},{n:"maxHeight",k:"i",lo:1,hi:4320}],6,"screenshot"),wa=y("gem.screenshot.denied",[{n:"reason",k:"e",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"b"}],12,"screenshot"),Ra=y("gem.requestContext",[],12,"feedbackContext"),Sa=y("gem.gameContext",[{n:"context",k:"j"}],12,"feedbackContext"),xa=y("gem.signal",[{n:"signal",k:"e",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}],1200,"p2p"),Aa=y("gem.dedicatedOffer",[{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",max:10240},{n:"intent",k:"e",v:["initial","ice_restart","full_reconnect"]}],60,"dedicated"),Pa=y("gem.partyRequest",[{n:"requestId",k:"s",max:64}],12,"parties"),Ta=y("gem.ready",[],5),Ea=y("gem.engaged",[],5,"engagement"),Ia=y("gem.progress",[{n:"loaded",k:"i",lo:0,hi:1099511627776},{n:"total",k:"i",lo:0,hi:1099511627776}],600),Ca=y("gem.requestToken",[{n:"requestId",k:"s",max:64},{n:"reason",k:"e",v:["initial","expiring","rejected"]}],12),Ma=y("gem.requestLocalServer",[{n:"requestId",k:"s",max:64},{n:"gameRoomId",k:"s",max:64}],6,"localHost"),Oa=y("gem.localServer",[{n:"requestId",k:"s",max:64},{n:"serverId",k:"s",o:1,max:128}],30,"localHost"),La=y("gem.localServer.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"reason",k:"e",v:["refused","unavailable"]}],30,"localHost"),Ga=y("gem.exit",[{n:"reason",k:"s",o:1,max:64}],5),Da=y("gem.openExternal",[{n:"url",k:"s",max:2048,f:"url"}],6),qa=y("gem.requestFullscreen",[{n:"enabled",k:"b"}],30),$a=y("gem.audioState",[{n:"muted",k:"b"}],120,"audioState"),Fa=y("gem.rewardCue",[{n:"currencySlug",k:"s",max:32},{n:"expected",k:"i",o:1,lo:1,hi:1e9},{n:"origin",k:"o",o:1,fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384}]}],60,"rewardCue"),ja=y("gem.walletDisplay",[{n:"visible",k:"b"},{n:"currencies",k:"a",o:1,max:8,it:{n:"",k:"s",max:64}},{n:"score",k:"b",o:1}],60,"walletDisplay"),Na=y("gem.controlsDeclare",[{n:"uses",k:"o",fs:[{n:"lookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"gamepadLookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"invertLookY",k:"s",o:1,max:16,f:"code"},{n:"touchMovement",k:"s",o:1,max:16,f:"code"}]}],60,"controls"),Ua=y("gem.menu",[{n:"settings",k:"b"},{n:"items",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"id",k:"s",max:32},{n:"label",k:"s",max:40}]}}],60,"gameMenu"),Wa=y("gem.menuSelect",[{n:"entry",k:"e",v:["settings","item"]},{n:"id",k:"s",o:1,max:32}],60,"gameMenu"),Ba=y("gem.gemCorner",[{n:"corner",k:"e",v:["top-left","top-right","bottom-left","bottom-right"]}],12,"gemCorner"),Va=y("gem.requestShare",[{n:"params",k:"a",max:16,it:{n:"",k:"o",fs:[{n:"key",k:"s",max:64},{n:"value",k:"s",max:512}]}}],6,"share"),Ha=y("gem.requestAvatarPicker",[{n:"tab",k:"e",o:1,v:["2d","3d"]}],6,"avatarPicker"),Ka=y("gem.vibrate",[{n:"pattern",k:"a",max:99,it:{n:"",k:"i",lo:0,hi:1e4}}],600,"vibration"),Ja=y("gem.frameStats",[{n:"fps",k:"i",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"i",lo:0,hi:1e5}],120,"frameStats"),za=y("gem.portraitBorders",[{n:"name",k:"s",o:1,max:40}],60,"portraitBorders"),Xa=y("gem.error",[{n:"code",k:"e",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"s",o:1,max:256}],60),Ya=y("gem.requestPurchase",[{n:"requestId",k:"s",max:64},{n:"purchaseKind",k:"e",v:["item","recipe"]},{n:"targetId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"quantity",k:"i",o:1,lo:1,hi:10},{n:"catalogId",k:"s",o:1,max:64}],12,"purchases"),Qa=y("gem.requestAvatar3dPurchase",[{n:"requestId",k:"s",max:64},{n:"itemId",k:"s",max:64},{n:"currencySlug",k:"s",max:32}],12,"avatar3dPurchases"),Za=y("gem.purchaseResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["ok","declined","unavailable"]},{n:"reason",k:"s",o:1,max:64,f:"code"},{n:"purchaseId",k:"s",o:1,max:64}],30,"purchases"),el=y("gem.deviceSettings.put",[{n:"requestId",k:"s",max:64},{n:"settings",k:"j"}],30,"deviceSettings"),tl=y("gem.deviceSettings.result",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["stored","too_large","unavailable"]}],30,"deviceSettings"),nl=y("gem.requestAd",[{n:"requestId",k:"s",max:64},{n:"placement",k:"s",max:32},{n:"format",k:"e",v:["interstitial","rewarded"]}],6,"ads"),rl=y("gem.adResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["shown","no_ad","unavailable"]}],12,"ads"),il=y("gem.signalMoment",[{n:"requestId",k:"s",max:64},{n:"kind",k:"e",v:["level_end","run_end","match_end","menu_return","other_break"]},{n:"placement",k:"s",o:1,max:32}],6,"moments"),ol=y("gem.momentResult",[{n:"requestId",k:"s",max:64},{n:"shown",k:"b"}],12,"moments"),sl=y("gem.requestSignIn",[{n:"requestId",k:"s",max:64}],6,"signIn"),al=y("gem.signInResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["signed_in","declined","unavailable"]}],12,"signIn"),ll=y("gem.requestFriendChallenge",[{n:"requestId",k:"s",max:64},{n:"playerId",k:"s",max:64},{n:"template",k:"s",max:64},{n:"params",k:"j",o:1}],12,"friendChallenges"),dl=y("gem.friendChallengeResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"s",o:1,max:64},{n:"param",k:"s",o:1,max:64},{n:"channel",k:"s",o:1,max:16},{n:"configVersion",k:"i",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:864e5},{n:"detail",k:"s",o:1,max:300}],30,"friendChallenges"),de=Object.freeze(zn);le.__malformed=60;Object.freeze(le);Object.freeze(Bt);var st=3;function W(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=W(t);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Ii=2e3,Ci=5e3;function Mi(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 a,s=new Promise(l=>{let d=false,m=null;a=c=>{d||(d=true,r=null,n.clock.clearTimeout(m),l(c));},m=n.clock.setTimeout(()=>{t=true,a([]);},n.timeoutMs??Ii);});return r={promise:s,settle:a},s};return {resolveList:o,resolve(){return e.length>0||t||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(a=>a[0])},refresh(a){return !Xn(e,a)||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(s=>{let l=null,d=m=>{i.delete(d)&&(n.clock.clearTimeout(l),s(m));};i.set(d,a),l=n.clock.setTimeout(()=>d(e),n.refreshTimeoutMs??Ci);})},accept(a,s){let l=ve(s),d=W(a),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[c,p]of [...i])Xn(m,p)||c(m);}}}}function Xn(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Oi=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Vt(n){return typeof n=="string"&&Oi.test(n)}function Yn(n){if(n===null||Vt(n))return n;let e=typeof n=="string"?JSON.stringify(n.length>48?`${n.slice(0,48)}\u2026`:n):`a value of type ${typeof n}`;console.warn(`[gem] showPortraitBorders: ${e} is not a border name, so nothing was sent. A name is 1 to 40 of a-z, 0-9, _ and -, starting with a letter or digit, exactly as your store page declares it under media.portrait_borders. Pass null for no art.`);}var De=16384,at=24;function S(n){return e=>typeof e=="string"&&e.length>0&&e.length<=n?e:void 0}function te(n,e){return t=>typeof t=="number"&&Number.isInteger(t)&&t>=n&&t<=e?t:void 0}function _e(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function Qn(n){return typeof n=="boolean"?n:void 0}var L=S(64),qe=te(0,2147483647);function Ht(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 T(n,e,t){return {to:n,from:e,read:t,required:true}}function x(n,e,t){return {to:n,from:e,read:t,required:false}}function ke(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 $e(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 Zn=[T("sdp","sdp",S(10240)),T("signaling_intent","intent",_e("initial","ice_restart","full_reconnect"))];function lt(n,e,t){if(typeof t!="object"||t===null||Array.isArray(t))return {reason:"offer: data must be an object"};let r=t,i=ke(r,Zn);return i===null?{reason:`offer: '${Zn.find(a=>a.read(r[a.from])===void 0)?.from??"?"}' is missing or out of bounds`}:{frame:{type:"webrtc_offer",match_id:n,game_id:e,...i}}}var Kt=Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"})),Li=new Set(["error"]),Gi=Object.freeze(Object.assign(Object.create(null),{answer:[T("sdp","sdp",S(10240)),x("sessionId","session_id",S(64))],error:[x("code","code",S(64)),x("message","message",S(256))],matchEnded:[x("reason","reason",S(64))]}));function dt(n,e,t){let r=$e(n);if(r===null)return null;let i=Kt[r.type];if(i===void 0)return null;let o=L(r.data.match_id);if(typeof o!="string"||!(Li.has(i)?t(o):r.data.game_id===e))return null;let s=ke(r.data,Gi[i]??[]);return s===null?null:{event:i,matchId:o,...s}}var Di=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=_e("disconnected","failed","closed")(e.iceState),r=te(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}}},qi=Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[T("sdp","sdp",S(10240)),T("signaling_intent","intent",_e("initial","ice_restart","full_reconnect")),x("sdp_hash","sdpHash",S(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[T("peer_id","peerId",L),T("sdp","sdp",S(10240)),T("assigned_peer_id","assignedPeerId",te(0,4294967295)),x("sdp_hash","sdpHash",S(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[T("peer_id","peerId",L),T("candidate","candidate",S(512)),x("sdp_mid","sdpMid",S(64)),x("sdp_mline_index","sdpMLineIndex",te(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[T("host_epoch","hostEpoch",qe)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[T("host_epoch","hostEpoch",qe),x("evidence","evidence",Di)]}}));function ct(n,e,t,r){let i=qi[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,a=ke(o,i.args);if(a===null){let s=i.args.find(l=>l.required&&l.read(o[l.from])===void 0);return {reason:`${n}: '${s?.from??"?"}' is missing or out of bounds`}}return {frame:{type:i.type,match_id:e,...i.gameScoped?{game_id:t}:{},...a}}}var $i=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"})),Fi=new Set(["error"]),ji=Object.freeze(Object.assign(Object.create(null),{hello:[T("playerId","player_id",L),T("hostPlayerId","host_player_id",L),T("hostEpoch","host_epoch",qe),x("members","members",Ht)],offer:[T("fromPlayerId","from_player_id",L),T("sdp","sdp",S(10240)),x("sessionId","signaling_session_id",S(128)),x("sdpHash","sdp_hash",S(128)),x("iceUfrag","ice_ufrag",S(64)),x("intent","signaling_intent",_e("initial","ice_restart","full_reconnect"))],answer:[T("fromPlayerId","from_player_id",L),T("sdp","sdp",S(10240)),x("sessionId","signaling_session_id",S(128)),x("sdpHash","sdp_hash",S(128)),x("iceUfrag","ice_ufrag",S(64)),x("assignedPeerId","assigned_peer_id",te(0,4294967295))],ice:[T("fromPlayerId","from_player_id",L),T("candidate","candidate",S(512)),x("sdpMid","sdp_mid",S(64)),x("sdpMLineIndex","sdp_m_line_index",te(0,255)),x("sdpMLineIndexAlt","sdp_mline_index",te(0,255))],peerJoined:[T("playerId","player_id",L)],peerLeft:[T("playerId","player_id",L),x("reason","reason",S(64))],migration:[T("hostPlayerId","new_host_player_id",L),T("hostEpoch","host_epoch",qe),x("reason","reason",S(64)),x("kickedPlayerIds","kicked_player_ids",Ht),x("migrationComplete","migration_complete",Qn)],matchEnded:[x("reason","reason",S(64))],error:[x("code","code",S(64)),x("message","message",S(256))]}));function ut(n,e,t){let r=$e(n);if(r===null)return null;let i=$i[r.type];if(i===void 0)return null;let o=L(r.data.match_id);if(typeof o!="string"||!(Fi.has(i)?t(o):r.data.game_id===e))return null;let s=ke(r.data,ji[i]??[]);return s===null?null:{event:i,matchId:o,data:s}}var Ni=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 Fe(n){let e=$e(n);if(e===null)return null;let t=Ni[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=te(0,Number.MAX_SAFE_INTEGER)(r.version),a=L(r.game_room_id),s=L(r.game_id),l=L(r.inviter_player_id),d=S(80)(r.inviter_display_tag),m=S(64)(r.party_name);return {event:t,partyId:i,...o===void 0?{}:{version:o},...a===void 0?{}:{gameRoomId:a},...s===void 0?{}:{gameId:s},...l===void 0?{}:{inviterPlayerId:l},...d===void 0?{}:{inviterDisplayTag:d},...m===void 0?{}:{partyName:m}}}var ie={now:()=>Date.now(),setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n)},ne=class{constructor(e=ie){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let t=le[e];if(t===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??t,a=Math.max(0,r-i),s=Math.min(t,o+a*t/6e4);return s<1?(this.tokens.set(e,s),this.lastRefill.set(e,r),false):(this.tokens.set(e,s-1),this.lastRefill.set(e,r),true)}};function Re(n,e){return n.toLowerCase()===e.toLowerCase()}function mt(n){let e=n.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function tr(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:mt(t.hostname)&&mt(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 Ui=7,zt=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Wi=/^[a-z][a-z0-9_]{0,31}$/,Bi=8,rr=256,Vi=["universal","mobile"],Hi={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"},Ki=new Set(["match_ended","p2p_match_ended"]),Ji="game_room_auto_start_failed",ir={matchmaking_ticket_queued:"queued",matchmaking_ticket_matched:"matched",matchmaking_ticket_expired:"expired",matchmaking_ticket_cancelled:"cancelled",matchmaking_ticket_failed:"failed"},zi=64,or=/^[a-z][a-z0-9_]{0,63}$/,je=64,Xi=8,Yt=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 Se(n){if(!(typeof n!="string"||n.length===0||n.length>je))return n}function sr(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>=0?n:void 0}function Yi(n){return n instanceof Error?n.message:String(n)}function ar(n,e){if(!n.has(e)){if(n.size>=Xi){let t=n.values().next().value;t!==void 0&&n.delete(t);}n.add(e);}}function Xt(){return new MessageChannel}var Qi=6e4/(le["gem.handshake"]??1),Zi=6e4,Qt=class{constructor(e){this.options=e;if(!ot(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(!ot(e.embedderOrigin))throw new Error(`GemHost: embedderOrigin must be a concrete origin, got '${e.embedderOrigin}'.`);this.clock=e.clock??ie,this.inbound=new ne(this.clock),this.outbound=new ne(this.clock),this.socketWindow=new Yt(this.clock,24);}options;state="idle";port=null;version=null;timeoutHandle=null;reofferHandle=null;makeChannel=Xt;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=Xt){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?Xt():(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 ${Wt}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.`);},Wt);}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:h,type:"gem.handshake",versions:{min:ee.min,max:ee.max},embedder:this.options.embedderOrigin,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]},...this.options.unbidden===true?{unbidden:true}:{}},this.options.frameOrigin,[e.port2]),true}scheduleReoffer(){this.reofferHandle=this.clock.setTimeout(()=>{this.reofferHandle=null,this.state==="handshaking"&&(this.offer(),this.pruneStaleOffers(),this.scheduleReoffer());},Qi);}pruneStaleOffers(){let e=this.clock.now()-Zi;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 Re(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:h,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=Hi[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=Se(i.game_room_id);if(o===void 0)return false;let a=Ki.has(t.type)?void 0:Se(i.match_id);a!==void 0&&this.rememberMatch(a);let s=typeof i.version=="number"?i.version:void 0,l=typeof i.reason=="string"?i.reason.slice(0,je):void 0,d=r==="version_stale"&&Vi.includes(i.platform)?i.platform:void 0;return this.sendRoomEvent({event:r,roomId:o,...a===void 0?{}:{matchId:a},...s===void 0?{}:{version:s},...l===void 0?{}:{reason:l},...d===void 0?{}:{platform:d}})}sendRoomEvent(e){return this.frameSupports("rooms")?this.send({gem:h,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:h,type:"gem.socketState",connected:e.connected,...e.connected?{}:{reason:e.reason}}):false}sendSeatedEvent(e){return this.frameSupports("partySeating")?this.send({gem:h,type:"gem.seatedEvent",roomId:e}):false}relaySeatedEvent(e){if(this.gameId===null)return false;let t=Fe(e);if(t===null||t.event!=="gameRoomJoined"||t.gameId!==this.gameId)return false;let r=Se(t.gameRoomId);return r===void 0?false:this.sendSeatedEvent(r)}sendAutoStartFailedEvent(e){return this.frameSupports("autoStartFailure")?this.send({gem:h,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!==Ji||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=Se(r.game_room_id),o=typeof r.code=="string"&&or.test(r.code)?r.code:void 0;return i===void 0||o===void 0?false:this.sendAutoStartFailedEvent({roomId:i,code:o})}sendTicketEvent(e){return this.frameSupports("ticketEvents")?this.send({gem:h,type:"gem.ticketEvent",event:e.event,ticketId:e.ticketId,...e.partySize===void 0?{}:{partySize:e.partySize},...e.queuedAt===void 0?{}:{queuedAt:e.queuedAt},...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt},...e.reason===void 0?{}:{reason:e.reason},...e.roomId===void 0?{}:{roomId:e.roomId}}):false}relayTicketEvent(e){if(this.gameId===null||typeof e!="object"||e===null||Array.isArray(e))return false;let t=e;if(typeof t.type!="string"||!Object.hasOwn(ir,t.type))return false;let r=ir[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=Se(i.ticket_id);if(o===void 0)return false;if(r==="queued"){let s=typeof i.party_size=="number"&&Number.isInteger(i.party_size)&&i.party_size>=1&&i.party_size<=zi?i.party_size:void 0,l=sr(i.queued_at),d=sr(i.expires_at);return this.sendTicketEvent({event:r,ticketId:o,...s===void 0?{}:{partySize:s},...l===void 0?{}:{queuedAt:l},...d===void 0?{}:{expiresAt:d}})}if(r==="matched"){let s=Se(i.game_room_id);return this.sendTicketEvent({event:r,ticketId:o,...s===void 0?{}:{roomId:s}})}let a=typeof i.reason=="string"&&or.test(i.reason)?i.reason:void 0;return this.sendTicketEvent({event:r,ticketId:o,...a===void 0?{}:{reason:a}})}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"),this.relayTicketEvent(e)&&t.push("ticket");let r=Fe(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=ut(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:h,type:"gem.signalEvent",event:e.event,matchId:e.matchId,data:e.data}):false}relayDedicatedEvent(e){if(this.gameId===null)return false;let t=dt(e,this.gameId,r=>this.knowsMatch(r));return t===null?false:this.sendDedicatedEvent(t)}sendDedicatedEvent(e){return this.frameSupports("dedicated")?this.send({gem:h,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){ar(this.knownMatches,e);}rememberAsked(e){ar(this.askedMatches,e);}answerPartyRequest(e,t){return this.send({gem:h,type:"gem.partyResult",requestId:e,...t===void 0?{}:{partyId:t}})}answerPurchase(e,t,r,i){return this.send({gem:h,type:"gem.purchaseResult",requestId:e,outcome:t,...r===void 0||t!=="ok"?{}:{purchaseId:r},...i===void 0||t==="ok"?{}:{reason:i}})}answerDeviceSettingsPut(e,t){return this.send({gem:h,type:"gem.deviceSettings.result",requestId:e,outcome:t})}sendDeviceSettings(e){return this.frameSupports("deviceSettings")?this.send({gem:h,type:"gem.deviceSettings",...e===void 0?{}:{settings:e}}):false}sendMenuSelect(e){return this.frameSupports("gameMenu")?this.send(e==="settings"?{gem:h,type:"gem.menuSelect",entry:"settings"}:{gem:h,type:"gem.menuSelect",entry:"item",id:e.id}):false}answerAd(e,t){return this.send({gem:h,type:"gem.adResult",requestId:e,outcome:t})}answerMoment(e,t){return this.send({gem:h,type:"gem.momentResult",requestId:e,shown:t})}answerSignIn(e,t){return this.send({gem:h,type:"gem.signInResult",requestId:e,outcome:t})}answerFriendChallenge(e,t,r={}){let i={};if(t==="invalid"){let{code:o,param:a,channel:s,configVersion:l,detail:d}=r;typeof o=="string"&&o.length<=64&&(i.code=o),typeof a=="string"&&a.length<=64&&(i.param=a),typeof s=="string"&&s.length<=16&&(i.channel=s),typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&(i.configVersion=l),typeof d=="string"&&(i.detail=d.slice(0,300));}else if(t==="rate_limited"){let o=r.retryAfterMs;typeof o=="number"&&Number.isFinite(o)&&(i.retryAfterMs=Math.min(864e5,Math.max(0,Math.round(o))));}return this.send({gem:h,type:"gem.friendChallengeResult",requestId:e,outcome:t,...i})}denyToken(e){this.send({gem:h,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:h,type:"gem.localServer",requestId:e.requestId,...e.serverId===void 0?{}:{serverId:e.serverId}}):false}denyLocalServer(e){return this.frameSupports("localHost")?this.send({gem:h,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:h,type:"gem.clusterTarget",clusterTargetId:i,...typeof e=="string"?{}:{clusterTargetIds:[...t]}})}sendPlayer(e){let{displayName:t,displayTag:r}=e.untrusted,i=e.badges?.map(({itemId:m,iconUrl:c})=>({itemId:m,iconUrl:c})),o=e.boost&&{multipliers:e.boost.multipliers.map(({currencyId:m,currencySlug:c,multiplierBp:p})=>({currencyId:m,currencySlug:c,multiplierBp:p})),...e.boost.expiresInDays===void 0?{}:{expiresInDays:Math.min(Ui,e.boost.expiresInDays)}},a=e.discriminator!==void 0&&/^[0-9]{1,8}$/.test(e.discriminator)?e.discriminator:void 0,s=e.avatarIconId!==void 0&&zt.test(e.avatarIconId)?e.avatarIconId:void 0,l=e.avatar3dId!==void 0&&zt.test(e.avatar3dId)?e.avatar3dId:void 0,d;if(e.avatars3d!==void 0){let m=new Set;d=[];for(let{family:c,id:p,modelUrl:f,iconUrl:b}of e.avatars3d){if(d.length===Bi)break;!zt.test(p)||!Wi.test(c)||m.has(c)||f.length>rr||b.length>rr||(m.add(c),d.push({family:c,id:p,modelUrl:f,iconUrl:b}));}}this.send({gem:h,type:"gem.player",untrusted:{displayName:t,...r===void 0?{}:{displayTag:r},displayHandle:r??t},...e.playerId===void 0?{}:{playerId:e.playerId},...a===void 0?{}:{discriminator:a},...e.avatarIconUrl===void 0?{}:{avatarIconUrl:e.avatarIconUrl},...s===void 0?{}:{avatarIconId:s},...l===void 0?{}:{avatar3dId:l},...e.avatar3dModelUrl===void 0?{}:{avatar3dModelUrl:e.avatar3dModelUrl},...e.avatar3dIconUrl===void 0?{}:{avatar3dIconUrl:e.avatar3dIconUrl},...d===void 0?{}:{avatars3d:d},...i===void 0?{}:{badges:i},...o===void 0?{}:{boost:o},displayTag:a??"",...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:h,type:"gem.pause",paused:e});}sendDevtools(e){this.send({gem:h,type:"gem.devtools",action:e});}requestScreenshot(e,t){return this.frameSupports("screenshot")?this.send({gem:h,type:"gem.screenshot",maxWidth:t.maxWidth,maxHeight:t.maxHeight},[e]):false}requestContext(){return this.frameSupports("feedbackContext")?this.send({gem:h,type:"gem.requestContext"}):false}sendPrefs(e){this.send({gem:h,type:"gem.prefs",...e});}sendCohorts(e){return this.frameSupports("cohorts")?this.send({gem:h,type:"gem.cohorts",cohorts:e.map(t=>({experimentId:t.experimentId,variantKey:t.variantKey}))}):false}sendEarnAllowanceChanged(){return this.frameSupports("earnAllowance")?this.send({gem:h,type:"gem.earnAllowanceChanged"}):false}sendViewport(e){if(!this.frameSupports("viewport"))return false;let t=(e.reserved??[]).map(({x:o,y:a,width:s,height:l})=>({x:o,y:a,width:s,height:l})),r=this.frameSupports("reservedAreas"),i=e.insets.top;if(!r)for(let o of t)o.y===0&&(i=Math.max(i,o.height));return this.send({gem:h,type:"gem.viewport",insets:{top:i,right:e.insets.right,bottom:e.insets.bottom,left:e.insets.left},...r?{reserved:t}:{}})}sendWillTerminate(e,t){this.send({gem:h,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=de[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=de[r];if(!i){this.refuseMalformed("unsupported",`unknown message type ${JSON.stringify(r.slice(0,je))}`);return}if(r==="gem.controlsDeclare")return;if(!this.inbound.allow(r)){this.fail("rate_limited",`frame exceeded the limit for ${r}`);return}let o=it(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 a=i(e);if(a){this.fail("invalid_message",`${r}: ${a}`);return}let s=e;r!=="gem.handshake.accept"&&!this.versionMatches(s,r)||this.dispatch(r,s,t);}refuseMalformed(e,t){if(!this.inbound.allow(be)){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=ct(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=lt(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: ${Yi(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<ee.min||i>ee.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.engaged":this.options.onEngaged?.();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.walletDisplay":this.options.onWalletDisplay?.(t);break;case "gem.menu":this.options.onMenu?.(t);break;case "gem.gemCorner":this.options.onGemCorner?.(t);break;case "gem.frameStats":this.options.onFrameStats?.(t);break;case "gem.portraitBorders":{let{name:i}=t;i==null?this.options.onPortraitBorders?.(null):Vt(i)&&this.options.onPortraitBorders?.(i);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.requestAvatar3dPurchase":{let i=t;if(!this.frameSupports("avatar3dPurchases")||!this.frameSupports("purchases")){this.fail("unsupported_capability","refusing gem.requestAvatar3dPurchase: the frame did not advertise 'avatar3dPurchases' and 'purchases', so it cannot receive gem.purchaseResult. Nothing was prompted and nothing was spent.");break}if(this.options.onRequestAvatar3dPurchase===void 0){this.answerPurchase(i.requestId,"unavailable");break}this.options.onRequestAvatar3dPurchase(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.signalMoment":{let i=t;if(!this.frameSupports("moments")){this.fail("unsupported_capability","refusing gem.signalMoment: the frame did not advertise 'moments', so it cannot receive gem.momentResult. Nothing was rendered.");break}if(this.options.onSignalMoment===void 0){this.answerMoment(i.requestId,false);break}this.options.onSignalMoment(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.requestFriendChallenge":{let i=t;if(!this.frameSupports("friendChallenges")){this.fail("unsupported_capability","refusing gem.requestFriendChallenge: the frame did not advertise 'friendChallenges', so it cannot receive gem.friendChallengeResult. Nothing was previewed, rendered or sent.");break}if(this.options.onRequestFriendChallenge===void 0){this.answerFriendChallenge(i.requestId,"unavailable");break}this.options.onRequestFriendChallenge(i);break}case "gem.requestShare":if(!this.frameSupports("share")){this.fail("unsupported_capability","refusing gem.requestShare: the frame did not advertise 'share'. Nothing was shared.");break}this.options.onRequestShare?.(t);break;case "gem.requestAvatarPicker":if(!this.frameSupports("avatarPicker")){this.fail("unsupported_capability","refusing gem.requestAvatarPicker: the frame did not advertise 'avatarPicker'. Nothing was opened.");break}{let i=t.tab;this.options.onRequestAvatarPicker?.(i==="2d"||i==="3d"?{tab:i}:{});}break;case "gem.vibrate":{if(!this.frameSupports("vibration")){this.fail("unsupported_capability","refusing gem.vibrate: the frame did not advertise 'vibration'. Nothing was played.");break}let i=t,o=i.pattern.reduce((a,s)=>a+s,0);if(o>1e4){this.fail("invalid_message",`refusing gem.vibrate: the pattern totals ${o} ms, over ${1e4}. Nothing was played.`);break}this.options.onVibrate?.(i);break}case "gem.error":this.fail(t.code,t.message);break;default:this.fail("unsupported",`no parent handler for '${e}'`);}}};var B=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 ue(n){return new B(n)}var eo={toPlain(n){return B.unwrap(n)},compare(n,e,t){let r=n instanceof B?B.unwrap(n):n,i=e instanceof B?B.unwrap(e):e;if(typeof Intl>"u"||typeof Intl.Collator!="function")return r<i?-1:r>i?1:0;let o;try{o=new Intl.Collator(t);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(n,e){let t=n instanceof B?B.unwrap(n):n,r=e instanceof B?B.unwrap(e):e;return t.normalize("NFC")===r.normalize("NFC")}};function lr(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function to(n,e){if(n!==true)return {visible:false};let t=[],r=false;for(let i of Array.isArray(e)?e:[])i==="score"?r=true:typeof i=="string"&&i.length>0&&i.length<=64&&!t.includes(i)&&t.push(i);return !r&&t.length===0?{visible:true}:{visible:true,currencies:t.slice(0,8),score:r}}function no(n){let e=[];for(let t of Array.isArray(n)?n:[]){if(e.length===4)break;if(typeof t!="object"||t===null)continue;let{id:r,label:i}=t;typeof r!="string"||r.length===0||r.length>32||typeof i!="string"||i.trim().length===0||e.some(o=>o.id===r)||e.push({id:r,label:i.trim().slice(0,40)});}return e.length===0?{settings:false}:{settings:false,items:e}}function dr(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function ro(n){let e=n.untrusted,t=ue(e.displayName),r=e.displayTag||e.displayHandle,i=r?ue(r):void 0,o=n.discriminator||n.displayTag,a=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,s=n.avatarIconUrl||n.avatarUrl,l=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,d=n.avatarIconId,m=n.avatar3dId,c={displayName:t,displayHandle:i??t,badges:(n.badges??[]).map(w=>({itemId:w.itemId,iconUrl:w.iconUrl}))};n.playerId&&(c.playerId=n.playerId),a&&(c.discriminator=a),i&&(c.displayTag=i),s&&(c.avatarIconUrl=c.avatarUrl=s),d&&l.test(d)&&(c.avatarIconId=d),m&&l.test(m)&&(c.avatar3dId=m),n.avatar3dModelUrl&&(c.avatar3dModelUrl=n.avatar3dModelUrl),n.avatar3dIconUrl&&(c.avatar3dIconUrl=n.avatar3dIconUrl),n.avatars3d&&(c.avatars3d=n.avatars3d.filter(w=>l.test(w.id)&&/^[a-z][a-z0-9_]*$/.test(w.family)).filter((w,A,C)=>C.findIndex(E=>E.family==w.family)==A).map(({family:w,id:A,modelUrl:C,iconUrl:E})=>({family:w,id:A,modelUrl:C,iconUrl:E})));let p=n.boost,f=(p?.multipliers??[]).map(w=>({currencyId:w.currencyId,currencySlug:w.currencySlug,multiplier:w.multiplierBp/1e4})),b=f.some(w=>w.multiplier>1);return c.boost=b&&p?.expiresInDays?{active:b,multipliers:f,expiresInDays:p.expiresInDays}:{active:b,multipliers:f},c}var io=1e4,Zt=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??ie,this.inbound=new ne(this.clock),this.outbound=new ne(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;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}get unbiddenLaunch(){return this.unbidden}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(s=>Re(s,e.origin))||tr(e.origin,this.options.selfOrigin)))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),this.state==="waiting"&&this.transition("refused"),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=de["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!Re(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 a=Jt(ee,i.versions);return a===null?(o.onmessage=null,o.postMessage({gem:h,type:"gem.error",code:"version_mismatch",message:`frame supports v${ee.min}..v${ee.max}`}),o.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=o,this.version=a,o.onmessage=s=>this.receive(s.data,s.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],this.unbidden=i.unbidden===true,o.postMessage({gem:h,type:"gem.handshake.accept",v:a,...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:h,type:"gem.ready"});}settled(e=io){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:h,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:h,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:h,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),true):false}exit(e){this.send(e===void 0?{gem:h,type:"gem.exit"}:{gem:h,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:h,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:h,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.gated("audioState")?(this.send({gem:h,type:"gem.audioState",muted:e}),true):false}reportEngaged(){return this.engagedSent||!this.gated("engagement")||!this.send({gem:h,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(!this.gated("rewardCue"))return false;let t={gem:h,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:lr(e.origin.x),y:lr(e.origin.y)}),this.send(t),true}showPortraitBorders(e){let t=Yn(e);return t===void 0||!this.gated("portraitBorders")?false:this.send(t===null?{gem:h,type:"gem.portraitBorders"}:{gem:h,type:"gem.portraitBorders",name:t})}setWalletVisible(e,t){return this.gated("walletDisplay")?this.send({gem:h,type:"gem.walletDisplay",...to(e,t?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:h,type:"gem.menu",...no(e)}):false}setGemCorner(e){return this.gated("gemCorner")?this.send({gem:h,type:"gem.gemCorner",corner:e}):false}requestShare(e){return this.gated("share")?this.send({gem:h,type:"gem.requestShare",params:e.map(({key:t,value:r})=>({key:t,value:r}))}):false}requestAvatarPicker(e){return this.gated("avatarPicker")?this.send({gem:h,type:"gem.requestAvatarPicker",...e==="2d"||e==="3d"?{tab:e}:{}}):false}requestVibrate(e){return this.gated("vibration")?this.send({gem:h,type:"gem.vibrate",pattern:[...e]}):false}reportFrameStats(e){return this.gated("frameStats")?(this.send({gem:h,type:"gem.frameStats",fps:dr(e.fps,1e3),frameTimeP95Ms:dr(e.frameTimeP95Ms,1e5)}),true):false}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:h,type:"gem.gameContext",context:e}),true)}signal(e,t,r){this.send({gem:h,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:h,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:h,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,i,o,a){return this.send({gem:h,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...a===void 0?{}:{catalogId:a}})}requestAvatar3dPurchase(e,t,r){return this.parentSupports("avatar3dPurchases")?this.send({gem:h,type:"gem.requestAvatar3dPurchase",requestId:e,itemId:t,currencySlug:r}):false}putDeviceSettings(e,t){return this.send({gem:h,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:h,type:"gem.requestAd",requestId:e,placement:t,format:r})}signalMoment(e,t,r){return this.send({gem:h,type:"gem.signalMoment",requestId:e,kind:t,...r===void 0?{}:{placement:r}})}readyCalled(){return this.readySent||this.readyPending}requestSignIn(e){return this.send({gem:h,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,t,r,i){return this.send({gem:h,type:"gem.requestFriendChallenge",requestId:e,playerId:t,template:r,...i===void 0?{}:{params:i}})}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(be)){this.options.onDropped?.(e,t);return}this.fail(e,t);}dropUnknownType(e){this.inbound.allow(be)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,t){e.ports?.[0]?.close?.(),this.inbound.allow(be)&&this.options.onRefused?.(t);}fail(e,t){this.options.onError?.(e,t),this.state==="connected"&&this.port&&this.send({gem:h,type:"gem.error",code:e,...t===void 0?{}:{message:t}});}gated(e){return this.state==="connected"&&this.parentSupports(e)}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=de[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||cr(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=de[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=it(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 a=i(e);if(a)return this.fail("invalid_message",`${r}: ${a}`),false;let s=e;if(s.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(s);break;case "gem.pause":this.options.onPause?.(s);break;case "gem.menuSelect":this.options.onMenuSelect?.(s);break;case "gem.prefs":this.options.onPrefs?.(s);break;case "gem.cohorts":this.options.onCohorts?.(s);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(s);break;case "gem.willTerminate":this.options.onWillTerminate?.(s);break;case "gem.devtools":this.options.onDevtools?.(s.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=t[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:s.maxWidth,maxHeight:s.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return cr(t.slice(1)),this.options.onScreenshot(d,l,(m,c)=>this.screenshotDenied(m,c)),true}case "gem.token.denied":this.options.onTokenDenied?.(s);break;case "gem.localServer":this.options.onLocalServer?.(s);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(s);break;case "gem.player":{this.options.onPlayer?.(ro(s));break}case "gem.roomEvent":this.options.onRoomEvent?.(s);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(s);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(s);break;case "gem.ticketEvent":this.options.onTicketEvent?.(s);break;case "gem.socketState":this.options.onSocketState?.(s);break;case "gem.signalEvent":this.options.onSignalEvent?.(s);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(s);break;case "gem.clusterTarget":this.options.onClusterTarget?.(s);break;case "gem.partyResult":this.options.onPartyResult?.(s);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(s);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(s);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(s);break;case "gem.adResult":this.options.onAdResult?.(s);break;case "gem.momentResult":this.options.onMomentResult?.(s);break;case "gem.signInResult":this.options.onSignInResult?.(s);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(s);break;case "gem.error":this.options.onError?.(s.code,s.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,t){this.send({gem:h,type:"gem.screenshot.denied",reason:e,retryable:t});}};function cr(n){for(let e of n)try{e?.close?.();}catch{}}var oo=16384;function so(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:ao(e)}function ao(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 ur=["p2p","dedicated","unknown"],pt=["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 me=class{constructor(e){this.options=e;}options;async post(e,t){let r=this.options.gameId();if(r===null||r==="")return;let i=lo(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 lo(n,e,t){let r=Math.floor(t/1e3);return n.filter(i=>pt.includes(i.type)).slice(0,100).map(i=>{let o=co(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function co(n){if(n!==void 0)return ur.includes(n)?n:"unknown"}function en(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 j=class extends Error{constructor(t,r,i,o,a){super(`${t} (${r}): ${i}`);this.reason=t;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=a;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}};var mo=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),u=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="DedicatedServerError",this.retryable=mo.has(t),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var mr=["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"],po=new Set(mr);function xe(n){return typeof n=="string"&&po.has(n)?n:"unknown"}var Ne="webrtc_dedicated",nn=["universal","mobile","web"];var go="p2p_unavailable",ho="capacity_unavailable",fo=2,pr=3e4,gr=1e3,hr=2e4;async function gt(n){let e=W(n.clusterTargetId),t=n.nextClusterTarget,r=0,i=n.clock??ie,o=n.retry??{},a=o.budgetMs??pr,s=o.maxDelayMs??hr,l=o.initialDelayMs??gr,d=i.now(),m=d+a,c=0;for(;;){c++;try{let p=await on(n.signal,"while allocating",()=>n.client.post(`${br(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!yo(p)||a<=0)throw p;if(p.status===503&&p.code===go)throw new u("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});if(r=p.code===ho?r+1:0,t!==void 0&&r>=fo){let C=t;t=void 0;let E=W(await C());E!==void 0&&(e=E,r=0);}let f=Math.min(s,l*2**(c-1)),b=Math.min(s,(p.retryAfterSeconds??0)*1e3),A=Math.max(f/2,b)+Math.random()*(f/2);if(i.now()+A>m)throw bo(n,p,c,i.now()-d,a);if(o.onWaiting?.({attempt:c,elapsedMs:i.now()-d,budgetMs:a,nextAttemptInMs:A,status:p.status,message:p.message}),await yt(i,A,n.signal),n.signal?.aborted)throw tn("while waiting to allocate")}}}function yo(n){return n instanceof j?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function bo(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 u("start_rate_limited",`the platform was still limiting match starts for room ${n.roomId} after ${o}: ${e.message}`,{cause:e}):new u("no_server_ready",`the platform had no server ready for room ${n.roomId} after ${o}: ${e.message}`,{cause:e})}var vo=12e4,_o=1e3;async function ht(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??_o,i=n.timeoutMs??vo,o=e.now()+i,a=fr(n),s={seen:n.knownToExist===true};for(;;){let l=await yr(n,a,s);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new u("timeout",`match ${t} was still ${l.status} after ${i}ms`);await yt(e,r,n.signal);}}async function rn(n){return (await yr(n,fr(n),{seen:n.knownToExist===true})).outcome}function fr(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${br(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function yr(n,e,t){let{matchId:r}=n,i=n.clock.now(),o;try{o=await on(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(a){if(a instanceof j&&a.reason==="not_found")return {status:"not_found",outcome:t.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw a}if(t.seen=true,o.status==="ready")return {status:"ready",outcome:ko(r,o,i)};if(o.status==="failed"){let a=o.ended_reason;return typeof a=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:xe(a)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function ft(n){let e=await on(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 on(n,e,t){if(n?.aborted)throw tn(e);try{return await t()}catch(r){throw n?.aborted?tn(e,r):r}}function tn(n,e){return new u("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function ko(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 br(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function yt(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"]),an="embedder_relay_unavailable",Ro="embedder_no_relay",So=new Set([an]),ln=new Set([Ro]),bt=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new sn(this)}handleEvent(e){let t=this.pending.get(e.matchId);if(t!==void 0){if(e.event==="matchEnded"){t.refuse(new u("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 u("signaling_failed","the parent relayed an answer with no SDP in it"));return}t.settle({sdp:e.sdp});return}t.refuse(xo(e.code,e.message));}}register(e,t){this.pending.get(e)?.refuse(new u("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 u("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 docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new u("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See docs/dedicated-server-flow.md \xA72.");return e}};function xo(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new u(Ao(n),r,{platformCode:n})}function Ao(n){return n===void 0||So.has(n)?"signaling_failed":ln.has(n)?"offer_refused":wo.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var sn=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,t){if(this.closed)return Promise.reject(new u("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 u("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let a=()=>{s(),o(new u("aborted","the caller aborted the signaling exchange"));},s=()=>{t?.removeEventListener("abort",a),this.hub.release(e.matchId,l),this.teardown===s&&(this.teardown=null);},l={settle:d=>{s(),i(d);},refuse:d=>{s(),o(d);}};this.teardown=s,t?.addEventListener("abort",a),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof u?d:new u("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var vr="match_ended:",_r="server_shutdown:",kr="kicked:",Po=123;function To(n){if(typeof n!="string"||n.length===0||n.length>Po)return {kind:"other"};if(n.startsWith(vr)){let e=xe(n.slice(vr.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(_r)?{kind:"server_shutdown",cause:n.slice(_r.length)}:n.startsWith(kr)?{kind:"kicked",detail:n.slice(kr.length)}:{kind:"other"}}function dn(n,e,t){let r=To(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 Eo="join",Io="welcome",Co="rejected",cn=25e3,Mo=1e3,un=1;function mn(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var Oo={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 pn(n){let e=typeof n=="string"?n:"unknown";return new u(Oo[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function Ue(n){let{channel:e,clock:t}=n;return new Promise((r,i)=>{let o=false,a=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??cn),s=t.setTimeout(()=>w(new u("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(a,Mo)),l=A=>{let C=A.data;if(typeof C!="string"){c(C);return}let E;try{E=JSON.parse(C);}catch{c(C);return}if(o){c(C);return}if(E.t===Io){let g=mn(E.heartbeat_interval);b({...typeof E.player_id=="string"?{playerId:E.player_id}:{},...typeof E.match_id=="string"?{matchId:E.match_id}:{},...g===void 0?{}:{heartbeatIntervalMs:g}});return}if(E.t===Co){w(pn(E.reason));return}c(C);},d=()=>{w(new u("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{w(new u("aborted","the caller aborted during the join exchange"));},c=A=>{o&&n.onMessage?.(A);},p=()=>{t.clearTimeout(s),e.removeEventListener("close",d),n.signal?.removeEventListener("abort",m);},f=()=>{e.removeEventListener("message",l);},b=A=>{o=true,p(),n.onMessage===void 0&&f(),r({welcome:A,detach:f});},w=A=>{o||(o=true,p(),f(),i(A));};if(e.addEventListener("message",l),e.addEventListener("close",d),n.signal?.aborted){m();return}n.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:Eo,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:un}:{}}));}catch(A){w(new u("connection_failed",`the join frame could not be sent on the open channel: ${String(A)}`,{cause:A}));}})}function vt(){return {exchange(){return Promise.reject(new u("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 docs/dedicated-server-flow.md \xA72."))},close(){}}}var pe=1,We=2,gn=4,yn=8,Lo=2,Go=1e3,bn="heartbeat timeout",_t="gem-uu",kt=2,Rr="gem_transports";function Be(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!Do(r)||e.includes(r)||e.push(r);}return e}function Do(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function wt(n,e){if(typeof n!="object"||n===null)return null;let t=n[Rr];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 Rt(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var Sr=new TextEncoder,xr=new TextDecoder;function vn(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function _n(n){let e=0;return n?.reliable===false&&(e|=pe),n?.ordered===false&&(e|=We),e}function kn(n){return {reliable:(n&pe)===0,ordered:(n&We)===0}}var wn={reliable:true,ordered:true};function Ar(n){return JSON.stringify({t:"join",credential:n,wire:kt,heartbeat:un})}function Pr(n){let e;try{e=JSON.parse(n);}catch{throw new u("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let t=mn(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"?pn(e.reason):new u("join_refused","the server answered the join out of protocol")}function Rn(){return typeof globalThis.WebTransport=="function"&&Sn===null}function St(){return Sn}var Sn=null;var wr="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function qo(n){let e=en(n);if(e.byteLength!==32)throw new u("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var hn=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 u("connection_failed",`a control-stream record claims ${o} bytes`);if(this.buffered.byteLength<4+o)break;let a=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:a[0]??0,payload:a.slice(1)});}return r}};function fn(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 Ve(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webTransport;if(t===void 0){let s=globalThis.WebTransport;if(s===void 0)throw new u("connection_failed","this environment has no WebTransport");t=n.certHashBase64===void 0?new s(n.url):new s(n.url,{serverCertificateHashes:[{algorithm:"sha-256",value:qo(n.certHashBase64)}]});}let r=t,i=s=>{try{r.close();}catch{}throw s},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(Sn=wr,i(new u("connection_failed",`${wr}; the rung is skipped for the rest of this page (a reload probes again)`)));let a=new Promise((s,l)=>{setTimeout(()=>l(new u("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,a]);let s=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([s.read(),a]);if(s.releaseLock(),l.done||l.value===void 0)return i(new u("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(fn(gn,Sr.encode(Ar(n.credential))));let c=new hn,p=d.readable.getReader(),f;for(;f===void 0;){let b=await Promise.race([p.read(),a]);if(b.done||b.value===void 0)return i(new u("connection_failed","the control stream closed before the join was answered"));for(let w of c.push(b.value)){f=Pr(xr.decode(w.payload));break}}return {link:$o(r,m,p,c,n.log??(b=>console.warn(b)),Er(f,n.clock)),welcome:f}}catch(s){return i(s)}}function $o(n,e,t,r,i,o){let a,s,l=false,d=b=>{if(!l){l=true,m.stop();try{n.close();}catch{}s?.(b);}},m=An(o,()=>d(bn)),c=(b,w)=>{m.heard(),(b&yn)===0&&a!==void 0&&((b&gn)!==0?a(xr.decode(w),wn):a(w,kn(b)));};(async()=>{try{for(;;){let b=await t.read();if(b.done||b.value===void 0)break;for(let w of r.push(b.value))c(w.flags,w.payload);}}catch{}d("stream closed");})();let p,f;try{let b=n.datagrams;if(b?.readable!==void 0&&b.writable!==void 0){let w=b.readable.getReader();f=b.writable.getWriter(),p=b,(async()=>{try{for(;;){let A=await w.read();if(A.done||A.value===void 0)break;let C=A.value;C.byteLength!==0&&c((C[0]??0)|pe|We,C.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(b){p=void 0,f=void 0,i(`[gem] webtransport datagram lane unusable (${Rt(b)}); unreliable sends ride the stream`);}return n.closed.then(b=>d(Tr(b?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(b,w){if(l)return;if(typeof b=="string"){e.write(fn(gn,Sr.encode(b))).catch(()=>d("write failed"));return}let A=_n(w);if((A&pe)!==0&&f!==void 0){let C=vn(A,b),E=p?.maxDatagramSize;if(E===void 0||C.byteLength<=E){f.write(C).catch(()=>{});return}}e.write(fn(A,b)).catch(()=>d("write failed"));},onMessage(b){a=b;},onClose(b){s=b;},close(){d("closed");}}}function xn(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 u("connection_failed","this environment has no WebSocket"));t=new i(n.url);}let r=t;return r.binaryType="arraybuffer",new Promise((i,o)=>{let a=false,s=setTimeout(()=>{a||(a=true,r.close(),o(new u("timeout","websocket did not come up in time")));},e),l=f=>{a||(a=true,clearTimeout(s),r.close(),o(f));},d=()=>{r.send(Ar(n.credential));},m=f=>{if(a)return;if(typeof f.data!="string"){l(new u("join_refused","the server sent binary before answering the join"));return}let b;try{b=Pr(f.data);}catch(w){l(w);return}a=true,clearTimeout(s),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",c),r.removeEventListener("error",p),i({link:Fo(r,Er(b,n.clock)),welcome:b});},c=()=>{l(new u("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new u("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",m),r.addEventListener("close",c),r.addEventListener("error",p),r.readyState===1&&d();})}function Tr(n){return typeof n=="string"&&n.length>0?n:void 0}function Er(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function An(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,Go)*Lo,i=t.now(),o=null,a=()=>{o=null;let s=t.now()-i;if(s>=r){e();return}o=t.setTimeout(a,r-s);};return o=t.setTimeout(a,r),{heard:()=>{i=t.now();},stop:()=>{o!==null&&(t.clearTimeout(o),o=null);}}}function Fo(n,e){let t,r,i=false,o=s=>{if(!i){i=true,a.stop();try{n.close();}catch{}r?.(s);}},a=An(e,()=>o(bn));return n.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){t?.(s.data,wn);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&yn)===0&&t?.(l.slice(1),kn(d));})),n.addEventListener("close",(s=>o(Tr(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!i){if(typeof s=="string"){n.send(s);return}n.send(vn(_n(l),s));}},onMessage(s){t=s;},onClose(s){r=s;},close(){o("closed");}}}function Pn(n,e,t,r){let i,o,a=false,s=t,l=c=>{if(!a){a=true,d.stop();try{n.close();}catch{}try{e.close();}catch{}o?.(c);}},d=An(r,()=>l(bn)),m=(c,p)=>{if(d.heard(),typeof c=="string"){i?.(c,wn);return}let f=new Uint8Array(c);if(f.byteLength===0)return;let b=f[0]??0;(b&yn)===0&&i?.(f.slice(1),kn(b|p));};if(n.addEventListener("message",(c=>m(c.data,0))),n.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let c=e.connectionState;(c==="failed"||c==="closed")&&l(`connection ${c}`);})),s!==void 0){let c=s;c.addEventListener("message",(p=>m(p.data,pe|We))),c.addEventListener("close",(()=>{s=void 0;}));}return {transport:"webrtc",send(c,p){if(a)return;if(typeof c=="string"){n.send(c);return}let f=_n(p),b=vn(f,c);if((f&pe)!==0&&s!==void 0&&s.readyState==="open"){s.send(b);return}n.send(b);},onMessage(c){i=c;},onClose(c){o=c;},close(){l("closed");}}}var Ir=10240,Cr=2048,jo=new TextEncoder;function Mr(n){return jo.encode(n).length}function oe(n,e){let t=i=>{throw new u("invalid_sdp",`the ${e} ${i}`)},r=Mr(n);r>=Ir&&t(`is ${r} bytes, over the ${Ir} 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=Mr(i);o>Cr&&t(`has a ${o}-byte line, over the ${Cr} limit`);}}function xt(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 No=3e3,Uo=1e4,Wo=15e3;async function He(n){let e=n.peerConnection;try{Lr(n,"before the handshake started"),Tn(n);let t=e.createDataChannel(n.channelLabel??"gem",{ordered:!0});for(let a of n.extraChannels??[]){let s=e.createDataChannel(a.label,{...a.ordered===void 0?{}:{ordered:a.ordered},...a.maxRetransmits===void 0?{}:{maxRetransmits:a.maxRetransmits}});n.onExtraChannel?.(a.label,s);}let r=await e.createOffer();await e.setLocalDescription(r),await Ho(e,n),Tn(n);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new u("invalid_sdp","the offer carried no SDP");oe(i,"offer"),Or(i,"offer");let o=await Vo(n,i);if(Tn(n),typeof o?.sdp!="string")throw new u("invalid_sdp","the signaling channel answered without an SDP");return oe(o.sdp,"answer"),Or(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await Ko(t,n),Lr(n,"before the channel opened"),t}catch(t){throw e.close(),Bo(t)}}function Bo(n){return n instanceof u?n:qr(n)?ge():new u("connection_failed",$r(n),{cause:n})}function Or(n,e){if(xt(n))throw new u("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 Vo(n,e){let t=n.exchangeTimeoutMs??Uo,r=Dr(n,t),i=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(o=>{throw o instanceof u?o:qr(o)?ge():new u("signaling_failed",$r(o),{cause:o})});return Jo(i,n,r,()=>r.exhausted?En("while the offer was in flight"):new u("timeout",`no answer arrived within ${t}ms`))}function Ho(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let i=()=>{t.clearTimeout(a),n.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{n.iceGatheringState==="complete"&&i();},a=t.setTimeout(i,e.gatherTimeoutMs??No);n.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function Ko(n,e){if(e.signal?.aborted)return Promise.reject(ge());if(n.readyState==="open")return Promise.resolve();if(n.readyState!=="connecting")return Promise.reject(new u("connection_failed",`the data channel was already '${n.readyState}' when the answer was applied`));let{clock:t}=e,r=e.openTimeoutMs??Wo,i=Dr(e,r);return new Promise((o,a)=>{let s=()=>{t.clearTimeout(p),n.removeEventListener("open",l),n.removeEventListener("close",d),n.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{s(),o();},d=f=>{s(),a(new u("connection_failed","the data channel failed before it opened",Gr(f)===void 0?void 0:{cause:Gr(f)}));},m=()=>{s(),a(ge());},c=()=>{s(),a(i.exhausted?En("while the channel was still opening"):new u("timeout",`the data channel did not open within ${r}ms`));},p=t.setTimeout(c,i.ms);n.addEventListener("open",l),n.addEventListener("close",d),n.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function Dr(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 Jo(n,e,t,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(ge()):new Promise((a,s)=>{let l=c=>{i.clearTimeout(m),o?.removeEventListener("abort",d),c();},d=()=>l(()=>s(ge())),m=i.setTimeout(()=>l(()=>s(r())),t.ms);o?.addEventListener("abort",d),n.then(c=>l(()=>a(c)),c=>l(()=>s(c)));})}function Lr(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw En(`already ${e}`)}function En(n){return new u("credential_expired",`the join credential ran out ${n} \u2014 poll match status again for a fresh one`)}function Tn(n){if(n.signal?.aborted)throw ge()}function ge(){return new u("aborted","the caller aborted the connection attempt")}function qr(n){return n?.name==="AbortError"}function Gr(n){return n?.error}function $r(n){return n instanceof Error?n.message:String(n)}var Ke="0.1.0-beta",Fr="0-beta",Ae="web",zo=/^(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 Xo(n){let e=zo.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function jr(n,e){let t=Yo(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:Ke};let i=Xo(r);if(i===null)throw new u("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 '${Ke}' for it.`);if(i!==Fr)throw new u("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${Fr}' 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 '${Ke}' for it.`);return {...n,platform:t,engineVersion:r}}function Yo(n,e){if(n===void 0||n===Ae)return Ae;if(!nn.includes(n))throw new u("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${nn.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${Ae}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${Ae}' 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.`),Ae}function Qo(n){let{client:e,clock:t,rooms:r}=n,i=n.signaling??vt,o=n.log??(g=>console.warn(g)),a=new me({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(g,v)=>{let R=s.get(g)??new Set;R.add(v),s.set(g,R);},d=(g,v)=>{let R=s.get(g);R!==void 0&&(R.delete(v),R.size===0&&s.delete(g));},m=async g=>{if(r.isHost&&!as(r)&&r.currentRoom?.matchId===void 0){let v=W(g.clusterTargetId);await r.startMatch({...v===void 0?{}:{clusterTargetId:v},...g.retry===void 0?{}:{retry:g.retry},...g.signal===void 0?{}:{signal:g.signal}});}return Hr(r.matchConnectionState==="suspended"?await r.reconnectToMatch(In(g)):await r.awaitMatch(In(g)))},c=async g=>Hr(await r.pollMatchStatus(In(g))),p=async(g,v)=>{let R=false;try{let _=await m(g),G=r.currentRoom?.transports;if(G!==void 0&&!G.includes("webrtc"))throw new u("misconfigured",`the room template offers (${G.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 M=g.peerConnection??Kr();R=!0;let D=await He({peerConnection:M,signaling:v,clock:t,matchId:_.matchId,credentialExpiresAt:_.credentialExpiresAt,...At(g,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),F=null;if(g.presentCredential!==!1)try{F=await Ue({channel:D,clock:t,credential:_.joinCredential,credentialExpiresAt:_.credentialExpiresAt,...At(g,"onMessage","signal"),...g.welcomeTimeoutMs===void 0?{}:{ceilingMs:g.welcomeTimeoutMs}});}catch(N){throw J(D),J(M),N}return ss(r,_,D,M,v,g.reportDisconnect!==!1,g.reportConnected!==!1,F,{remember:l,forget:d},g.onMatchEnded)}catch(_){throw R&&Vr(a,_),J(v),_}},f=async(g,v,R,_,G,M)=>{if(g==="webtransport"){let O=_?.webtransport;if(O===void 0)throw new u("misconfigured","webtransport is not advertised");let X={credential:R.joinCredential,credentialExpiresAt:R.credentialExpiresAt,clock:t};if(typeof O.named_url=="string"&&O.named_url!==""){let re=Math.max(Math.floor(M/2),1e3);try{return await Ve({url:O.named_url,timeoutMs:re,log:o,...X})}catch(se){if(St()!==null)throw se;return o(`[gem] webtransport named dial failed (${Rt(se)}); retrying the pinned dial`),Ve({url:O.url,certHashBase64:O.cert_sha256_b64,timeoutMs:re,log:o,...X})}}return Ve({url:O.url,certHashBase64:O.cert_sha256_b64,timeoutMs:M,...X})}if(g==="websocket"){let O=_?.websocket;if(O===void 0)throw new u("misconfigured","websocket is not advertised");return xn({url:O.url,credential:R.joinCredential,credentialExpiresAt:R.credentialExpiresAt,clock:t,timeoutMs:M})}let D=v.peerConnection??Kr(),F,N=await He({peerConnection:D,signaling:G,clock:t,matchId:R.matchId,credentialExpiresAt:R.credentialExpiresAt,extraChannels:[{label:_t,ordered:false,maxRetransmits:0}],onExtraChannel:(O,X)=>{O===_t&&(F=X);},...At(v,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...v.exchangeTimeoutMs===void 0&&v.redial===true?{exchangeTimeoutMs:es}:{}}),K;try{K=await Ue({channel:N,clock:t,credential:R.joinCredential,credentialExpiresAt:R.credentialExpiresAt,wire:kt,heartbeat:!0,...At(v,"signal"),...v.welcomeTimeoutMs===void 0?{}:{ceilingMs:v.welcomeTimeoutMs}});}catch(O){throw J(N),J(D),O}let P=K.welcome.heartbeatIntervalMs;return {link:Pn(N,D,F,P===void 0?void 0:{clock:t,intervalMs:P}),welcome:K.welcome,channel:N,peerConnection:D}},b=(g,v,R,_,G)=>{let M=false,D;_.link.onClose(P=>{!M&&g.reportDisconnect!==false&&dn(r,v.matchId,P),D?.(P);}),g.reportDisconnect!==false&&g.reportConnected!==false&&r.notifyMatchConnected(v.matchId);let F={transport:_.link.transport,send:(P,O)=>_.link.send(P,O),onMessage:P=>_.link.onMessage(P),onClose:P=>{D=P;},close:()=>_.link.close()},N=()=>{M||(M=true,J(_.link),J(G));},K=P=>{if(!M){try{g.onMatchEnded?.(P);}catch{}N();}};return l(v.matchId,K),{matchId:v.matchId,transport:R,link:F,joinCredential:v.joinCredential,credentialExpiresAt:v.credentialExpiresAt,welcome:_.welcome,..._.channel===void 0?{}:{channel:_.channel},..._.peerConnection===void 0?{}:{peerConnection:_.peerConnection},close(){d(v.matchId,K),N();}}},w=async(g,v)=>{let R=r.currentRoom?.id,_=r.gameId,G=()=>({advert:wt(r.currentRoom?.settings,g),template:r.currentRoom?.transports??null});if(R===void 0||_===null)return G();try{let M=await e.get(`/v2/games/${encodeURIComponent(_)}/game-rooms/${encodeURIComponent(R)}`,v);return {advert:wt(M.settings,g),template:Be(M.transports)??r.currentRoom?.transports??null}}catch{return G()}},A=(g,v)=>{let R=g??Nr;return v.length===0?R:R.filter(_=>v.includes(_))},C=async(g,v,R)=>{try{let _=await m(g),{advert:G,template:M}=await w(_.matchId,g.signal),D=A(M,v),F=D.filter(q=>rs(q,G)),N=St();if(N!==null&&D.includes("webtransport")&&G?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${N} (learned on an earlier dial in this page)`),F.length===0){let q=M===null?`the default order (${Nr.join(", ")})`:`the room template's transports (${M.join(", ")||"none"})`;throw new u("misconfigured",`none of ${q}`+(v.length>0?`, narrowed to (${v.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let K=g.transportAttemptTimeoutMs??Zo,P=()=>g.deadlineAt===void 0?1/0:g.deadlineAt-t.now(),O=q=>n.signalingReady===void 0||q<=0?Promise.resolve(!0):n.signalingReady(q),X=[],re=[];for(let q of F){if(P()<Wr){o(`[gem] ${q} rung not tried: the reconnect budget is spent`);break}re.length>0&&_.credentialExpiresAt-t.now()<Br&&(_=await c(g)),re.push(q);let Wn=!1,Bn=!1,nt={attempts:0,waitedMs:0};for(;;){if(q==="webrtc"&&g.redial===!0){let Z=Math.min(Ur,P());await O(Z)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(Z)}ms; offering anyway`);}let Ri=Math.max(Math.min(K,P()),Wr);try{return b(g,_,q,await f(q,g,_,G,R,Ri),R)}catch(Z){let U=Z instanceof u?Z:new u("connection_failed",Z instanceof Error?Z.message:String(Z),{cause:Z});if(q==="webrtc"&&Vr(a,U),(U.reason==="credential_expired"||U.reason==="credential_reused")&&!Wn){Wn=!0,_=await c(g);continue}if(q==="webrtc"&&U.reason==="signaling_failed"&&U.platformCode===an&&!Bn){Bn=!0;let ae=Math.min(Ur,P());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 O(ae))continue}if(U.reason==="join_rate_limited"){let ae=ns(nt,Math.random,P());if(ae!==null){if(nt.attempts+=1,nt.waitedMs+=ae,o(`[gem] ${q} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ae)}ms before presenting again (retry ${nt.attempts} of ${zr.maxAttempts})`),await yt(t,ae,g.signal),g.signal?.aborted)throw new u("aborted","the caller aborted while waiting out a join rate limit");_.credentialExpiresAt-t.now()<Br&&(_=await c(g));continue}}if(ts.has(U.reason)||U.reason==="credential_expired"||q==="webrtc"&&Jr(U)){o(`[gem] ${q} rung failed (${U.reason}): ${Rt(U.cause??U)} \u2014 `+(re.length<F.length?`falling through to ${F[re.length]}`:"no rungs left")),X.push(U);break}throw o(`[gem] ${q} rung refused the session (${U.reason}): ${U.message}`),U}}}let se=X[X.length-1];throw se===void 0?new u("timeout",`the reconnect budget ran out before any transport (${F.join(", ")}) could be tried`):new u(se.reason,`every transport tried (${re.join(", ")}) failed; the last said: ${se.message}`,{cause:X,platformCode:se.platformCode})}catch(_){throw J(R),_}};return {listClusterTargets:async(g={})=>ft({client:e,...g}),handleMatchEnded(g,v){let R=s.get(g);if(R!==void 0){s.delete(g);for(let _ of R)_(v);}},connect:(async(g={})=>{let v=g.signaling??i();return g.transports===void 0?p(g,v):C(g,g.transports,v)})}}var Nr=["webtransport","webrtc","websocket"],Zo=1e4,es=5e3,Ur=3e3,Wr=1e3,Br=1e4,ts=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Jr(n){return n.platformCode!==void 0&&ln.has(n.platformCode)}var zr={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function ns(n,e=Math.random,t=1/0){let r=zr;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 rs(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&Rn():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||is(e.websocket.url)}function is(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return mt(e)}function In(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var os=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Vr(n,e){e instanceof u&&(!os.has(e.reason)&&!Jr(e)||n.report([{type:"connection_failures_total",value:1}]));}function ss(n,e,t,r,i,o,a,s,l,d){let m=false,c=()=>{m||dn(n,e.matchId,void 0);};o&&(t.addEventListener("close",c),a&&n.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,t.removeEventListener("close",c),s?.detach(),J(t),J(r),J(i));},f=b=>{if(!m){try{d?.(b);}catch{}p();}};return l.remember(e.matchId,f),{matchId:e.matchId,channel:t,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:s?.welcome??null,close(){l.forget(e.matchId,f),p();}}}function as(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function Hr(n){if(n.status==="failed")throw new u("allocation_failed",`match ${n.matchId} did not come up: ${n.reason}`);if(n.status==="ended")throw new u("match_ended",`match ${n.matchId} ended (${n.reason}) before this side connected.`);if(n.protocol!==Ne)throw new u("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${Ne}' 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 u("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 Kr(){let n=globalThis.RTCPeerConnection;if(!n)throw new u("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 J(n){try{n.close();}catch{}}function At(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var Pe=class{constructor(e){this.options=e;this.reporter=new me({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:Pt(i.credential)??"",hostFingerprint:Pt(i.host_fingerprint)??"",hostEpoch:Tt(i.host_epoch)??0,expiresAt:(Tt(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 l of Array.isArray(i.ice_servers)?i.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);m.length!==0&&o.push({urls:m,username:Pt(d.username)??"",credential:Pt(d.credential)??""});}let a=Tt(i.expires_at),s=Tt(i.ttl_seconds);return {iceServers:o,expiresAt:a!==void 0?a*1e3:Date.now()+(s??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 Pt(n){return typeof n=="string"&&n.length>0?n:void 0}function Tt(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var ls=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=ls.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 ds=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function he(n){let e=null;for(let t of n.split(/\r\n|\n/)){if(!t.startsWith("a=fingerprint:"))continue;let r=Je(t.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function Je(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 ds.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 Cn=5e3,cs=12e4+Cn,us=1024,ms=6e4,ps=1e4,Xr=64*1024,Yr=5;function It(n){let e=new Map,t=-1/0,r=null,i=(()=>{let s;try{s=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 s.username!==""||s.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:s.href,shown:`${s.protocol}//${s.host}`}})(),o=()=>{let s=n.subtle??globalThis.crypto?.subtle;if(!s)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 s},a=async()=>{if(!i.ok)throw new k("keys_unavailable",i.reason);let s=n.fetch??((p,f)=>globalThis.fetch(p,f)),l;try{l=await s(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(ps)});}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(!l.ok)throw new k("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let p=await l.text();if(p.length>Xr)throw new k("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${Xr} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof k?p:new k("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>Yr)throw new k("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${Yr} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=o();for(let p of m){let f=p;if(f.kty==="RSA"&&!(f.alg!==void 0&&f.alg!=="RS256")&&!(f.use!==void 0&&f.use!=="sig")&&!(typeof f.kid!="string"||f.kid.length===0))try{let b=await c.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(f.kid,b);}catch{}}};return {async key(s){let l=e.get(s);if(l)return l;if(!i.ok)throw new k("keys_unavailable",i.reason);if(r)return await r,e.get(s)??null;let d=n.now();if(!Number.isFinite(d))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 d<t&&(t=-1/0),d-t<ms?null:(t=d,r??=a().finally(()=>{r=null;}),await r,e.get(s)??null)}}}var ze=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>=us){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+cs),true}};function Zr(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 Qr(n){try{let e=new TextDecoder().decode(Zr(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function Ct(n,e,t,r,i){let o=P=>{throw new k("peer_unauthenticated",`the peer's join credential is not usable: ${P}`)},a=n.split(".");a.length!==3&&o("it is not a three-part JWT");let[s,l,d]=a,m=Qr(s);m===null&&o("its header does not decode"),m.alg!=="RS256"&&o(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let c=m.kid;(typeof c!="string"||c.length===0)&&o("it names no key");let p=await t.key(c);p===null&&o("it was signed by a key this build cannot resolve");let f=i.subtle??globalThis.crypto?.subtle;f||o("this environment has no WebCrypto");let b=new TextEncoder().encode(`${s}.${l}`),w;try{w=Zr(d);}catch{o("its signature does not decode");}await f.verify({name:"RSASSA-PKCS1-v1_5"},p,w,b)||o("its signature does not verify");let C=Qr(l);C===null&&o("its payload does not decode");let E=C,g=P=>typeof E[P]=="string"?E[P]:"",v=P=>typeof E[P]=="number"&&Number.isFinite(E[P])?E[P]:NaN;g("iss")!==i.issuer&&o("it was issued by someone else"),g("aud")!==`${i.issuer}/p2p-match`&&o("its audience is not this platform"),g("match_id")!==e.matchId&&o("it is for another match"),g("game_id")!==e.gameId&&o("it is for another game");let R=v("exp")*1e3,_=v("nbf")*1e3;(!Number.isFinite(R)||e.now>R+Cn)&&o("it has expired"),Number.isFinite(_)&&e.now<_-Cn&&o("it is not valid yet");let G=g("role");G!=="host"&&G!=="client"&&o("it names no usable role");let M=v("host_epoch");M!==e.hostEpoch&&o("it names a different host epoch");let D=Je(g("fingerprint"));D===null&&o("its fingerprint claim is malformed"),Te(D,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let F=Je(g("host_fingerprint"));F===null&&o("its host fingerprint claim is malformed"),Te(F,e.hostFingerprint)||o("it was issued against a different host certificate");let N=g("jti");N.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(N,e.now)||o("it has already been used");let K=g("sub");return K.length===0&&o("it names no player"),{playerId:K.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:M,role:G,fingerprint:D,hostFingerprint:F,jti:N,expiresAt:R}}var fe=32769;function Mn(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 On(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 Ln(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function Gn(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 ei(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 ti(n){switch(n){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var ni=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 Mt={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}},Xe=["reliable","ordered","unreliable"];function Ot(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 Lt(){let n=globalThis.RTCPeerConnection;return n?.generateCertificate?n.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var ii=1,bs=3e4,oi=2e3,vs=5e3,si=6e4,_s=8,qn=class{constructor(e=_s){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;}},ks=new qn,ws=8,Rs=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??It({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Et;links=new Map;replays=new ze;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=ii+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??bs;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),i=W(this.options.clusterTargetId);if(i!==void 0)try{let s=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=s.iceServers,this.mark("turn leased");}catch(s){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: ${Dn(s)}`);}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),a=()=>this.fail(new k("aborted","the caller aborted while connecting"));e?.aborted?a():e?.addEventListener("abort",a);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",a),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=$(e.playerId),r=$(e.hostPlayerId),i=Gt(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,ii),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");oe(o,"offer"),this.refuseMedia(o,"offer"),this.options.signaling.offer(o,e),this.mark("offer sent"),this.fetchCredential().catch(a=>this.report_(a));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,i=r===void 0?null:he(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??ks,a=()=>this.closed||e!==this.credentialGeneration,s=vs;for(;;){let l=o.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,a))return;o.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,i);if(a())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(a())return;let m=d.status,c;if(m===409)c=oi;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?c=p*1e3:(c=s,s=Math.min(s*2,si)),c=Math.min(Math.max(c,oi),si);}else throw d;if(!await this.waitForCredential(c,a))return}}}async waitForCredential(e,t){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!t())}async onOffer(e){let t=$(e.fromPlayerId),r=$(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=ws){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(t,e);return}if(!this.isHost||this.migration.isKicked(t)===true)return;let i=$(e.sessionId);if(i!==null&&this.answeredSessions.get(t)===i)return;oe(r,"offer"),this.refuseMedia(r,"offer");let o=he(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 a=this.links.get(t);a&&this.dropLink(a,"resignalled",false);let s=this.openLink(t,this.nextPeerId++);s.remoteFingerprint=o,await s.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(s);let l=await s.connection.createAnswer();await s.connection.setLocalDescription(l);let d=s.connection.localDescription?.sdp??l.sdp;if(!d)throw new k("invalid_sdp","the browser produced an answer with no SDP");oe(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(t,d,s.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let t=$(e.fromPlayerId),r=$(e.sdp);if(t===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||t!==this.hostPlayerId)return;oe(r,"answer"),this.refuseMedia(r,"answer");let o=he(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=$(e.fromPlayerId),r=$(e.candidate);if(t===null||r===null)return;let i=this.links.get(t);if(!i)return;let o=$(e.sdpMid),a=Gt(e.sdpMLineIndex)??Gt(e.sdpMLineIndexAlt),s={candidate:r,...o===null?{}:{sdpMid:o},...a===null?{}:{sdpMLineIndex:a}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(s);return}await i.connection.addIceCandidate(s);}onPeerLeft(e){let t=$(e.playerId);if(t===null)return;let r=$(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=$(e.hostPlayerId),r=Gt(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:t,hostEpoch:r,...$(e.reason)===null?{}:{reason:$(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=$(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=$(e.code)??"unknown",r=$(e.message)??"the platform refused a signaling message";this.report_(new k("signaling_failed",`${t}: ${r}`));}openLink(e,t){let i=(this.options.peerConnectionFactory??Ot)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let p of Xe){let f=i.createDataChannel(p,Mt[p]);f.binaryType="arraybuffer",o[p]=f;}let a={playerId:e,assignedPeerId:t,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},s=p=>{let f=p.candidate;f?.candidate&&this.options.signaling.candidate(e,f.candidate,f.sdpMid??void 0,f.sdpMLineIndex??void 0);},l=()=>this.onIceState(a),d=()=>this.onConnectionState(a),m=p=>{this.onHandshakeMessage(a,p.data).catch(f=>this.report_(f));},c=()=>{this.onReliableOpen(a).catch(p=>this.report_(p));};return i.addEventListener("icecandidate",s),i.addEventListener("iceconnectionstatechange",l),i.addEventListener("connectionstatechange",d),o.reliable.addEventListener("open",c),o.reliable.addEventListener("message",m),a.detachHandshake=()=>{o.reliable.removeEventListener("open",c),o.reliable.removeEventListener("message",m);},a.detachAll=()=>{a.detachHandshake(),i.removeEventListener("icecandidate",s),i.removeEventListener("iceconnectionstatechange",l),i.removeEventListener("connectionstatechange",d);},this.links.set(e,a),a}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(Mn({jwt:t.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,t){if(!(t instanceof ArrayBuffer))return;let r=Gn(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(ti(r.reason),ei(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=he(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 Ct(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(a){let s=a instanceof k&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",Dn(a)),s&&this.fail(a);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(On({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(Ln(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 Xe)ai(e.channels[i]);ai(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",Dn(e),{cause:e}));}count(e){this.counted||!Rs.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(xt(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){return typeof n=="string"&&n.length>0?n:null}function Gt(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function Dn(n){return n instanceof Error?n.message:String(n)}function ai(n){try{n.close();}catch{}}var Ss=100,xs=50,Ce=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??Ss)){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 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??xs));}};var $n="webrtc_p2p";function As(n){let e=new Pe({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 docs/p2p-and-parties.md \xA72.");let i=W(r.clusterTargetId),o=i??W(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 a=await n.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(a.protocol!==$n)throw new k("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${$n}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new Ce({bridge:n.bridge,matchId:a.matchId,clock:n.clock}),l=new Ie({api:e,clock:n.clock,matchId:a.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:s,...o===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Lt(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...n.boot===void 0?{}:{boot:n.boot},...n.log===void 0?{}:{log:n.log}});s.onDropped(d=>l.notifyCandidatesDropped(d)),t.set(a.matchId,l),l.on("matchEnded",()=>t.delete(a.matchId));try{await l.start(r.signal);}catch(d){throw t.delete(a.matchId),l.close(),d}return l}}}function li(n){return typeof n=="string"&&n.trim()!==""}function di(n,e){return li(n)?n.trim():li(e)?e:null}function Ye(n){let e=String(n);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function ci(n,e,t){let r=`/v1/games/${Ye(n.gameId())}/matchmaking/tickets/${Ye(e)}`;return n.client.delete(r,t?.signal)}async function ui(n,e,t){let r=`/v1/games/${Ye(n.gameId())}/matchmaking/tickets`;return n.client.post(r,e,t?.signal)}async function mi(n,e,t){let r=`/v1/games/${Ye(n.gameId())}/matchmaking/tickets/${Ye(e)}/heartbeat`;return n.client.post(r,void 0,t?.signal)}function Qe(n){let e=n??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let t=e.heartbeat_interval_seconds;return {id:e.ticket_id,status:typeof e.status=="string"?e.status:"queued",...typeof e.reason=="string"?{reason:e.reason}:{},...typeof e.game_room_id=="string"?{roomId:e.game_room_id}:{},partySize:typeof e.party_size=="number"?e.party_size:1,queuedAt:pi(e.queued_at),expiresAt:pi(e.expires_at),heartbeatIntervalSeconds:typeof t=="number"&&t>0?t:0}}function pi(n){if(typeof n!="string")return 0;let e=Date.parse(n);return Number.isFinite(e)?Math.floor(e/1e3):0}var Ps=3,gi=1e3,Dt=class{constructor(e){this.options=e;this.snapshot=e.first;let t=new Promise((o,a)=>{this.resolve=o,this.reject=a;});t.catch(()=>{});let r=()=>this.snapshot,i=()=>this.status;this.ticket={get id(){return r().id},get status(){return i()},get partySize(){return r().partySize},get queuedAt(){return r().queuedAt},get expiresAt(){return r().expiresAt},outcome:t,cancel:()=>(this.requestCancel(),t)};}options;ticket;snapshot;status="queued";timer=null;busy=false;again=false;cancelRequested=false;soon=false;misses=0;settled=false;resolve;reject;start(){this.apply(this.snapshot);}poke(){this.settled||(this.soon=true,!this.busy&&(this.clearTimer(),this.tick()));}abandon(e=false){this.settled||(this.options.cancel(this.snapshot.id,e).catch(()=>{}),this.settle({status:"cancelled",reason:"requested"}));}requestCancel(){this.settled||(this.cancelRequested=true,this.trigger());}trigger(){if(this.busy){this.again=true;return}this.clearTimer(),this.tick();}schedule(e=false){if(this.settled)return;this.clearTimer();let t=e?gi:Math.max(gi,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},t);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,t=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){t=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(t);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof j&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<Ps){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let t=e instanceof j&&e.code==="matchmaking_unavailable";this.settle({status:t?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let t=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:t});}catch(t){this.busy=false,this.fail(t);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};function Y(n){return typeof n=="string"&&n!==""?n:void 0}var Ts=new Set(["localhost","127.0.0.1","[::1]"]);function Me(n){return Es(n)}function Es(n){let e=Y(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:"&&Ts.has(t.hostname)))return e}var Is=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Cs=/^[a-z][a-z0-9_]{0,31}$/;function Ms(n){if(!Array.isArray(n))return;let e=[],t=new Set;for(let r of n.slice(0,8)){let i=r??{},o=Y(i.family),a=Y(i.avatar_3d_id),s=Me(i.model_url),l=Me(i.icon_url);o===void 0||!Cs.test(o)||t.has(o)||a===void 0||!Is.test(a)||s===void 0||l===void 0||(t.add(o),e.push({family:o,id:a,modelUrl:s,iconUrl:l}));}return e}function Os(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=t??{},i=Y(r.item_id),o=Me(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function hi(n){let e=n??{},t=Y(e.player_id),r=Y(e.display_name),i=Y(e.discriminator),o=Y(e.display_tag),a=Y(e.avatar_icon_id),s=Me(e.avatar_icon_url),l=Y(e.avatar_3d_id),d=Me(e.avatar_3d_model_url),m=Me(e.avatar_3d_icon_url),c=Ms(e.avatars_3d);return {...t===void 0?{}:{playerId:t},...r===void 0?{}:{displayName:ue(r)},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:ue(o)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},...l===void 0?{}:{avatar3dId:l},...d===void 0?{}:{avatar3dModelUrl:d},...m===void 0?{}:{avatar3dIconUrl:m},...c===void 0?{}:{avatars3d:c},badges:Os(e.badges)}}function qt(n){if(typeof n!="object"||n===null)return;let e={};for(let[t,r]of Object.entries(n)){let i=Fn(r);i!==void 0&&(e[t]=i);}return e}function $t(n){if(Array.isArray(n))return n.map(Ls).filter(e=>!!e)}function Fn(n){if(jn(n)||Array.isArray(n)&&n.every(jn))return n}function jn(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function Ls(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=Fn(e.fixed),r=Fn(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},...Oe("description",Gs(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(jn)?{allowed:e.allowed}:{},...Oe("min",Ze(e.min)),...Oe("max",Ze(e.max)),...Oe("minItems",Ze(e.min_items)),...Oe("maxItems",Ze(e.max_items)),...Oe("maxLength",Ze(e.max_length))}}function Gs(n){return typeof n=="string"&&n.length>0?n:void 0}function Ze(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Oe(n,e){return e===void 0?{}:{[n]:e}}function z(n){let e=n??{},t=I(e.id)??I(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(Nn):[];return {id:t,gameId:I(e.game_id)??"",name:I(e.name)??"",status:I(e.status)??"open",hostPlayerId:I(e.host_player_id)??"",maxPlayers:Q(e.max_players)??0,memberCount:Q(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...H("joinCode",I(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...H("roomArgs",qt(e.room_args)),...H("roomArgsTemplate",$t(e.room_args_template)),gameChannel:I(e.game_channel)??"release",...H("region",I(e.region)),...H("clusterTargetId",I(e.cluster_target_id)),selfHosted:e.self_hosted===true,...H("matchId",I(e.match_id)),version:Q(e.version)??0,...H("templateId",I(e.template_id)),...H("templateSlug",I(e.template_slug)),roomType:I(e.game_room_type)??"Standard",...H("transports",Be(e.transports)??void 0),createdAt:Q(e.created_at)??0,updatedAt:Q(e.updated_at)??0,...H("startedAt",Q(e.started_at))}}function Nn(n){let e=n??{};return {...hi(e),playerId:I(e.player_id)??"",isReady:e.is_ready===true,role:I(e.role)??"member",joinedAt:Q(e.joined_at)??0,...H("groupId",I(e.group_id)),...H("platform",I(e.platform))}}function et(n){let e=n??{};return {id:I(e.id)??I(e.game_room_id)??"",gameId:I(e.game_id)??"",name:I(e.name)??"",status:I(e.status)??"open",hostPlayerId:I(e.host_player_id)??"",maxPlayers:Q(e.max_players)??0,memberCount:Q(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:I(e.game_channel)??"release",roomType:I(e.game_room_type)??"Standard",createdAt:Q(e.created_at)??0}}function I(n){return typeof n=="string"&&n.length>0?n:void 0}function Q(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function H(n,e){return e===void 0?{}:{[n]:e}}var Le=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(et),...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(et)}))}create(e,t,r){return qs(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},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...e.roomArgs===void 0?{}:{room_args:e.roomArgs},...tt(t)},e.signal).then(z)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(z)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...tt(r)},t.signal).then(z)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...tt(r)},t.signal).then(z)}quickJoin(e,t,r=[]){let i=this.asksSelfHosted(e.partyId);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},...Ds(e.templateSlugs,i),...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},...i?{self_hosted:true}:{},...tt(t)},e.signal).then(z)}createTicket(e,t,r=[]){return ui(this.generated(),{templates:e.templateSlugs.map(i=>({template_slug:i})),...r.length===0?{}:{cluster_target_ids:[...r]},...e.partyId===void 0?{}:{party_id:e.partyId},...tt(t)},{...e.signal===void 0?{}:{signal:e.signal}}).then(Qe)}heartbeatTicket(e){return mi(this.generated(),e).then(Qe)}cancelTicket(e,t=false){return t?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(Qe):ci(this.generated(),e).then(Qe)}leave(e,t,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:t},r,{keepalive:i}).then(()=>{})}asksSelfHosted(e){return e===void 0&&this.options.selfHosted?.()===true}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(z)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(z)}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(z)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}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 Ds(n,e){return n===void 0?{}:{templates:(e?n.slice(0,1):n).map(r=>({template_slug:r}))}}function tt(n){return {platform:n.platform,game_version:n.gameVersion,engine_version:n.engineVersion}}function qs(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 Ge=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;}};var Ft=class{constructor(e){this.options=e;let t=e.first,r=new Promise(s=>{this.resolve=s;}),i=()=>this.status;this.ticket={id:t.ticketId,get status(){return i()},partySize:t.partySize??0,queuedAt:t.queuedAt??0,expiresAt:t.expiresAt??0,outcome:r};let o=t.queuedAt!==void 0&&t.expiresAt!==void 0?(t.expiresAt-t.queuedAt)*1e3:9e5,a=Math.min(Math.max(o,0),9e5)+5e3;this.timer=e.clock.setTimeout(()=>{this.timer=null,this.end({status:"lost"});},a);}options;ticket;status="queued";timer=null;resolve;get id(){return this.ticket.id}end(e){this.status==="queued"&&(this.status=e.status,this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null),this.options.onSettled(),this.resolve(e));}};function $s(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var Fs=1e3,js=3e3,Ns=6e4,Us=2,fi=new Set(["game_room_closed","game_room_gone"]),Ws=12e4,Bs=5e3,Vs=new Set(["invalid_cluster_target","capacity_unavailable"]),Hs=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function ki(n){return new Un(n)}var Un=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Le({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Ge;api;room=null;ticketWatch=null;queueing=false;partyWatch=null;heldQueued=null;queuedFromRoomId=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;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("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 a=>{let s=await this.afterRefusedClusters(a,o);if(s[0]===void 0||s[0]===o[0])throw a;return this.api.create(r,this.version("create"),s[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,t={}){this.assertNotInRoom("join"),this.assertNotQueued("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"),this.askForLocalServer(i),i}async joinByCode(e,t={}){this.assertNotInRoom("joinByCode"),this.assertNotQueued("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"),this.askForLocalServer(i),i}async quickJoin(e){this.assertNotInRoom("quickJoin"),this.assertNotQueued("quickJoin"),zs(e);let t=this.clusterTargets(),r=await this.attachParty(e),i=a=>this.api.quickJoin(r,this.version("quickJoin"),a).catch(s=>this.retryPastStaleMembership(s,r,a)),o=await this.run("quickJoin",async()=>{let a=await t;return i(a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||_i(l,a))throw s;return i(l)})});return this.enter(o,"joined"),this.askForLocalServer(o),o}async queueForMatch(e){this.assertNotQueued("queueForMatch"),Js(e?.templateSlugs),this.queueing=true;try{let t=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("queueForMatch",async()=>{let a=await t;return this.api.createTicket(r,this.version("queueForMatch"),a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||_i(l,a))throw s;return this.api.createTicket(r,this.version("queueForMatch"),l)})});this.heldQueued?.ticketId===i.id&&(this.heldQueued=null),this.partyWatch?.end({status:"lost"});let o=new Dt({clock:this.options.clock,first:i,heartbeat:a=>this.track(this.api.heartbeatTicket(a)),cancel:(a,s)=>this.track(this.api.cancelTicket(a,s)),seat:a=>this.enterMatchedRoom(a),onSettled:()=>{this.ticketWatch===o&&(this.ticketWatch=null),this.retuneSeatWatch();}});return this.ticketWatch=o,this.retuneSeatWatch(),o.start(),o.ticket}finally{this.queueing=false;let t=this.heldQueued;this.heldQueued=null,t!==null&&this.showPartyTicket(t);}}async enterMatchedRoom(e){let t=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?t:(this.room!==null&&this.room.id!==t.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(t,"joined"),this.room?.id===t.id?this.room:t)}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 j&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let a=await this.askWhyEnded(o,e);this.endMatch(o,a??"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(()=>rn({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(a){return a instanceof j&&a.reason==="not_found"?i??null:(this.reportError("reconcile",a),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=xe(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}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,t){let r=this.requireRoom("startMatch");if(!this.isHost)throw new u("misconfigured",`only the host of room ${r.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.`);this.startsInFlight++;try{return await this.startIn(r,e,t)}finally{this.startsInFlight--;}}async startIn(e,t,r){let i=W(t.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),a=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let s=(m,c)=>gt({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...i===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...t.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),t.retry?.onWaiting?.(p);}},...t.signal===void 0?{}:{signal:t.signal}}),l=()=>s(o,[a]).catch(async m=>{if(i!==void 0||!vi(m))throw m;let c=await this.nextCluster([a],true);if(c===void 0)throw m;return s(c,[a,c])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new u("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 ht({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 u("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!fi.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new u("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(!jt()){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<Fs){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($s(e.attempt,t.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!jt()){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(()=>rn({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,!fi.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(a){this.reportError("reconcile",a),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 u("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 u("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 u("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 currentTicket(){return this.ticketWatch?.ticket??null}get partyTicket(){return this.partyWatch?.ticket??null}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.ticketWatch!==null&&e.event!=="version_stale"&&e.roomId!==this.room?.id&&this.ticketWatch.poke(),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){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(t);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:t,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let i=new AbortController;this.autoStartRetry=i,this.track(this.requestStart({signal:i.signal},false).then(()=>{},o=>{i.signal.aborted||this.reportError("startMatch",o);}).finally(()=>{this.autoStartRetry===i&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!Vs.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}handleTicketEvent(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}if(this.queueing){e.event==="queued"?this.heldQueued=e:this.heldQueued?.ticketId===e.ticketId&&(this.heldQueued=null);return}if(e.event==="queued"){this.showPartyTicket(e);return}if(e.event==="matched"){e.roomId!==void 0&&this.handleSeated(e.roomId),this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:"matched"});return}this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:e.event,reason:e.reason??e.event});}}showPartyTicket(e){if(this.disposed||this.partyWatch?.id===e.ticketId)return;this.partyWatch?.end({status:"lost"});let t=new Ft({clock:this.options.clock,first:e,onSettled:()=>{this.partyWatch===t&&(this.partyWatch=null);}});this.partyWatch=t,this.emitter.emit("partyQueued",t.ticket);}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)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.partyWatch?.end({status:"matched"}),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.ticketWatch===null&&this.seatPollMs>0&&jt())){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(),!!jt())){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}if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of yi)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.ticketWatch?.abandon(),this.heldQueued=null,this.partyWatch?.end({status:"lost"}),this.abortAutoStartRetry(),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 yi)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??Bs}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new u("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=di(this.options.platformGameVersion?.(),t?.gameVersion);if(r===null)throw new u("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 jr({...t,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return ve(await this.options.resolveClusterTargets());let e=W(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,t){return !vi(e)||t.length===0?[]:ve(await this.options.refreshClusterTargets?.(t)??[])}async nextCluster(e,t=false){let r=a=>a.find(s=>!e.includes(s)),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 j)||e.reason!=="conflict"||!Hs.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new j(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 j(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 j(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 u("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.`)}assertNotQueued(e){if(!(this.ticketWatch===null&&!this.queueing))throw new u("misconfigured",`${e} refused: this player is waiting on a matchmaking ticket, which will seat them in a room of its own. Cancel it first \u2014 currentTicket.cancel() \u2014 or wait for its outcome.`)}requireRoom(e){if(this.room===null)throw new u("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 j?{operation:e,code:t.status,reason:t.reason,message:t.message,retryable:t.retryable}:{operation:e,code:0,reason:t instanceof u?t.reason:"unavailable",message:t instanceof Error?t.message:String(t),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let t=this.options.ensureLocalServer;t===void 0||!e.selfHosted||e.status!=="open"||t(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,t){this.room=e,this.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,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.abortAutoStartRetry(),this.autoStartRetried=false,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(s=>[s.playerId,s])),i=new Map(e.members.map(s=>[s.playerId,s])),o=this.playerId();for(let s of i.keys())r.has(s)||this.emitter.emit("memberJoined",s);for(let s of r.keys())if(!i.has(s)){if(s===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",s);}for(let[s,l]of i){let d=r.get(s);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",s,l.isReady);}t.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let a=Ks(t,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),a&&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.autoStartRetried=false,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??Ws;return new Promise((i,o)=>{let a=c=>{s(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),c();},s=this.emitter.on("matchAllocationStarted",c=>a(()=>i(c))),l=this.emitter.on("matchFailed",(c,p)=>a(()=>o(new u("allocation_failed",`match ${c} did not come up: ${p}`)))),d=()=>a(()=>o(new u("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>a(()=>o(new u("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?d():e.signal?.addEventListener("abort",d);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??js}pushedInterval(){return this.options.pushedPollIntervalMs??Ns}pushed(){return this.options.clock.now()-this.lastPushAt<Us*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=>{if(this.ticketWatch?.abandon(true),t?.persisted!==true&&(this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{})),this.queuedFromRoomId!==null)){let r=this.queuedFromRoomId;this.queuedFromRoomId=null,this.track(this.api.leave(r,true,void 0,true).catch(()=>{}));}},e.addEventListener("pagehide",this.unloadListener));}};function jt(){let n=globalThis.document;return n?.visibilityState===void 0||n.visibilityState==="visible"}var yi=["visibilitychange","focus","pageshow","online"];function Ks(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||bi(n)!==bi(e)}function bi(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function vi(n){return n instanceof j&&n.code==="invalid_cluster_target"}var Nt=8;function Js(n){if(!(Array.isArray(n)&&n.length>=1&&n.length<=Nt&&n.every(t=>typeof t=="string"&&t.length>0)))throw new u("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${Nt} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function zs(n){let e=n?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=Nt&&e.every(r=>typeof r=="string"&&r.length>0)))throw new u("misconfigured",`quickJoin's templateSlugs is an array naming one to ${Nt} room templates by slug \u2014 quickJoin({ templateSlugs: ['duel', 'brawl'] }). A room that has to be created is made from the first.`);if(n?.templateSlug!==void 0||n?.templateId!==void 0)throw new u("misconfigured","quickJoin takes templateSlugs or a single templateSlug / templateId, not both. Put every template this player accepts in templateSlugs, with the one to create from first.")}function _i(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}function wi(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={},a=l=>{t.delete(r)&&(n.clock.clearTimeout(o.timer),i(l));};t.set(r,a),o.timer=n.clock.setTimeout(()=>a(void 0),n.timeoutMs??2e3);let s=false;try{s=n.bridge.requestParty(r);}catch{}s||a(void 0);})},settle(r,i){t.get(r)?.(i);}}}
|
|
1
|
+
globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:13.2.2]";var h="gem-web-bridge",ee={min:1,max:1},ye=65536,Vn=8,rt=5e3,Hn=1024,Wt=1e4,le=Object.create(null),be="__malformed",Ys=["gem.handshake","gem.token","gem.token.denied","gem.player","gem.pause","gem.prefs","gem.cohorts","gem.earnAllowanceChanged","gem.viewport","gem.deviceSettings","gem.willTerminate","gem.roomEvent","gem.socketState","gem.seatedEvent","gem.autoStartFailedEvent","gem.ticketEvent","gem.signalEvent","gem.dedicatedEvent","gem.partyResult","gem.clusterTarget","gem.devtools","gem.screenshot","gem.requestContext","gem.localServer","gem.localServer.denied","gem.menuSelect","gem.error","gem.purchaseResult","gem.deviceSettings.result","gem.adResult","gem.momentResult","gem.signInResult","gem.friendChallengeResult"],Qs=["gem.handshake.accept","gem.screenshot.denied","gem.gameContext","gem.signal","gem.dedicatedOffer","gem.partyRequest","gem.ready","gem.engaged","gem.progress","gem.requestToken","gem.requestLocalServer","gem.exit","gem.openExternal","gem.requestFullscreen","gem.audioState","gem.rewardCue","gem.walletDisplay","gem.controlsDeclare","gem.menu","gem.gemCorner","gem.requestShare","gem.requestAvatarPicker","gem.vibrate","gem.frameStats","gem.portraitBorders","gem.error","gem.requestPurchase","gem.requestAvatar3dPurchase","gem.deviceSettings.put","gem.requestAd","gem.signalMoment","gem.requestSignIn","gem.requestFriendChallenge"],Bt=Object.create(null),Si=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"]]);function it(n){let e=Bt[n];if(e!==void 0)return e;for(let[t,r]of Si)if(n.startsWith(t))return r}function ot(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 xi(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 Ai(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function Pi(n){return /^[a-z_]+$/.test(n)}function Ut(n,e,t){if(e>Vn)return `nesting deeper than ${Vn}`;if(++t.nodes>rt)return `more than ${rt} values`;if(t.bytes>ye)return `over the ${ye} 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>Hn)return `an array of ${n.length} entries, over the ${Hn} limit`;t.bytes+=2;for(let s of n){let l=Ut(s,e+1,t);if(l)return l}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 a=n;for(let s in a){if(!Object.prototype.hasOwnProperty.call(a,s))continue;if(++t.nodes>rt)return `more than ${rt} values`;if(t.bytes+=s.length*3+4,t.bytes>ye)return `over the ${ye} byte limit`;let l=Ut(a[s],e+1,t);if(l)return l}return null}function Ti(n){let e={nodes:0,bytes:0,seen:new Set},t=Ut(n,0,e);return t?`message contains ${t}`:e.bytes>ye?`message is over the ${ye} byte limit`:null}var Ei={origin:[ot,"not a well-formed origin"],url:[xi,"not a safe absolute http(s) URL"],bcp47:[Ai,"not a well-formed BCP 47 tag"],code:[Pi,"not a code of lower-case letters and underscores"]};function Kn(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 a=Jn(o,r,i);if(a)return a}return null}function Jn(n,e,t){switch(e.k){case "s":{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]=Ei[e.f];if(!r(n))return `${t}: ${i}`}return null}case "i":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 "b":return typeof n=="boolean"?null:`${t}: expected boolean`;case "e":{let r=e.v;return r.includes(n)?null:`${t}: not one of ${r.join("|")}`}case "o":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected object`:Kn(n,e.fs,t);case "j":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected a plain object`:null;case "a":{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 a=Jn(o,r,i);if(a)return a}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}var zn=Object.create(null);function y(n,e,t,r){return le[n]=t,r&&(Bt[n]=r),zn[n]=i=>{let o=Ti(i);if(o)return o;if(typeof i!="object"||i===null||Array.isArray(i))return "message: expected object";let a=i;return a.gem!==h?"gem: wrong protocol marker":a.type!==n?`type: expected ${n}`:Kn(a,e,"")}}var Zs=y("gem.handshake",[{n:"versions",k:"o",fs:[{n:"min",k:"i",lo:1,hi:1e3},{n:"max",k:"i",lo:1,hi:1e3}]},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}},{n:"embedder",k:"s",max:2048,f:"origin"},{n:"unbidden",k:"b",o:1}],30),ea=y("gem.handshake.accept",[{n:"v",k:"i",lo:1,hi:1e3},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}}],5),ta=y("gem.token",[{n:"token",k:"s",max:4096},{n:"requestId",k:"s",o:1,max:64},{n:"generation",k:"i",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"s",o:1,max:512,f:"url"},{n:"playerId",k:"s",max:64},{n:"gameId",k:"s",max:64},{n:"channel",k:"e",v:["dev","test","release"]},{n:"gameVersion",k:"s",o:1,max:64},{n:"expiresAt",k:"i",lo:0,hi:4102444800},{n:"chainEndsAt",k:"i",lo:0,hi:4102444800},{n:"allowDevTools",k:"b",o:1}],30),na=y("gem.token.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:36e5},{n:"reason",k:"e",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"s",max:64}],30),ra=y("gem.player",[{n:"untrusted",k:"o",fs:[{n:"displayName",k:"s",max:64},{n:"displayTag",k:"s",o:1,max:80},{n:"displayHandle",k:"s",max:80}]},{n:"playerId",k:"s",o:1,max:64},{n:"discriminator",k:"s",o:1,max:8},{n:"avatarIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatarIconId",k:"s",o:1,max:64},{n:"avatar3dId",k:"s",o:1,max:64},{n:"avatar3dModelUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatar3dIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatars3d",k:"a",o:1,max:8,it:{n:"",k:"o",fs:[{n:"family",k:"s",max:32},{n:"id",k:"s",max:64},{n:"modelUrl",k:"s",max:256,f:"url"},{n:"iconUrl",k:"s",max:256,f:"url"}]}},{n:"badges",k:"a",o:1,max:2,it:{n:"",k:"o",fs:[{n:"itemId",k:"s",max:64},{n:"iconUrl",k:"s",max:2048,f:"url"}]}},{n:"displayTag",k:"s",max:8},{n:"avatarUrl",k:"s",o:1,max:2048,f:"url"},{n:"boost",k:"o",o:1,fs:[{n:"multipliers",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"currencyId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"multiplierBp",k:"i",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"i",o:1,lo:1,hi:7}]}],12),ia=y("gem.pause",[{n:"paused",k:"b"}],120),oa=y("gem.prefs",[{n:"reducedMotion",k:"b"},{n:"muted",k:"b"},{n:"showFrameStats",k:"b",o:1},{n:"locale",k:"s",max:35,f:"bcp47"},{n:"recommended",k:"o",o:1,fs:[{n:"volume",k:"i",lo:0,hi:100},{n:"batterySaver",k:"b"},{n:"keyboardLayout",k:"e",v:["wasd","arrows"]},{n:"gamepadConfirm",k:"e",v:["south","east"]},{n:"vibration",k:"b"},{n:"lookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"gamepadLookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"invertLookY",k:"b",o:1},{n:"touchMovement",k:"s",o:1,max:16,f:"code"},{n:"graphicsQuality",k:"s",o:1,max:16,f:"code"},{n:"graphicsQualityAuto",k:"b",o:1}]}],60),sa=y("gem.cohorts",[{n:"cohorts",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"experimentId",k:"s",max:36},{n:"variantKey",k:"s",max:32}]}}],12,"cohorts"),aa=y("gem.earnAllowanceChanged",[],30,"earnAllowance"),la=y("gem.viewport",[{n:"insets",k:"o",fs:[{n:"top",k:"i",lo:0,hi:4096},{n:"right",k:"i",lo:0,hi:4096},{n:"bottom",k:"i",lo:0,hi:4096},{n:"left",k:"i",lo:0,hi:4096}]},{n:"reserved",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384},{n:"width",k:"i",lo:0,hi:16384},{n:"height",k:"i",lo:0,hi:16384}]}}],60,"viewport"),da=y("gem.deviceSettings",[{n:"settings",k:"j",o:1}],12,"deviceSettings"),ca=y("gem.willTerminate",[{n:"reason",k:"e",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"i",lo:0,hi:6e4}],10),ua=y("gem.roomEvent",[{n:"event",k:"e",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"s",max:64},{n:"matchId",k:"s",o:1,max:64},{n:"version",k:"i",o:1,lo:0,hi:2147483647},{n:"reason",k:"s",o:1,max:64},{n:"platform",k:"e",o:1,v:["universal","mobile"]}],120,"rooms"),ma=y("gem.socketState",[{n:"connected",k:"b"},{n:"reason",k:"e",o:1,v:["connecting","dropped","watchdog","terminal"]}],12,"socketState"),pa=y("gem.seatedEvent",[{n:"roomId",k:"s",max:64}],60,"partySeating"),ga=y("gem.autoStartFailedEvent",[{n:"roomId",k:"s",max:64},{n:"code",k:"s",max:64}],30,"autoStartFailure"),ha=y("gem.ticketEvent",[{n:"event",k:"e",v:["queued","matched","expired","cancelled","failed"]},{n:"ticketId",k:"s",max:64},{n:"partySize",k:"i",o:1,lo:1,hi:64},{n:"queuedAt",k:"i",o:1,lo:0,hi:4102444800},{n:"expiresAt",k:"i",o:1,lo:0,hi:4102444800},{n:"reason",k:"s",o:1,max:64},{n:"roomId",k:"s",o:1,max:64}],60,"ticketEvents"),fa=y("gem.signalEvent",[{n:"event",k:"e",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}],1800,"p2p"),ya=y("gem.dedicatedEvent",[{n:"event",k:"e",v:["answer","error","matchEnded"]},{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",o:1,max:10240},{n:"sessionId",k:"s",o:1,max:64},{n:"code",k:"s",o:1,max:64},{n:"message",k:"s",o:1,max:256},{n:"reason",k:"s",o:1,max:64}],120,"dedicated"),ba=y("gem.partyResult",[{n:"requestId",k:"s",max:64},{n:"partyId",k:"s",o:1,max:64}],30,"parties"),va=y("gem.clusterTarget",[{n:"clusterTargetId",k:"s",max:64},{n:"clusterTargetIds",k:"a",o:1,max:3,it:{n:"",k:"s",max:64}}],12,"clusterTarget"),_a=y("gem.devtools",[{n:"action",k:"e",v:["open","close","toggle"]}],30,"devtools"),ka=y("gem.screenshot",[{n:"maxWidth",k:"i",lo:1,hi:7680},{n:"maxHeight",k:"i",lo:1,hi:4320}],6,"screenshot"),wa=y("gem.screenshot.denied",[{n:"reason",k:"e",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"b"}],12,"screenshot"),Ra=y("gem.requestContext",[],12,"feedbackContext"),Sa=y("gem.gameContext",[{n:"context",k:"j"}],12,"feedbackContext"),xa=y("gem.signal",[{n:"signal",k:"e",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}],1200,"p2p"),Aa=y("gem.dedicatedOffer",[{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",max:10240},{n:"intent",k:"e",v:["initial","ice_restart","full_reconnect"]}],60,"dedicated"),Pa=y("gem.partyRequest",[{n:"requestId",k:"s",max:64}],12,"parties"),Ta=y("gem.ready",[],5),Ea=y("gem.engaged",[],5,"engagement"),Ia=y("gem.progress",[{n:"loaded",k:"i",lo:0,hi:1099511627776},{n:"total",k:"i",lo:0,hi:1099511627776}],600),Ca=y("gem.requestToken",[{n:"requestId",k:"s",max:64},{n:"reason",k:"e",v:["initial","expiring","rejected"]}],12),Ma=y("gem.requestLocalServer",[{n:"requestId",k:"s",max:64},{n:"gameRoomId",k:"s",max:64}],6,"localHost"),Oa=y("gem.localServer",[{n:"requestId",k:"s",max:64},{n:"serverId",k:"s",o:1,max:128}],30,"localHost"),La=y("gem.localServer.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"reason",k:"e",v:["refused","unavailable"]}],30,"localHost"),Ga=y("gem.exit",[{n:"reason",k:"s",o:1,max:64}],5),Da=y("gem.openExternal",[{n:"url",k:"s",max:2048,f:"url"}],6),qa=y("gem.requestFullscreen",[{n:"enabled",k:"b"}],30),$a=y("gem.audioState",[{n:"muted",k:"b"}],120,"audioState"),Fa=y("gem.rewardCue",[{n:"currencySlug",k:"s",max:32},{n:"expected",k:"i",o:1,lo:1,hi:1e9},{n:"origin",k:"o",o:1,fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384}]}],60,"rewardCue"),ja=y("gem.walletDisplay",[{n:"visible",k:"b"},{n:"currencies",k:"a",o:1,max:8,it:{n:"",k:"s",max:64}},{n:"score",k:"b",o:1}],60,"walletDisplay"),Na=y("gem.controlsDeclare",[{n:"uses",k:"o",fs:[{n:"lookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"gamepadLookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"invertLookY",k:"s",o:1,max:16,f:"code"},{n:"touchMovement",k:"s",o:1,max:16,f:"code"}]}],60,"controls"),Ua=y("gem.menu",[{n:"settings",k:"b"},{n:"items",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"id",k:"s",max:32},{n:"label",k:"s",max:40}]}}],60,"gameMenu"),Wa=y("gem.menuSelect",[{n:"entry",k:"e",v:["settings","item"]},{n:"id",k:"s",o:1,max:32}],60,"gameMenu"),Ba=y("gem.gemCorner",[{n:"corner",k:"e",v:["top-left","top-right","bottom-left","bottom-right"]}],12,"gemCorner"),Va=y("gem.requestShare",[{n:"params",k:"a",max:16,it:{n:"",k:"o",fs:[{n:"key",k:"s",max:64},{n:"value",k:"s",max:512}]}}],6,"share"),Ha=y("gem.requestAvatarPicker",[{n:"tab",k:"e",o:1,v:["2d","3d"]}],6,"avatarPicker"),Ka=y("gem.vibrate",[{n:"pattern",k:"a",max:99,it:{n:"",k:"i",lo:0,hi:1e4}}],600,"vibration"),Ja=y("gem.frameStats",[{n:"fps",k:"i",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"i",lo:0,hi:1e5}],120,"frameStats"),za=y("gem.portraitBorders",[{n:"name",k:"s",o:1,max:40}],60,"portraitBorders"),Xa=y("gem.error",[{n:"code",k:"e",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"s",o:1,max:256}],60),Ya=y("gem.requestPurchase",[{n:"requestId",k:"s",max:64},{n:"purchaseKind",k:"e",v:["item","recipe"]},{n:"targetId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"quantity",k:"i",o:1,lo:1,hi:10},{n:"catalogId",k:"s",o:1,max:64}],12,"purchases"),Qa=y("gem.requestAvatar3dPurchase",[{n:"requestId",k:"s",max:64},{n:"itemId",k:"s",max:64},{n:"currencySlug",k:"s",max:32}],12,"avatar3dPurchases"),Za=y("gem.purchaseResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["ok","declined","unavailable"]},{n:"reason",k:"s",o:1,max:64,f:"code"},{n:"purchaseId",k:"s",o:1,max:64}],30,"purchases"),el=y("gem.deviceSettings.put",[{n:"requestId",k:"s",max:64},{n:"settings",k:"j"}],30,"deviceSettings"),tl=y("gem.deviceSettings.result",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["stored","too_large","unavailable"]}],30,"deviceSettings"),nl=y("gem.requestAd",[{n:"requestId",k:"s",max:64},{n:"placement",k:"s",max:32},{n:"format",k:"e",v:["interstitial","rewarded"]}],6,"ads"),rl=y("gem.adResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["shown","no_ad","unavailable"]}],12,"ads"),il=y("gem.signalMoment",[{n:"requestId",k:"s",max:64},{n:"kind",k:"e",v:["level_end","run_end","match_end","menu_return","other_break"]},{n:"placement",k:"s",o:1,max:32}],6,"moments"),ol=y("gem.momentResult",[{n:"requestId",k:"s",max:64},{n:"shown",k:"b"}],12,"moments"),sl=y("gem.requestSignIn",[{n:"requestId",k:"s",max:64}],6,"signIn"),al=y("gem.signInResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["signed_in","declined","unavailable"]}],12,"signIn"),ll=y("gem.requestFriendChallenge",[{n:"requestId",k:"s",max:64},{n:"playerId",k:"s",max:64},{n:"template",k:"s",max:64},{n:"params",k:"j",o:1}],12,"friendChallenges"),dl=y("gem.friendChallengeResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"s",o:1,max:64},{n:"param",k:"s",o:1,max:64},{n:"channel",k:"s",o:1,max:16},{n:"configVersion",k:"i",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:864e5},{n:"detail",k:"s",o:1,max:300}],30,"friendChallenges"),de=Object.freeze(zn);le.__malformed=60;Object.freeze(le);Object.freeze(Bt);var st=3;function W(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=W(t);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Ii=2e3,Ci=5e3;function Mi(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 a,s=new Promise(l=>{let d=false,m=null;a=c=>{d||(d=true,r=null,n.clock.clearTimeout(m),l(c));},m=n.clock.setTimeout(()=>{t=true,a([]);},n.timeoutMs??Ii);});return r={promise:s,settle:a},s};return {resolveList:o,resolve(){return e.length>0||t||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(a=>a[0])},refresh(a){return !Xn(e,a)||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(s=>{let l=null,d=m=>{i.delete(d)&&(n.clock.clearTimeout(l),s(m));};i.set(d,a),l=n.clock.setTimeout(()=>d(e),n.refreshTimeoutMs??Ci);})},accept(a,s){let l=ve(s),d=W(a),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[c,p]of [...i])Xn(m,p)||c(m);}}}}function Xn(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Oi=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Vt(n){return typeof n=="string"&&Oi.test(n)}function Yn(n){if(n===null||Vt(n))return n;let e=typeof n=="string"?JSON.stringify(n.length>48?`${n.slice(0,48)}\u2026`:n):`a value of type ${typeof n}`;console.warn(`[gem] showPortraitBorders: ${e} is not a border name, so nothing was sent. A name is 1 to 40 of a-z, 0-9, _ and -, starting with a letter or digit, exactly as your store page declares it under media.portrait_borders. Pass null for no art.`);}var De=16384,at=24;function S(n){return e=>typeof e=="string"&&e.length>0&&e.length<=n?e:void 0}function te(n,e){return t=>typeof t=="number"&&Number.isInteger(t)&&t>=n&&t<=e?t:void 0}function _e(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function Qn(n){return typeof n=="boolean"?n:void 0}var L=S(64),qe=te(0,2147483647);function Ht(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 T(n,e,t){return {to:n,from:e,read:t,required:true}}function x(n,e,t){return {to:n,from:e,read:t,required:false}}function ke(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 $e(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 Zn=[T("sdp","sdp",S(10240)),T("signaling_intent","intent",_e("initial","ice_restart","full_reconnect"))];function lt(n,e,t){if(typeof t!="object"||t===null||Array.isArray(t))return {reason:"offer: data must be an object"};let r=t,i=ke(r,Zn);return i===null?{reason:`offer: '${Zn.find(a=>a.read(r[a.from])===void 0)?.from??"?"}' is missing or out of bounds`}:{frame:{type:"webrtc_offer",match_id:n,game_id:e,...i}}}var Kt=Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"})),Li=new Set(["error"]),Gi=Object.freeze(Object.assign(Object.create(null),{answer:[T("sdp","sdp",S(10240)),x("sessionId","session_id",S(64))],error:[x("code","code",S(64)),x("message","message",S(256))],matchEnded:[x("reason","reason",S(64))]}));function dt(n,e,t){let r=$e(n);if(r===null)return null;let i=Kt[r.type];if(i===void 0)return null;let o=L(r.data.match_id);if(typeof o!="string"||!(Li.has(i)?t(o):r.data.game_id===e))return null;let s=ke(r.data,Gi[i]??[]);return s===null?null:{event:i,matchId:o,...s}}var Di=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=_e("disconnected","failed","closed")(e.iceState),r=te(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}}},qi=Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[T("sdp","sdp",S(10240)),T("signaling_intent","intent",_e("initial","ice_restart","full_reconnect")),x("sdp_hash","sdpHash",S(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[T("peer_id","peerId",L),T("sdp","sdp",S(10240)),T("assigned_peer_id","assignedPeerId",te(0,4294967295)),x("sdp_hash","sdpHash",S(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[T("peer_id","peerId",L),T("candidate","candidate",S(512)),x("sdp_mid","sdpMid",S(64)),x("sdp_mline_index","sdpMLineIndex",te(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[T("host_epoch","hostEpoch",qe)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[T("host_epoch","hostEpoch",qe),x("evidence","evidence",Di)]}}));function ct(n,e,t,r){let i=qi[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,a=ke(o,i.args);if(a===null){let s=i.args.find(l=>l.required&&l.read(o[l.from])===void 0);return {reason:`${n}: '${s?.from??"?"}' is missing or out of bounds`}}return {frame:{type:i.type,match_id:e,...i.gameScoped?{game_id:t}:{},...a}}}var $i=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"})),Fi=new Set(["error"]),ji=Object.freeze(Object.assign(Object.create(null),{hello:[T("playerId","player_id",L),T("hostPlayerId","host_player_id",L),T("hostEpoch","host_epoch",qe),x("members","members",Ht)],offer:[T("fromPlayerId","from_player_id",L),T("sdp","sdp",S(10240)),x("sessionId","signaling_session_id",S(128)),x("sdpHash","sdp_hash",S(128)),x("iceUfrag","ice_ufrag",S(64)),x("intent","signaling_intent",_e("initial","ice_restart","full_reconnect"))],answer:[T("fromPlayerId","from_player_id",L),T("sdp","sdp",S(10240)),x("sessionId","signaling_session_id",S(128)),x("sdpHash","sdp_hash",S(128)),x("iceUfrag","ice_ufrag",S(64)),x("assignedPeerId","assigned_peer_id",te(0,4294967295))],ice:[T("fromPlayerId","from_player_id",L),T("candidate","candidate",S(512)),x("sdpMid","sdp_mid",S(64)),x("sdpMLineIndex","sdp_m_line_index",te(0,255)),x("sdpMLineIndexAlt","sdp_mline_index",te(0,255))],peerJoined:[T("playerId","player_id",L)],peerLeft:[T("playerId","player_id",L),x("reason","reason",S(64))],migration:[T("hostPlayerId","new_host_player_id",L),T("hostEpoch","host_epoch",qe),x("reason","reason",S(64)),x("kickedPlayerIds","kicked_player_ids",Ht),x("migrationComplete","migration_complete",Qn)],matchEnded:[x("reason","reason",S(64))],error:[x("code","code",S(64)),x("message","message",S(256))]}));function ut(n,e,t){let r=$e(n);if(r===null)return null;let i=$i[r.type];if(i===void 0)return null;let o=L(r.data.match_id);if(typeof o!="string"||!(Fi.has(i)?t(o):r.data.game_id===e))return null;let s=ke(r.data,ji[i]??[]);return s===null?null:{event:i,matchId:o,data:s}}var Ni=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 Fe(n){let e=$e(n);if(e===null)return null;let t=Ni[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=te(0,Number.MAX_SAFE_INTEGER)(r.version),a=L(r.game_room_id),s=L(r.game_id),l=L(r.inviter_player_id),d=S(80)(r.inviter_display_tag),m=S(64)(r.party_name);return {event:t,partyId:i,...o===void 0?{}:{version:o},...a===void 0?{}:{gameRoomId:a},...s===void 0?{}:{gameId:s},...l===void 0?{}:{inviterPlayerId:l},...d===void 0?{}:{inviterDisplayTag:d},...m===void 0?{}:{partyName:m}}}var ie={now:()=>Date.now(),setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n)},ne=class{constructor(e=ie){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let t=le[e];if(t===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??t,a=Math.max(0,r-i),s=Math.min(t,o+a*t/6e4);return s<1?(this.tokens.set(e,s),this.lastRefill.set(e,r),false):(this.tokens.set(e,s-1),this.lastRefill.set(e,r),true)}};function Re(n,e){return n.toLowerCase()===e.toLowerCase()}function mt(n){let e=n.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function tr(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:mt(t.hostname)&&mt(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 Ui=7,zt=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Wi=/^[a-z][a-z0-9_]{0,31}$/,Bi=8,rr=256,Vi=["universal","mobile"],Hi={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"},Ki=new Set(["match_ended","p2p_match_ended"]),Ji="game_room_auto_start_failed",ir={matchmaking_ticket_queued:"queued",matchmaking_ticket_matched:"matched",matchmaking_ticket_expired:"expired",matchmaking_ticket_cancelled:"cancelled",matchmaking_ticket_failed:"failed"},zi=64,or=/^[a-z][a-z0-9_]{0,63}$/,je=64,Xi=8,Yt=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 Se(n){if(!(typeof n!="string"||n.length===0||n.length>je))return n}function sr(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>=0?n:void 0}function Yi(n){return n instanceof Error?n.message:String(n)}function ar(n,e){if(!n.has(e)){if(n.size>=Xi){let t=n.values().next().value;t!==void 0&&n.delete(t);}n.add(e);}}function Xt(){return new MessageChannel}var Qi=6e4/(le["gem.handshake"]??1),Zi=6e4,Qt=class{constructor(e){this.options=e;if(!ot(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(!ot(e.embedderOrigin))throw new Error(`GemHost: embedderOrigin must be a concrete origin, got '${e.embedderOrigin}'.`);this.clock=e.clock??ie,this.inbound=new ne(this.clock),this.outbound=new ne(this.clock),this.socketWindow=new Yt(this.clock,24);}options;state="idle";port=null;version=null;timeoutHandle=null;reofferHandle=null;makeChannel=Xt;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=Xt){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?Xt():(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 ${Wt}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.`);},Wt);}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:h,type:"gem.handshake",versions:{min:ee.min,max:ee.max},embedder:this.options.embedderOrigin,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]},...this.options.unbidden===true?{unbidden:true}:{}},this.options.frameOrigin,[e.port2]),true}scheduleReoffer(){this.reofferHandle=this.clock.setTimeout(()=>{this.reofferHandle=null,this.state==="handshaking"&&(this.offer(),this.pruneStaleOffers(),this.scheduleReoffer());},Qi);}pruneStaleOffers(){let e=this.clock.now()-Zi;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 Re(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:h,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=Hi[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=Se(i.game_room_id);if(o===void 0)return false;let a=Ki.has(t.type)?void 0:Se(i.match_id);a!==void 0&&this.rememberMatch(a);let s=typeof i.version=="number"?i.version:void 0,l=typeof i.reason=="string"?i.reason.slice(0,je):void 0,d=r==="version_stale"&&Vi.includes(i.platform)?i.platform:void 0;return this.sendRoomEvent({event:r,roomId:o,...a===void 0?{}:{matchId:a},...s===void 0?{}:{version:s},...l===void 0?{}:{reason:l},...d===void 0?{}:{platform:d}})}sendRoomEvent(e){return this.frameSupports("rooms")?this.send({gem:h,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:h,type:"gem.socketState",connected:e.connected,...e.connected?{}:{reason:e.reason}}):false}sendSeatedEvent(e){return this.frameSupports("partySeating")?this.send({gem:h,type:"gem.seatedEvent",roomId:e}):false}relaySeatedEvent(e){if(this.gameId===null)return false;let t=Fe(e);if(t===null||t.event!=="gameRoomJoined"||t.gameId!==this.gameId)return false;let r=Se(t.gameRoomId);return r===void 0?false:this.sendSeatedEvent(r)}sendAutoStartFailedEvent(e){return this.frameSupports("autoStartFailure")?this.send({gem:h,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!==Ji||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=Se(r.game_room_id),o=typeof r.code=="string"&&or.test(r.code)?r.code:void 0;return i===void 0||o===void 0?false:this.sendAutoStartFailedEvent({roomId:i,code:o})}sendTicketEvent(e){return this.frameSupports("ticketEvents")?this.send({gem:h,type:"gem.ticketEvent",event:e.event,ticketId:e.ticketId,...e.partySize===void 0?{}:{partySize:e.partySize},...e.queuedAt===void 0?{}:{queuedAt:e.queuedAt},...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt},...e.reason===void 0?{}:{reason:e.reason},...e.roomId===void 0?{}:{roomId:e.roomId}}):false}relayTicketEvent(e){if(this.gameId===null||typeof e!="object"||e===null||Array.isArray(e))return false;let t=e;if(typeof t.type!="string"||!Object.hasOwn(ir,t.type))return false;let r=ir[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=Se(i.ticket_id);if(o===void 0)return false;if(r==="queued"){let s=typeof i.party_size=="number"&&Number.isInteger(i.party_size)&&i.party_size>=1&&i.party_size<=zi?i.party_size:void 0,l=sr(i.queued_at),d=sr(i.expires_at);return this.sendTicketEvent({event:r,ticketId:o,...s===void 0?{}:{partySize:s},...l===void 0?{}:{queuedAt:l},...d===void 0?{}:{expiresAt:d}})}if(r==="matched"){let s=Se(i.game_room_id);return this.sendTicketEvent({event:r,ticketId:o,...s===void 0?{}:{roomId:s}})}let a=typeof i.reason=="string"&&or.test(i.reason)?i.reason:void 0;return this.sendTicketEvent({event:r,ticketId:o,...a===void 0?{}:{reason:a}})}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"),this.relayTicketEvent(e)&&t.push("ticket");let r=Fe(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=ut(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:h,type:"gem.signalEvent",event:e.event,matchId:e.matchId,data:e.data}):false}relayDedicatedEvent(e){if(this.gameId===null)return false;let t=dt(e,this.gameId,r=>this.knowsMatch(r));return t===null?false:this.sendDedicatedEvent(t)}sendDedicatedEvent(e){return this.frameSupports("dedicated")?this.send({gem:h,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){ar(this.knownMatches,e);}rememberAsked(e){ar(this.askedMatches,e);}answerPartyRequest(e,t){return this.send({gem:h,type:"gem.partyResult",requestId:e,...t===void 0?{}:{partyId:t}})}answerPurchase(e,t,r,i){return this.send({gem:h,type:"gem.purchaseResult",requestId:e,outcome:t,...r===void 0||t!=="ok"?{}:{purchaseId:r},...i===void 0||t==="ok"?{}:{reason:i}})}answerDeviceSettingsPut(e,t){return this.send({gem:h,type:"gem.deviceSettings.result",requestId:e,outcome:t})}sendDeviceSettings(e){return this.frameSupports("deviceSettings")?this.send({gem:h,type:"gem.deviceSettings",...e===void 0?{}:{settings:e}}):false}sendMenuSelect(e){return this.frameSupports("gameMenu")?this.send(e==="settings"?{gem:h,type:"gem.menuSelect",entry:"settings"}:{gem:h,type:"gem.menuSelect",entry:"item",id:e.id}):false}answerAd(e,t){return this.send({gem:h,type:"gem.adResult",requestId:e,outcome:t})}answerMoment(e,t){return this.send({gem:h,type:"gem.momentResult",requestId:e,shown:t})}answerSignIn(e,t){return this.send({gem:h,type:"gem.signInResult",requestId:e,outcome:t})}answerFriendChallenge(e,t,r={}){let i={};if(t==="invalid"){let{code:o,param:a,channel:s,configVersion:l,detail:d}=r;typeof o=="string"&&o.length<=64&&(i.code=o),typeof a=="string"&&a.length<=64&&(i.param=a),typeof s=="string"&&s.length<=16&&(i.channel=s),typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&(i.configVersion=l),typeof d=="string"&&(i.detail=d.slice(0,300));}else if(t==="rate_limited"){let o=r.retryAfterMs;typeof o=="number"&&Number.isFinite(o)&&(i.retryAfterMs=Math.min(864e5,Math.max(0,Math.round(o))));}return this.send({gem:h,type:"gem.friendChallengeResult",requestId:e,outcome:t,...i})}denyToken(e){this.send({gem:h,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:h,type:"gem.localServer",requestId:e.requestId,...e.serverId===void 0?{}:{serverId:e.serverId}}):false}denyLocalServer(e){return this.frameSupports("localHost")?this.send({gem:h,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:h,type:"gem.clusterTarget",clusterTargetId:i,...typeof e=="string"?{}:{clusterTargetIds:[...t]}})}sendPlayer(e){let{displayName:t,displayTag:r}=e.untrusted,i=e.badges?.map(({itemId:m,iconUrl:c})=>({itemId:m,iconUrl:c})),o=e.boost&&{multipliers:e.boost.multipliers.map(({currencyId:m,currencySlug:c,multiplierBp:p})=>({currencyId:m,currencySlug:c,multiplierBp:p})),...e.boost.expiresInDays===void 0?{}:{expiresInDays:Math.min(Ui,e.boost.expiresInDays)}},a=e.discriminator!==void 0&&/^[0-9]{1,8}$/.test(e.discriminator)?e.discriminator:void 0,s=e.avatarIconId!==void 0&&zt.test(e.avatarIconId)?e.avatarIconId:void 0,l=e.avatar3dId!==void 0&&zt.test(e.avatar3dId)?e.avatar3dId:void 0,d;if(e.avatars3d!==void 0){let m=new Set;d=[];for(let{family:c,id:p,modelUrl:f,iconUrl:b}of e.avatars3d){if(d.length===Bi)break;!zt.test(p)||!Wi.test(c)||m.has(c)||f.length>rr||b.length>rr||(m.add(c),d.push({family:c,id:p,modelUrl:f,iconUrl:b}));}}this.send({gem:h,type:"gem.player",untrusted:{displayName:t,...r===void 0?{}:{displayTag:r},displayHandle:r??t},...e.playerId===void 0?{}:{playerId:e.playerId},...a===void 0?{}:{discriminator:a},...e.avatarIconUrl===void 0?{}:{avatarIconUrl:e.avatarIconUrl},...s===void 0?{}:{avatarIconId:s},...l===void 0?{}:{avatar3dId:l},...e.avatar3dModelUrl===void 0?{}:{avatar3dModelUrl:e.avatar3dModelUrl},...e.avatar3dIconUrl===void 0?{}:{avatar3dIconUrl:e.avatar3dIconUrl},...d===void 0?{}:{avatars3d:d},...i===void 0?{}:{badges:i},...o===void 0?{}:{boost:o},displayTag:a??"",...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:h,type:"gem.pause",paused:e});}sendDevtools(e){this.send({gem:h,type:"gem.devtools",action:e});}requestScreenshot(e,t){return this.frameSupports("screenshot")?this.send({gem:h,type:"gem.screenshot",maxWidth:t.maxWidth,maxHeight:t.maxHeight},[e]):false}requestContext(){return this.frameSupports("feedbackContext")?this.send({gem:h,type:"gem.requestContext"}):false}sendPrefs(e){this.send({gem:h,type:"gem.prefs",...e});}sendCohorts(e){return this.frameSupports("cohorts")?this.send({gem:h,type:"gem.cohorts",cohorts:e.map(t=>({experimentId:t.experimentId,variantKey:t.variantKey}))}):false}sendEarnAllowanceChanged(){return this.frameSupports("earnAllowance")?this.send({gem:h,type:"gem.earnAllowanceChanged"}):false}sendViewport(e){if(!this.frameSupports("viewport"))return false;let t=(e.reserved??[]).map(({x:o,y:a,width:s,height:l})=>({x:o,y:a,width:s,height:l})),r=this.frameSupports("reservedAreas"),i=e.insets.top;if(!r)for(let o of t)o.y===0&&(i=Math.max(i,o.height));return this.send({gem:h,type:"gem.viewport",insets:{top:i,right:e.insets.right,bottom:e.insets.bottom,left:e.insets.left},...r?{reserved:t}:{}})}sendWillTerminate(e,t){this.send({gem:h,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=de[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=de[r];if(!i){this.refuseMalformed("unsupported",`unknown message type ${JSON.stringify(r.slice(0,je))}`);return}if(r==="gem.controlsDeclare")return;if(!this.inbound.allow(r)){this.fail("rate_limited",`frame exceeded the limit for ${r}`);return}let o=it(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 a=i(e);if(a){this.fail("invalid_message",`${r}: ${a}`);return}let s=e;r!=="gem.handshake.accept"&&!this.versionMatches(s,r)||this.dispatch(r,s,t);}refuseMalformed(e,t){if(!this.inbound.allow(be)){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=ct(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=lt(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: ${Yi(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<ee.min||i>ee.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.engaged":this.options.onEngaged?.();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.walletDisplay":this.options.onWalletDisplay?.(t);break;case "gem.menu":this.options.onMenu?.(t);break;case "gem.gemCorner":this.options.onGemCorner?.(t);break;case "gem.frameStats":this.options.onFrameStats?.(t);break;case "gem.portraitBorders":{let{name:i}=t;i==null?this.options.onPortraitBorders?.(null):Vt(i)&&this.options.onPortraitBorders?.(i);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.requestAvatar3dPurchase":{let i=t;if(!this.frameSupports("avatar3dPurchases")||!this.frameSupports("purchases")){this.fail("unsupported_capability","refusing gem.requestAvatar3dPurchase: the frame did not advertise 'avatar3dPurchases' and 'purchases', so it cannot receive gem.purchaseResult. Nothing was prompted and nothing was spent.");break}if(this.options.onRequestAvatar3dPurchase===void 0){this.answerPurchase(i.requestId,"unavailable");break}this.options.onRequestAvatar3dPurchase(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.signalMoment":{let i=t;if(!this.frameSupports("moments")){this.fail("unsupported_capability","refusing gem.signalMoment: the frame did not advertise 'moments', so it cannot receive gem.momentResult. Nothing was rendered.");break}if(this.options.onSignalMoment===void 0){this.answerMoment(i.requestId,false);break}this.options.onSignalMoment(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.requestFriendChallenge":{let i=t;if(!this.frameSupports("friendChallenges")){this.fail("unsupported_capability","refusing gem.requestFriendChallenge: the frame did not advertise 'friendChallenges', so it cannot receive gem.friendChallengeResult. Nothing was previewed, rendered or sent.");break}if(this.options.onRequestFriendChallenge===void 0){this.answerFriendChallenge(i.requestId,"unavailable");break}this.options.onRequestFriendChallenge(i);break}case "gem.requestShare":if(!this.frameSupports("share")){this.fail("unsupported_capability","refusing gem.requestShare: the frame did not advertise 'share'. Nothing was shared.");break}this.options.onRequestShare?.(t);break;case "gem.requestAvatarPicker":if(!this.frameSupports("avatarPicker")){this.fail("unsupported_capability","refusing gem.requestAvatarPicker: the frame did not advertise 'avatarPicker'. Nothing was opened.");break}{let i=t.tab;this.options.onRequestAvatarPicker?.(i==="2d"||i==="3d"?{tab:i}:{});}break;case "gem.vibrate":{if(!this.frameSupports("vibration")){this.fail("unsupported_capability","refusing gem.vibrate: the frame did not advertise 'vibration'. Nothing was played.");break}let i=t,o=i.pattern.reduce((a,s)=>a+s,0);if(o>1e4){this.fail("invalid_message",`refusing gem.vibrate: the pattern totals ${o} ms, over ${1e4}. Nothing was played.`);break}this.options.onVibrate?.(i);break}case "gem.error":this.fail(t.code,t.message);break;default:this.fail("unsupported",`no parent handler for '${e}'`);}}};var B=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 ue(n){return new B(n)}var eo={toPlain(n){return B.unwrap(n)},compare(n,e,t){let r=n instanceof B?B.unwrap(n):n,i=e instanceof B?B.unwrap(e):e;if(typeof Intl>"u"||typeof Intl.Collator!="function")return r<i?-1:r>i?1:0;let o;try{o=new Intl.Collator(t);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(n,e){let t=n instanceof B?B.unwrap(n):n,r=e instanceof B?B.unwrap(e):e;return t.normalize("NFC")===r.normalize("NFC")}};function lr(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function to(n,e){if(n!==true)return {visible:false};let t=[],r=false;for(let i of Array.isArray(e)?e:[])i==="score"?r=true:typeof i=="string"&&i.length>0&&i.length<=64&&!t.includes(i)&&t.push(i);return !r&&t.length===0?{visible:true}:{visible:true,currencies:t.slice(0,8),score:r}}function no(n){let e=[];for(let t of Array.isArray(n)?n:[]){if(e.length===4)break;if(typeof t!="object"||t===null)continue;let{id:r,label:i}=t;typeof r!="string"||r.length===0||r.length>32||typeof i!="string"||i.trim().length===0||e.some(o=>o.id===r)||e.push({id:r,label:i.trim().slice(0,40)});}return e.length===0?{settings:false}:{settings:false,items:e}}function dr(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function ro(n){let e=n.untrusted,t=ue(e.displayName),r=e.displayTag||e.displayHandle,i=r?ue(r):void 0,o=n.discriminator||n.displayTag,a=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,s=n.avatarIconUrl||n.avatarUrl,l=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,d=n.avatarIconId,m=n.avatar3dId,c={displayName:t,displayHandle:i??t,badges:(n.badges??[]).map(w=>({itemId:w.itemId,iconUrl:w.iconUrl}))};n.playerId&&(c.playerId=n.playerId),a&&(c.discriminator=a),i&&(c.displayTag=i),s&&(c.avatarIconUrl=c.avatarUrl=s),d&&l.test(d)&&(c.avatarIconId=d),m&&l.test(m)&&(c.avatar3dId=m),n.avatar3dModelUrl&&(c.avatar3dModelUrl=n.avatar3dModelUrl),n.avatar3dIconUrl&&(c.avatar3dIconUrl=n.avatar3dIconUrl),n.avatars3d&&(c.avatars3d=n.avatars3d.filter(w=>l.test(w.id)&&/^[a-z][a-z0-9_]*$/.test(w.family)).filter((w,A,C)=>C.findIndex(E=>E.family==w.family)==A).map(({family:w,id:A,modelUrl:C,iconUrl:E})=>({family:w,id:A,modelUrl:C,iconUrl:E})));let p=n.boost,f=(p?.multipliers??[]).map(w=>({currencyId:w.currencyId,currencySlug:w.currencySlug,multiplier:w.multiplierBp/1e4})),b=f.some(w=>w.multiplier>1);return c.boost=b&&p?.expiresInDays?{active:b,multipliers:f,expiresInDays:p.expiresInDays}:{active:b,multipliers:f},c}var io=1e4,Zt=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??ie,this.inbound=new ne(this.clock),this.outbound=new ne(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;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}get unbiddenLaunch(){return this.unbidden}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(s=>Re(s,e.origin))||tr(e.origin,this.options.selfOrigin)))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),this.state==="waiting"&&this.transition("refused"),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=de["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!Re(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 a=Jt(ee,i.versions);return a===null?(o.onmessage=null,o.postMessage({gem:h,type:"gem.error",code:"version_mismatch",message:`frame supports v${ee.min}..v${ee.max}`}),o.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=o,this.version=a,o.onmessage=s=>this.receive(s.data,s.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],this.unbidden=i.unbidden===true,o.postMessage({gem:h,type:"gem.handshake.accept",v:a,...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:h,type:"gem.ready"});}settled(e=io){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:h,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:h,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:h,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),true):false}exit(e){this.send(e===void 0?{gem:h,type:"gem.exit"}:{gem:h,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:h,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:h,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.gated("audioState")?(this.send({gem:h,type:"gem.audioState",muted:e}),true):false}reportEngaged(){return this.engagedSent||!this.gated("engagement")||!this.send({gem:h,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(!this.gated("rewardCue"))return false;let t={gem:h,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:lr(e.origin.x),y:lr(e.origin.y)}),this.send(t),true}showPortraitBorders(e){let t=Yn(e);return t===void 0||!this.gated("portraitBorders")?false:this.send(t===null?{gem:h,type:"gem.portraitBorders"}:{gem:h,type:"gem.portraitBorders",name:t})}setWalletVisible(e,t){return this.gated("walletDisplay")?this.send({gem:h,type:"gem.walletDisplay",...to(e,t?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:h,type:"gem.menu",...no(e)}):false}setGemCorner(e){return this.gated("gemCorner")?this.send({gem:h,type:"gem.gemCorner",corner:e}):false}requestShare(e){return this.gated("share")?this.send({gem:h,type:"gem.requestShare",params:e.map(({key:t,value:r})=>({key:t,value:r}))}):false}requestAvatarPicker(e){return this.gated("avatarPicker")?this.send({gem:h,type:"gem.requestAvatarPicker",...e==="2d"||e==="3d"?{tab:e}:{}}):false}requestVibrate(e){return this.gated("vibration")?this.send({gem:h,type:"gem.vibrate",pattern:[...e]}):false}reportFrameStats(e){return this.gated("frameStats")?(this.send({gem:h,type:"gem.frameStats",fps:dr(e.fps,1e3),frameTimeP95Ms:dr(e.frameTimeP95Ms,1e5)}),true):false}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:h,type:"gem.gameContext",context:e}),true)}signal(e,t,r){this.send({gem:h,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:h,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:h,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,i,o,a){return this.send({gem:h,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...a===void 0?{}:{catalogId:a}})}requestAvatar3dPurchase(e,t,r){return this.parentSupports("avatar3dPurchases")?this.send({gem:h,type:"gem.requestAvatar3dPurchase",requestId:e,itemId:t,currencySlug:r}):false}putDeviceSettings(e,t){return this.send({gem:h,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:h,type:"gem.requestAd",requestId:e,placement:t,format:r})}signalMoment(e,t,r){return this.send({gem:h,type:"gem.signalMoment",requestId:e,kind:t,...r===void 0?{}:{placement:r}})}readyCalled(){return this.readySent||this.readyPending}requestSignIn(e){return this.send({gem:h,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,t,r,i){return this.send({gem:h,type:"gem.requestFriendChallenge",requestId:e,playerId:t,template:r,...i===void 0?{}:{params:i}})}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(be)){this.options.onDropped?.(e,t);return}this.fail(e,t);}dropUnknownType(e){this.inbound.allow(be)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,t){e.ports?.[0]?.close?.(),this.inbound.allow(be)&&this.options.onRefused?.(t);}fail(e,t){this.options.onError?.(e,t),this.state==="connected"&&this.port&&this.send({gem:h,type:"gem.error",code:e,...t===void 0?{}:{message:t}});}gated(e){return this.state==="connected"&&this.parentSupports(e)}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=de[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||cr(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=de[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=it(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 a=i(e);if(a)return this.fail("invalid_message",`${r}: ${a}`),false;let s=e;if(s.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(s);break;case "gem.pause":this.options.onPause?.(s);break;case "gem.menuSelect":this.options.onMenuSelect?.(s);break;case "gem.prefs":this.options.onPrefs?.(s);break;case "gem.cohorts":this.options.onCohorts?.(s);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(s);break;case "gem.willTerminate":this.options.onWillTerminate?.(s);break;case "gem.devtools":this.options.onDevtools?.(s.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=t[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:s.maxWidth,maxHeight:s.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return cr(t.slice(1)),this.options.onScreenshot(d,l,(m,c)=>this.screenshotDenied(m,c)),true}case "gem.token.denied":this.options.onTokenDenied?.(s);break;case "gem.localServer":this.options.onLocalServer?.(s);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(s);break;case "gem.player":{this.options.onPlayer?.(ro(s));break}case "gem.roomEvent":this.options.onRoomEvent?.(s);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(s);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(s);break;case "gem.ticketEvent":this.options.onTicketEvent?.(s);break;case "gem.socketState":this.options.onSocketState?.(s);break;case "gem.signalEvent":this.options.onSignalEvent?.(s);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(s);break;case "gem.clusterTarget":this.options.onClusterTarget?.(s);break;case "gem.partyResult":this.options.onPartyResult?.(s);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(s);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(s);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(s);break;case "gem.adResult":this.options.onAdResult?.(s);break;case "gem.momentResult":this.options.onMomentResult?.(s);break;case "gem.signInResult":this.options.onSignInResult?.(s);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(s);break;case "gem.error":this.options.onError?.(s.code,s.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,t){this.send({gem:h,type:"gem.screenshot.denied",reason:e,retryable:t});}};function cr(n){for(let e of n)try{e?.close?.();}catch{}}var oo=16384;function so(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:ao(e)}function ao(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 ur=["p2p","dedicated","unknown"],pt=["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 me=class{constructor(e){this.options=e;}options;async post(e,t){let r=this.options.gameId();if(r===null||r==="")return;let i=lo(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 lo(n,e,t){let r=Math.floor(t/1e3);return n.filter(i=>pt.includes(i.type)).slice(0,100).map(i=>{let o=co(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function co(n){if(n!==void 0)return ur.includes(n)?n:"unknown"}function en(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 j=class extends Error{constructor(t,r,i,o,a){super(`${t} (${r}): ${i}`);this.reason=t;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=a;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}};var mo=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),u=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="DedicatedServerError",this.retryable=mo.has(t),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var mr=["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"],po=new Set(mr);function xe(n){return typeof n=="string"&&po.has(n)?n:"unknown"}var Ne="webrtc_dedicated",nn=["universal","mobile","web"];var go="p2p_unavailable",ho="capacity_unavailable",fo=2,pr=3e4,gr=1e3,hr=2e4;async function gt(n){let e=W(n.clusterTargetId),t=n.nextClusterTarget,r=0,i=n.clock??ie,o=n.retry??{},a=o.budgetMs??pr,s=o.maxDelayMs??hr,l=o.initialDelayMs??gr,d=i.now(),m=d+a,c=0;for(;;){c++;try{let p=await on(n.signal,"while allocating",()=>n.client.post(`${br(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!yo(p)||a<=0)throw p;if(p.status===503&&p.code===go)throw new u("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});if(r=p.code===ho?r+1:0,t!==void 0&&r>=fo){let C=t;t=void 0;let E=W(await C());E!==void 0&&(e=E,r=0);}let f=Math.min(s,l*2**(c-1)),b=Math.min(s,(p.retryAfterSeconds??0)*1e3),A=Math.max(f/2,b)+Math.random()*(f/2);if(i.now()+A>m)throw bo(n,p,c,i.now()-d,a);if(o.onWaiting?.({attempt:c,elapsedMs:i.now()-d,budgetMs:a,nextAttemptInMs:A,status:p.status,message:p.message}),await yt(i,A,n.signal),n.signal?.aborted)throw tn("while waiting to allocate")}}}function yo(n){return n instanceof j?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function bo(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 u("start_rate_limited",`the platform was still limiting match starts for room ${n.roomId} after ${o}: ${e.message}`,{cause:e}):new u("no_server_ready",`the platform had no server ready for room ${n.roomId} after ${o}: ${e.message}`,{cause:e})}var vo=12e4,_o=1e3;async function ht(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??_o,i=n.timeoutMs??vo,o=e.now()+i,a=fr(n),s={seen:n.knownToExist===true};for(;;){let l=await yr(n,a,s);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new u("timeout",`match ${t} was still ${l.status} after ${i}ms`);await yt(e,r,n.signal);}}async function rn(n){return (await yr(n,fr(n),{seen:n.knownToExist===true})).outcome}function fr(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${br(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function yr(n,e,t){let{matchId:r}=n,i=n.clock.now(),o;try{o=await on(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(a){if(a instanceof j&&a.reason==="not_found")return {status:"not_found",outcome:t.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw a}if(t.seen=true,o.status==="ready")return {status:"ready",outcome:ko(r,o,i)};if(o.status==="failed"){let a=o.ended_reason;return typeof a=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:xe(a)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function ft(n){let e=await on(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 on(n,e,t){if(n?.aborted)throw tn(e);try{return await t()}catch(r){throw n?.aborted?tn(e,r):r}}function tn(n,e){return new u("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function ko(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 br(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function yt(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"]),an="embedder_relay_unavailable",Ro="embedder_no_relay",So=new Set([an]),ln=new Set([Ro]),bt=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new sn(this)}handleEvent(e){let t=this.pending.get(e.matchId);if(t!==void 0){if(e.event==="matchEnded"){t.refuse(new u("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 u("signaling_failed","the parent relayed an answer with no SDP in it"));return}t.settle({sdp:e.sdp});return}t.refuse(xo(e.code,e.message));}}register(e,t){this.pending.get(e)?.refuse(new u("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 u("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 docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new u("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See docs/dedicated-server-flow.md \xA72.");return e}};function xo(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new u(Ao(n),r,{platformCode:n})}function Ao(n){return n===void 0||So.has(n)?"signaling_failed":ln.has(n)?"offer_refused":wo.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var sn=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,t){if(this.closed)return Promise.reject(new u("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 u("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let a=()=>{s(),o(new u("aborted","the caller aborted the signaling exchange"));},s=()=>{t?.removeEventListener("abort",a),this.hub.release(e.matchId,l),this.teardown===s&&(this.teardown=null);},l={settle:d=>{s(),i(d);},refuse:d=>{s(),o(d);}};this.teardown=s,t?.addEventListener("abort",a),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof u?d:new u("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var vr="match_ended:",_r="server_shutdown:",kr="kicked:",Po=123;function To(n){if(typeof n!="string"||n.length===0||n.length>Po)return {kind:"other"};if(n.startsWith(vr)){let e=xe(n.slice(vr.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(_r)?{kind:"server_shutdown",cause:n.slice(_r.length)}:n.startsWith(kr)?{kind:"kicked",detail:n.slice(kr.length)}:{kind:"other"}}function dn(n,e,t){let r=To(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 Eo="join",Io="welcome",Co="rejected",cn=25e3,Mo=1e3,un=1;function mn(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var Oo={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 pn(n){let e=typeof n=="string"?n:"unknown";return new u(Oo[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function Ue(n){let{channel:e,clock:t}=n;return new Promise((r,i)=>{let o=false,a=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??cn),s=t.setTimeout(()=>w(new u("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(a,Mo)),l=A=>{let C=A.data;if(typeof C!="string"){c(C);return}let E;try{E=JSON.parse(C);}catch{c(C);return}if(o){c(C);return}if(E.t===Io){let g=mn(E.heartbeat_interval);b({...typeof E.player_id=="string"?{playerId:E.player_id}:{},...typeof E.match_id=="string"?{matchId:E.match_id}:{},...g===void 0?{}:{heartbeatIntervalMs:g}});return}if(E.t===Co){w(pn(E.reason));return}c(C);},d=()=>{w(new u("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{w(new u("aborted","the caller aborted during the join exchange"));},c=A=>{o&&n.onMessage?.(A);},p=()=>{t.clearTimeout(s),e.removeEventListener("close",d),n.signal?.removeEventListener("abort",m);},f=()=>{e.removeEventListener("message",l);},b=A=>{o=true,p(),n.onMessage===void 0&&f(),r({welcome:A,detach:f});},w=A=>{o||(o=true,p(),f(),i(A));};if(e.addEventListener("message",l),e.addEventListener("close",d),n.signal?.aborted){m();return}n.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:Eo,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:un}:{}}));}catch(A){w(new u("connection_failed",`the join frame could not be sent on the open channel: ${String(A)}`,{cause:A}));}})}function vt(){return {exchange(){return Promise.reject(new u("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 docs/dedicated-server-flow.md \xA72."))},close(){}}}var pe=1,We=2,gn=4,yn=8,Lo=2,Go=1e3,bn="heartbeat timeout",_t="gem-uu",kt=2,Rr="gem_transports";function Be(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!Do(r)||e.includes(r)||e.push(r);}return e}function Do(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function wt(n,e){if(typeof n!="object"||n===null)return null;let t=n[Rr];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 Rt(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var Sr=new TextEncoder,xr=new TextDecoder;function vn(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function _n(n){let e=0;return n?.reliable===false&&(e|=pe),n?.ordered===false&&(e|=We),e}function kn(n){return {reliable:(n&pe)===0,ordered:(n&We)===0}}var wn={reliable:true,ordered:true};function Ar(n){return JSON.stringify({t:"join",credential:n,wire:kt,heartbeat:un})}function Pr(n){let e;try{e=JSON.parse(n);}catch{throw new u("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let t=mn(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"?pn(e.reason):new u("join_refused","the server answered the join out of protocol")}function Rn(){return typeof globalThis.WebTransport=="function"&&Sn===null}function St(){return Sn}var Sn=null;var wr="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function qo(n){let e=en(n);if(e.byteLength!==32)throw new u("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var hn=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 u("connection_failed",`a control-stream record claims ${o} bytes`);if(this.buffered.byteLength<4+o)break;let a=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:a[0]??0,payload:a.slice(1)});}return r}};function fn(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 Ve(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webTransport;if(t===void 0){let s=globalThis.WebTransport;if(s===void 0)throw new u("connection_failed","this environment has no WebTransport");t=n.certHashBase64===void 0?new s(n.url):new s(n.url,{serverCertificateHashes:[{algorithm:"sha-256",value:qo(n.certHashBase64)}]});}let r=t,i=s=>{try{r.close();}catch{}throw s},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(Sn=wr,i(new u("connection_failed",`${wr}; the rung is skipped for the rest of this page (a reload probes again)`)));let a=new Promise((s,l)=>{setTimeout(()=>l(new u("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,a]);let s=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([s.read(),a]);if(s.releaseLock(),l.done||l.value===void 0)return i(new u("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(fn(gn,Sr.encode(Ar(n.credential))));let c=new hn,p=d.readable.getReader(),f;for(;f===void 0;){let b=await Promise.race([p.read(),a]);if(b.done||b.value===void 0)return i(new u("connection_failed","the control stream closed before the join was answered"));for(let w of c.push(b.value)){f=Pr(xr.decode(w.payload));break}}return {link:$o(r,m,p,c,n.log??(b=>console.warn(b)),Er(f,n.clock)),welcome:f}}catch(s){return i(s)}}function $o(n,e,t,r,i,o){let a,s,l=false,d=b=>{if(!l){l=true,m.stop();try{n.close();}catch{}s?.(b);}},m=An(o,()=>d(bn)),c=(b,w)=>{m.heard(),(b&yn)===0&&a!==void 0&&((b&gn)!==0?a(xr.decode(w),wn):a(w,kn(b)));};(async()=>{try{for(;;){let b=await t.read();if(b.done||b.value===void 0)break;for(let w of r.push(b.value))c(w.flags,w.payload);}}catch{}d("stream closed");})();let p,f;try{let b=n.datagrams;if(b?.readable!==void 0&&b.writable!==void 0){let w=b.readable.getReader();f=b.writable.getWriter(),p=b,(async()=>{try{for(;;){let A=await w.read();if(A.done||A.value===void 0)break;let C=A.value;C.byteLength!==0&&c((C[0]??0)|pe|We,C.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(b){p=void 0,f=void 0,i(`[gem] webtransport datagram lane unusable (${Rt(b)}); unreliable sends ride the stream`);}return n.closed.then(b=>d(Tr(b?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(b,w){if(l)return;if(typeof b=="string"){e.write(fn(gn,Sr.encode(b))).catch(()=>d("write failed"));return}let A=_n(w);if((A&pe)!==0&&f!==void 0){let C=vn(A,b),E=p?.maxDatagramSize;if(E===void 0||C.byteLength<=E){f.write(C).catch(()=>{});return}}e.write(fn(A,b)).catch(()=>d("write failed"));},onMessage(b){a=b;},onClose(b){s=b;},close(){d("closed");}}}function xn(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 u("connection_failed","this environment has no WebSocket"));t=new i(n.url);}let r=t;return r.binaryType="arraybuffer",new Promise((i,o)=>{let a=false,s=setTimeout(()=>{a||(a=true,r.close(),o(new u("timeout","websocket did not come up in time")));},e),l=f=>{a||(a=true,clearTimeout(s),r.close(),o(f));},d=()=>{r.send(Ar(n.credential));},m=f=>{if(a)return;if(typeof f.data!="string"){l(new u("join_refused","the server sent binary before answering the join"));return}let b;try{b=Pr(f.data);}catch(w){l(w);return}a=true,clearTimeout(s),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",c),r.removeEventListener("error",p),i({link:Fo(r,Er(b,n.clock)),welcome:b});},c=()=>{l(new u("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new u("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",m),r.addEventListener("close",c),r.addEventListener("error",p),r.readyState===1&&d();})}function Tr(n){return typeof n=="string"&&n.length>0?n:void 0}function Er(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function An(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,Go)*Lo,i=t.now(),o=null,a=()=>{o=null;let s=t.now()-i;if(s>=r){e();return}o=t.setTimeout(a,r-s);};return o=t.setTimeout(a,r),{heard:()=>{i=t.now();},stop:()=>{o!==null&&(t.clearTimeout(o),o=null);}}}function Fo(n,e){let t,r,i=false,o=s=>{if(!i){i=true,a.stop();try{n.close();}catch{}r?.(s);}},a=An(e,()=>o(bn));return n.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){t?.(s.data,wn);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&yn)===0&&t?.(l.slice(1),kn(d));})),n.addEventListener("close",(s=>o(Tr(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!i){if(typeof s=="string"){n.send(s);return}n.send(vn(_n(l),s));}},onMessage(s){t=s;},onClose(s){r=s;},close(){o("closed");}}}function Pn(n,e,t,r){let i,o,a=false,s=t,l=c=>{if(!a){a=true,d.stop();try{n.close();}catch{}try{e.close();}catch{}o?.(c);}},d=An(r,()=>l(bn)),m=(c,p)=>{if(d.heard(),typeof c=="string"){i?.(c,wn);return}let f=new Uint8Array(c);if(f.byteLength===0)return;let b=f[0]??0;(b&yn)===0&&i?.(f.slice(1),kn(b|p));};if(n.addEventListener("message",(c=>m(c.data,0))),n.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let c=e.connectionState;(c==="failed"||c==="closed")&&l(`connection ${c}`);})),s!==void 0){let c=s;c.addEventListener("message",(p=>m(p.data,pe|We))),c.addEventListener("close",(()=>{s=void 0;}));}return {transport:"webrtc",send(c,p){if(a)return;if(typeof c=="string"){n.send(c);return}let f=_n(p),b=vn(f,c);if((f&pe)!==0&&s!==void 0&&s.readyState==="open"){s.send(b);return}n.send(b);},onMessage(c){i=c;},onClose(c){o=c;},close(){l("closed");}}}var Ir=10240,Cr=2048,jo=new TextEncoder;function Mr(n){return jo.encode(n).length}function oe(n,e){let t=i=>{throw new u("invalid_sdp",`the ${e} ${i}`)},r=Mr(n);r>=Ir&&t(`is ${r} bytes, over the ${Ir} 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=Mr(i);o>Cr&&t(`has a ${o}-byte line, over the ${Cr} limit`);}}function xt(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 No=3e3,Uo=1e4,Wo=15e3;async function He(n){let e=n.peerConnection;try{Lr(n,"before the handshake started"),Tn(n);let t=e.createDataChannel(n.channelLabel??"gem",{ordered:!0});for(let a of n.extraChannels??[]){let s=e.createDataChannel(a.label,{...a.ordered===void 0?{}:{ordered:a.ordered},...a.maxRetransmits===void 0?{}:{maxRetransmits:a.maxRetransmits}});n.onExtraChannel?.(a.label,s);}let r=await e.createOffer();await e.setLocalDescription(r),await Ho(e,n),Tn(n);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new u("invalid_sdp","the offer carried no SDP");oe(i,"offer"),Or(i,"offer");let o=await Vo(n,i);if(Tn(n),typeof o?.sdp!="string")throw new u("invalid_sdp","the signaling channel answered without an SDP");return oe(o.sdp,"answer"),Or(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await Ko(t,n),Lr(n,"before the channel opened"),t}catch(t){throw e.close(),Bo(t)}}function Bo(n){return n instanceof u?n:qr(n)?ge():new u("connection_failed",$r(n),{cause:n})}function Or(n,e){if(xt(n))throw new u("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 Vo(n,e){let t=n.exchangeTimeoutMs??Uo,r=Dr(n,t),i=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(o=>{throw o instanceof u?o:qr(o)?ge():new u("signaling_failed",$r(o),{cause:o})});return Jo(i,n,r,()=>r.exhausted?En("while the offer was in flight"):new u("timeout",`no answer arrived within ${t}ms`))}function Ho(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let i=()=>{t.clearTimeout(a),n.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{n.iceGatheringState==="complete"&&i();},a=t.setTimeout(i,e.gatherTimeoutMs??No);n.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function Ko(n,e){if(e.signal?.aborted)return Promise.reject(ge());if(n.readyState==="open")return Promise.resolve();if(n.readyState!=="connecting")return Promise.reject(new u("connection_failed",`the data channel was already '${n.readyState}' when the answer was applied`));let{clock:t}=e,r=e.openTimeoutMs??Wo,i=Dr(e,r);return new Promise((o,a)=>{let s=()=>{t.clearTimeout(p),n.removeEventListener("open",l),n.removeEventListener("close",d),n.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{s(),o();},d=f=>{s(),a(new u("connection_failed","the data channel failed before it opened",Gr(f)===void 0?void 0:{cause:Gr(f)}));},m=()=>{s(),a(ge());},c=()=>{s(),a(i.exhausted?En("while the channel was still opening"):new u("timeout",`the data channel did not open within ${r}ms`));},p=t.setTimeout(c,i.ms);n.addEventListener("open",l),n.addEventListener("close",d),n.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function Dr(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 Jo(n,e,t,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(ge()):new Promise((a,s)=>{let l=c=>{i.clearTimeout(m),o?.removeEventListener("abort",d),c();},d=()=>l(()=>s(ge())),m=i.setTimeout(()=>l(()=>s(r())),t.ms);o?.addEventListener("abort",d),n.then(c=>l(()=>a(c)),c=>l(()=>s(c)));})}function Lr(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw En(`already ${e}`)}function En(n){return new u("credential_expired",`the join credential ran out ${n} \u2014 poll match status again for a fresh one`)}function Tn(n){if(n.signal?.aborted)throw ge()}function ge(){return new u("aborted","the caller aborted the connection attempt")}function qr(n){return n?.name==="AbortError"}function Gr(n){return n?.error}function $r(n){return n instanceof Error?n.message:String(n)}var Ke="0.1.0-beta",Fr="0-beta",Ae="web",zo=/^(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 Xo(n){let e=zo.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function jr(n,e){let t=Yo(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:Ke};let i=Xo(r);if(i===null)throw new u("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 '${Ke}' for it.`);if(i!==Fr)throw new u("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${Fr}' 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 '${Ke}' for it.`);return {...n,platform:t,engineVersion:r}}function Yo(n,e){if(n===void 0||n===Ae)return Ae;if(!nn.includes(n))throw new u("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${nn.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${Ae}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${Ae}' 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.`),Ae}function Qo(n){let{client:e,clock:t,rooms:r}=n,i=n.signaling??vt,o=n.log??(g=>console.warn(g)),a=new me({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(g,v)=>{let R=s.get(g)??new Set;R.add(v),s.set(g,R);},d=(g,v)=>{let R=s.get(g);R!==void 0&&(R.delete(v),R.size===0&&s.delete(g));},m=async g=>{if(r.isHost&&!as(r)&&r.currentRoom?.matchId===void 0){let v=W(g.clusterTargetId);await r.startMatch({...v===void 0?{}:{clusterTargetId:v},...g.retry===void 0?{}:{retry:g.retry},...g.signal===void 0?{}:{signal:g.signal}});}return Hr(r.matchConnectionState==="suspended"?await r.reconnectToMatch(In(g)):await r.awaitMatch(In(g)))},c=async g=>Hr(await r.pollMatchStatus(In(g))),p=async(g,v)=>{let R=false;try{let _=await m(g),G=r.currentRoom?.transports;if(G!==void 0&&!G.includes("webrtc"))throw new u("misconfigured",`the room template offers (${G.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 M=g.peerConnection??Kr();R=!0;let D=await He({peerConnection:M,signaling:v,clock:t,matchId:_.matchId,credentialExpiresAt:_.credentialExpiresAt,...At(g,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),F=null;if(g.presentCredential!==!1)try{F=await Ue({channel:D,clock:t,credential:_.joinCredential,credentialExpiresAt:_.credentialExpiresAt,...At(g,"onMessage","signal"),...g.welcomeTimeoutMs===void 0?{}:{ceilingMs:g.welcomeTimeoutMs}});}catch(N){throw J(D),J(M),N}return ss(r,_,D,M,v,g.reportDisconnect!==!1,g.reportConnected!==!1,F,{remember:l,forget:d},g.onMatchEnded)}catch(_){throw R&&Vr(a,_),J(v),_}},f=async(g,v,R,_,G,M)=>{if(g==="webtransport"){let O=_?.webtransport;if(O===void 0)throw new u("misconfigured","webtransport is not advertised");let X={credential:R.joinCredential,credentialExpiresAt:R.credentialExpiresAt,clock:t};if(typeof O.named_url=="string"&&O.named_url!==""){let re=Math.max(Math.floor(M/2),1e3);try{return await Ve({url:O.named_url,timeoutMs:re,log:o,...X})}catch(se){if(St()!==null)throw se;return o(`[gem] webtransport named dial failed (${Rt(se)}); retrying the pinned dial`),Ve({url:O.url,certHashBase64:O.cert_sha256_b64,timeoutMs:re,log:o,...X})}}return Ve({url:O.url,certHashBase64:O.cert_sha256_b64,timeoutMs:M,...X})}if(g==="websocket"){let O=_?.websocket;if(O===void 0)throw new u("misconfigured","websocket is not advertised");return xn({url:O.url,credential:R.joinCredential,credentialExpiresAt:R.credentialExpiresAt,clock:t,timeoutMs:M})}let D=v.peerConnection??Kr(),F,N=await He({peerConnection:D,signaling:G,clock:t,matchId:R.matchId,credentialExpiresAt:R.credentialExpiresAt,extraChannels:[{label:_t,ordered:false,maxRetransmits:0}],onExtraChannel:(O,X)=>{O===_t&&(F=X);},...At(v,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...v.exchangeTimeoutMs===void 0&&v.redial===true?{exchangeTimeoutMs:es}:{}}),K;try{K=await Ue({channel:N,clock:t,credential:R.joinCredential,credentialExpiresAt:R.credentialExpiresAt,wire:kt,heartbeat:!0,...At(v,"signal"),...v.welcomeTimeoutMs===void 0?{}:{ceilingMs:v.welcomeTimeoutMs}});}catch(O){throw J(N),J(D),O}let P=K.welcome.heartbeatIntervalMs;return {link:Pn(N,D,F,P===void 0?void 0:{clock:t,intervalMs:P}),welcome:K.welcome,channel:N,peerConnection:D}},b=(g,v,R,_,G)=>{let M=false,D;_.link.onClose(P=>{!M&&g.reportDisconnect!==false&&dn(r,v.matchId,P),D?.(P);}),g.reportDisconnect!==false&&g.reportConnected!==false&&r.notifyMatchConnected(v.matchId);let F={transport:_.link.transport,send:(P,O)=>_.link.send(P,O),onMessage:P=>_.link.onMessage(P),onClose:P=>{D=P;},close:()=>_.link.close()},N=()=>{M||(M=true,J(_.link),J(G));},K=P=>{if(!M){try{g.onMatchEnded?.(P);}catch{}N();}};return l(v.matchId,K),{matchId:v.matchId,transport:R,link:F,joinCredential:v.joinCredential,credentialExpiresAt:v.credentialExpiresAt,welcome:_.welcome,..._.channel===void 0?{}:{channel:_.channel},..._.peerConnection===void 0?{}:{peerConnection:_.peerConnection},close(){d(v.matchId,K),N();}}},w=async(g,v)=>{let R=r.currentRoom?.id,_=r.gameId,G=()=>({advert:wt(r.currentRoom?.settings,g),template:r.currentRoom?.transports??null});if(R===void 0||_===null)return G();try{let M=await e.get(`/v2/games/${encodeURIComponent(_)}/game-rooms/${encodeURIComponent(R)}`,v);return {advert:wt(M.settings,g),template:Be(M.transports)??r.currentRoom?.transports??null}}catch{return G()}},A=(g,v)=>{let R=g??Nr;return v.length===0?R:R.filter(_=>v.includes(_))},C=async(g,v,R)=>{try{let _=await m(g),{advert:G,template:M}=await w(_.matchId,g.signal),D=A(M,v),F=D.filter(q=>rs(q,G)),N=St();if(N!==null&&D.includes("webtransport")&&G?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${N} (learned on an earlier dial in this page)`),F.length===0){let q=M===null?`the default order (${Nr.join(", ")})`:`the room template's transports (${M.join(", ")||"none"})`;throw new u("misconfigured",`none of ${q}`+(v.length>0?`, narrowed to (${v.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let K=g.transportAttemptTimeoutMs??Zo,P=()=>g.deadlineAt===void 0?1/0:g.deadlineAt-t.now(),O=q=>n.signalingReady===void 0||q<=0?Promise.resolve(!0):n.signalingReady(q),X=[],re=[];for(let q of F){if(P()<Wr){o(`[gem] ${q} rung not tried: the reconnect budget is spent`);break}re.length>0&&_.credentialExpiresAt-t.now()<Br&&(_=await c(g)),re.push(q);let Wn=!1,Bn=!1,nt={attempts:0,waitedMs:0};for(;;){if(q==="webrtc"&&g.redial===!0){let Z=Math.min(Ur,P());await O(Z)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(Z)}ms; offering anyway`);}let Ri=Math.max(Math.min(K,P()),Wr);try{return b(g,_,q,await f(q,g,_,G,R,Ri),R)}catch(Z){let U=Z instanceof u?Z:new u("connection_failed",Z instanceof Error?Z.message:String(Z),{cause:Z});if(q==="webrtc"&&Vr(a,U),(U.reason==="credential_expired"||U.reason==="credential_reused")&&!Wn){Wn=!0,_=await c(g);continue}if(q==="webrtc"&&U.reason==="signaling_failed"&&U.platformCode===an&&!Bn){Bn=!0;let ae=Math.min(Ur,P());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 O(ae))continue}if(U.reason==="join_rate_limited"){let ae=ns(nt,Math.random,P());if(ae!==null){if(nt.attempts+=1,nt.waitedMs+=ae,o(`[gem] ${q} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ae)}ms before presenting again (retry ${nt.attempts} of ${zr.maxAttempts})`),await yt(t,ae,g.signal),g.signal?.aborted)throw new u("aborted","the caller aborted while waiting out a join rate limit");_.credentialExpiresAt-t.now()<Br&&(_=await c(g));continue}}if(ts.has(U.reason)||U.reason==="credential_expired"||q==="webrtc"&&Jr(U)){o(`[gem] ${q} rung failed (${U.reason}): ${Rt(U.cause??U)} \u2014 `+(re.length<F.length?`falling through to ${F[re.length]}`:"no rungs left")),X.push(U);break}throw o(`[gem] ${q} rung refused the session (${U.reason}): ${U.message}`),U}}}let se=X[X.length-1];throw se===void 0?new u("timeout",`the reconnect budget ran out before any transport (${F.join(", ")}) could be tried`):new u(se.reason,`every transport tried (${re.join(", ")}) failed; the last said: ${se.message}`,{cause:X,platformCode:se.platformCode})}catch(_){throw J(R),_}};return {listClusterTargets:async(g={})=>ft({client:e,...g}),handleMatchEnded(g,v){let R=s.get(g);if(R!==void 0){s.delete(g);for(let _ of R)_(v);}},connect:(async(g={})=>{let v=g.signaling??i();return g.transports===void 0?p(g,v):C(g,g.transports,v)})}}var Nr=["webtransport","webrtc","websocket"],Zo=1e4,es=5e3,Ur=3e3,Wr=1e3,Br=1e4,ts=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Jr(n){return n.platformCode!==void 0&&ln.has(n.platformCode)}var zr={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function ns(n,e=Math.random,t=1/0){let r=zr;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 rs(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&Rn():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||is(e.websocket.url)}function is(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return mt(e)}function In(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var os=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Vr(n,e){e instanceof u&&(!os.has(e.reason)&&!Jr(e)||n.report([{type:"connection_failures_total",value:1}]));}function ss(n,e,t,r,i,o,a,s,l,d){let m=false,c=()=>{m||dn(n,e.matchId,void 0);};o&&(t.addEventListener("close",c),a&&n.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,t.removeEventListener("close",c),s?.detach(),J(t),J(r),J(i));},f=b=>{if(!m){try{d?.(b);}catch{}p();}};return l.remember(e.matchId,f),{matchId:e.matchId,channel:t,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:s?.welcome??null,close(){l.forget(e.matchId,f),p();}}}function as(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function Hr(n){if(n.status==="failed")throw new u("allocation_failed",`match ${n.matchId} did not come up: ${n.reason}`);if(n.status==="ended")throw new u("match_ended",`match ${n.matchId} ended (${n.reason}) before this side connected.`);if(n.protocol!==Ne)throw new u("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${Ne}' 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 u("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 Kr(){let n=globalThis.RTCPeerConnection;if(!n)throw new u("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 J(n){try{n.close();}catch{}}function At(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var Pe=class{constructor(e){this.options=e;this.reporter=new me({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:Pt(i.credential)??"",hostFingerprint:Pt(i.host_fingerprint)??"",hostEpoch:Tt(i.host_epoch)??0,expiresAt:(Tt(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 l of Array.isArray(i.ice_servers)?i.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);m.length!==0&&o.push({urls:m,username:Pt(d.username)??"",credential:Pt(d.credential)??""});}let a=Tt(i.expires_at),s=Tt(i.ttl_seconds);return {iceServers:o,expiresAt:a!==void 0?a*1e3:Date.now()+(s??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 Pt(n){return typeof n=="string"&&n.length>0?n:void 0}function Tt(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var ls=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=ls.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 ds=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function he(n){let e=null;for(let t of n.split(/\r\n|\n/)){if(!t.startsWith("a=fingerprint:"))continue;let r=Je(t.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function Je(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 ds.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 Cn=5e3,cs=12e4+Cn,us=1024,ms=6e4,ps=1e4,Xr=64*1024,Yr=5;function It(n){let e=new Map,t=-1/0,r=null,i=(()=>{let s;try{s=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 s.username!==""||s.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:s.href,shown:`${s.protocol}//${s.host}`}})(),o=()=>{let s=n.subtle??globalThis.crypto?.subtle;if(!s)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 s},a=async()=>{if(!i.ok)throw new k("keys_unavailable",i.reason);let s=n.fetch??((p,f)=>globalThis.fetch(p,f)),l;try{l=await s(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(ps)});}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(!l.ok)throw new k("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let p=await l.text();if(p.length>Xr)throw new k("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${Xr} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof k?p:new k("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>Yr)throw new k("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${Yr} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=o();for(let p of m){let f=p;if(f.kty==="RSA"&&!(f.alg!==void 0&&f.alg!=="RS256")&&!(f.use!==void 0&&f.use!=="sig")&&!(typeof f.kid!="string"||f.kid.length===0))try{let b=await c.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(f.kid,b);}catch{}}};return {async key(s){let l=e.get(s);if(l)return l;if(!i.ok)throw new k("keys_unavailable",i.reason);if(r)return await r,e.get(s)??null;let d=n.now();if(!Number.isFinite(d))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 d<t&&(t=-1/0),d-t<ms?null:(t=d,r??=a().finally(()=>{r=null;}),await r,e.get(s)??null)}}}var ze=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>=us){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+cs),true}};function Zr(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 Qr(n){try{let e=new TextDecoder().decode(Zr(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function Ct(n,e,t,r,i){let o=P=>{throw new k("peer_unauthenticated",`the peer's join credential is not usable: ${P}`)},a=n.split(".");a.length!==3&&o("it is not a three-part JWT");let[s,l,d]=a,m=Qr(s);m===null&&o("its header does not decode"),m.alg!=="RS256"&&o(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let c=m.kid;(typeof c!="string"||c.length===0)&&o("it names no key");let p=await t.key(c);p===null&&o("it was signed by a key this build cannot resolve");let f=i.subtle??globalThis.crypto?.subtle;f||o("this environment has no WebCrypto");let b=new TextEncoder().encode(`${s}.${l}`),w;try{w=Zr(d);}catch{o("its signature does not decode");}await f.verify({name:"RSASSA-PKCS1-v1_5"},p,w,b)||o("its signature does not verify");let C=Qr(l);C===null&&o("its payload does not decode");let E=C,g=P=>typeof E[P]=="string"?E[P]:"",v=P=>typeof E[P]=="number"&&Number.isFinite(E[P])?E[P]:NaN;g("iss")!==i.issuer&&o("it was issued by someone else"),g("aud")!==`${i.issuer}/p2p-match`&&o("its audience is not this platform"),g("match_id")!==e.matchId&&o("it is for another match"),g("game_id")!==e.gameId&&o("it is for another game");let R=v("exp")*1e3,_=v("nbf")*1e3;(!Number.isFinite(R)||e.now>R+Cn)&&o("it has expired"),Number.isFinite(_)&&e.now<_-Cn&&o("it is not valid yet");let G=g("role");G!=="host"&&G!=="client"&&o("it names no usable role");let M=v("host_epoch");M!==e.hostEpoch&&o("it names a different host epoch");let D=Je(g("fingerprint"));D===null&&o("its fingerprint claim is malformed"),Te(D,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let F=Je(g("host_fingerprint"));F===null&&o("its host fingerprint claim is malformed"),Te(F,e.hostFingerprint)||o("it was issued against a different host certificate");let N=g("jti");N.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(N,e.now)||o("it has already been used");let K=g("sub");return K.length===0&&o("it names no player"),{playerId:K.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:M,role:G,fingerprint:D,hostFingerprint:F,jti:N,expiresAt:R}}var fe=32769;function Mn(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 On(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 Ln(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function Gn(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 ei(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 ti(n){switch(n){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var ni=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 Mt={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}},Xe=["reliable","ordered","unreliable"];function Ot(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 Lt(){let n=globalThis.RTCPeerConnection;return n?.generateCertificate?n.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var ii=1,bs=3e4,oi=2e3,vs=5e3,si=6e4,_s=8,qn=class{constructor(e=_s){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;}},ks=new qn,ws=8,Rs=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??It({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Et;links=new Map;replays=new ze;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=ii+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??bs;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),i=W(this.options.clusterTargetId);if(i!==void 0)try{let s=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=s.iceServers,this.mark("turn leased");}catch(s){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: ${Dn(s)}`);}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),a=()=>this.fail(new k("aborted","the caller aborted while connecting"));e?.aborted?a():e?.addEventListener("abort",a);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",a),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=$(e.playerId),r=$(e.hostPlayerId),i=Gt(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,ii),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");oe(o,"offer"),this.refuseMedia(o,"offer"),this.options.signaling.offer(o,e),this.mark("offer sent"),this.fetchCredential().catch(a=>this.report_(a));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,i=r===void 0?null:he(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??ks,a=()=>this.closed||e!==this.credentialGeneration,s=vs;for(;;){let l=o.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,a))return;o.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,i);if(a())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(a())return;let m=d.status,c;if(m===409)c=oi;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?c=p*1e3:(c=s,s=Math.min(s*2,si)),c=Math.min(Math.max(c,oi),si);}else throw d;if(!await this.waitForCredential(c,a))return}}}async waitForCredential(e,t){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!t())}async onOffer(e){let t=$(e.fromPlayerId),r=$(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=ws){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(t,e);return}if(!this.isHost||this.migration.isKicked(t)===true)return;let i=$(e.sessionId);if(i!==null&&this.answeredSessions.get(t)===i)return;oe(r,"offer"),this.refuseMedia(r,"offer");let o=he(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 a=this.links.get(t);a&&this.dropLink(a,"resignalled",false);let s=this.openLink(t,this.nextPeerId++);s.remoteFingerprint=o,await s.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(s);let l=await s.connection.createAnswer();await s.connection.setLocalDescription(l);let d=s.connection.localDescription?.sdp??l.sdp;if(!d)throw new k("invalid_sdp","the browser produced an answer with no SDP");oe(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(t,d,s.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let t=$(e.fromPlayerId),r=$(e.sdp);if(t===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||t!==this.hostPlayerId)return;oe(r,"answer"),this.refuseMedia(r,"answer");let o=he(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=$(e.fromPlayerId),r=$(e.candidate);if(t===null||r===null)return;let i=this.links.get(t);if(!i)return;let o=$(e.sdpMid),a=Gt(e.sdpMLineIndex)??Gt(e.sdpMLineIndexAlt),s={candidate:r,...o===null?{}:{sdpMid:o},...a===null?{}:{sdpMLineIndex:a}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(s);return}await i.connection.addIceCandidate(s);}onPeerLeft(e){let t=$(e.playerId);if(t===null)return;let r=$(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=$(e.hostPlayerId),r=Gt(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:t,hostEpoch:r,...$(e.reason)===null?{}:{reason:$(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=$(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=$(e.code)??"unknown",r=$(e.message)??"the platform refused a signaling message";this.report_(new k("signaling_failed",`${t}: ${r}`));}openLink(e,t){let i=(this.options.peerConnectionFactory??Ot)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let p of Xe){let f=i.createDataChannel(p,Mt[p]);f.binaryType="arraybuffer",o[p]=f;}let a={playerId:e,assignedPeerId:t,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},s=p=>{let f=p.candidate;f?.candidate&&this.options.signaling.candidate(e,f.candidate,f.sdpMid??void 0,f.sdpMLineIndex??void 0);},l=()=>this.onIceState(a),d=()=>this.onConnectionState(a),m=p=>{this.onHandshakeMessage(a,p.data).catch(f=>this.report_(f));},c=()=>{this.onReliableOpen(a).catch(p=>this.report_(p));};return i.addEventListener("icecandidate",s),i.addEventListener("iceconnectionstatechange",l),i.addEventListener("connectionstatechange",d),o.reliable.addEventListener("open",c),o.reliable.addEventListener("message",m),a.detachHandshake=()=>{o.reliable.removeEventListener("open",c),o.reliable.removeEventListener("message",m);},a.detachAll=()=>{a.detachHandshake(),i.removeEventListener("icecandidate",s),i.removeEventListener("iceconnectionstatechange",l),i.removeEventListener("connectionstatechange",d);},this.links.set(e,a),a}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(Mn({jwt:t.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,t){if(!(t instanceof ArrayBuffer))return;let r=Gn(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(ti(r.reason),ei(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=he(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 Ct(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(a){let s=a instanceof k&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",Dn(a)),s&&this.fail(a);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(On({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(Ln(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 Xe)ai(e.channels[i]);ai(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",Dn(e),{cause:e}));}count(e){this.counted||!Rs.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(xt(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){return typeof n=="string"&&n.length>0?n:null}function Gt(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function Dn(n){return n instanceof Error?n.message:String(n)}function ai(n){try{n.close();}catch{}}var Ss=100,xs=50,Ce=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??Ss)){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 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??xs));}};var $n="webrtc_p2p";function As(n){let e=new Pe({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 docs/p2p-and-parties.md \xA72.");let i=W(r.clusterTargetId),o=i??W(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 a=await n.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(a.protocol!==$n)throw new k("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${$n}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new Ce({bridge:n.bridge,matchId:a.matchId,clock:n.clock}),l=new Ie({api:e,clock:n.clock,matchId:a.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:s,...o===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Lt(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...n.boot===void 0?{}:{boot:n.boot},...n.log===void 0?{}:{log:n.log}});s.onDropped(d=>l.notifyCandidatesDropped(d)),t.set(a.matchId,l),l.on("matchEnded",()=>t.delete(a.matchId));try{await l.start(r.signal);}catch(d){throw t.delete(a.matchId),l.close(),d}return l}}}function li(n){return typeof n=="string"&&n.trim()!==""}function di(n,e){return li(n)?n.trim():li(e)?e:null}function Ye(n){let e=String(n);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function ci(n,e,t){let r=`/v1/games/${Ye(n.gameId())}/matchmaking/tickets/${Ye(e)}`;return n.client.delete(r,t?.signal)}async function ui(n,e,t){let r=`/v1/games/${Ye(n.gameId())}/matchmaking/tickets`;return n.client.post(r,e,t?.signal)}async function mi(n,e,t){let r=`/v1/games/${Ye(n.gameId())}/matchmaking/tickets/${Ye(e)}/heartbeat`;return n.client.post(r,void 0,t?.signal)}function Qe(n){let e=n??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let t=e.heartbeat_interval_seconds;return {id:e.ticket_id,status:typeof e.status=="string"?e.status:"queued",...typeof e.reason=="string"?{reason:e.reason}:{},...typeof e.game_room_id=="string"?{roomId:e.game_room_id}:{},partySize:typeof e.party_size=="number"?e.party_size:1,queuedAt:pi(e.queued_at),expiresAt:pi(e.expires_at),heartbeatIntervalSeconds:typeof t=="number"&&t>0?t:0}}function pi(n){if(typeof n!="string")return 0;let e=Date.parse(n);return Number.isFinite(e)?Math.floor(e/1e3):0}var Ps=3,gi=1e3,Dt=class{constructor(e){this.options=e;this.snapshot=e.first;let t=new Promise((o,a)=>{this.resolve=o,this.reject=a;});t.catch(()=>{});let r=()=>this.snapshot,i=()=>this.status;this.ticket={get id(){return r().id},get status(){return i()},get partySize(){return r().partySize},get queuedAt(){return r().queuedAt},get expiresAt(){return r().expiresAt},outcome:t,cancel:()=>(this.requestCancel(),t)};}options;ticket;snapshot;status="queued";timer=null;busy=false;again=false;cancelRequested=false;soon=false;misses=0;settled=false;resolve;reject;start(){this.apply(this.snapshot);}poke(){this.settled||(this.soon=true,!this.busy&&(this.clearTimer(),this.tick()));}abandon(e=false){this.settled||(this.options.cancel(this.snapshot.id,e).catch(()=>{}),this.settle({status:"cancelled",reason:"requested"}));}requestCancel(){this.settled||(this.cancelRequested=true,this.trigger());}trigger(){if(this.busy){this.again=true;return}this.clearTimer(),this.tick();}schedule(e=false){if(this.settled)return;this.clearTimer();let t=e?gi:Math.max(gi,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},t);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,t=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){t=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(t);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof j&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<Ps){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let t=e instanceof j&&e.code==="matchmaking_unavailable";this.settle({status:t?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let t=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:t});}catch(t){this.busy=false,this.fail(t);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};function Y(n){return typeof n=="string"&&n!==""?n:void 0}var Ts=new Set(["localhost","127.0.0.1","[::1]"]);function Me(n){return Es(n)}function Es(n){let e=Y(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:"&&Ts.has(t.hostname)))return e}var Is=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Cs=/^[a-z][a-z0-9_]{0,31}$/;function Ms(n){if(!Array.isArray(n))return;let e=[],t=new Set;for(let r of n.slice(0,8)){let i=r??{},o=Y(i.family),a=Y(i.avatar_3d_id),s=Me(i.model_url),l=Me(i.icon_url);o===void 0||!Cs.test(o)||t.has(o)||a===void 0||!Is.test(a)||s===void 0||l===void 0||(t.add(o),e.push({family:o,id:a,modelUrl:s,iconUrl:l}));}return e}function Os(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=t??{},i=Y(r.item_id),o=Me(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function hi(n){let e=n??{},t=Y(e.player_id),r=Y(e.display_name),i=Y(e.discriminator),o=Y(e.display_tag),a=Y(e.avatar_icon_id),s=Me(e.avatar_icon_url),l=Y(e.avatar_3d_id),d=Me(e.avatar_3d_model_url),m=Me(e.avatar_3d_icon_url),c=Ms(e.avatars_3d);return {...t===void 0?{}:{playerId:t},...r===void 0?{}:{displayName:ue(r)},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:ue(o)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},...l===void 0?{}:{avatar3dId:l},...d===void 0?{}:{avatar3dModelUrl:d},...m===void 0?{}:{avatar3dIconUrl:m},...c===void 0?{}:{avatars3d:c},badges:Os(e.badges)}}function qt(n){if(typeof n!="object"||n===null)return;let e={};for(let[t,r]of Object.entries(n)){let i=Fn(r);i!==void 0&&(e[t]=i);}return e}function $t(n){if(Array.isArray(n))return n.map(Ls).filter(e=>!!e)}function Fn(n){if(jn(n)||Array.isArray(n)&&n.every(jn))return n}function jn(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function Ls(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=Fn(e.fixed),r=Fn(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},...Oe("description",Gs(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(jn)?{allowed:e.allowed}:{},...Oe("min",Ze(e.min)),...Oe("max",Ze(e.max)),...Oe("minItems",Ze(e.min_items)),...Oe("maxItems",Ze(e.max_items)),...Oe("maxLength",Ze(e.max_length))}}function Gs(n){return typeof n=="string"&&n.length>0?n:void 0}function Ze(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Oe(n,e){return e===void 0?{}:{[n]:e}}function z(n){let e=n??{},t=I(e.id)??I(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(Nn):[];return {id:t,gameId:I(e.game_id)??"",name:I(e.name)??"",status:I(e.status)??"open",hostPlayerId:I(e.host_player_id)??"",maxPlayers:Q(e.max_players)??0,memberCount:Q(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...H("joinCode",I(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...H("roomArgs",qt(e.room_args)),...H("roomArgsTemplate",$t(e.room_args_template)),gameChannel:I(e.game_channel)??"release",...H("region",I(e.region)),...H("clusterTargetId",I(e.cluster_target_id)),selfHosted:e.self_hosted===true,...H("matchId",I(e.match_id)),version:Q(e.version)??0,...H("templateId",I(e.template_id)),...H("templateSlug",I(e.template_slug)),roomType:I(e.game_room_type)??"Standard",...H("transports",Be(e.transports)??void 0),createdAt:Q(e.created_at)??0,updatedAt:Q(e.updated_at)??0,...H("startedAt",Q(e.started_at))}}function Nn(n){let e=n??{};return {...hi(e),playerId:I(e.player_id)??"",isReady:e.is_ready===true,role:I(e.role)??"member",joinedAt:Q(e.joined_at)??0,...H("groupId",I(e.group_id)),...H("platform",I(e.platform))}}function et(n){let e=n??{};return {id:I(e.id)??I(e.game_room_id)??"",gameId:I(e.game_id)??"",name:I(e.name)??"",status:I(e.status)??"open",hostPlayerId:I(e.host_player_id)??"",maxPlayers:Q(e.max_players)??0,memberCount:Q(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:I(e.game_channel)??"release",roomType:I(e.game_room_type)??"Standard",createdAt:Q(e.created_at)??0}}function I(n){return typeof n=="string"&&n.length>0?n:void 0}function Q(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function H(n,e){return e===void 0?{}:{[n]:e}}var Le=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(et),...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(et)}))}create(e,t,r){return qs(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},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...e.roomArgs===void 0?{}:{room_args:e.roomArgs},...tt(t)},e.signal).then(z)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(z)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...tt(r)},t.signal).then(z)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...tt(r)},t.signal).then(z)}quickJoin(e,t,r=[]){let i=this.asksSelfHosted(e.partyId);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},...Ds(e.templateSlugs,i),...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},...i?{self_hosted:true}:{},...tt(t)},e.signal).then(z)}createTicket(e,t,r=[]){return ui(this.generated(),{templates:e.templateSlugs.map(i=>({template_slug:i})),...r.length===0?{}:{cluster_target_ids:[...r]},...e.partyId===void 0?{}:{party_id:e.partyId},...tt(t)},{...e.signal===void 0?{}:{signal:e.signal}}).then(Qe)}heartbeatTicket(e){return mi(this.generated(),e).then(Qe)}cancelTicket(e,t=false){return t?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(Qe):ci(this.generated(),e).then(Qe)}leave(e,t,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:t},r,{keepalive:i}).then(()=>{})}asksSelfHosted(e){return e===void 0&&this.options.selfHosted?.()===true}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(z)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(z)}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(z)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}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 Ds(n,e){return n===void 0?{}:{templates:(e?n.slice(0,1):n).map(r=>({template_slug:r}))}}function tt(n){return {platform:n.platform,game_version:n.gameVersion,engine_version:n.engineVersion}}function qs(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 Ge=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;}};var Ft=class{constructor(e){this.options=e;let t=e.first,r=new Promise(s=>{this.resolve=s;}),i=()=>this.status;this.ticket={id:t.ticketId,get status(){return i()},partySize:t.partySize??0,queuedAt:t.queuedAt??0,expiresAt:t.expiresAt??0,outcome:r};let o=t.queuedAt!==void 0&&t.expiresAt!==void 0?(t.expiresAt-t.queuedAt)*1e3:9e5,a=Math.min(Math.max(o,0),9e5)+5e3;this.timer=e.clock.setTimeout(()=>{this.timer=null,this.end({status:"lost"});},a);}options;ticket;status="queued";timer=null;resolve;get id(){return this.ticket.id}end(e){this.status==="queued"&&(this.status=e.status,this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null),this.options.onSettled(),this.resolve(e));}};function $s(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var Fs=1e3,js=3e3,Ns=6e4,Us=2,fi=new Set(["game_room_closed","game_room_gone"]),Ws=12e4,Bs=5e3,Vs=new Set(["invalid_cluster_target","capacity_unavailable"]),Hs=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function ki(n){return new Un(n)}var Un=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Le({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Ge;api;room=null;ticketWatch=null;queueing=false;partyWatch=null;heldQueued=null;queuedFromRoomId=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;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("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 a=>{let s=await this.afterRefusedClusters(a,o);if(s[0]===void 0||s[0]===o[0])throw a;return this.api.create(r,this.version("create"),s[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,t={}){this.assertNotInRoom("join"),this.assertNotQueued("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"),this.askForLocalServer(i),i}async joinByCode(e,t={}){this.assertNotInRoom("joinByCode"),this.assertNotQueued("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"),this.askForLocalServer(i),i}async quickJoin(e){this.assertNotInRoom("quickJoin"),this.assertNotQueued("quickJoin"),zs(e);let t=this.clusterTargets(),r=await this.attachParty(e),i=a=>this.api.quickJoin(r,this.version("quickJoin"),a).catch(s=>this.retryPastStaleMembership(s,r,a)),o=await this.run("quickJoin",async()=>{let a=await t;return i(a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||_i(l,a))throw s;return i(l)})});return this.enter(o,"joined"),this.askForLocalServer(o),o}async queueForMatch(e){this.assertNotQueued("queueForMatch"),Js(e?.templateSlugs),this.queueing=true;try{let t=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("queueForMatch",async()=>{let a=await t;return this.api.createTicket(r,this.version("queueForMatch"),a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||_i(l,a))throw s;return this.api.createTicket(r,this.version("queueForMatch"),l)})});this.heldQueued?.ticketId===i.id&&(this.heldQueued=null),this.partyWatch?.end({status:"lost"});let o=new Dt({clock:this.options.clock,first:i,heartbeat:a=>this.track(this.api.heartbeatTicket(a)),cancel:(a,s)=>this.track(this.api.cancelTicket(a,s)),seat:a=>this.enterMatchedRoom(a),onSettled:()=>{this.ticketWatch===o&&(this.ticketWatch=null),this.retuneSeatWatch();}});return this.ticketWatch=o,this.retuneSeatWatch(),o.start(),o.ticket}finally{this.queueing=false;let t=this.heldQueued;this.heldQueued=null,t!==null&&this.showPartyTicket(t);}}async enterMatchedRoom(e){let t=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?t:(this.room!==null&&this.room.id!==t.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(t,"joined"),this.room?.id===t.id?this.room:t)}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 j&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let a=await this.askWhyEnded(o,e);this.endMatch(o,a??"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(()=>rn({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(a){return a instanceof j&&a.reason==="not_found"?i??null:(this.reportError("reconcile",a),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=xe(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}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,t){let r=this.requireRoom("startMatch");if(!this.isHost)throw new u("misconfigured",`only the host of room ${r.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.`);this.startsInFlight++;try{return await this.startIn(r,e,t)}finally{this.startsInFlight--;}}async startIn(e,t,r){let i=W(t.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),a=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let s=(m,c)=>gt({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...i===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...t.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),t.retry?.onWaiting?.(p);}},...t.signal===void 0?{}:{signal:t.signal}}),l=()=>s(o,[a]).catch(async m=>{if(i!==void 0||!vi(m))throw m;let c=await this.nextCluster([a],true);if(c===void 0)throw m;return s(c,[a,c])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new u("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 ht({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 u("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!fi.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new u("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(!jt()){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<Fs){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($s(e.attempt,t.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!jt()){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(()=>rn({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,!fi.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(a){this.reportError("reconcile",a),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 u("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 u("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 u("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 currentTicket(){return this.ticketWatch?.ticket??null}get partyTicket(){return this.partyWatch?.ticket??null}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.ticketWatch!==null&&e.event!=="version_stale"&&e.roomId!==this.room?.id&&this.ticketWatch.poke(),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){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(t);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:t,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let i=new AbortController;this.autoStartRetry=i,this.track(this.requestStart({signal:i.signal},false).then(()=>{},o=>{i.signal.aborted||this.reportError("startMatch",o);}).finally(()=>{this.autoStartRetry===i&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!Vs.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}handleTicketEvent(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}if(this.queueing){e.event==="queued"?this.heldQueued=e:this.heldQueued?.ticketId===e.ticketId&&(this.heldQueued=null);return}if(e.event==="queued"){this.showPartyTicket(e);return}if(e.event==="matched"){e.roomId!==void 0&&this.handleSeated(e.roomId),this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:"matched"});return}this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:e.event,reason:e.reason??e.event});}}showPartyTicket(e){if(this.disposed||this.partyWatch?.id===e.ticketId)return;this.partyWatch?.end({status:"lost"});let t=new Ft({clock:this.options.clock,first:e,onSettled:()=>{this.partyWatch===t&&(this.partyWatch=null);}});this.partyWatch=t,this.emitter.emit("partyQueued",t.ticket);}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)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.partyWatch?.end({status:"matched"}),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.ticketWatch===null&&this.seatPollMs>0&&jt())){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(),!!jt())){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}if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of yi)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.ticketWatch?.abandon(),this.heldQueued=null,this.partyWatch?.end({status:"lost"}),this.abortAutoStartRetry(),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 yi)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??Bs}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new u("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=di(this.options.platformGameVersion?.(),t?.gameVersion);if(r===null)throw new u("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 jr({...t,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return ve(await this.options.resolveClusterTargets());let e=W(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,t){return !vi(e)||t.length===0?[]:ve(await this.options.refreshClusterTargets?.(t)??[])}async nextCluster(e,t=false){let r=a=>a.find(s=>!e.includes(s)),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 j)||e.reason!=="conflict"||!Hs.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new j(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 j(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 j(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 u("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.`)}assertNotQueued(e){if(!(this.ticketWatch===null&&!this.queueing))throw new u("misconfigured",`${e} refused: this player is waiting on a matchmaking ticket, which will seat them in a room of its own. Cancel it first \u2014 currentTicket.cancel() \u2014 or wait for its outcome.`)}requireRoom(e){if(this.room===null)throw new u("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 j?{operation:e,code:t.status,reason:t.reason,message:t.message,retryable:t.retryable}:{operation:e,code:0,reason:t instanceof u?t.reason:"unavailable",message:t instanceof Error?t.message:String(t),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let t=this.options.ensureLocalServer;t===void 0||!e.selfHosted||e.status!=="open"||t(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,t){this.room=e,this.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,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.abortAutoStartRetry(),this.autoStartRetried=false,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(s=>[s.playerId,s])),i=new Map(e.members.map(s=>[s.playerId,s])),o=this.playerId();for(let s of i.keys())r.has(s)||this.emitter.emit("memberJoined",s);for(let s of r.keys())if(!i.has(s)){if(s===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",s);}for(let[s,l]of i){let d=r.get(s);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",s,l.isReady);}t.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let a=Ks(t,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),a&&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.autoStartRetried=false,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??Ws;return new Promise((i,o)=>{let a=c=>{s(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),c();},s=this.emitter.on("matchAllocationStarted",c=>a(()=>i(c))),l=this.emitter.on("matchFailed",(c,p)=>a(()=>o(new u("allocation_failed",`match ${c} did not come up: ${p}`)))),d=()=>a(()=>o(new u("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>a(()=>o(new u("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?d():e.signal?.addEventListener("abort",d);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??js}pushedInterval(){return this.options.pushedPollIntervalMs??Ns}pushed(){return this.options.clock.now()-this.lastPushAt<Us*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=>{if(this.ticketWatch?.abandon(true),t?.persisted!==true&&(this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{})),this.queuedFromRoomId!==null)){let r=this.queuedFromRoomId;this.queuedFromRoomId=null,this.track(this.api.leave(r,true,void 0,true).catch(()=>{}));}},e.addEventListener("pagehide",this.unloadListener));}};function jt(){let n=globalThis.document;return n?.visibilityState===void 0||n.visibilityState==="visible"}var yi=["visibilitychange","focus","pageshow","online"];function Ks(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||bi(n)!==bi(e)}function bi(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function vi(n){return n instanceof j&&n.code==="invalid_cluster_target"}var Nt=8;function Js(n){if(!(Array.isArray(n)&&n.length>=1&&n.length<=Nt&&n.every(t=>typeof t=="string"&&t.length>0)))throw new u("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${Nt} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function zs(n){let e=n?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=Nt&&e.every(r=>typeof r=="string"&&r.length>0)))throw new u("misconfigured",`quickJoin's templateSlugs is an array naming one to ${Nt} room templates by slug \u2014 quickJoin({ templateSlugs: ['duel', 'brawl'] }). A room that has to be created is made from the first.`);if(n?.templateSlug!==void 0||n?.templateId!==void 0)throw new u("misconfigured","quickJoin takes templateSlugs or a single templateSlug / templateId, not both. Put every template this player accepts in templateSlugs, with the one to create from first.")}function _i(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}function wi(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={},a=l=>{t.delete(r)&&(n.clock.clearTimeout(o.timer),i(l));};t.set(r,a),o.timer=n.clock.setTimeout(()=>a(void 0),n.timeoutMs??2e3);let s=false;try{s=n.bridge.requestParty(r);}catch{}s||a(void 0);})},settle(r,i){t.get(r)?.(i);}}}
|
|
2
2
|
export{Bt as CAPABILITY_GATES,Si as CAPABILITY_NAMESPACE_GATES,Mt as CHANNELS,Xe as CHANNEL_KINDS,me as ClientTelemetry,Kt as DEDICATED_INBOUND_EVENTS,cn as DEFAULT_WELCOME_CEILING_MS,oo as DEVICE_SETTINGS_MAX_BYTES,u as DedicatedServerError,bt as DedicatedSignalingHub,Qs as FRAME_TO_PARENT,Zt as GemFrame,Qt as GemHost,Wt as HANDSHAKE_TIMEOUT_MS,Ee as HostMigration,be as MALFORMED_INBOUND_KEY,Hn as MAX_ARRAY_LENGTH,st as MAX_CLUSTER_TARGETS,ye as MAX_MESSAGE_BYTES,Vn as MAX_MESSAGE_DEPTH,rt as MAX_MESSAGE_NODES,at as MAX_SIGNALS_PER_SECOND,De as MAX_SOCKET_FRAME_BYTES,ni as MIGRATION_TIMEOUT_MS,Pe as P2pApi,k as P2pError,Ie as P2pSession,Ys as PARENT_TO_FRAME,h as PROTOCOL,B as PlayerText,le as RATE_LIMITS,ne as RateLimiter,Ge as RoomEmitter,Le as RoomsApi,ee as SUPPORTED_VERSIONS,Ce as SignalingClient,pt as TELEMETRY_EVENTS,ur as TRANSPORT_LABELS,de as VALIDATORS,Ne as WEBRTC_DEDICATED,$n as WEBRTC_P2P,Ke as WEB_ENGINE_VERSION,fe as WEB_PROTOCOL_VERSION,ue as asPlayerText,ht as awaitMatchOutcome,Ot as browserPeerConnection,lt as buildDedicatedOfferFrame,ct as buildSocketFrame,it as capabilityFor,Mi as createClusterTargetSource,Qo as createDedicatedServerApi,It as createKeySource,As as createP2pApi,wi as createPartyResolver,ki as createRoomManager,so as deviceSettingsByteLength,He as establishDataChannel,he as fingerprintOf,Te as fingerprintsMatch,Lt as generateCertificate,ot as isOrigin,ft as listClusterTargets,Nn as memberFromWire,Jt as negotiateVersion,W as normaliseClusterTarget,ve as normaliseClusterTargets,Je as normaliseFingerprint,Re as originsEqual,Ue as presentJoinCredential,dt as projectDedicatedEvent,Fe as projectPartyEvent,ut as projectSignal,qt as roomArgValuesFromWire,$t as roomArgsTemplateFromWire,z as roomFromWire,gt as startMatch,et as summaryFromWire,ie as systemClock,eo as text,vt as unavailableSignaling,rl as validateGemAdResult,$a as validateGemAudioState,ga as validateGemAutoStartFailedEvent,va as validateGemClusterTarget,sa as validateGemCohorts,Na as validateGemControlsDeclare,ya as validateGemDedicatedEvent,Aa as validateGemDedicatedOffer,da as validateGemDeviceSettings,el as validateGemDeviceSettingsPut,tl as validateGemDeviceSettingsResult,_a as validateGemDevtools,aa as validateGemEarnAllowanceChanged,Ea as validateGemEngaged,Xa as validateGemError,Ga as validateGemExit,Ja as validateGemFrameStats,dl as validateGemFriendChallengeResult,Sa as validateGemGameContext,Ba as validateGemGemCorner,Zs as validateGemHandshake,ea as validateGemHandshakeAccept,Oa as validateGemLocalServer,La as validateGemLocalServerDenied,Ua as validateGemMenu,Wa as validateGemMenuSelect,ol as validateGemMomentResult,Da as validateGemOpenExternal,Pa as validateGemPartyRequest,ba as validateGemPartyResult,ia as validateGemPause,ra as validateGemPlayer,za as validateGemPortraitBorders,oa as validateGemPrefs,Ia as validateGemProgress,Za as validateGemPurchaseResult,Ta as validateGemReady,nl as validateGemRequestAd,Qa as validateGemRequestAvatar3dPurchase,Ha as validateGemRequestAvatarPicker,Ra as validateGemRequestContext,ll as validateGemRequestFriendChallenge,qa as validateGemRequestFullscreen,Ma as validateGemRequestLocalServer,Ya as validateGemRequestPurchase,Va as validateGemRequestShare,sl as validateGemRequestSignIn,Ca as validateGemRequestToken,Fa as validateGemRewardCue,ua as validateGemRoomEvent,ka as validateGemScreenshot,wa as validateGemScreenshotDenied,pa as validateGemSeatedEvent,al as validateGemSignInResult,xa as validateGemSignal,fa as validateGemSignalEvent,il as validateGemSignalMoment,ma as validateGemSocketState,ha as validateGemTicketEvent,ta as validateGemToken,na as validateGemTokenDenied,Ka as validateGemVibrate,la as validateGemViewport,ja as validateGemWalletDisplay,ca as validateGemWillTerminate,Ti as validateSize,Ct as verifyCredential};//# sourceMappingURL=gem-web-sdk.esm.js.map
|
|
3
3
|
//# sourceMappingURL=gem-web-sdk.esm.js.map
|