@indiegems/gem-web-sdk 7.1.0 → 7.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- var Dl=Object.defineProperty;var $l=(n,e)=>{for(var t in e)Dl(n,t,{get:e[t],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:7.1.0]";function Ko(){let n=globalThis.__gemWebSdkVersion;if(typeof n!="string")return "";let e=n.lastIndexOf(":"),t=n.lastIndexOf("]");return e<0||t<=e+1?"":n.slice(e+1,t)}function Fl(n,e){return e!==void 0?!e:n==="chain_exhausted"}var Ze=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;get currentState(){return this.state}get lastFailure(){return this.failure}async get(){if(this.state==="lost")throw new se(this.failure??"unavailable","the session cannot be renewed");let e=this.seconds();if(this.grant&&e<this.grant.expiresAt-this.renewBefore())return this.grant.token;if(this.grant&&e>=this.grant.chainEndsAt)throw this.enter("lost","chain_exhausted"),new se("chain_exhausted","the token chain reached its ceiling");return this.refresh(this.nextReason())}nextReason(){return this.rejected?"rejected":this.grant?"expiring":"initial"}invalidate(e){e!==void 0&&this.grant!==null&&this.grant.token!==e||this.rejected&&this.grant===null||(this.grant=null,this.generation+=1,this.inFlight=null,this.rejected=true,this.state!=="lost"&&this.enter("pending"));}accept(e){this.state!=="lost"&&(this.grant=e,this.rejected=false,this.enter("ready"));}close(e="unavailable"){this.grant=null,this.generation+=1,this.inFlight=null,this.enter("lost",e);}refresh(e){if(this.inFlight)return this.inFlight;let t=this.generation;this.enter("pending");let r=this.options.request(e).then(o=>{if(t!==this.generation)throw new se("internal","token arrived for a superseded generation");return this.grant=o,this.rejected=false,this.enter("ready"),o.token}).catch(o=>{let i=jl(o),a=o?.retryable;throw t===this.generation&&this.enter(Fl(i,typeof a=="boolean"?a:void 0)?"lost":"degraded",i),o instanceof se?o:new se(i,String(o))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,t){this.failure=t??(e==="ready"?null:this.failure),this.state!==e&&(this.state=e,this.options.onStateChange?.(e,t));}renewBefore(){return this.options.renewBeforeSeconds??60}seconds(){return Math.floor(this.options.clock.now()/1e3)}},se=class n extends Error{constructor(t,r){super(`auth ${t}: ${r}`);this.reason=t;this.name="AuthError";}reason;static isAuthError(t){if(t instanceof n)return true;let r=t;return r?.name==="AuthError"&&typeof r.reason=="string"}};function jl(n){if(n instanceof se)return n.reason;let e=n?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var ne=class n extends Error{retryable=false;constructor(e){super(e),this.name="TransportRefusal";}static isRefusal(e){if(e instanceof n)return true;let t=e;return t?.name==="TransportRefusal"&&t.retryable===false}},nn=["if-match","if-none-match"],Jo=4096;function ql(n){if(!n)return;let e={};for(let[t,r]of Object.entries(n)){let o=t.toLowerCase();if(!nn.includes(o)||r===void 0)continue;let i=typeof r=="string"?Nl(r):r;if(typeof i!="string"||i.length>Jo||!Ul(i))throw new ne(`the ${o} header value cannot be sent \u2014 it is not a string, is longer than ${Jo} characters, or contains a character outside the range an HTTP header value may carry. This is a malformed request, not a server failure; the value is withheld here rather than written to logs.`);i!==""&&(e[o]=i);}return Object.freeze(e)}function Nl(n){let e=o=>o===32||o===9||o===10||o===13,t=0,r=n.length;for(;t<r&&e(n.charCodeAt(t));)t++;for(;r>t&&e(n.charCodeAt(r-1));)r--;return n.slice(t,r)}function Ul(n){for(let e=0;e<n.length;e++){let t=n.charCodeAt(e);if(t!==9&&(t<32||t===127||t>255))return false}return true}function Bl(n){let{bytes:e}=n;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new ne("the raw body is not a Uint8Array, so it cannot be sent as bytes. This is a malformed request, not a server failure.");if(n.body!==void 0)throw new ne("the request carries both a JSON body and a raw body, and only one can be sent. This is a malformed request, not a server failure.");return new Uint8Array(e)}}function zo(n,e){let t=e.replayUnauthorizedOnce??true;return {async request(r){let o={...r},i=ql(o.headers),a=Bl(o),s=Object.freeze({...o,headers:i,...a===void 0?{}:{bytes:a}}),l=await e.tokenSource.get(),d=await n(s,l);if(d.status!==401||!t)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),c=await n(s,m);if(c.status===401)throw e.tokenSource.close("unavailable"),new se("unavailable","the server refused a freshly minted token");return c}}}function rn(n){let e=typeof n=="string"?new TextEncoder().encode(n):n;return btoa(Hl(e))}function on(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}function ar(n){return new TextDecoder().decode(on(n))}function Hl(n){let t="";for(let r=0;r<n.length;r+=32768)t+=String.fromCharCode(...n.subarray(r,r+32768));return t}var D=class extends Error{constructor(t,r,o,i,a){super(`${t} (${r}): ${o}`);this.reason=t;this.status=r;this.detail=o;this.retryAfterSeconds=i;this.code=a;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},Xo=new WeakMap;function Qo(n){return Xo.get(n)??{}}var Vl=new Set([408,429,500,502,503,504]),Wl=6e4;function Kl(n){if(n===void 0)return 2;if(!Number.isInteger(n)||n<0||n>10)throw new ne(`maxRetries must be a whole number between 0 and 10; received ${JSON.stringify(n)}. This is a configuration fault, not a server failure.`);return n}var Ie=class{constructor(e){this.options=e;}options;async get(e,t){return this.send({method:"GET",path:e,signal:t},true)}async getWithEtag(e,t={}){let r=await this.sendRaw({method:"GET",path:e,...t.signal===void 0?{}:{signal:t.signal},...t.ifNoneMatch===void 0?{}:{headers:{"if-none-match":t.ifNoneMatch}}},true),o=r.etag===void 0?{}:{etag:r.etag};return r.status===304?{modified:false,...o}:{modified:true,body:r.body,...o}}async put(e,t,r,o={}){return this.send({method:"PUT",path:e,body:t,signal:r,...ht(o)},o.replaySafe===true)}async post(e,t,r,o={}){return this.send({method:"POST",path:e,body:t,signal:r,...ht(o)},o.replaySafe===true)}async postBytes(e,t,r,o={}){let i=await this.sendRaw({method:"POST",path:e,bytes:t,responseType:"bytes",signal:r,...ht(o)},o.replaySafe===true);return {bytes:Jl(i.body),...i.invocationId===void 0?{}:{invocationId:i.invocationId}}}async patch(e,t,r,o={}){return this.send({method:"PATCH",path:e,body:t,signal:r,...ht(o)},o.replaySafe===true)}async delete(e,t,r={}){return this.send({method:"DELETE",path:e,signal:t,...ht(r)},r.replaySafe===true)}async send(e,t){return (await this.sendRaw(e,t)).body}async sendRaw(e,t){let r=t?Kl(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw Yo(e.signal);for(let i=0;i<r;i++){if(i>0&&await this.backoff(i,o,e.signal),e.signal?.aborted)throw Yo(e.signal);let a;try{a=await this.options.transport.request(e);}catch(l){if(se.isAuthError(l)||ne.isRefusal(l)||e.signal?.aborted||zl(l))throw l;o=new D("unavailable",0,String(l));continue}if(a.status>=200&&a.status<300||a.status===304)return a;let s=Yl(a);if(!Vl.has(a.status))throw s;o=s;}throw o??new D("unavailable",0,"no attempt was made")}backoff(e,t,r){if(r?.aborted)return Promise.resolve();let o=t?.retryAfterSeconds,i=o!==void 0?o*1e3:2**(e-1)*250,a=2**(e-1)*250,s=Math.min(Math.max(i,a),Wl);return new Promise(l=>{let d=this.options.clock,m=false,c=false,p,g=()=>{m||(m=true,c&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,s),c=true,m&&d.clearTimeout(p);})}};function Jl(n){if(n instanceof Uint8Array)return n;if(n==null)return new Uint8Array(0);let e=typeof n=="string"?n:JSON.stringify(n);return new TextEncoder().encode(e)}function ht(n){return {...n.keepalive===void 0?{}:{keepalive:n.keepalive},...n.ifMatch===void 0?{}:{headers:{"if-match":n.ifMatch}}}}function Yo(n){return n.reason!==void 0?n.reason:new DOMException("The operation was aborted.","AbortError")}function zl(n){let e=n?.name;return e==="AbortError"||e==="TimeoutError"}function Yl(n){let e=Xl(n),t=Zl(n.body),r={...t===void 0?{}:{details:t},...n.invocationId===void 0?{}:{invocationId:n.invocationId}};return Object.keys(r).length>0&&Xo.set(e,r),e}function Xl(n){let{status:e,body:t}=n,r=Ql(t),o=n.retryAfterSeconds??td(t),i=ed(t);switch(e){case 304:return new D("not_modified",e,r);case 400:case 422:return new D("invalid",e,r,void 0,i);case 403:return new D("forbidden",e,r,void 0,i);case 404:return new D("not_found",e,r,void 0,i);case 402:return new D("insufficient_funds",e,r,void 0,i);case 409:return new D("conflict",e,r,void 0,i);case 412:return new D("precondition_failed",e,r,void 0,i);case 413:return new D("too_large",e,r,void 0,i);case 429:return new D("rate_limited",e,r,o,i);default:return new D("unavailable",e,r,o,i)}}function Ql(n){if(typeof n=="string")return n;let e=n?.message;if(typeof e=="string")return e;let t=n?.error;if(typeof t=="string")return t;let r=t?.message;return typeof r=="string"?r:"no detail"}function Zl(n){let t=n?.error?.details;return t===null?void 0:t}function ed(n){let t=n?.error?.code;return typeof t=="string"&&t.length>0?t:void 0}function td(n){let e=n?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function _(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 Zo(n,e,t){let r=`/v1/inventory/transfers/${_(e)}/accept`;return n.client.post(r,void 0,t?.signal)}async function ei(n,e,t,r,o,i){let a=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/add`;return n.client.post(a,o,i?.signal)}async function ti(n,e,t){let r=`/v1/inventory/transfers/${_(e)}/cancel`;return n.client.post(r,void 0,t?.signal)}async function ni(n,e,t,r,o,i){let a=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/claim`;return n.client.post(a,o,i?.signal)}async function ri(n,e,t){return n.client.post("/v1/characters",e,t?.signal)}async function oi(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/orders/batch`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function ii(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/orders`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function si(n,e,t,r,o){let i=`/v1/settings/${_(e)}/${_(t)}/${_(r)}`;return n.client.delete(i,o?.signal)}async function ai(n,e,t,r,o){let i=`/v1/saves/${_(e)}/${_(t)}/${_(r)}`;return n.client.delete(i,o?.signal)}async function li(n,e,t,r){let o=`/v1/showcase/players/${_(e)}/${_(t)}`;return n.client.delete(o,r?.signal)}async function di(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/recipes/execute`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function ci(n,e,t,r,o,i){let a=`/v1/saves/${_(e)}/${_(t)}/${_(r)}/finalize`;return n.client.post(a,o,i?.signal)}async function ui(n,e,t){let r=`/v1/games/${_(n.gameId())}/config/channels/${_(e)}`;return n.client.getWithEtag(r,{...t?.signal===void 0?{}:{signal:t.signal},...t?.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}})}async function mi(n,e,t){let r=`/v1/characters/${_(e)}`;return n.client.get(r,t?.signal)}async function pi(n,e,t){let r=`/v1/inventory/loot-tables/${_(e)}/drop-rates`;return n.client.get(r,t?.signal)}async function gi(n,e,t,r,o){let i=`/v1/settings/${_(e)}/${_(t)}/${_(r)}`;return n.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function yi(n,e,t,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),a=`/v1/inventory/${_(e)}/${_(t)}`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function fi(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/items/${_(r)}`;return n.client.get(i,o?.signal)}async function hi(n,e,t,r,o){let i=new URLSearchParams;o?.bucket_1!==void 0&&i.set("bucket_1",String(o?.bucket_1)),o?.bucket_2!==void 0&&i.set("bucket_2",String(o?.bucket_2)),o?.limit!==void 0&&i.set("limit",String(o?.limit));let a=i.toString(),s=`/v1/leaderboards/${_(e)}/${_(t)}/${_(r)}`+(a?`?${a}`:"");return n.client.get(s,o?.signal)}async function bi(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/orders/${_(r)}`;return n.client.get(i,o?.signal)}async function vi(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}`;return n.client.get(i,o?.signal)}async function _i(n,e,t,r,o,i){let a=`/v1/inventory/${_(e)}/${_(t)}/catalogs/${_(r)}/recipes/${_(o)}/availability`;return n.client.get(a,i?.signal)}async function wi(n,e,t,r){let o=new URLSearchParams;o.set("limit",String(r?.limit));let i=o.toString(),a=`/v1/inventory/${_(e)}/${_(t)}/recipe-usage`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function lr(n,e,t,r,o){let i=`/v1/saves/${_(e)}/${_(t)}/${_(r)}`;return n.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Si(n,e,t){let r=new URLSearchParams;t?.bucket_1!==void 0&&r.set("bucket_1",String(t?.bucket_1)),t?.bucket_2!==void 0&&r.set("bucket_2",String(t?.bucket_2));let o=r.toString(),i=`/v1/leaderboards/${_(e)}/friends`+(o?`?${o}`:"");return n.client.get(i,t?.signal)}async function Ri(n,e,t){let r=`/v1/showcase/friends/${_(e)}`;return n.client.get(r,t?.signal)}async function ki(n,e,t){let r=new URLSearchParams;t?.bucket_1!==void 0&&r.set("bucket_1",String(t?.bucket_1)),t?.bucket_2!==void 0&&r.set("bucket_2",String(t?.bucket_2));let o=r.toString(),i=`/v1/leaderboards/${_(e)}`+(o?`?${o}`:"");return n.client.get(i,t?.signal)}async function sn(n,e){return n.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function xi(n,e,t){let r=`/v1/profiles/players/${_(e)}`;return n.client.get(r,t?.signal)}async function Ai(n,e){let t=new URLSearchParams;e?.config_version!==void 0&&t.set("config_version",String(e?.config_version));let r=t.toString(),o="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function Pi(n,e,t){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${_(e)}`;return n.client.get(r,t?.signal)}async function Ti(n,e,t,r){let o=`/v1/showcase/players/${_(e)}/${_(t)}`;return n.client.get(o,r?.signal)}async function Ei(n,e){return n.client.get("/v1/characters/slots",e?.signal)}async function Ii(n,e,t){let r=`/v1/inventory/transfers/${_(e)}`;return n.client.get(r,t?.signal)}async function Ci(n,e,t){let r=`/v1/games/${_(n.gameId())}/analytics/events`;return n.client.post(r,e,t?.signal,{...t?.keepalive===void 0?{}:{keepalive:t.keepalive},replaySafe:true})}async function Mi(n,e,t){return n.client.post("/v1/inventory/transfers",e,t?.signal)}async function Oi(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/platform-funded-game-inventory-purchases`;return n.client.post(i,r,o?.signal)}async function Li(n,e,t){return n.client.postBytes("/v1/functions/invoke",e,t?.signal)}async function Gi(n,e){let t=new URLSearchParams;e?.periods_back!==void 0&&t.set("periods_back",String(e?.periods_back));let r=t.toString(),o="/v1/challenges"+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function Di(n,e){return n.client.get("/v1/characters",e?.signal)}async function $i(n,e,t,r){let o=`/v1/settings/${_(e)}/${_(t)}`;return n.client.get(o,r?.signal)}async function Fi(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/inventory/${_(e)}/${_(t)}/orders`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function ji(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/saves/${_(e)}/${_(t)}`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function qi(n,e){let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",String(e?.limit)),e?.cursor!==void 0&&t.set("cursor",String(e?.cursor));let r=t.toString(),o="/v1/friends"+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function Ni(n,e){let t=new URLSearchParams;e.entity_type!==void 0&&t.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&t.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&t.set("direction",String(e?.direction)),e?.status!==void 0&&t.set("status",String(e?.status)),e?.cursor!==void 0&&t.set("cursor",String(e?.cursor)),e?.limit!==void 0&&t.set("limit",String(e?.limit));let r=t.toString(),o="/v1/inventory/transfers"+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function Ui(n,e,t,r){let o=`/v1/games/${_(n.gameId())}/matches/${_(e)}/end`;return n.client.post(o,t,r?.signal)}async function Bi(n,e,t,r,o,i){let a=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/max`;return n.client.post(a,o,i?.signal)}async function Hi(n,e,t,r,o,i){let a=`/v1/settings/${_(e)}/${_(t)}/${_(r)}`;return n.client.put(a,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Vi(n,e,t,r,o){let i=`/v1/showcase/players/${_(e)}/${_(t)}`;return n.client.put(i,r,o?.signal)}async function Wi(n,e,t){let r=`/v1/inventory/transfers/${_(e)}/reject`;return n.client.post(r,void 0,t?.signal)}async function Ki(n,e,t,r){let o=`/v1/characters/${_(e)}`;return n.client.patch(o,t,r?.signal)}async function Ji(n,e,t,r,o,i){let a=`/v1/saves/${_(e)}/${_(t)}/${_(r)}/upload-url`;return n.client.post(a,o,i?.signal,{replaySafe:true})}async function zi(n,e,t,r,o,i){let a=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/reset`;return n.client.post(a,o,i?.signal)}async function Yi(n,e,t){let r=`/v1/characters/${_(e)}`;return n.client.delete(r,t?.signal)}var z="gem-web-bridge",ln={min:1,max:1},et=65536,Xi=8,an=5e3,Qi=1024;function cr(n){return Object.freeze(Object.assign(Object.create(null),n))}var Zi=cr({"gem.handshake":30,"gem.handshake.accept":5,"gem.token":30,"gem.token.denied":30,"gem.player":12,"gem.pause":120,"gem.prefs":60,"gem.cohorts":12,"gem.viewport":60,"gem.deviceSettings":12,"gem.willTerminate":10,"gem.roomEvent":120,"gem.socketState":12,"gem.seatedEvent":60,"gem.autoStartFailedEvent":30,"gem.signalEvent":1800,"gem.dedicatedEvent":120,"gem.partyResult":30,"gem.clusterTarget":12,"gem.devtools":30,"gem.screenshot":6,"gem.screenshot.denied":12,"gem.requestContext":12,"gem.gameContext":12,"gem.signal":1200,"gem.dedicatedOffer":60,"gem.partyRequest":12,"gem.ready":5,"gem.progress":600,"gem.requestToken":12,"gem.requestLocalServer":6,"gem.localServer":30,"gem.localServer.denied":30,"gem.exit":5,"gem.openExternal":6,"gem.requestFullscreen":30,"gem.audioState":120,"gem.rewardCue":60,"gem.frameStats":120,"gem.error":60,"gem.requestPurchase":12,"gem.purchaseResult":30,"gem.deviceSettings.put":30,"gem.deviceSettings.result":30,"gem.requestAd":6,"gem.adResult":12,"gem.requestSignIn":6,"gem.signInResult":12,__malformed:60}),dn="__malformed";var nd=cr({"gem.requestAd":"ads","gem.adResult":"ads","gem.requestSignIn":"signIn","gem.signInResult":"signIn","gem.requestPurchase":"purchases","gem.purchaseResult":"purchases","gem.devtools":"devtools","gem.screenshot":"screenshot","gem.screenshot.denied":"screenshot","gem.requestContext":"feedbackContext","gem.gameContext":"feedbackContext","gem.roomEvent":"rooms","gem.signal":"p2p","gem.signalEvent":"p2p","gem.dedicatedOffer":"dedicated","gem.dedicatedEvent":"dedicated","gem.clusterTarget":"clusterTarget","gem.partyRequest":"parties","gem.partyResult":"parties","gem.autoStartFailedEvent":"autoStartFailure","gem.seatedEvent":"partySeating","gem.socketState":"socketState","gem.audioState":"audioState","gem.rewardCue":"rewardCue","gem.frameStats":"frameStats","gem.viewport":"viewport","gem.requestLocalServer":"localHost","gem.localServer":"localHost","gem.localServer.denied":"localHost","gem.cohorts":"cohorts","gem.deviceSettings":"deviceSettings","gem.deviceSettings.put":"deviceSettings","gem.deviceSettings.result":"deviceSettings"}),rd=Object.freeze([["gem.asyncOpponents.","asyncOpponents"]]);function es(n){let e=nd[n];if(e!==void 0)return e;for(let[t,r]of rd)if(n.startsWith(t))return r}function ur(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 od(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 id(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function dr(n,e,t){if(e>Xi)return `nesting deeper than ${Xi}`;if(++t.nodes>an)return `more than ${an} values`;if(t.bytes>et)return `over the ${et} 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 o=n;if(t.seen.has(o))return "a repeated or cyclic object reference";if(t.seen.add(o),Array.isArray(n)){if(n.length>Qi)return `an array of ${n.length} entries, over the ${Qi} limit`;t.bytes+=2;for(let s of n){let l=dr(s,e+1,t);if(l)return l}return null}let i=Object.getPrototypeOf(n);if(i!==Object.prototype&&i!==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>an)return `more than ${an} values`;if(t.bytes+=s.length*3+4,t.bytes>et)return `over the ${et} byte limit`;let l=dr(a[s],e+1,t);if(l)return l}return null}function sd(n){let e={nodes:0,bytes:0,seen:new Set},t=dr(n,0,e);return t?`message contains ${t}`:e.bytes>et?`message is over the ${et} byte limit`:null}var ad={origin:[ur,"not a well-formed origin"],url:[od,"not a safe absolute http(s) URL"],bcp47:[id,"not a well-formed BCP 47 tag"]};function ts(n,e,t){for(let r of e){let o=t===""?r.n:`${t}.${r.n}`,i=n[r.n];if(i==null){if(r.o)continue;return `${o}: required`}let a=ns(i,r,o);if(a)return a}return null}function ns(n,e,t){switch(e.k){case "string":{if(typeof n!="string")return `${t}: expected string`;if(n.length>e.max)return `${t}: exceeds ${e.max} characters`;if(e.f){let[r,o]=ad[e.f];if(!r(n))return `${t}: ${o}`}return null}case "int":return typeof n!="number"||!Number.isInteger(n)?`${t}: expected integer`:n<e.lo||n>e.hi?`${t}: out of range ${e.lo}..${e.hi}`:null;case "boolean":return typeof n=="boolean"?null:`${t}: expected boolean`;case "enum":{let r=e.v;return r.includes(n)?null:`${t}: not one of ${r.join("|")}`}case "object":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected object`:ts(n,e.fs,t);case "json":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected a plain object`:null;case "array":{if(!Array.isArray(n))return `${t}: expected array`;if(n.length>e.max)return `${t}: exceeds ${e.max} items`;let r=e.it,o=`${t}[]`;for(let i of n){if(i==null){if(r.o)continue;return `${o}: required`}let a=ns(i,r,o);if(a)return a}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}function M(n,e){return t=>{let r=sd(t);if(r)return r;if(typeof t!="object"||t===null||Array.isArray(t))return "message: expected object";let o=t;return o.gem!==z?"gem: wrong protocol marker":o.type!==n?`type: expected ${n}`:ts(o,e,"")}}var ld=M("gem.handshake",[{n:"versions",k:"object",fs:[{n:"min",k:"int",lo:1,hi:1e3},{n:"max",k:"int",lo:1,hi:1e3}]},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}},{n:"embedder",k:"string",max:2048,f:"origin"}]),dd=M("gem.handshake.accept",[{n:"v",k:"int",lo:1,hi:1e3},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}}]),cd=M("gem.token",[{n:"token",k:"string",max:4096},{n:"requestId",k:"string",o:1,max:64},{n:"generation",k:"int",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"string",o:1,max:512,f:"url"},{n:"playerId",k:"string",max:64},{n:"gameId",k:"string",max:64},{n:"channel",k:"enum",v:["dev","test","release"]},{n:"gameVersion",k:"string",o:1,max:64},{n:"expiresAt",k:"int",lo:0,hi:4102444800},{n:"chainEndsAt",k:"int",lo:0,hi:4102444800},{n:"allowDevTools",k:"boolean",o:1}]),ud=M("gem.token.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:36e5},{n:"reason",k:"enum",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"string",max:64}]),md=M("gem.player",[{n:"untrusted",k:"object",fs:[{n:"displayName",k:"string",max:64},{n:"displayTag",k:"string",o:1,max:80},{n:"displayHandle",k:"string",max:80}]},{n:"playerId",k:"string",o:1,max:64},{n:"discriminator",k:"string",o:1,max:8},{n:"avatarIconUrl",k:"string",o:1,max:2048,f:"url"},{n:"badges",k:"array",o:1,max:2,it:{n:"",k:"object",fs:[{n:"itemId",k:"string",max:64},{n:"iconUrl",k:"string",max:2048,f:"url"}]}},{n:"displayTag",k:"string",max:8},{n:"avatarUrl",k:"string",o:1,max:2048,f:"url"},{n:"boost",k:"object",o:1,fs:[{n:"multipliers",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"currencyId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"multiplierBp",k:"int",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"int",o:1,lo:1,hi:7}]}]),pd=M("gem.pause",[{n:"paused",k:"boolean"}]),gd=M("gem.prefs",[{n:"reducedMotion",k:"boolean"},{n:"muted",k:"boolean"},{n:"showFrameStats",k:"boolean",o:1},{n:"locale",k:"string",max:35,f:"bcp47"}]),yd=M("gem.cohorts",[{n:"cohorts",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"experimentId",k:"string",max:36},{n:"variantKey",k:"string",max:32}]}}]),fd=M("gem.viewport",[{n:"insets",k:"object",fs:[{n:"top",k:"int",lo:0,hi:4096},{n:"right",k:"int",lo:0,hi:4096},{n:"bottom",k:"int",lo:0,hi:4096},{n:"left",k:"int",lo:0,hi:4096}]}]),hd=M("gem.deviceSettings",[{n:"settings",k:"json",o:1}]),bd=M("gem.willTerminate",[{n:"reason",k:"enum",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"int",lo:0,hi:6e4}]),vd=M("gem.roomEvent",[{n:"event",k:"enum",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"string",max:64},{n:"matchId",k:"string",o:1,max:64},{n:"version",k:"int",o:1,lo:0,hi:2147483647},{n:"reason",k:"string",o:1,max:64},{n:"platform",k:"enum",o:1,v:["universal","mobile"]}]),_d=M("gem.socketState",[{n:"connected",k:"boolean"},{n:"reason",k:"enum",o:1,v:["connecting","dropped","watchdog","terminal"]}]),wd=M("gem.seatedEvent",[{n:"roomId",k:"string",max:64}]),Sd=M("gem.autoStartFailedEvent",[{n:"roomId",k:"string",max:64},{n:"code",k:"string",max:64}]),Rd=M("gem.signalEvent",[{n:"event",k:"enum",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),kd=M("gem.dedicatedEvent",[{n:"event",k:"enum",v:["answer","error","matchEnded"]},{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",o:1,max:10240},{n:"sessionId",k:"string",o:1,max:64},{n:"code",k:"string",o:1,max:64},{n:"message",k:"string",o:1,max:256},{n:"reason",k:"string",o:1,max:64}]),xd=M("gem.partyResult",[{n:"requestId",k:"string",max:64},{n:"partyId",k:"string",o:1,max:64}]),Ad=M("gem.clusterTarget",[{n:"clusterTargetId",k:"string",max:64},{n:"clusterTargetIds",k:"array",o:1,max:3,it:{n:"",k:"string",max:64}}]),Pd=M("gem.devtools",[{n:"action",k:"enum",v:["open","close","toggle"]}]),Td=M("gem.screenshot",[{n:"maxWidth",k:"int",lo:1,hi:7680},{n:"maxHeight",k:"int",lo:1,hi:4320}]),Ed=M("gem.screenshot.denied",[{n:"reason",k:"enum",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"boolean"}]),Id=M("gem.requestContext",[]),Cd=M("gem.gameContext",[{n:"context",k:"json"}]),Md=M("gem.signal",[{n:"signal",k:"enum",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Od=M("gem.dedicatedOffer",[{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",max:10240},{n:"intent",k:"enum",v:["initial","ice_restart","full_reconnect"]}]),Ld=M("gem.partyRequest",[{n:"requestId",k:"string",max:64}]),Gd=M("gem.ready",[]),Dd=M("gem.progress",[{n:"loaded",k:"int",lo:0,hi:1099511627776},{n:"total",k:"int",lo:0,hi:1099511627776}]),$d=M("gem.requestToken",[{n:"requestId",k:"string",max:64},{n:"reason",k:"enum",v:["initial","expiring","rejected"]}]),Fd=M("gem.requestLocalServer",[{n:"requestId",k:"string",max:64},{n:"gameRoomId",k:"string",max:64}]),jd=M("gem.localServer",[{n:"requestId",k:"string",max:64},{n:"serverId",k:"string",o:1,max:128}]),qd=M("gem.localServer.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"reason",k:"enum",v:["refused","unavailable"]}]),Nd=M("gem.exit",[{n:"reason",k:"string",o:1,max:64}]),Ud=M("gem.openExternal",[{n:"url",k:"string",max:2048,f:"url"}]),Bd=M("gem.requestFullscreen",[{n:"enabled",k:"boolean"}]),Hd=M("gem.audioState",[{n:"muted",k:"boolean"}]),Vd=M("gem.rewardCue",[{n:"currencySlug",k:"string",max:32},{n:"expected",k:"int",o:1,lo:1,hi:1e9},{n:"origin",k:"object",o:1,fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384}]}]),Wd=M("gem.frameStats",[{n:"fps",k:"int",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"int",lo:0,hi:1e5}]),Kd=M("gem.error",[{n:"code",k:"enum",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"string",o:1,max:256}]),Jd=M("gem.requestPurchase",[{n:"requestId",k:"string",max:64},{n:"purchaseKind",k:"enum",v:["item","recipe"]},{n:"targetId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"quantity",k:"int",o:1,lo:1,hi:10},{n:"catalogId",k:"string",o:1,max:64}]),zd=M("gem.purchaseResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["ok","declined","unavailable"]},{n:"purchaseId",k:"string",o:1,max:64}]),Yd=M("gem.deviceSettings.put",[{n:"requestId",k:"string",max:64},{n:"settings",k:"json"}]),Xd=M("gem.deviceSettings.result",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["stored","too_large","unavailable"]}]),Qd=M("gem.requestAd",[{n:"requestId",k:"string",max:64},{n:"placement",k:"string",max:32},{n:"format",k:"enum",v:["interstitial","rewarded"]}]),Zd=M("gem.adResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["shown","no_ad","unavailable"]}]),ec=M("gem.requestSignIn",[{n:"requestId",k:"string",max:64}]),tc=M("gem.signInResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["signed_in","declined","unavailable"]}]),cn=cr({"gem.handshake":ld,"gem.handshake.accept":dd,"gem.token":cd,"gem.token.denied":ud,"gem.player":md,"gem.pause":pd,"gem.prefs":gd,"gem.cohorts":yd,"gem.viewport":fd,"gem.deviceSettings":hd,"gem.willTerminate":bd,"gem.roomEvent":vd,"gem.socketState":_d,"gem.seatedEvent":wd,"gem.autoStartFailedEvent":Sd,"gem.signalEvent":Rd,"gem.dedicatedEvent":kd,"gem.partyResult":xd,"gem.clusterTarget":Ad,"gem.devtools":Pd,"gem.screenshot":Td,"gem.screenshot.denied":Ed,"gem.requestContext":Id,"gem.gameContext":Cd,"gem.signal":Md,"gem.dedicatedOffer":Od,"gem.partyRequest":Ld,"gem.ready":Gd,"gem.progress":Dd,"gem.requestToken":$d,"gem.requestLocalServer":Fd,"gem.localServer":jd,"gem.localServer.denied":qd,"gem.exit":Nd,"gem.openExternal":Ud,"gem.requestFullscreen":Bd,"gem.audioState":Hd,"gem.rewardCue":Vd,"gem.frameStats":Wd,"gem.error":Kd,"gem.requestPurchase":Jd,"gem.purchaseResult":zd,"gem.deviceSettings.put":Yd,"gem.deviceSettings.result":Xd,"gem.requestAd":Qd,"gem.adResult":Zd,"gem.requestSignIn":ec,"gem.signInResult":tc});var ae={now:()=>Date.now(),setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n)},bt=class{constructor(e=ae){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let t=Zi[e];if(t===void 0)return false;let r=this.clock.now(),o=this.lastRefill.get(e)??r,i=this.tokens.get(e)??t,a=Math.max(0,r-o),s=Math.min(t,i+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 mr(n,e){return n.toLowerCase()===e.toLowerCase()}function un(n){let e=n.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function rs(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:un(t.hostname)&&un(r.hostname)}function os(n,e){if(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 mn=class{constructor(e,t){this.inventory=e;this.resolveCurrencyId=t;}inventory;resolveCurrencyId;async list(e={}){return (await this.inventory.snapshot({buckets:e.buckets})).currencies.data.map(r=>({currencyId:r.currencyId,total:r.total,...r.buckets===void 0?{}:{buckets:r.buckets}}))}async get(e,t={}){let o=(await this.inventory.snapshot({buckets:t.buckets})).currencies.data,i=o.find(s=>s.currencyId===e),a;return !i&&this.resolveCurrencyId&&(a=await this.resolveCurrencyId(e).catch(()=>{}),a!==void 0&&(i=o.find(s=>s.currencyId===a))),{currencyId:i?i.currencyId:a??e,total:i?i.total:null,...i?.buckets===void 0?{}:{buckets:i.buckets}}}};function gr(n){let e=Array.isArray(n.achievements)?n.achievements:[],t=[];for(let r of e){let o=r??{};typeof o.id!="string"||o.id===""||typeof o.threshold!="number"||!Number.isFinite(o.threshold)||t.push({id:o.id,threshold:o.threshold,points:typeof o.points=="number"?o.points:0,hidden:o.hidden===true,...typeof o.unlocked_at=="number"&&Number.isFinite(o.unlocked_at)?{unlockedAt:o.unlocked_at}:{},...o.revoked===true?{revoked:true}:{}});}return {...t.length>0?{achievements:t}:{},...n.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var is="inventory",tt=n=>typeof n=="number"?n:0,vt=n=>typeof n=="string"?n:"";function pr(n,e){let t=n??{},r=typeof t.next_cursor=="string"?t.next_cursor:void 0;return {data:Array.isArray(t.data)?t.data.map(e):[],...r===void 0?{}:{nextCursor:r}}}function ss(n){let e=n??{};return {itemDefinitionId:vt(e.item_definition_id),instanceId:vt(e.instance_id),quantity:tt(e.quantity),acquiredAt:tt(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function nc(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0;return {currencies:pr(e.currencies,r=>{let o=r??{},i=Array.isArray(o.buckets)?o.buckets.map(a=>{let s=a??{};return {bucket:vt(s.bucket),balance:tt(s.balance)}}):void 0;return {currencyId:vt(o.currency_id),total:tt(o.total),...i===void 0?{}:{buckets:i}}}),items:pr(e.items,ss),progressions:pr(e.progressions,r=>{let o=r??{};return {progressionDefinitionId:vt(o.progression_definition_id),currentValue:tt(o.current_value),completionCount:tt(o.completion_count),isCompleted:o.is_completed===true,...gr(o)}}),...t===void 0?{}:{etag:t}}}var pn=class{constructor(e,t,r){this.api=e;this.entity=t;this.cache=r;}api;entity;cache;snapshot(e={}){let t=e.buckets?`${is}#buckets`:is;return this.cache.read(t,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,t){let r=await this.snapshot();if(r.items.nextCursor===void 0){let i=r.items.data.filter(a=>a.itemDefinitionId===e);if(i.length>0)return i}let o=await fi(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return Array.isArray(o)?o.map(ss):[]}page(e){return this.fetch(e)}refresh(){this.invalidate();}onChanged(e){return this.cache.onInvalidate(e)}invalidate(){this.cache.invalidate();}async fetch(e){let t=await yi(this.api,this.entity.type,this.entity.id,{...e.includeBuckets?{include_buckets:true}:{},...e.currencyCursor===void 0?{}:{currency_cursor:e.currencyCursor},...e.itemCursor===void 0?{}:{item_cursor:e.itemCursor},...e.progressionCursor===void 0?{}:{progression_cursor:e.progressionCursor},...e.currencyLimit===void 0?{}:{currency_limit:e.currencyLimit},...e.itemLimit===void 0?{}:{item_limit:e.itemLimit},...e.progressionLimit===void 0?{}:{progression_limit:e.progressionLimit},...e.signal===void 0?{}:{signal:e.signal}});return nc(t)}};var te=n=>typeof n=="string"?n:"",rc=n=>typeof n=="string"?n:te(n&&typeof n=="object"?n.type:void 0),xe=n=>typeof n=="number"?n:0;function oc(n){let e=n??{};return {prerequisiteType:te(e.prerequisite_type),referenceId:te(e.reference_id),required:xe(e.required),current:xe(e.current)}}function _t(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0;return {orderId:te(e.order_id),status:te(e.status),...t===void 0?{}:{etag:t}}}function gn(){return crypto.randomUUID()}var ic="recipe-usage",as=100;function yn(n){let e=n??{};switch(e.type){case "currency":return {kind:"currency",currencyId:te(e.currency_id),bucket:te(e.bucket),delta:xe(e.delta),balanceAfter:xe(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:te(e.item_definition_id),instanceId:te(e.instance_id),delta:xe(e.delta),quantityAfter:xe(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:te(e.progression_definition_id),delta:xe(e.delta),valueAfter:xe(e.value_after),completed:e.completed===true};default:return {kind:"other",type:te(e.type)}}}function sc(n){let e=n??{},t=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:te(e.entry_id),...t===void 0?{}:{rarityTier:t},rollNumber:xe(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(yn):[]}}function ac(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(sc):void 0;return {orderId:te(e.order_id),status:te(e.status),...t===void 0?{}:{etag:t},granted:Array.isArray(e.granted)?e.granted.map(yn):[],consumed:Array.isArray(e.consumed)?e.consumed.map(yn):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(yn):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function lc(n){let e=n??{},t=e.price??{};return {payment:"platform_currency",orderId:te(e.target_order_id)||te(e.source_order_id),status:te(e.status),purchaseId:te(e.purchase_id),sourceOrderId:te(e.source_order_id),price:{currencyId:te(t.platform_currency_id),amount:xe(t.price)}}}function dc(n){let e=n??{},t=typeof e.last_used_at=="string"?e.last_used_at:void 0,r=typeof e.cooldown_expires_at=="string"?e.cooldown_expires_at:void 0;return {recipeId:te(e.recipe_id),useCount:typeof e.use_count=="number"?e.use_count:0,isOnCooldown:e.is_on_cooldown===true,...t===void 0?{}:{lastUsedAt:t},...r===void 0?{}:{cooldownExpiresAt:r}}}function ls(n){switch(n.type){case "currency_grant":case "currency_consume":return {type:n.type,currency_id:n.currencyId,amount:n.amount};default:return {type:n.type,item_definition_id:n.itemDefinitionId,quantity:n.quantity}}}var fn=class{constructor(e,t,r){this.api=e;this.entity=t;this.cache=r;}api;entity;cache;async create(e,t={}){let r=await this.write(()=>ii(this.api,this.entity.type,this.entity.id,{operations:e.map(ls),source:t.source??"play",nonce:gn()},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}));return _t(r)}async createMany(e,t={}){return this.write(()=>oi(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(ls),nonce:gn()})),source:t.source??"play"},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}))}async recipeAvailability(e,t,r){let i=await _i(this.api,this.entity.type,this.entity.id,e,t,r===void 0?{}:{signal:r})??{},a=typeof i.uses_remaining=="number"?i.uses_remaining:void 0,s=typeof i.cooldown_expires_at=="string"?i.cooldown_expires_at:void 0,l=Array.isArray(i.lock_reasons)?i.lock_reasons.map(oc):[];return {canExecute:i.can_execute===true,locked:i.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(i.reasons)?i.reasons.map(d=>rc(d)):[],...a===void 0?{}:{usesRemaining:a},...s===void 0?{}:{cooldownExpiresAt:s}}}async recipeUsageAll(){return this.cache.read(ic,[],async()=>{let t=await wi(this.api,this.entity.type,this.entity.id,{limit:as})??{},r=Array.isArray(t.usages)?t.usages:[];return {usages:r.map(dc),truncated:r.length>=as}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,t={}){if(e.payment.kind==="configured"){let c=e,p=await this.write(()=>di(this.api,this.entity.type,this.entity.id,{catalog_id:c.catalogId,recipe_id:c.targetId,game_id:this.api.gameId(),nonce:gn()},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}));return {payment:"configured",...ac(p)}}if(this.entity.type!=="players"||this.entity.id!=="me")throw new TypeError("platform-currency purchases are available only on gem.me.mutations");let[r,o]=await Promise.all([Ai(this.api,t.signal===void 0?{}:{signal:t.signal}),sn(this.api,t.signal===void 0?{}:{signal:t.signal})]),i=e.payment.currencySlug.toLowerCase(),a=o.currencies.find(c=>c.currency_id.toLowerCase()===i||c.slug.toLowerCase()===i);if(a===void 0)throw new RangeError(`platform currency ${JSON.stringify(e.payment.currencySlug)} is not active`);let s=e.kind==="item"?r.items.find(c=>c.item_id===e.targetId):r.recipes.find(c=>c.recipe_id===e.targetId&&c.catalog_id===e.catalogId);if(s===void 0)throw new RangeError(`purchase target ${JSON.stringify(e.targetId)} is not published`);let l=s.platform_prices.find(c=>c.platform_currency_id===a.currency_id);if(l===void 0)throw new RangeError(`purchase target ${JSON.stringify(e.targetId)} has no ${e.payment.currencySlug} price`);let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new RangeError("item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>Oi(this.api,this.entity.type,this.entity.id,{purchase_kind:e.kind,target_id:e.targetId,...e.kind==="recipe"?{catalog_id:e.catalogId}:{},quantity:d,expected_price:{platform_currency_id:a.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:gn(),confirmation:"none"},t.signal===void 0?{}:{signal:t.signal}));return lc(m)}async executeRecipe(e,t,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:t,payment:{kind:"configured"}},r)}async addProgression(e,t,r){let o=await this.write(()=>ei(this.api,this.entity.type,this.entity.id,e,{amount:t,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return _t(o)}async maxProgression(e,t,r){let o=await this.write(()=>Bi(this.api,this.entity.type,this.entity.id,e,{value:t,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return _t(o)}async claimProgression(e,t){let r=await this.write(()=>ni(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},t===void 0?{}:{signal:t}));return _t(r)}async resetProgression(e,t){let r=await this.write(()=>zi(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},t===void 0?{}:{signal:t}));return _t(r)}async write(e){return this.cache.invalidate(),e()}};var yr=n=>typeof n=="string"?n:"",cc=n=>typeof n=="number"?n:0;function ds(n){let e=n??{};return {orderId:yr(e.order_id),status:yr(e.status),source:yr(e.source),createdAt:cc(e.created_at)}}var hn=class{constructor(e,t){this.api=e;this.entity=t;}api;entity;async list(e={}){let r=await Fi(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}})??{},o=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {data:Array.isArray(r.orders)?r.orders.map(ds):[],...o===void 0?{}:{nextCursor:o}}}async get(e,t){let r=await bi(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return ds(r)}};var cs=n=>typeof n=="number"?n:0,uc=n=>typeof n=="string"?n:"";function mc(n){let e=n??{};return {progressionDefinitionId:uc(e.progression_definition_id),currentValue:cs(e.current_value),completionCount:cs(e.completion_count),isCompleted:e.is_completed===true,...gr(e)}}var bn=class{constructor(e,t,r){this.api=e;this.entity=t;this.inventory=r;}api;entity;inventory;async list(){return (await this.inventory.snapshot()).progressions.data}async get(e,t){let o=(await this.inventory.snapshot()).progressions.data.find(i=>i.progressionDefinitionId===e);if(o&&o.achievementsUnavailable!==true)return o;try{let i=await vi(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return mc(i)}catch{return o??null}}};var vn=class{constructor(e,t){this.clock=e;this.identity=t;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,t,r,o){this.rebind();let i=t.length===0,a=i?e:e+"\0"+t.join("\0"),s=this.slots.get(a);if(s){let c=s.filledAt;if(c!==void 0&&(o===void 0||this.clock.now()-c<=o))return Promise.resolve(s.value);if(s.inFlight)return s.inFlight}let l=s??{};this.slots.set(a,l);let d=this.generation,m=r().then(c=>(i&&this.generation===d&&(l.value=c,l.filledAt=this.clock.now()),c)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(a)===l&&this.slots.delete(a));});return l.inFlight=m,m}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function fr(n){let e=o=>new RegExp(`<${o}>([^<]{0,300})</${o}>`).exec(n)?.[1]?.trim()||void 0,t=[e("Code"),e("AuthenticationErrorDetail")??e("Message")].filter(Boolean);if(t.length>0)return t.join(" \u2014 ");let r=n.trim();return r?r.slice(0,300):""}async function hr(n){try{let e=fr(await n.text());return e?`Storage said: ${e}`:""}catch{return ""}}var oe=class extends Error{constructor(t,r){super(r);this.reason=t;this.name="GemSaveError";}reason},pc=3e4,us="the save payload could not reach storage. From a browser this is almost always the storage account's CORS rule, which the platform owns and your game cannot change. If every save fails this way, report it rather than working around it",gc=/^[A-Za-z0-9_]{1,64}$/;function Ae(n){let e=n.length===0?"a save key cannot be empty":n.length>64?`it is ${n.length} characters; a save key is at most 64`:n.startsWith("_")||n.startsWith("$")?`it begins with ${JSON.stringify(n[0])}, and \`_\` and \`$\` are reserved prefixes`:"a save key is ASCII letters, digits and underscores only \u2014 no hyphens, spaces or other punctuation, unlike a template slug";if(!gc.test(n)||n.startsWith("_"))throw new TypeError(`${JSON.stringify(n)} is not a usable save key: ${e}.`);return n}function ms(n,e){let t=new AbortController,r=AbortSignal.timeout(e),o=()=>t.abort(r.reason),i=()=>t.abort(n?.reason);return n?.aborted?t.abort(n.reason):(r.addEventListener("abort",o,{once:true}),n?.addEventListener("abort",i,{once:true})),{signal:t.signal,release:()=>{r.removeEventListener("abort",o),n?.removeEventListener("abort",i);}}}function br(n,e){return n.aborted&&e?.aborted!==true}var yc=new Set(["x-ms-blob-type"]),fc=/^[ -~]+$/;function hc(n,e){if(n==null)return {};if(typeof n!="object"||Array.isArray(n))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} described its upload headers as ${Array.isArray(n)?"a list":typeof n}, which is not a set of headers.`);let t={};for(let[r,o]of Object.entries(n)){let i=r.toLowerCase();if(!yc.has(i))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} asked the upload to send ${JSON.stringify(r)}, which this SDK does not put on a storage request. Report it \u2014 a platform that needs a new upload header needs an SDK release too.`);if(typeof o!="string"||!fc.test(o))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} gave header ${JSON.stringify(r)} a value that is not usable as one.`);if(i in t)throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(i)} twice.`);t[i]=o;}return t}function vr(n){let e=typeof n.metadata=="object"&&n.metadata!==null&&!Array.isArray(n.metadata)?n.metadata:void 0;return {key:n.key,sizeBytes:n.size_bytes,etag:n.etag,...e===void 0?{}:{metadata:e},createdAt:n.created_at,updatedAt:n.updated_at}}function _r(n){return n?.reason==="not_found"}var _n=class{constructor(e,t,r={}){this.api=e;this.entity=t;this.options=r;}api;entity;options;async put(e,t,r={}){let o;try{o=JSON.stringify(t);}catch(i){throw new oe("save_malformed",`save ${JSON.stringify(e)} could not be serialised to JSON: ${String(i)}. Retrying stores the same unserialisable value.`)}if(o===void 0)throw new oe("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(o),{...r,contentType:"application/json"})}async putBytes(e,t,r={}){let o=r.contentType??"application/octet-stream",i=this.budget(r.timeoutMs),a=ms(r.signal,i);try{let s=await Ji(this.api,this.entity.type,this.entity.id,Ae(e),{size_bytes:t.byteLength,content_type:o,...r.metadata===void 0?{}:{metadata:r.metadata}},{signal:a.signal});if(typeof s.upload_url!="string"||typeof s.session_id!="string")throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=hc(s.upload_headers,e),d,m=this.options.fetch??globalThis.fetch.bind(globalThis);try{d=await m(s.upload_url,{method:"PUT",headers:{"content-type":o,...l},body:t,credentials:"omit",signal:a.signal});}catch(c){throw br(a.signal,r.signal)?this.timeout("upload",i):new oe("upload_failed",`${us} for PUT. Underlying error: ${c}`)}if(!d.ok){let c=await hr(d);throw new oe("upload_failed",d.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+c:`the save upload answered ${d.status}. `+(d.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+c)}return vr(await ci(this.api,this.entity.type,this.entity.id,Ae(e),{session_id:s.session_id},{signal:a.signal}))}catch(s){throw this.rethrow(s,r.signal,a.signal,"save",i)}finally{a.release();}}async get(e,t={}){let r=await this.getBytes(e,t);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(o){throw new oe("save_malformed",`the stored save ${JSON.stringify(e)} is not JSON, so put() did not write it. Read it with getBytes() and decode it yourself. Underlying error: ${o}`)}}async getBytes(e,t={}){let r=this.budget(t.timeoutMs),o=ms(t.signal,r);try{let i;try{let l=await lr(this.api,this.entity.type,this.entity.id,Ae(e),{signal:o.signal});if(!l.modified)return null;i=l.body;}catch(l){if(_r(l))return null;throw l}if(typeof i.download_url!="string")throw new oe("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let a=this.options.fetch??globalThis.fetch.bind(globalThis),s;try{s=await a(i.download_url,{credentials:"omit",signal:o.signal});}catch(l){throw br(o.signal,t.signal)?this.timeout("download",r):new oe("download_failed",`${us} for GET. Underlying error: ${l}`)}if(!s.ok){let l=await hr(s);throw new oe("download_failed",`the save download answered ${s.status}. `+(s.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+l)}return new Uint8Array(await s.arrayBuffer())}catch(i){throw this.rethrow(i,t.signal,o.signal,"load",r)}finally{o.release();}}async describe(e,t={}){try{let r=await lr(this.api,this.entity.type,this.entity.id,Ae(e),{...t.signal===void 0?{}:{signal:t.signal},...t.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}});return r.modified?vr(r.body):null}catch(r){if(_r(r))return null;throw r}}async list(e={}){let t=await ji(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}}),r=t.next_cursor;return {saves:(t.data??[]).map(vr),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,t){try{await ai(this.api,this.entity.type,this.entity.id,Ae(e),{...t===void 0?{}:{signal:t}});}catch(r){if(!_r(r))throw r}}budget(e){return e??this.options.timeoutMs??pc}timeout(e,t){return new oe("save_timeout",`the save ${e} did not finish within ${t}ms`)}rethrow(e,t,r,o,i){return e instanceof oe?e:br(r,t)?this.timeout(o,i):e}};function bc(n){try{return ar(n)}catch{return n}}function wr(n,e){let t=n??{},r=typeof t.etag=="string"?t.etag:e;return {key:typeof t.key=="string"?t.key:"",value:typeof t.value=="string"?bc(t.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof t.updated_at=="number"?t.updated_at:0}}var wn=class{constructor(e,t){this.api=e;this.entity=t;}api;entity;async list(e){let r=(await $i(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(o=>wr(o)):[]}async get(e,t={}){try{let r=await gi(this.api,this.entity.type,this.entity.id,e,{...t.signal===void 0?{}:{signal:t.signal},...t.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}});return r.modified?wr(r.body,r.etag):null}catch(r){if(ps(r))return null;throw r}}async put(e,t,r={}){let o=await Hi(this.api,this.entity.type,this.entity.id,e,{value:rn(t)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return wr(o)}async delete(e,t){try{await si(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});}catch(r){if(!ps(r))throw r}}};function ps(n){return n?.reason==="not_found"}function Sn(n,e,t={}){let r=new vn(ae,t.identity);t.onInventoryChanged&&r.onInvalidate(t.onInventoryChanged);let o=new pn(n,e,r);return {settings:new wn(n,e),inventory:o,saves:new _n(n,e,t.saves??{}),currencies:new mn(o,t.resolveCurrencyId),mutations:new fn(n,e,r),orders:new hn(n,e),progressions:new bn(n,e,o)}}var Sr={type:"players",id:"me"};var Fe=n=>typeof n=="string"?n:"",nt=n=>typeof n=="number"?n:0;function Rn(n,e){let t=e??{},r=Fe(t.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...n(r),id:r,playerId:Fe(t.player_id),gameId:Fe(t.game_id),channel:Fe(t.channel)||"release",name:Fe(t.name),slotIndex:nt(t.slot_index),isActive:t.is_active!==false,createdAt:Fe(t.created_at),updatedAt:Fe(t.updated_at)}}var kn=class{constructor(e,t,r,o){this.api=e;this.saves=t;this.identity=r;this.resolveCurrencyId=o;}api;saves;identity;resolveCurrencyId;scopes=new Map;scope=e=>{let t=this.scopes.get(e);return t||(t=Sn(this.api,{type:"characters",id:e},{saves:this.saves,identity:this.identity,resolveCurrencyId:this.resolveCurrencyId}),this.scopes.set(e,t)),t};async list(e){let r=(await Di(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(o=>Rn(this.scope,o)):[]}async get(e,t){let r=await mi(this.api,e,t===void 0?{}:{signal:t});return Rn(this.scope,r)}async create(e){let t=await ri(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Rn(this.scope,t)}async update(e,t,r){let o=await Ki(this.api,e,{name:t},r===void 0?{}:{signal:r});return Rn(this.scope,o)}async delete(e,t){await Yi(this.api,e,t===void 0?{}:{signal:t});}async slots(e){let r=await Ei(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:nt(r?.total_slots),availableSlots:nt(r?.available_slots),activeCharacterCount:nt(r?.active_character_count),defaultMaxSlots:nt(r?.default_max_slots),purchasedExtraSlots:nt(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var ge=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 ye(n){return new ge(n)}var je={toPlain(n){return ge.unwrap(n)},compare(n,e,t){let r=n instanceof ge?ge.unwrap(n):n,o=e instanceof ge?ge.unwrap(e):e,i;try{i=new Intl.Collator(t);}catch{i=new Intl.Collator;}return i.compare(r,o)},equals(n,e){let t=n instanceof ge?ge.unwrap(n):n,r=e instanceof ge?ge.unwrap(e):e;return t.normalize("NFC")===r.normalize("NFC")}};var rt=n=>typeof n=="string"?n:"";function xn(n){let e=n??{},t=typeof e.message=="string"&&e.message.length>0?e.message:void 0,r=typeof e.resolved_at=="string"?e.resolved_at:void 0;return {id:rt(e.transfer_id),status:rt(e.status),sourceEntityId:rt(e.source_entity_id),targetEntityId:rt(e.target_entity_id),...t===void 0?{}:{message:ye(t)},createdAt:rt(e.created_at),expiresAt:rt(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function vc(){return crypto.randomUUID()}var An=class{constructor(e,t,r){this.api=e;this.self=t;this.inventory=r;}api;self;inventory;async initiate(e){this.inventory.invalidate();let t=await Mi(this.api,{source_entity_type:this.self.type,source_entity_id:this.self.id,target_entity_type:e.to.type,target_entity_id:e.to.id,items:(e.items??[]).map(r=>({item_definition_id:r.itemDefinitionId,quantity:r.quantity})),currencies:(e.currencies??[]).map(r=>({currency_id:r.currencyId,amount:r.amount})),...e.message===void 0?{}:{message:e.message},nonce:vc()},e.signal===void 0?{}:{signal:e.signal});return xn(t)}async list(e={}){let r=await Ni(this.api,{entity_type:this.self.type,entity_id:this.self.id,...e.direction===void 0?{}:{direction:e.direction},...e.status===void 0?{}:{status:e.status},...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit},...e.signal===void 0?{}:{signal:e.signal}})??{},o=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {transfers:Array.isArray(r.transfers)?r.transfers.map(xn):[],...o===void 0?{}:{nextCursor:o}}}async get(e,t){let r=await Ii(this.api,e,t===void 0?{}:{signal:t});return xn(r)}async accept(e,t){return this.resolve(()=>Zo(this.api,e,t===void 0?{}:{signal:t}))}async reject(e,t){return this.resolve(()=>Wi(this.api,e,t===void 0?{}:{signal:t}))}async cancel(e,t){return this.resolve(()=>ti(this.api,e,t===void 0?{}:{signal:t}))}async resolve(e){return this.inventory.invalidate(),xn(await e())}};var _c=n=>typeof n=="string"?n:"",wc=n=>typeof n=="string"&&n?n:void 0,Sc=n=>typeof n=="number"?n:void 0;function gs(n){let e=new Map(n.map(r=>[r.id,r])),t=new Map(n.filter(r=>r.slug).map(r=>[r.slug,r]));return r=>e.get(r)??t.get(r)??null}function Rc(n){if(typeof n!="object"||n===null||Array.isArray(n))throw new de("config_malformed",`the config document is ${n===null?"null":typeof n}, expected a JSON object`);let e=n,t=l=>{let d=e[l];if(d==null)return [];if(!Array.isArray(d))throw new de("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=Sc(e.version);if(r===void 0)throw new de("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let o=(l,d,m)=>{let c=_c(l.id);if(!c)throw new de("config_malformed",`${d}[${m}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return c},i=t("items");i.forEach((l,d)=>o(l??{},"items",d));let a=t("currencies");a.forEach((l,d)=>o(l??{},"currencies",d));let s=n;return {...s,version:r,hash:typeof s.hash=="string"?s.hash:"",items:i,currencies:a,catalogs:t("catalogs"),loot_tables:t("loot_tables"),affix_pools:t("affix_pools"),progressions:t("progressions"),game_room_templates:t("game_room_templates"),kv:typeof s.kv=="object"&&s.kv!==null&&!Array.isArray(s.kv)?s.kv:{},item:gs(i),currency:gs(a)}}var de=class extends Error{constructor(t,r){super(r);this.reason=t;this.name="GemConfigError";}reason},ys=10*1024*1024,fs=15e3,hs=new Set(["dev","test","release"]);function kc(n){if(!hs.has(n))throw new de("config_channel_unknown",`the play token names channel "${n}", which is not one of ${[...hs].join(", ")}. gem-api would reject the assignment read.`);return n}var Pn=n=>typeof n=="number"?n:0,Rr=n=>typeof n=="string"?n:"";function xc(n){let e=n??{},t=Array.isArray(e.entries)?e.entries.map(r=>{let o=r??{},i=typeof o.rarity_tier=="string"?o.rarity_tier:void 0;return {entryId:Rr(o.entry_id),weight:Pn(o.weight),dropRate:Pn(o.drop_rate),...i===void 0?{}:{rarityTier:i}}}):[];return {lootTableId:Rr(e.loot_table_id),name:Rr(e.name),rollCount:Pn(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Pn(e.total_weight),entries:t}}var Tn=class{constructor(e,t,r={}){this.api=e;this.channel=t;this.options=r;}api;channel;options;loaded=null;inFlight=null;generation=0;dropRatesByConfig=new WeakMap;load(){if(this.loaded)return Promise.resolve(this.loaded);if(this.inFlight)return this.inFlight;let e=this.generation,t=this.fetchConfig().then(r=>(this.generation===e&&(this.loaded=r),r)).finally(()=>{this.inFlight===t&&(this.inFlight=null);});return this.inFlight=t,t}refresh(){this.loaded=null,this.inFlight=null,this.generation+=1;}async dropRates(e,t){let r=await this.load();if(r===null)throw new de("config_channel_unknown",`dropRates(${e}) needs a loaded config, and this session's channel has none`);let o=this.dropRatesByConfig.get(r);o===void 0&&(o=new Map,this.dropRatesByConfig.set(r,o));let i=o.get(e);if(i!==void 0)return i;let a=(async()=>{let s=await pi(this.api,e,t===void 0?{}:{signal:t});return xc(s)})().catch(s=>{throw o?.get(e)===a&&o.delete(e),s});return o.set(e,a),a}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??fs),t;try{let l=await ui(this.api,kc(this.channel()),{signal:e});if(!l.modified)throw new de("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");t=l.body;}catch(l){if(l instanceof de)throw l;if(l?.reason==="not_found")return null;throw l}let r=wc(t.config_url);if(r===void 0)return null;let o=this.options.fetch??globalThis.fetch.bind(globalThis),i;try{i=await o(r,{credentials:"omit",signal:e});}catch(l){throw e.aborted?new de("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??fs}ms`):new de("config_unreachable",`could not fetch the game config document. From a browser this is almost always the storage CORS rule: the storage account must allow this game origin for GET. It is NOT a CSP problem \u2014 game origins carry no fetch directives by design. Underlying error: ${String(l)}`)}if(!i.ok){let l=await i.text().then(d=>fr(d)).catch(()=>"");throw new de("config_unreachable",`the config document answered ${i.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let a=await i.text();if(a.length>ys)throw new de("config_too_large",`the config document is ${a.length} bytes, over the ${ys} cap`);let s;try{s=JSON.parse(a);}catch(l){throw new de("config_malformed",`config document is not JSON: ${String(l)}`)}return Rc(s)}};var kr=400,qe=n=>typeof n=="string"?n:"",Ac=/(?:Z|[+-]\d{2}:?\d{2})$/i;function bs(n){let e=qe(n);if(!Ac.test(e))return 0;let t=Date.parse(e);return Number.isFinite(t)?Math.floor(t/1e3):0}var Pc=/^[0-9a-f]{1,64}$/,Tc=/^[0-9a-f]{16}$/,Ec=4096,Ic=new TextEncoder;function Cc(n){let e=qe(n.challenge_data),t=qe(n.challenge_data_hash);return e===""||!Tc.test(t)?{}:Ic.encode(e).length>Ec?{}:{data:e,dataHash:t}}function Mc(n){let e=n??{},t=bs(e.period_start_at),r=bs(e.period_ends_at);if(t===0||r===0)return;let o=qe(e.slug),i=qe(e.seed);return {id:qe(e.progression_definition_id),...o===""?{}:{slug:o},window:qe(e.window),periodStartAt:t,periodEndsAt:r,seed:Pc.test(i)?i:"",...Cc(e)}}var wt=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:t}=e;if(t!==void 0&&(!Number.isInteger(t)||t<0||t>kr))throw new TypeError(`periodsBack must be an integer between 0 and ${kr}, got ${String(t)}`);let o=await Gi(this.#e,{...t===void 0?{}:{periods_back:t},...e.signal===void 0?{}:{signal:e.signal}})??{};return Array.isArray(o.challenges)?o.challenges.map(Mc).filter(i=>i!==void 0):[]}};function Ne(n){return typeof n=="string"&&n!==""?n:void 0}var vs=new Set(["localhost","127.0.0.1","[::1]"]);function xr(n){let e=Ne(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:"&&vs.has(t.hostname)))return e}function Oc(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=t??{},o=Ne(r.item_id),i=xr(r.icon_url);o!==void 0&&i!==void 0&&e.push({itemId:o,iconUrl:i});}return e}function ve(n){let e=n??{},t=Ne(e.player_id),r=Ne(e.display_name),o=Ne(e.discriminator),i=Ne(e.display_tag),a=Ne(e.avatar_icon_id),s=xr(e.avatar_icon_url);return {...t===void 0?{}:{playerId:t},...r===void 0?{}:{displayName:ye(r)},...o===void 0?{}:{discriminator:o},...i===void 0?{}:{displayTag:ye(i)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},badges:Oc(e.badges)}}var Lc=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Gc(n){if(n===void 0)return;let e=xr(n);if(e===void 0)return;let t=new URL(e);return vs.has(t.hostname)||Lc.has(t.origin)?e:void 0}var _s=100,St=n=>typeof n=="string"?n:"",ot=n=>typeof n=="number"?n:0,Rt=n=>typeof n=="string"?n:void 0,Dc=n=>typeof n=="number"?n:void 0,Rs={player:"players",character:"characters"};function $c(n,e){let t=n??{},r=Rt(t.entity_id),o=typeof t.entity_type=="string"&&Object.hasOwn(Rs,t.entity_type)?t.entity_type:void 0,i=ks(t.stats),a=t.properties!==null&&typeof t.properties=="object"?t.properties:void 0,s=e?t.is_viewer===true:void 0;return {...ve(t),rank:ot(t.rank),occurredAt:ot(t.occurred_at),...s===void 0?{}:{isViewer:s},...r===void 0?{}:{entityId:r},...o===void 0?{}:{entityType:o},...i===void 0?{}:{stats:i},...a===void 0?{}:{properties:a}}}function ws(n,e){let t=n??{},r=Rt(t.bucket_1),o=Rt(t.bucket_2),i=Dc(t.update_frequency_seconds);return {leaderboardType:St(t.leaderboard_type),runType:St(t.run_type),...r===void 0?{}:{bucket1:r},...o===void 0?{}:{bucket2:o},entries:Array.isArray(t.entries)?t.entries.map(a=>$c(a,e)):[],generatedAt:ot(t.generated_at),...i===void 0?{}:{updateFrequencySeconds:i}}}function Ss(n){if(n===null||typeof n!="object"||Array.isArray(n))return;let e=n;if(!Number.isFinite(e.rank))return;let t=ks(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:ot(e.occurred_at),...t===void 0?{}:{stats:t},...r===void 0?{}:{properties:r}}}function ks(n){if(n===null||typeof n!="object")return;let e={};for(let[t,r]of Object.entries(n))typeof r=="number"&&(e[t]=r);return e}function Fc(n,e,t){let r=n??{},o=Rt(r.bucket_1),i=Rt(r.bucket_2);return {leaderboardType:St(r.leaderboard_type),runType:St(r.run_type),entityType:e,entityId:t,...o===void 0?{}:{bucket1:o},...i===void 0?{}:{bucket2:i},entries:Array.isArray(r.entries)?r.entries.map(Ss).filter(a=>a!==void 0):[],personalBest:Ss(r.personal_best)??null,totalRuns:ot(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:ot(r.generated_at)}}var kt=class{#e;constructor(e){this.#e=e;}async get(e,t={}){let r=await ki(this.#e,e,{...t.bucket1===void 0?{}:{bucket_1:t.bucket1},...t.bucket2===void 0?{}:{bucket_2:t.bucket2},...t.signal===void 0?{}:{signal:t.signal}});return ws(r,false)}async friends(e,t={}){let r=await Si(this.#e,e,{...t.bucket1===void 0?{}:{bucket_1:t.bucket1},...t.bucket2===void 0?{}:{bucket_2:t.bucket2},...t.signal===void 0?{}:{signal:t.signal}});return ws(r,true)}async mine(e,t={}){return this.#i(e,"player","me",t)}async character(e,t,r={}){return this.#i(e,"character",t,r)}async#i(e,t,r,o){if(o.limit!==void 0){let{limit:s}=o;if(!Number.isInteger(s)||s<1||s>_s)throw new TypeError(`limit must be an integer between 1 and ${_s}, got ${String(s)}`)}let i=await hi(this.#e,e,Rs[t],r,{...o.bucket1===void 0?{}:{bucket_1:o.bucket1},...o.bucket2===void 0?{}:{bucket_2:o.bucket2},...o.limit===void 0?{}:{limit:o.limit},...o.signal===void 0?{}:{signal:o.signal}}),a=t==="player"&&r==="me"&&St((i??{}).entity_id)||r;return Fc(i,t,a)}};var En=n=>typeof n=="string"?n:"",Ar=n=>typeof n=="number"?n:0;function xs(n){let e=n??{};return {playerId:En(e.player_id),key:En(e.key),value:e.value,updatedAt:Ar(e.updated_at)}}function jc(n){let e=n??{};return {...ve(e),playerId:En(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:Ar(e.updated_at)}}function qc(n){return n?.reason==="not_found"}var xt=class{constructor(e,t){this.api=e;this.selfPlayerId=t;}api;selfPlayerId;async friends(e,t={}){let o=await Ri(this.api,Ae(e),{...t.signal===void 0?{}:{signal:t.signal}})??{};return {key:En(o.key),entries:Array.isArray(o.entries)?o.entries.map(jc):[],generatedAt:Ar(o.generated_at)}}async of(e,t,r={}){try{return xs(await Ti(this.api,e,Ae(t),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(o){if(qc(o))return null;throw o}}async set(e,t,r={}){if(Ae(e),t===void 0)throw new TypeError(`showcase value for ${JSON.stringify(e)} is undefined, which is not JSON. Use clear() to remove one.`);try{JSON.stringify(t);}catch(i){throw new TypeError(`showcase value for ${JSON.stringify(e)} could not be serialised to JSON: ${String(i)}.`,{cause:i})}let o=await this.selfPlayerId();return xs(await Vi(this.api,o,e,{value:t},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,t={}){let r=await this.selfPlayerId();await li(this.api,r,Ae(e),{...t.signal===void 0?{}:{signal:t.signal}});}};var As=n=>typeof n=="string"?n:void 0;function Nc(n){let e=n??{};return {...ve(e),playerId:As(e.player_id)??""}}function Uc(n){let e=n??{},t=e.has_more===true?As(e.next_cursor):void 0;return {friends:Array.isArray(e.data)?e.data.map(Nc):[],...t===void 0?{}:{nextCursor:t}}}var At=class{#e;constructor(e){this.#e=e;}async list(e={}){let t=await qi(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Uc(t)}};var Ps=n=>typeof n=="string"?n:void 0;function Bc(n){let e=n??{},t=Ps(e.currency_id);if(t===void 0||t==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Ps(e.slug)??"",currencyId:t,balance:r,access:e.access==="spend"?"spend":"read"}}var In=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await sn(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=Bc(i);a!==void 0&&o.push(a);}return o}},Pt=class{currencies;constructor(e){this.currencies=new In(e);}};var Pr=n=>typeof n=="string"?n:"",Ts=n=>typeof n=="number"?n:0;function Hc(n){let e=n??{};return {key:Pr(e.key),visibility:Pr(e.visibility),value:e.value,updatedAt:Ts(e.updated_at)}}function Vc(n){let e=n??{};return {...ve(e),playerId:Pr(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Hc):[],generatedAt:Ts(e.generated_at)}}function Wc(n){return n?.reason==="not_found"}var Tt=class{#e;constructor(e){this.#e=e;}async of(e,t={}){try{return Vc(await xi(this.#e,e,{...t.signal===void 0?{}:{signal:t.signal}}))}catch(r){if(Wc(r))return null;throw r}}};var Kc=new Map([["function_error",false],["function_failed",false],["function_timeout",false],["function_not_published",false],["function_input_too_large",false],["functions_not_configured",false],["forbidden",false],["function_capacity_unavailable",true],["function_host_unreachable",true],["function_host_error",true],["rate_limited",true],["service_unavailable",true]]),Et=class extends D{constructor(e,t){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,t);}get retryable(){return (this.code===void 0?void 0:Kc.get(this.code))??super.retryable}},Ce=class{#e;constructor(e){this.#e=e;}async invoke(e,t={}){let r=Jc(e),o;try{o=await this.#e(r,t.signal===void 0?{}:{signal:t.signal});}catch(i){throw i instanceof D?Yc(i):i}return zc(o)}};function Jc(n){if(n instanceof ArrayBuffer)return new Uint8Array(n);if(ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);let e;try{e=JSON.stringify(n);}catch(t){throw new ne(`the function input could not be serialised to JSON: ${String(t)}. Pass bytes, or a value JSON can carry. This is a bug in the call, not a server failure.`)}if(e===void 0)throw new ne(`the function input is ${typeof n}, which JSON cannot carry. Pass bytes \u2014 an empty Uint8Array for no input \u2014 or a JSON value. This is a bug in the call, not a server failure.`);return new TextEncoder().encode(e)}function zc(n){let{bytes:e}=n,t=()=>new TextDecoder("utf-8",{fatal:true}).decode(e);return {bytes:e,...n.invocationId===void 0?{}:{invocationId:n.invocationId},text:t,json:()=>JSON.parse(t())}}function Yc(n){let{details:e,invocationId:t}=Qo(n),o=e?.untrusted?.message,i=e?.reason;return new Et(n,{...t===void 0?{}:{invocationId:t},...n.code==="function_error"&&typeof o=="string"?{functionMessage:o}:{},...n.code==="function_failed"&&typeof i=="string"?{failure:i}:{}})}var Xc=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],Tr="gem_";function Es(n){return n.startsWith(Tr)}var Is=1e4,Qc=50,Zc=500,eu=65536-4*1024,tu=24*1024;function Cs(n){let e={},t={};for(let[r,o]of Object.entries(n))typeof o=="string"?e[r]=o:typeof o=="number"&&Number.isFinite(o)&&(t[r]=o);return {dimensions:e,measures:t}}var Ms=n=>typeof n=="number"?n:0,nu=n=>typeof n=="string"?n:"";function Os(n=0){return {accepted:0,rejected:[],dropped:n,duplicate:false}}function ru(n,e){let t=n??{},r=Array.isArray(t.rejected)?t.rejected.map(o=>{let i=o??{};return {index:Ms(i.index),code:nu(i.code)}}):[];return {accepted:Ms(t.accepted),rejected:r,dropped:e,duplicate:t.duplicate===true}}function Ls(){let n=globalThis.crypto;return typeof n?.randomUUID=="function"?n.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.floor(Math.random()*16);return (e==="x"?t:t&3|8).toString(16)})}function ou(n){return n?.retryable===true}var It=class{#e;#i;#b;#u;#t=[];#m={};#r=0;#o=null;#p=false;#g=false;#y=false;#n=false;#f=null;#s=null;#a=false;#v=false;#_=false;constructor(e){this.#e=e,this.#i=e.options?.enabled!==false,this.#b=Math.max(Is,e.options?.flushIntervalMs??Is),this.#u=Math.max(1,Math.floor(e.options?.maxQueue??Zc));}track(e,t={}){if(!(!this.#i||this.#n)){if(Es(e)){this.#_||(this.#_=true,this.#c(`[gem] analytics: '${e}' was not recorded \u2014 the gem_ prefix is reserved for the platform's own events, which the SDK emits for you. Name your event something else.`));return}this.#w(e,Cs({...this.#m,...t}));}}setContext(e){this.#m={...this.#m,...e};}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){let t=this.#A();if(t===null||t==="")return this.#t.length>0&&!this.#v&&(this.#v=true,this.#c("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),Os();if(this.#S(),this.#t.length===0)return Os();let r=e.keepalive===true;this.#d();let o=this.#t.splice(0,this.#k(r)),i=this.#r;this.#r=0;let a=Math.round(this.#e.clock.now()),s={batch_id:Ls(),sent_at_ms:a,events:o.map(d=>Gs(d,a))},l={client:this.#e.client(),gameId:()=>t};this.#y=true;try{let d=await Ci(l,s,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=ru(d,i);return this.#x(m),m}catch(d){throw ou(d)?this.#R(o,i):this.#c(`[gem] analytics: ${o.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#y=false,this.#t.length>0&&this.#l();}}trackPlatform(e,t={}){this.#n||this.#w(e,Cs(t));}startSession(){this.#n||this.#s!==null||(this.#s=this.#e.clock.now(),this.#a=false,this.trackPlatform("gem_session_start"));}endSession(e){if(this.#n||this.#a)return;this.#a=true;let t=this.#s;this.trackPlatform("gem_session_end",{reason:e,...t===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-t))}}),this.#h({keepalive:true});}setPaused(e){this.#n||e===this.#p||(this.#p=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#d():this.#t.length>0&&this.#l());}setHidden(e){this.#n||e===this.#g||(this.#g=e,e?this.#d():this.#t.length>0&&this.#l());}dispose(){this.#n=true,this.#d(),this.#t=[],this.#r=0;}get pending(){return this.#t.length}#w(e,t){let{dimensions:r,measures:o}=t;for(this.#S();this.#t.length>=this.#u;)this.#t.shift(),this.#r+=1;this.#t.push({uid:Ls(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:o}),this.#t.length>=Qc?this.#h():this.#l();}#h(e={}){this.flush(e).catch(()=>{});}#R(e,t){for(this.#t=[...e,...this.#t],this.#r+=t;this.#t.length>this.#u;)this.#t.shift(),this.#r+=1;}#k(e){let t=e?tu:eu,r=Math.min(this.#t.length,100),o=128;for(let i=0;i<r;i+=1){let a=this.#t[i];if(a===void 0)break;if(o+=JSON.stringify(Gs(a,0)).length+1,o>t)return Math.max(1,i)}return r}#l(){this.#o!==null||this.#p||this.#g||this.#n||this.#y||(this.#o=this.#e.clock.setTimeout(()=>{this.#o=null,this.#h();},this.#b));}#d(){this.#o!==null&&(this.#e.clock.clearTimeout(this.#o),this.#o=null);}#S(){let e=this.#P();e===null||e===""||(this.#f!==null&&this.#f!==e&&(this.#t=[],this.#r=0,this.#s=null,this.#a=false),this.#f=e);}#x(e){for(let t of e.rejected)this.#c(`[gem] analytics: an event was refused (${t.code}). `+iu(t.code));}#c(e){let t=this.#e.log;t!==null&&(t===void 0?console.warn(e):t(e));}#A(){try{return this.#e.gameId()}catch{return null}}#P(){try{return this.#e.playerId()}catch{return null}}};function Gs(n,e){return {event_uid:n.uid,name:n.name,offset_ms:Math.round(n.atMs)-e,dimensions:n.dimensions,measures:n.measures}}function iu(n){switch(n){case "analytics_not_declared":return "This channel has no analytics_events section at all \u2014 promote a game config that declares one. The gem_* events in the same batch were still recorded.";case "unknown_event":return "This channel declares a set of events and this name is not in it \u2014 check the spelling, or declare it in analytics_events.";case "unknown_dimension":return "A string property on this event is not declared as one of its dimensions.";case "missing_dimension":return "A dimension this event declares was not supplied.";case "dimension_value_not_declared":return "A dimension value is outside the closed set the config declares for it.";case "unknown_measure":return "A numeric property on this event is not declared as one of its measures.";case "measure_wrong_type":return "A measure was the wrong shape \u2014 an int measure refuses a fractional value.";case "source_not_permitted":return "This event is declared for the server only, so a client may not emit it.";default:return "See the analytics_events section of your game config."}}function pe(n){if(typeof n!="string")return;let e=n.trim();return e.length===0?void 0:e}function Ct(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=pe(t);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var su=2e3,au=5e3;function $s(n){let e=[],t=false,r=null,o=new Map,i=()=>{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??su);});return r={promise:s,settle:a},s};return {resolveList:i,resolve(){return e.length>0||t||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):i().then(a=>a[0])},refresh(a){return !Ds(e,a)||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(s=>{let l=null,d=m=>{o.delete(d)&&(n.clock.clearTimeout(l),s(m));};o.set(d,a),l=n.clock.setTimeout(()=>d(e),n.refreshTimeoutMs??au);})},accept(a,s){let l=Ct(s),d=pe(a),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[c,p]of [...o])Ds(m,p)||c(m);}}}}function Ds(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var lu=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),h=class extends Error{constructor(t,r,o){super(`${t}: ${r}`,o);this.reason=t;this.name="DedicatedServerError",this.retryable=lu.has(t),this.platformCode=o?.platformCode;}reason;retryable;platformCode};var Fs=["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"],du=new Set(Fs);function Me(n){return typeof n=="string"&&du.has(n)?n:"unknown"}var Cn="webrtc_dedicated",Mr=["universal","mobile","web"];var cu="p2p_unavailable",uu="capacity_unavailable",mu=2,js=3e4,qs=1e3,Ns=2e4;async function Or(n){let e=pe(n.clusterTargetId),t=n.nextClusterTarget,r=0,o=n.clock??ae,i=n.retry??{},a=i.budgetMs??js,s=i.maxDelayMs??Ns,l=i.initialDelayMs??qs,d=o.now(),m=d+a,c=0;for(;;){c++;try{let p=await $r(n.signal,"while allocating",()=>n.client.post(`${Hs(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!pu(p)||a<=0)throw p;if(p.status===503&&p.code===cu)throw new h("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===uu?r+1:0,t!==void 0&&r>=mu){let C=t;t=void 0;let E=pe(await C());E!==void 0&&(e=E,r=0);}let g=Math.min(s,l*2**(c-1)),y=Math.min(s,(p.retryAfterSeconds??0)*1e3),x=Math.max(g/2,y)+Math.random()*(g/2);if(o.now()+x>m)throw gu(n,p,c,o.now()-d,a);if(i.onWaiting?.({attempt:c,elapsedMs:o.now()-d,budgetMs:a,nextAttemptInMs:x,status:p.status,message:p.message}),await Mn(o,x,n.signal),n.signal?.aborted)throw Cr("while waiting to allocate")}}}function pu(n){return n instanceof D?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function gu(n,e,t,r,o){let i=`${t} attempt${t===1?"":"s"} over ${r}ms of a ${o}ms budget`;return e.status===429?new h("start_rate_limited",`the platform was still limiting match starts for room ${n.roomId} after ${i}: ${e.message}`,{cause:e}):new h("no_server_ready",`the platform had no server ready for room ${n.roomId} after ${i}: ${e.message}`,{cause:e})}var yu=12e4,fu=1e3;async function Lr(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??fu,o=n.timeoutMs??yu,i=e.now()+o,a=Us(n),s={seen:n.knownToExist===true};for(;;){let l=await Bs(n,a,s);if(l.outcome!==null)return l.outcome;if(e.now()+r>i)throw new h("timeout",`match ${t} was still ${l.status} after ${o}ms`);await Mn(e,r,n.signal);}}async function Gr(n){return (await Bs(n,Us(n),{seen:n.knownToExist===true})).outcome}function Us(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${Hs(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function Bs(n,e,t){let{matchId:r}=n,o=n.clock.now(),i;try{i=await $r(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(a){if(a instanceof D&&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,i.status==="ready")return {status:"ready",outcome:hu(r,i,o)};if(i.status==="failed"){let a=i.ended_reason;return typeof a=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Me(a)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:i.failure_reason??"unknown"}}}return {status:i.status,outcome:null}}async function Dr(n){let e=await $r(n.signal,"while listing cluster targets",()=>n.client.get("/v1/ping/targets",n.signal)),t=[];for(let r of e.targets??[]){let o=r?.cluster_target_id;typeof o!="string"||o.length===0||t.push({id:o,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return t}async function $r(n,e,t){if(n?.aborted)throw Cr(e);try{return await t()}catch(r){throw n?.aborted?Cr(e,r):r}}function Cr(n,e){return new h("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function hu(n,e,t){let r=e.join_credential,o=e.expires_in_seconds,i=typeof r=="string"&&typeof o=="number";return {status:"ready",matchId:n,protocol:e.protocol??"unknown",...i?{joinCredential:r,credentialExpiresAt:t+o*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function Hs(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function Mn(n,e,t){return t?.aborted?Promise.resolve():new Promise(r=>{let o=()=>{n.clearTimeout(i),t?.removeEventListener("abort",o),r();},i=n.setTimeout(o,e);t?.addEventListener("abort",o);})}function Vs(n){return typeof n=="string"&&n.trim()!==""}function On(n,e){return Vs(n)?n.trim():Vs(e)?e:null}var Ln="0.1.0-beta",Ws="0-beta",it="web",bu=/^(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 vu(n){let e=bu.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function Ks(n,e){let t=_u(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:Ln};let o=vu(r);if(o===null)throw new h("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 '${Ln}' for it.`);if(o!==Ws)throw new h("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${o}', and '${Ws}' 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 '${o}' 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 '${Ln}' for it.`);return {...n,platform:t,engineVersion:r}}function _u(n,e){if(n===void 0||n===it)return it;if(!Mr.includes(n))throw new h("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${Mr.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${it}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${it}' 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.`),it}var wu="join",Su="welcome",Ru="rejected",Js=25e3,ku=1e3,Fr=1;function jr(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var xu={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 qr(n){let e=typeof n=="string"?n:"unknown";return new h(xu[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function Mt(n){let{channel:e,clock:t}=n;return new Promise((r,o)=>{let i=false,a=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??Js),s=t.setTimeout(()=>w(new h("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,ku)),l=x=>{let C=x.data;if(typeof C!="string"){c(C);return}let E;try{E=JSON.parse(C);}catch{c(C);return}if(i){c(C);return}if(E.t===Su){let v=jr(E.heartbeat_interval);y({...typeof E.player_id=="string"?{playerId:E.player_id}:{},...typeof E.match_id=="string"?{matchId:E.match_id}:{},...v===void 0?{}:{heartbeatIntervalMs:v}});return}if(E.t===Ru){w(qr(E.reason));return}c(C);},d=()=>{w(new h("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{w(new h("aborted","the caller aborted during the join exchange"));},c=x=>{i&&n.onMessage?.(x);},p=()=>{t.clearTimeout(s),e.removeEventListener("close",d),n.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=x=>{i=true,p(),n.onMessage===void 0&&g(),r({welcome:x,detach:g});},w=x=>{i||(i=true,p(),g(),o(x));};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:wu,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:Fr}:{}}));}catch(x){w(new h("connection_failed",`the join frame could not be sent on the open channel: ${String(x)}`,{cause:x}));}})}var Ue=1,Ot=2,Nr=4,Hr=8,Au=2,Pu=1e3,Vr="heartbeat timeout",Lt="gem-uu",Gn=2,Ys="gem_transports";function st(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!Tu(r)||e.includes(r)||e.push(r);}return e}function Tu(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function Gt(n,e){if(typeof n!="object"||n===null)return null;let t=n[Ys];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 Dn(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var Xs=new TextEncoder,Qs=new TextDecoder;function Wr(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function Kr(n){let e=0;return n?.reliable===false&&(e|=Ue),n?.ordered===false&&(e|=Ot),e}function Jr(n){return {reliable:(n&Ue)===0,ordered:(n&Ot)===0}}var zr={reliable:true,ordered:true};function Zs(n){return JSON.stringify({t:"join",credential:n,wire:Gn,heartbeat:Fr})}function ea(n){let e;try{e=JSON.parse(n);}catch{throw new h("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let t=jr(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"?qr(e.reason):new h("join_refused","the server answered the join out of protocol")}function $n(){return typeof globalThis.WebTransport=="function"&&Yr===null}function Fn(){return Yr}var Yr=null;var zs="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Eu(n){let e=on(n);if(e.byteLength!==32)throw new h("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var Ur=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 i=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(i===0||i>1<<20)throw new h("connection_failed",`a control-stream record claims ${i} bytes`);if(this.buffered.byteLength<4+i)break;let a=this.buffered.slice(4,4+i);this.buffered=this.buffered.slice(4+i),r.push({flags:a[0]??0,payload:a.slice(1)});}return r}};function Br(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 Dt(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 h("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:Eu(n.certHashBase64)}]});}let r=t,o=s=>{try{r.close();}catch{}throw s},i=r.datagrams;(i?.readable===void 0||i.writable===void 0)&&(Yr=zs,o(new h("connection_failed",`${zs}; the rung is skipped for the rest of this page (a reload probes again)`)));let a=new Promise((s,l)=>{setTimeout(()=>l(new h("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 o(new h("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(Br(Nr,Xs.encode(Zs(n.credential))));let c=new Ur,p=d.readable.getReader(),g;for(;g===void 0;){let y=await Promise.race([p.read(),a]);if(y.done||y.value===void 0)return o(new h("connection_failed","the control stream closed before the join was answered"));for(let w of c.push(y.value)){g=ea(Qs.decode(w.payload));break}}return {link:Iu(r,m,p,c,n.log??(y=>console.warn(y)),na(g,n.clock)),welcome:g}}catch(s){return o(s)}}function Iu(n,e,t,r,o,i){let a,s,l=false,d=y=>{if(!l){l=true,m.stop();try{n.close();}catch{}s?.(y);}},m=Qr(i,()=>d(Vr)),c=(y,w)=>{m.heard(),(y&Hr)===0&&a!==void 0&&((y&Nr)!==0?a(Qs.decode(w),zr):a(w,Jr(y)));};(async()=>{try{for(;;){let y=await t.read();if(y.done||y.value===void 0)break;for(let w of r.push(y.value))c(w.flags,w.payload);}}catch{}d("stream closed");})();let p,g;try{let y=n.datagrams;if(y?.readable!==void 0&&y.writable!==void 0){let w=y.readable.getReader();g=y.writable.getWriter(),p=y,(async()=>{try{for(;;){let x=await w.read();if(x.done||x.value===void 0)break;let C=x.value;C.byteLength!==0&&c((C[0]??0)|Ue|Ot,C.slice(1));}}catch{}})();}else o("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(y){p=void 0,g=void 0,o(`[gem] webtransport datagram lane unusable (${Dn(y)}); unreliable sends ride the stream`);}return n.closed.then(y=>d(ta(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,w){if(l)return;if(typeof y=="string"){e.write(Br(Nr,Xs.encode(y))).catch(()=>d("write failed"));return}let x=Kr(w);if((x&Ue)!==0&&g!==void 0){let C=Wr(x,y),E=p?.maxDatagramSize;if(E===void 0||C.byteLength<=E){g.write(C).catch(()=>{});return}}e.write(Br(x,y)).catch(()=>d("write failed"));},onMessage(y){a=y;},onClose(y){s=y;},close(){d("closed");}}}function Xr(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webSocket;if(t===void 0){let o=globalThis.WebSocket;if(o===void 0)return Promise.reject(new h("connection_failed","this environment has no WebSocket"));t=new o(n.url);}let r=t;return r.binaryType="arraybuffer",new Promise((o,i)=>{let a=false,s=setTimeout(()=>{a||(a=true,r.close(),i(new h("timeout","websocket did not come up in time")));},e),l=g=>{a||(a=true,clearTimeout(s),r.close(),i(g));},d=()=>{r.send(Zs(n.credential));},m=g=>{if(a)return;if(typeof g.data!="string"){l(new h("join_refused","the server sent binary before answering the join"));return}let y;try{y=ea(g.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),o({link:Cu(r,na(y,n.clock)),welcome:y});},c=()=>{l(new h("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new h("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 ta(n){return typeof n=="string"&&n.length>0?n:void 0}function na(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function Qr(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,Pu)*Au,o=t.now(),i=null,a=()=>{i=null;let s=t.now()-o;if(s>=r){e();return}i=t.setTimeout(a,r-s);};return i=t.setTimeout(a,r),{heard:()=>{o=t.now();},stop:()=>{i!==null&&(t.clearTimeout(i),i=null);}}}function Cu(n,e){let t,r,o=false,i=s=>{if(!o){o=true,a.stop();try{n.close();}catch{}r?.(s);}},a=Qr(e,()=>i(Vr));return n.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){t?.(s.data,zr);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&Hr)===0&&t?.(l.slice(1),Jr(d));})),n.addEventListener("close",(s=>i(ta(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!o){if(typeof s=="string"){n.send(s);return}n.send(Wr(Kr(l),s));}},onMessage(s){t=s;},onClose(s){r=s;},close(){i("closed");}}}function Zr(n,e,t,r){let o,i,a=false,s=t,l=c=>{if(!a){a=true,d.stop();try{n.close();}catch{}try{e.close();}catch{}i?.(c);}},d=Qr(r,()=>l(Vr)),m=(c,p)=>{if(d.heard(),typeof c=="string"){o?.(c,zr);return}let g=new Uint8Array(c);if(g.byteLength===0)return;let y=g[0]??0;(y&Hr)===0&&o?.(g.slice(1),Jr(y|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,Ue|Ot))),c.addEventListener("close",(()=>{s=void 0;}));}return {transport:"webrtc",send(c,p){if(a)return;if(typeof c=="string"){n.send(c);return}let g=Kr(p),y=Wr(g,c);if((g&Ue)!==0&&s!==void 0&&s.readyState==="open"){s.send(y);return}n.send(y);},onMessage(c){o=c;},onClose(c){i=c;},close(){l("closed");}}}function no(n){if(typeof n!="object"||n===null)return;let e={};for(let[t,r]of Object.entries(n)){let o=eo(r);o!==void 0&&(e[t]=o);}return e}function ro(n){if(Array.isArray(n))return n.map(Mu).filter(e=>!!e)}function eo(n){if(to(n)||Array.isArray(n)&&n.every(to))return n}function to(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function Mu(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=eo(e.fixed),r=eo(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},...at("description",Ou(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(to)?{allowed:e.allowed}:{},...at("min",$t(e.min)),...at("max",$t(e.max)),...at("minItems",$t(e.min_items)),...at("maxItems",$t(e.max_items)),...at("maxLength",$t(e.max_length))}}function Ou(n){return typeof n=="string"&&n.length>0?n:void 0}function $t(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function at(n,e){return e===void 0?{}:{[n]:e}}function Te(n){let e=n??{},t=Y(e.id)??Y(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(ra):[];return {id:t,gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Pe(e.max_players)??0,memberCount:Pe(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,..._e("joinCode",Y(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},..._e("roomArgs",no(e.room_args)),..._e("roomArgsTemplate",ro(e.room_args_template)),gameChannel:Y(e.game_channel)??"release",..._e("region",Y(e.region)),..._e("clusterTargetId",Y(e.cluster_target_id)),..._e("matchId",Y(e.match_id)),version:Pe(e.version)??0,..._e("templateId",Y(e.template_id)),roomType:Y(e.game_room_type)??"Standard",..._e("transports",st(e.transports)??void 0),createdAt:Pe(e.created_at)??0,updatedAt:Pe(e.updated_at)??0,..._e("startedAt",Pe(e.started_at))}}function ra(n){let e=n??{};return {...ve(e),playerId:Y(e.player_id)??"",isReady:e.is_ready===true,role:Y(e.role)??"member",joinedAt:Pe(e.joined_at)??0,..._e("groupId",Y(e.group_id)),..._e("platform",Y(e.platform))}}function jn(n){let e=n??{};return {id:Y(e.id)??Y(e.game_room_id)??"",gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Pe(e.max_players)??0,memberCount:Pe(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Y(e.game_channel)??"release",roomType:Y(e.game_room_type)??"Standard",createdAt:Pe(e.created_at)??0}}function Y(n){return typeof n=="string"&&n.length>0?n:void 0}function Pe(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function _e(n,e){return e===void 0?{}:{[n]:e}}var Ft=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(o=>({rooms:(o.game_rooms??[]).map(jn),...typeof o.next_cursor=="string"?{nextCursor:o.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(jn)}))}create(e,t,r){return Lu(e.maxPlayers),this.options.client.post(this.baseV2(),{name:e.name,...e.isPublic===void 0?{}:{is_public:e.isPublic},...e.settings===void 0?{}:{settings:e.settings},...e.region===void 0?{}:{region:e.region},...r===void 0?{}:{cluster_target_id:r},...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.partyId===void 0?{}:{party_id:e.partyId},...e.roomArgs===void 0?{}:{room_args:e.roomArgs},...qn(t)},e.signal).then(Te)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(Te)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...qn(r)},t.signal).then(Te)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...qn(r)},t.signal).then(Te)}quickJoin(e,t,r=[]){return this.options.client.post(`${this.baseV2()}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...qn(t)},e.signal).then(Te)}leave(e,t,r,o=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:t},r,{keepalive:o}).then(()=>{})}close(e,t){return this.options.client.delete(this.roomV1(e),t).then(()=>{})}update(e,t){return this.options.client.patch(this.roomV2(e),{...t.name===void 0?{}:{name:t.name},...t.maxPlayers===void 0?{}:{max_players:t.maxPlayers},...t.isPublic===void 0?{}:{is_public:t.isPublic},...t.settings===void 0?{}:{settings:t.settings},...t.roomArgs===void 0?{}:{room_args:t.roomArgs}},t.signal).then(Te)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(Te)}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(Te)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function qn(n){return {platform:n.platform,game_version:n.gameVersion,engine_version:n.engineVersion}}function Lu(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 jt=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 o=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(t)&&this.retainedMatch===o&&t(o);});}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,((...o)=>{r(),t(...o);}));return r}emit(e,...t){e==="matchReady"&&(this.retainedMatch=t[0]);let r=this.listeners.get(e);if(r)for(let o of [...r])o(...t);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};function Gu(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var Du=1e3,$u=3e3,Fu=6e4,ju=2,oa=new Set(["game_room_closed","game_room_gone"]),qu=12e4,Nu=5e3,Uu=new Set(["invalid_cluster_target","capacity_unavailable"]);function io(n){return new oo(n)}var oo=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Ft({client:e.client,gameId:()=>this.requireGameId()}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new jt;api;room=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create");let t=this.clusterTargets(),r=await this.attachParty(e),o=await this.run("create",async()=>{let i=await t;return this.api.create(r,this.version("create"),i[0]).catch(async a=>{let s=await this.afterRefusedClusters(a,i);if(s[0]===void 0||s[0]===i[0])throw a;return this.api.create(r,this.version("create"),s[0])})});return this.enter(o,"created"),o}async join(e,t={}){this.assertNotInRoom("join");let r=await this.attachParty(t),o=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(o,"joined"),o}async joinByCode(e,t={}){this.assertNotInRoom("joinByCode");let r=await this.attachParty(t),o=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(o,"joined"),o}async quickJoin(e){this.assertNotInRoom("quickJoin");let t=this.clusterTargets(),r=await this.attachParty(e),o=a=>this.api.quickJoin(r,this.version("quickJoin"),a).catch(s=>this.retryPastStaleMembership(s,r,a)),i=await this.run("quickJoin",async()=>{let a=await t;return o(a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||Hu(l,a))throw s;return o(l)})});return this.enter(i,"joined"),i}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,o=()=>this.run("leave",()=>this.api.leave(t.id,e.asGroup!==false,e.signal,r));if(r){let i=o();this.track(this.notifyLeavingMatch({keepalive:true})),await i;}else await this.notifyLeavingMatch(),await o();this.exit(),this.emitter.emit("left");}async leaveAll(e){let t=await this.myRooms(e),r=[];for(let o of t)try{await this.run("leaveAll",()=>this.api.leave(o.id,!0,e)),r.push(o.id),this.room?.id===o.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(o){if(o instanceof D&&o.reason==="not_found"){let i=this.heldMatchId;if(i!==null){let a=await this.askWhyEnded(i,e);this.endMatch(i,a??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",o),o}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 o=await this.askWhyEnded(r,e);o!==null&&this.endMatch(r,o,t.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,t){let r=this.room;if(r===null)return null;let o=this.takeHint(e),i;try{i=await this.track(this.onceGameIdKnown(()=>Gr({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 D&&a.reason==="not_found"?o??null:(this.reportError("reconcile",a),null)}return i===null?null:i.status==="ready"?(this.seenMatches.add(e),null):i.status==="failed"?(this.settleFailed(i.matchId,i.reason),null):i.reason==="unknown"&&o!==null?o:i.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=Me(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"),o=await this.run("setReady",()=>this.api.setReady(r.id,e,t));return this.apply(o),o}async kick(e,t){let r=this.requireRoom("kick"),o=await this.run("kick",()=>this.api.kick(r.id,e,t));return this.apply(o),o}async transferHost(e,t){let r=this.requireRoom("transferHost"),o=await this.run("transferHost",()=>this.api.transferHost(r.id,e,t));return this.apply(o),o}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 h("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 o=pe(t.clusterTargetId),i=o??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),a=i??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let s=(m,c)=>Or({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...o===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(i,[a]).catch(async m=>{if(o!==void 0||!sa(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 h("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),o=await this.run("pollMatchStatus",()=>this.chase(t.id,r,e));return this.settleOutcome(o)}chase(e,t,r){return Lr({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 h("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!oa.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new h("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 o={matchId:e,cause:t,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=o,this.track(this.reconnectStep(o));}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(!Be()){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<Du){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(Gu(e.attempt,t.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!Be()){this.park(e,()=>this.reconnectAttempt(e));return}let t=this.options.autoReconnect,r=this.room;if(t===void 0||r===null)return;let o=null;try{o=await this.track(this.onceGameIdKnown(()=>Gr({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(i){this.reportError("reconcile",i);}if(this.reconnecting(e)){if(o?.status==="ended"){this.endMatch(o.matchId,o.reason,!oa.has(o.reason)),this.track(this.reconcile().catch(()=>{}));return}if(o?.status==="failed"){this.abandonReconnect(e.matchId,o.reason),this.settleFailed(o.matchId,o.reason);return}if(o?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(o);let i;try{i=await t.redial(e.matchId,e.deadlineAt);}catch(a){this.reportError("reconcile",a),i="failed";}if(e.done||this.reconnect!==e)return;if(i==="closed"){this.finishReconnect();return}if(i==="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 h("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 h("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 h("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:t},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let t=this.heldMatchId;if(t!==null)try{await this.api.leaveMatch(t,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,t){let r=this.emitter.on(e,t);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}handleRoomEvent(e){if(this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let t=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(t).catch(()=>{}));}handleAutoStartFailed(e,t){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 o=new AbortController;this.autoStartRetry=o,this.track(this.requestStart({signal:o.signal},false).then(()=>{},i=>{o.signal.aborted||this.reportError("startMatch",i);}).finally(()=>{this.autoStartRetry===o&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!Uu.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){this.disposed||!this.watchingSeats||this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}async reconcileSeats(){if(this.disposed||!this.watchingSeats)return;let e;try{e=await this.myRooms();}catch{return}let t=new Set;for(let r of e)r.status!=="closed"&&(t.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])t.has(r)||this.reported.delete(r);}async reportSeat(e){let t=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||t===null||!r.members.some(o=>o.playerId===t)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.seatPollMs>0&&Be())){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(),!!Be())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of Nn)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.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 Nn)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??Nu}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new h("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=On(this.options.platformGameVersion?.(),t?.gameVersion);if(r===null)throw new h("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 Ks({...t,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return Ct(await this.options.resolveClusterTargets());let e=pe(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,t){return !sa(e)||t.length===0?[]:Ct(await this.options.refreshClusterTargets?.(t)??[])}async nextCluster(e,t=false){let r=a=>a.find(s=>!e.includes(s)),o=await this.clusterTargets(),i=r(o);return i!==void 0||!t?i:r(Ct(await this.options.refreshClusterTargets?.(o)??[]))}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 D)||e.reason!=="conflict")throw e;if(this.options.recoverStaleMembership===false)throw new D(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 o;try{o=await this.leaveAll(t.signal);}catch{throw new D(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(o.length===0)throw new D(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 h("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}requireRoom(e){if(this.room===null)throw new h("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 D?{operation:e,code:t.status,reason:t.reason,message:t.message,retryable:t.retryable}:{operation:e,code:0,reason:t instanceof h?t.reason:"unavailable",message:t instanceof Error?t.message:String(t),retryable:false};this.emitter.emit("error",r);}track(e){return this.inFlight.push(e),e}enter(e,t){this.room=e,this.abortFollow(),this.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])),o=new Map(e.members.map(s=>[s.playerId,s])),i=this.playerId();for(let s of o.keys())r.has(s)||this.emitter.emit("memberJoined",s);for(let s of r.keys())if(!o.has(s)){if(s===i){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",s);}for(let[s,l]of o){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=Bu(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(o=>{if(!r.signal.aborted)try{this.settleOutcome(o);}catch{}}).catch(o=>{r.signal.aborted||this.reportError("pollMatchStatus",o);}).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??qu;return new Promise((o,i)=>{let a=c=>{s(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),c();},s=this.emitter.on("matchAllocationStarted",c=>a(()=>o(c))),l=this.emitter.on("matchFailed",(c,p)=>a(()=>i(new h("allocation_failed",`match ${c} did not come up: ${p}`)))),d=()=>a(()=>i(new h("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>a(()=>i(new h("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??$u}pushedInterval(){return this.options.pushedPollIntervalMs??Fu}pushed(){return this.options.clock.now()-this.lastPushAt<ju*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=t=>{t?.persisted!==true&&this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{}));},e.addEventListener("pagehide",this.unloadListener));}};function Be(){let n=globalThis.document;return n?.visibilityState===void 0||n.visibilityState==="visible"}var Nn=["visibilitychange","focus","pageshow","online"];function Bu(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||ia(n)!==ia(e)}function ia(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function sa(n){return n instanceof D&&n.code==="invalid_cluster_target"}function Hu(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Vu=["p2p","dedicated","unknown"],so=["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 lt=class{constructor(e){this.options=e;}options;async post(e,t){let r=this.options.gameId();if(r===null||r==="")return;let o=Wu(e,this.options.transport,(this.options.now??Date.now)());o.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:o},t);}report(e){this.post(e).catch(()=>{});}};function Wu(n,e,t){let r=Math.floor(t/1e3);return n.filter(o=>so.includes(o.type)).slice(0,100).map(o=>{let i=Ku(o.transport??e);return {event_type:o.type,timestamp:r,...i===void 0?{}:{transport:i},data:o.value===void 0?{}:{value:o.value}}})}function Ku(n){if(n!==void 0)return Vu.includes(n)?n:"unknown"}var qt=class{constructor(e){this.options=e;this.reporter=new lt({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,t,r){let o=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:t},r);return {credential:Un(o.credential)??"",hostFingerprint:Un(o.host_fingerprint)??"",hostEpoch:Bn(o.host_epoch)??0,expiresAt:(Bn(o.expires_at)??0)*1e3}}async turnLease(e,t,r){let o=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:t},r),i=[];for(let l of Array.isArray(o.ice_servers)?o.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);m.length!==0&&i.push({urls:m,username:Un(d.username)??"",credential:Un(d.credential)??""});}let a=Bn(o.expires_at),s=Bn(o.ttl_seconds);return {iceServers:i,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 Un(n){return typeof n=="string"&&n.length>0?n:void 0}function Bn(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var Ju=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),O=class extends Error{constructor(t,r,o){super(`${t}: ${r}`,o);this.reason=t;this.name="P2pError",this.retryable=Ju.has(t);}reason;retryable};var aa=10240,la=2048,zu=new TextEncoder;function da(n){return zu.encode(n).length}function Oe(n,e){let t=o=>{throw new h("invalid_sdp",`the ${e} ${o}`)},r=da(n);r>=aa&&t(`is ${r} bytes, over the ${aa} 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 o of n.split(/\r\n|\n/)){let i=da(o);i>la&&t(`has a ${i}-byte line, over the ${la} limit`);}}function Hn(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 Vn=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,((...o)=>{r(),t(...o);}));return r}emit(e,...t){let r=this.listeners.get(e);if(r)for(let o of [...r])o(...t);}clear(){this.listeners.clear();}};var Yu=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function dt(n){let e=null;for(let t of n.split(/\r\n|\n/)){if(!t.startsWith("a=fingerprint:"))continue;let r=Wn(t.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function Wn(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 Yu.test(r)?r:null}function Nt(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 ao=5e3,Xu=12e4+ao,Qu=1024,Zu=6e4,em=1e4,ca=64*1024,ua=5;function lo(n){let e=new Map,t=-1/0,r=null,o=(()=>{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}`}})(),i=()=>{let s=n.subtle??globalThis.crypto?.subtle;if(!s)throw new O("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(!o.ok)throw new O("keys_unavailable",o.reason);let s=n.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await s(o.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(em)});}catch{throw new O("keys_unavailable",`the JWKS endpoint at ${o.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new O("keys_unavailable",`the JWKS endpoint answered ${o.shown} with an error`);let d;try{let p=await l.text();if(p.length>ca)throw new O("keys_unavailable",`the JWKS endpoint at ${o.shown} answered with more than ${ca} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof O?p:new O("keys_unavailable",`the JWKS endpoint at ${o.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>ua)throw new O("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${ua} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=i();for(let p of m){let g=p;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.kid.length===0))try{let y=await c.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,y);}catch{}}};return {async key(s){let l=e.get(s);if(l)return l;if(!o.ok)throw new O("keys_unavailable",o.reason);if(r)return await r,e.get(s)??null;let d=n.now();if(!Number.isFinite(d))throw new O("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<Zu?null:(t=d,r??=a().finally(()=>{r=null;}),await r,e.get(s)??null)}}}var Ut=class{seen=new Map;admit(e,t){for(let[r,o]of this.seen)o<=t&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=Qu){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+Xu),true}};function pa(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}function ma(n){try{let e=new TextDecoder().decode(pa(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function co(n,e,t,r,o){let i=G=>{throw new O("peer_unauthenticated",`the peer's join credential is not usable: ${G}`)},a=n.split(".");a.length!==3&&i("it is not a three-part JWT");let[s,l,d]=a,m=ma(s);m===null&&i("its header does not decode"),m.alg!=="RS256"&&i(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&i(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let c=m.kid;(typeof c!="string"||c.length===0)&&i("it names no key");let p=await t.key(c);p===null&&i("it was signed by a key this build cannot resolve");let g=o.subtle??globalThis.crypto?.subtle;g||i("this environment has no WebCrypto");let y=new TextEncoder().encode(`${s}.${l}`),w;try{w=pa(d);}catch{i("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,w,y)||i("its signature does not verify");let C=ma(l);C===null&&i("its payload does not decode");let E=C,v=G=>typeof E[G]=="string"?E[G]:"",S=G=>typeof E[G]=="number"&&Number.isFinite(E[G])?E[G]:NaN;v("iss")!==o.issuer&&i("it was issued by someone else"),v("aud")!==`${o.issuer}/p2p-match`&&i("its audience is not this platform"),v("match_id")!==e.matchId&&i("it is for another match"),v("game_id")!==e.gameId&&i("it is for another game");let A=S("exp")*1e3,R=S("nbf")*1e3;(!Number.isFinite(A)||e.now>A+ao)&&i("it has expired"),Number.isFinite(R)&&e.now<R-ao&&i("it is not valid yet");let H=v("role");H!=="host"&&H!=="client"&&i("it names no usable role");let j=S("host_epoch");j!==e.hostEpoch&&i("it names a different host epoch");let V=Wn(v("fingerprint"));V===null&&i("its fingerprint claim is malformed"),Nt(V,e.peerFingerprint)||i("it was issued for a different certificate than this connection used");let k=Wn(v("host_fingerprint"));k===null&&i("its host fingerprint claim is malformed"),Nt(k,e.hostFingerprint)||i("it was issued against a different host certificate");let P=v("jti");P.length===0&&i("it carries no jti, so replay cannot be detected"),r.admit(P,e.now)||i("it has already been used");let L=v("sub");return L.length===0&&i("it names no player"),{playerId:L.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:j,role:H,fingerprint:V,hostFingerprint:k,jti:P,expiresAt:A}}function uo(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 mo(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 po(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function go(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 ga(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 ya(n){switch(n){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var Bt=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 yo={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}},Ee=["reliable","ordered","unreliable"];function fo(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 Ht(){let n=globalThis.RTCPeerConnection;return n?.generateCertificate?n.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var ha=1,im=3e4,ba=2e3,sm=5e3,va=6e4,am=8,bo=class{constructor(e=am){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;}},lm=new bo,dm=8,cm=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),Wt=class{constructor(e){this.options=e;this.keys=e.keys??lo({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Vn;links=new Map;replays=new Ut;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=ha+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??im;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),o=pe(this.options.clusterTargetId);if(o!==void 0)try{let s=await this.options.api.turnLease(this.options.matchId,o,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: ${ho(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 i=this.options.clock.setTimeout(()=>{this.fail(new O("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 O("aborted","the caller aborted while connecting"));e?.aborted?a():e?.addEventListener("abort",a);try{await r;}finally{this.options.clock.clearTimeout(i),e?.removeEventListener("abort",a),this.ready=null;}}async kick(e){if(!this.isHost)throw new O("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=ie(e.playerId),r=ie(e.hostPlayerId),o=Kn(e.hostEpoch);if(!(t===null||r===null||o===null)&&(this.mark("signaling hello"),this.localPlayerId=t,this.migration===null&&(this.migration=new Bt(t,r,o)),!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,ha),o=await r.connection.createOffer();await r.connection.setLocalDescription(o);let i=r.connection.localDescription?.sdp??o.sdp;if(!i)throw new O("invalid_sdp","the browser produced an offer with no SDP");Oe(i,"offer"),this.refuseMedia(i,"offer"),this.options.signaling.offer(i,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,o=r===void 0?null:dt(r);if(o===null)throw new O("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let i=this.options.credentialPacing??lm,a=()=>this.closed||e!==this.credentialGeneration,s=sm;for(;;){let l=i.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,a))return;i.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,o);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=ba;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,va)),c=Math.min(Math.max(c,ba),va);}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=ie(e.fromPlayerId),r=ie(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=dm){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 o=ie(e.sessionId);if(o!==null&&this.answeredSessions.get(t)===o)return;Oe(r,"offer"),this.refuseMedia(r,"offer");let i=dt(r);if(i===null)throw new O("invalid_sdp",`the offer from ${t} carries no usable fingerprint`);this.mark("offer received"),o!==null&&this.answeredSessions.set(t,o);let a=this.links.get(t);a&&this.dropLink(a,"resignalled",false);let s=this.openLink(t,this.nextPeerId++);s.remoteFingerprint=i,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 O("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=ie(e.fromPlayerId),r=ie(e.sdp);if(t===null||r===null)return;let o=this.links.get(this.hostPlayerId);if(!o||t!==this.hostPlayerId)return;Oe(r,"answer"),this.refuseMedia(r,"answer");let i=dt(r);if(i===null)throw new O("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),o.remoteFingerprint=i,o.pendingAnswer=r,this.hostVerified(o)&&await this.applyAnswer(o,r);}hostVerified(e){let t=this.credential;return t===null||e.remoteFingerprint===null?false:Nt(t.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new O("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=ie(e.fromPlayerId),r=ie(e.candidate);if(t===null||r===null)return;let o=this.links.get(t);if(!o)return;let i=ie(e.sdpMid),a=Kn(e.sdpMLineIndex)??Kn(e.sdpMLineIndexAlt),s={candidate:r,...i===null?{}:{sdpMid:i},...a===null?{}:{sdpMLineIndex:a}};if(o.connection.remoteDescription===null){o.pendingCandidates.length<64&&o.pendingCandidates.push(s);return}await o.connection.addIceCandidate(s);}onPeerLeft(e){let t=ie(e.playerId);if(t===null)return;let r=ie(e.reason)??"left";if(t===this.localPlayerId){this.fail(new O("kicked",`this player was removed from the match (${r})`)),this.close();return}let o=this.links.get(t);o&&this.dropLink(o,r,true);}async onMigration(e){let t=ie(e.hostPlayerId),r=Kn(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let o=this.migration.apply({hostPlayerId:t,hostEpoch:r,...ie(e.reason)===null?{}:{reason:ie(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(i=>typeof i=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(o.kind!=="duplicate"){if(o.kind==="completed"){this.emitter.emit("hostChanged",t,r);return}if(o.kind==="refused"){this.report_(new O("migration_failed",o.why));return}for(let i of [...this.links.values()])this.dropLink(i,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",t,r),o.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 O("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=ie(e.reason)??"ended";this.ended=t,this.emitter.emit("matchEnded",t),this.ready!==null&&this.fail(new O("match_ended",`the match ended: ${t}`)),this.close();}onSignalingError(e){let t=ie(e.code)??"unknown",r=ie(e.message)??"the platform refused a signaling message";this.report_(new O("signaling_failed",`${t}: ${r}`));}openLink(e,t){let o=(this.options.peerConnectionFactory??fo)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),i={};for(let p of Ee){let g=o.createDataChannel(p,yo[p]);g.binaryType="arraybuffer",i[p]=g;}let a={playerId:e,assignedPeerId:t,connection:o,channels:i,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},s=p=>{let g=p.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},l=()=>this.onIceState(a),d=()=>this.onConnectionState(a),m=p=>{this.onHandshakeMessage(a,p.data).catch(g=>this.report_(g));},c=()=>{this.onReliableOpen(a).catch(p=>this.report_(p));};return o.addEventListener("icecandidate",s),o.addEventListener("iceconnectionstatechange",l),o.addEventListener("connectionstatechange",d),i.reliable.addEventListener("open",c),i.reliable.addEventListener("message",m),a.detachHandshake=()=>{i.reliable.removeEventListener("open",c),i.reliable.removeEventListener("message",m);},a.detachAll=()=>{a.detachHandshake(),o.removeEventListener("icecandidate",s),o.removeEventListener("iceconnectionstatechange",l),o.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 O("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 O("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(uo({jwt:t.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,t){if(!(t instanceof ArrayBuffer))return;let r=go(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 O(ya(r.reason),ga(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 o=dt(e.connection.localDescription?.sdp??"");if(o===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 i;try{i=await co(t,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:o,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(a){let s=a instanceof O&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",ho(a)),s&&this.fail(a);return}if(i.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${i.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(i.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(mo({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,t,r,o){this.warn(`refused to admit ${e.playerId}: ${o}`);try{e.channels.reliable.send(po(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 o of Ee)_a(e.channels[o]);_a(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 O?e:new O("connection_failed",ho(e),{cause:e}));}count(e){this.counted||!cm.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(Hn(e))throw new O("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 ie(n){return typeof n=="string"&&n.length>0?n:null}function Kn(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function ho(n){return n instanceof Error?n.message:String(n)}function _a(n){try{n.close();}catch{}}var um=100,mm=50,Kt=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,o){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??um)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:t,...r===void 0?{}:{sdpMid:r},...o===void 0?{}:{sdpMLineIndex:o}}),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 O("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new O("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see public-docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId:t,candidate:r,sdpMid:o,sdpMLineIndex:i}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:t,candidate:r,...o===void 0?{}:{sdpMid:o},...i===void 0?{}:{sdpMLineIndex:i}});}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??mm));}};function N(n){return e=>typeof e=="string"&&e.length>0&&e.length<=n?e:void 0}function Le(n,e){return t=>typeof t=="number"&&Number.isInteger(t)&&t>=n&&t<=e?t:void 0}function ct(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function wa(n){return typeof n=="boolean"?n:void 0}var fe=N(64),Jt=Le(0,2147483647);function vo(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(e.length>=64)break;let r=fe(t);typeof r=="string"&&e.push(r);}return e}function W(n,e,t){return {to:n,from:e,read:t,required:true}}function U(n,e,t){return {to:n,from:e,read:t,required:false}}var ym=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=ct("disconnected","failed","closed")(e.iceState),r=Le(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}}};Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[W("sdp","sdp",N(10240)),W("signaling_intent","intent",ct("initial","ice_restart","full_reconnect")),U("sdp_hash","sdpHash",N(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[W("peer_id","peerId",fe),W("sdp","sdp",N(10240)),W("assigned_peer_id","assignedPeerId",Le(0,4294967295)),U("sdp_hash","sdpHash",N(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[W("peer_id","peerId",fe),W("candidate","candidate",N(512)),U("sdp_mid","sdpMid",N(64)),U("sdp_mline_index","sdpMLineIndex",Le(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[W("host_epoch","hostEpoch",Jt)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[W("host_epoch","hostEpoch",Jt),U("evidence","evidence",ym)]}}));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"}));Object.freeze(Object.assign(Object.create(null),{hello:[W("playerId","player_id",fe),W("hostPlayerId","host_player_id",fe),W("hostEpoch","host_epoch",Jt),U("members","members",vo)],offer:[W("fromPlayerId","from_player_id",fe),W("sdp","sdp",N(10240)),U("sessionId","signaling_session_id",N(128)),U("sdpHash","sdp_hash",N(128)),U("iceUfrag","ice_ufrag",N(64)),U("intent","signaling_intent",ct("initial","ice_restart","full_reconnect"))],answer:[W("fromPlayerId","from_player_id",fe),W("sdp","sdp",N(10240)),U("sessionId","signaling_session_id",N(128)),U("sdpHash","sdp_hash",N(128)),U("iceUfrag","ice_ufrag",N(64)),U("assignedPeerId","assigned_peer_id",Le(0,4294967295))],ice:[W("fromPlayerId","from_player_id",fe),W("candidate","candidate",N(512)),U("sdpMid","sdp_mid",N(64)),U("sdpMLineIndex","sdp_m_line_index",Le(0,255)),U("sdpMLineIndexAlt","sdp_mline_index",Le(0,255))],peerJoined:[W("playerId","player_id",fe)],peerLeft:[W("playerId","player_id",fe),U("reason","reason",N(64))],migration:[W("hostPlayerId","new_host_player_id",fe),W("hostEpoch","host_epoch",Jt),U("reason","reason",N(64)),U("kickedPlayerIds","kicked_player_ids",vo),U("migrationComplete","migration_complete",wa)],matchEnded:[U("reason","reason",N(64))],error:[U("code","code",N(64)),U("message","message",N(256))]}));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"}));var Ve="webrtc_p2p";function Ra(n){let e=new qt({client:n.client,gameId:n.gameId}),t=new Map;return {handleSignalEvent(r,o,i){t.get(r)?.handleSignal(o,i);},session(r){return t.get(r)??null},async connect(r={}){if(n.bridge===null)throw new O("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See public-docs/p2p-and-parties.md \xA72.");let o=pe(r.clusterTargetId),i=o??pe(await n.resolveClusterTarget?.());n.rooms.isHost&&n.rooms.currentMatch===null&&n.rooms.currentRoom?.matchId===void 0&&await n.rooms.startMatch({...o===void 0?{}:{clusterTargetId:o},...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!==Ve)throw new O("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${Ve}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new Kt({bridge:n.bridge,matchId:a.matchId,clock:n.clock}),l=new Wt({api:e,clock:n.clock,matchId:a.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:s,...i===void 0?{}:{clusterTargetId:i},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Ht(),...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 ka(n){let{analytics:e,rooms:t}=n,r=n.target??globalThis,o=n.document??globalThis.document,i=[];if(typeof r.addEventListener=="function"){let s=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",s),i.push(()=>r.removeEventListener?.("pagehide",s));let l=()=>e.setHidden(!Be());for(let d of Nn)r.addEventListener(d,l),i.push(()=>r.removeEventListener?.(d,l));typeof o?.addEventListener=="function"&&(o.addEventListener("resume",l),i.push(()=>o.removeEventListener?.("resume",l))),e.setHidden(!Be());}let a=new Map;return i.push(t.on("matchReady",s=>{let l=s.protocol===Ve?"p2p":"dedicated";a.set(s.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),i.push(t.on("matchEnded",s=>{let l=a.get(s.matchId);l!==void 0&&(a.delete(s.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let s of i.splice(0))try{s();}catch{}a.clear();}}async function Jn(n,e,t,r){let o=await t;return n.mark(e)&&r&&r(`[gem] boot: ${n.timeline()}`),o}function _o(n,e){let t=false;return async r=>{let o=await r;return !t&&e&&(t=true,e(`[gem] boot: ${n.timeline()}`)),o}}function wo(n={}){let e=n.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),t=[],r=new Set;return {marks:t,mark(o,i){return r.has(o)?false:(r.add(o),t.push({name:o,at:i??e()}),true)},timeline(){let o=[...t].sort((i,a)=>i.at-a.at);return o.map((i,a)=>{let s=o[a-1],l=s===void 0?"":` (+${Math.round(i.at-s.at)}ms)`;return `${i.name}@${Math.round(i.at)}ms${l}`}).join(" \u2192 ")}}}var fm="GemWebSdkHandshake";var hm=()=>Date.now();function xa(n,e,t={}){let r=n[fm];if(r===void 0)return null;let o=t.ttlMs??9500,i=t.now??hm,a=r.events.splice(0),s=r.times?.splice(0),l=0,d=0,m=false,c=i()-o;for(let p=a.length-1;p>=0;p--){let g=s?.[p];if(g!==void 0&&g<c){d+=1;continue}if(l+=1,e(a[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}var So=false;async function Ea(n,e,t,r){if(So){e.close(),t("busy",true);return}So=true;let o=null;try{let i=await vm(n,r);if(typeof i=="string"){e.close(),t(i,bm(i));return}o=i;let s=await(r.encodeRef??(l=>Rm(l,r)))(o);if(o.close(),o=null,s===null){e.close(),t("failed",!0);return}if(s.size>Sm){e.close(),t("too_large",!1);return}e.postMessage(s);}catch(i){e.close(),t("failed",true),console.error("[gem] screenshot capture failed",i);}finally{So=false,o?.close();}}function bm(n){switch(n){case "no_source":case "busy":case "failed":return true;case "not_wired":case "unsupported":case "unreadable":case "tainted":case "too_large":case "declined":return false}}async function vm(n,e){if(e.handler){let i=await e.handler(n);return i===null?"declined":Aa(i,n)}if(!e.useDefaultStrategy)return "not_wired";let t=e.documentRef??globalThis.document;if(!t)return "no_source";let r=wm(t);if(!r)return "no_source";let o=_m(r);if(o!==null)return o;try{return Aa(await createImageBitmap(r),n)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}function _m(n){let e;try{e=n.getContext("webgl2")??n.getContext("webgl");}catch{return "unreadable"}if(e){let t=e.getContextAttributes();return !t||t.preserveDrawingBuffer!==true?"unsupported":null}try{if(n.getContext("2d"))return null}catch{return "unreadable"}return "unreadable"}function wm(n){let e=null,t=0;for(let r of Array.from(n.querySelectorAll("canvas"))){let o=r.width*r.height;o<=0||r.clientWidth<=0||r.clientHeight<=0||o>t&&(e=r,t=o);}return e}async function Aa(n,e){let{maxWidth:t,maxHeight:r}=e;if(n.width<=t&&n.height<=r)return n;let o=Math.min(t/n.width,r/n.height),i=Math.max(1,Math.floor(n.width*o)),a=Math.max(1,Math.floor(n.height*o));try{let s=await createImageBitmap(n,{resizeWidth:i,resizeHeight:a,resizeQuality:"high"});return n.close(),s}catch{return n.close(),"too_large"}}var Sm=8*1024*1024,Pa="image/webp",Ta=.92;async function Rm(n,e){try{if(typeof OffscreenCanvas=="function"){let i=new OffscreenCanvas(n.width,n.height),a=i.getContext("2d");if(a){a.drawImage(n,0,0);let s=await i.convertToBlob({type:Pa,quality:Ta});if(s&&s.size>0)return s}}}catch{}let t=e.documentRef??globalThis.document;if(!t)return null;let r=t.createElement("canvas");r.width=n.width,r.height=n.height;let o=r.getContext("2d");return !o||(o.drawImage(n,0,0),typeof r.toBlob!="function")?null:await new Promise(i=>{r.toBlob(a=>i(a),Pa,Ta);})}async function Ia(n,e){if(!e)return;let t;try{t=await km(e);}catch(r){console.error("[gem] onFeedbackContext threw; sending the report without context",r);return}if(t!=null){if(typeof t!="object"||Array.isArray(t)){console.error("[gem] onFeedbackContext must return a plain object or null; got",t);return}n.sendGameContext(t);}}function km(n){return new Promise((e,t)=>{let r=false,o=setTimeout(()=>{r||(r=true,console.warn("[gem] onFeedbackContext did not answer within 1000ms; sending the report without context. Gather cheaply, or keep a snapshot."),e(null));},1e3);(async()=>n())().then(i=>{r||(r=true,clearTimeout(o),e(i??null));},i=>{r||(r=true,clearTimeout(o),t(i instanceof Error?i:new Error(String(i))));});})}var Ca=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function Ma(n=globalThis){let t=n[Ca];if(t!==void 0)return t;let r=false,o=()=>r,i=[],a=xm(n,o);a!==null&&i.push(a);let s=Am(n,o);s!==null&&i.push(s);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let c of i)c();}}};return Object.defineProperty(n,Ca,{value:l,configurable:true}),l}function xm(n,e){let t=n.AudioNode?.prototype,r=n.AudioDestinationNode;if(t===void 0||r===void 0)return null;let o=n.OfflineAudioContext,i=t.connect,a=t.disconnect,s=new Map,l=m=>{let c=m.gain,p=m.context.currentTime;c.cancelScheduledValues(p),e()?c.setValueAtTime(0,p):c.setTargetAtTime(1,p,.01);},d=m=>{let c=m.context;if(o!==void 0&&c instanceof o)return null;let p=s.get(c);return p===void 0&&(p=c.createGain(),p.gain.value=e()?0:1,i.call(p,m),s.set(c,p)),p};return t.connect=function(...c){let[p,...g]=c;if(p instanceof r){let y;try{y=d(p);}catch{y=null;}if(y!==null)return i.call(this,y,...g),p}return i.apply(this,c)},t.disconnect=function(...c){let[p,...g]=c;if(p instanceof r){let y=s.get(p.context);if(y!==void 0&&y!==this)try{return a.call(this,y,...g)}catch{}}return a.apply(this,c)},()=>{for(let[m,c]of s){if(m.state==="closed"){s.delete(m);continue}try{l(c);}catch{}}}}function Am(n,e){let t=n.HTMLMediaElement;if(t===void 0)return null;let r=t.prototype,o=Object.getOwnPropertyDescriptor(r,"muted"),i=o?.get,a=o?.set;if(i===void 0||a===void 0)return null;let s=r.play,l=new WeakMap,d=new WeakSet,m=new Set,c=p=>{l.has(p)||l.set(p,!!i.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),a.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:o?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!i.call(this):p},set(p){l.set(this,!!p),c(this);}}),r.play=function(){try{c(this);}catch{}return s.call(this)},n.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof t)try{c(g);}catch{}},true),()=>{for(let p of m){let g=p.deref();if(g===void 0){m.delete(p);continue}try{a.call(g,(l.get(g)??!1)||e());}catch{}}}}function Oa(n){let e=n.windowMs??1e3,t=n.realm??globalThis,r=false,o=false,i=false,a=null,s=null,l=null,d=[],m=()=>r&&!o&&!i,c=()=>{s=null,l=null,d=[];},p=w=>{if(a=null,!m()){c();return}if(l!==null&&d.push(w-l),l=w,s===null)s=w;else {let x=w-s;x>=e&&d.length>0&&(n.report(Pm(d,x)),s=w,d=[]);}g();},g=()=>{let w=t.requestAnimationFrame;typeof w=="function"&&(a=w.call(t,p));},y=()=>{if(m()){a===null&&(c(),g());return}a!==null&&(t.cancelAnimationFrame?.call(t,a),a=null),c();};return {setRequested(w){r=w,y();},setPaused(w){o=w,y();},get running(){return a!==null},dispose(){i=true,y();}}}function Pm(n,e){let t=[...n].sort((o,i)=>o-i),r=Math.max(1,Math.ceil(t.length*.95));return {fps:n.length*1e3/e,frameTimeP95Ms:t[r-1]}}var zn=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function La(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function Ga(n,e){n!==null&&(n.style.setProperty(zn.top,`${e.top}px`),n.style.setProperty(zn.right,`${e.right}px`),n.style.setProperty(zn.bottom,`${e.bottom}px`),n.style.setProperty(zn.left,`${e.left}px`));}var Tm=3e4,Yn=class extends Error{retryable;reason;constructor(e,t,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=t;}};function Da(n){let e=n.clock??ae,t=n.timeoutMs??Tm,r=new Map,o=new Map,i=0,a=s=>{let l=r.get(s);return l?(r.delete(s),o.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return n.bridge.parentSupports("localHost")},ensure(s){if(!n.bridge.parentSupports("localHost"))return Promise.resolve();let l=o.get(s);if(l)return l;let d=new Promise((m,c)=>{let p=`ls${++i}`,g=e.setTimeout(()=>{r.delete(p),o.delete(s),c(new Yn("timeout",true,`the embedder did not answer a local-server request for room ${s} within ${String(t)}ms`));},t);r.set(p,{room:s,resolve:m,reject:c,timer:g}),n.bridge.requestLocalServer(p,s)||(a(p),m());});return o.set(s,d),d.catch(()=>{}),d},accept(s){a(s.requestId)?.resolve();},refuse(s){let l=a(s.requestId);l&&l.reject(new Yn(s.reason,s.retryable,s.reason==="refused"?`the platform refused to let this machine serve room ${l.room}. Check that you are signed in as a developer on this game, that the room is on the dev or test channel, and that you host it.`:`this machine could not start a server for room ${l.room}. Your development tool has the reason.`));}}}var zt={url:"https://downloads.indiegems.games/sdk/v7.1.0/gem-web-sdk.devtools.min.js",integrity:"sha384-gZRDwtsO6O/zj/n4z7E/SunCj/xKnSl/OYdZx8y9TIXAznOhFsmiwCWoCU7oJ4Tl"};var mt=null;function Em(){return mt!==null||(mt=new Promise((n,e)=>{let t=document.createElement("script");t.src=zt.url,t.integrity=zt.integrity,t.crossOrigin="anonymous",t.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){mt=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${zt.url} is not a gem-web-sdk devtools build.`));return}n(r);},t.onerror=()=>{mt=null,e(new Error(`gem devtools: could not load ${zt.url}. Either the network refused it or its Subresource Integrity check failed, or the CDN did not answer the CORS preflight this request needs \u2014 SRI is only checkable on bytes the page may read. A locally rebuilt SDK is the commonest cause: it produces panel bytes that do not match the hash compiled into this build.`));},document.head.append(t);})),mt}function $a(n,e){let t=null,r=0;async function o(i){if(t!==null)return true;let a=++r;if(!e())return false;let s=await Em();return !e()||a!==r?false:(t!==null||(t=s.mount(n(),{openedBy:i,text:je,onDismiss:()=>{t?.unmount(),t=null;}})),true)}return {get isOpen(){return t!==null},close(){r+=1,t?.unmount(),t=null;},open:()=>o("game"),openFrom:o}}var Im=1e4,Fa={reason:"unavailable",retryable:false};function ja(n){let e=new Map,t=null,r=null,o=0,i=(d,m)=>{m.timer=n.clock.setTimeout(()=>{e.delete(d),m.reject({reason:"timeout",retryable:true});},n.timeoutMs??Im);},a=(d,m)=>{let c=s(d);c&&m(c);},s=d=>{let m=e.get(d);return m?(e.delete(d),n.clock.clearTimeout(m.timer),m):null},l=new Ze({clock:n.clock,onStateChange:n.onStateChange,request:d=>new Promise((m,c)=>{let p=n.bridge.currentState;if(p==="refused"||p==="closed"){c(Fa);return}let g=`t${++o}`,y={resolve:m,reject:c,reason:d,timer:null,held:p!=="connected"};e.set(g,y),i(g,y),y.held||n.bridge.requestToken(g,d);})});return {source:l,onToken(d){let m={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(t={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){a(d.requestId,c=>c.resolve(m));return}l.accept(m);},onDenied(d){a(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,c]of e)c.held&&(c.held=false,n.clock.clearTimeout(c.timer),i(m,c),n.bridge.requestToken(m,c.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])a(m,c=>c.reject(Fa));},get identity(){return t},get gameVersion(){return r}}}function Cm(n){let e=n.lastIndexOf("@");return (e===-1?n:`***@${n.slice(e+1)}`).slice(0,200)}var Mm=new Set(nn);function Om(n){if(!n)return {};let e={};for(let[t,r]of Object.entries(n))Mm.has(t.toLowerCase())&&(e[t.toLowerCase()]=r);return e}function Xn(n){let e=n.fetch??globalThis.fetch.bind(globalThis);return zo(async(t,r)=>{let o;try{o=new URL(n.baseUrl.replace(/\/+$/,""));}catch{throw new ne("the configured baseUrl is not a valid URL. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure.")}let i;try{i=new URL(o.href.replace(/\/+$/,"")+t.path);}catch{throw new ne(`${JSON.stringify(typeof t.path=="string"?Cm(t.path):"(a non-string path)")} does not form a valid URL against ${o.protocol}//${o.host}. This is a malformed request, not a server failure.`)}if(i.protocol!==o.protocol||i.host!==o.host)throw new ne(`${JSON.stringify(i.pathname)} resolves to ${i.protocol}//${i.host}, not ${o.protocol}//${o.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(i.username!==""||i.password!==""){let g=o.username!==""||o.password!=="",y=i.username!==o.username||i.password!==o.password,w=g?y?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new ne(`the ${w} puts credentials in the URL, which cannot be fetched (${t.method} ${i.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[g,y]of Object.entries(n.defaultQuery??{}))i.searchParams.has(g)||i.searchParams.set(g,y);let a=t.bytes,s=t.bytes===void 0?void 0:"application/octet-stream";try{t.body!==void 0&&(a=JSON.stringify(t.body),s="application/json");}catch(g){throw new ne(`the body of ${t.method} ${JSON.stringify(i.pathname)} could not be serialised to JSON: ${String(g)}. This is a bug in the request, not a server failure \u2014 retrying sends the same unserialisable value.`)}let l=await e(i.toString(),{method:t.method,headers:{authorization:`Bearer ${r}`,...s===void 0?{}:{"content-type":s},...Om(t.headers)},body:a,signal:t.signal,...t.keepalive===void 0?{}:{keepalive:t.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(t.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let m=l.headers.get("etag"),c=Lm(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...c===void 0?{}:{retryAfterSeconds:c},...p===null||p===""?{}:{invocationId:p}}},n)}function Lm(n){if(n===null)return;let e=n.trim();if(!/^\d+$/.test(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0}var Gm=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),ko="embedder_relay_unavailable",Dm="embedder_no_relay",$m=new Set([ko]),xo=new Set([Dm]),Yt=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new Ro(this)}handleEvent(e){let t=this.pending.get(e.matchId);if(t!==void 0){if(e.event==="matchEnded"){t.refuse(new h("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 h("signaling_failed","the parent relayed an answer with no SDP in it"));return}t.settle({sdp:e.sdp});return}t.refuse(Fm(e.code,e.message));}}register(e,t){this.pending.get(e)?.refuse(new h("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 h("signaling_unavailable","this game is not running inside a page that holds the player's notification socket, so there is nothing to carry an offer. Dedicated signaling needs that socket and only the page can hold one \u2014 see public-docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new h("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See public-docs/dedicated-server-flow.md \xA72.");return e}};function Fm(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new h(jm(n),r,{platformCode:n})}function jm(n){return n===void 0||$m.has(n)?"signaling_failed":xo.has(n)?"offer_refused":Gm.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var Ro=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,t){if(this.closed)return Promise.reject(new h("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(o){return Promise.reject(o)}return t?.aborted?Promise.reject(new h("aborted","the caller aborted before the offer was sent")):new Promise((o,i)=>{let a=()=>{s(),i(new h("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(),o(d);},refuse:d=>{s(),i(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 h?d:new h("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var qa="match_ended:",Na="server_shutdown:",Ua="kicked:",qm=123;function Nm(n){if(typeof n!="string"||n.length===0||n.length>qm)return {kind:"other"};if(n.startsWith(qa)){let e=Me(n.slice(qa.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(Na)?{kind:"server_shutdown",cause:n.slice(Na.length)}:n.startsWith(Ua)?{kind:"kicked",detail:n.slice(Ua.length)}:{kind:"other"}}function Ao(n,e,t){let r=Nm(t),o=r.kind==="kicked"?"kicked":"link_closed";n.notifyMatchDisconnected(o).catch(()=>{}),r.kind==="match_ended"&&n.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}function Po(){return {exchange(){return Promise.reject(new h("signaling_unavailable","no signaling channel is wired. The exchange rides the notification WebSocket, and POST /v1/ws/ticket accepts only account credentials \u2014 a game frame holds a game-scoped token and cannot mint one \u2014 so it has to be relayed by the page embedding this game. Run inside a parent that advertises `dedicated`, or pass your own `signaling` implementation. See public-docs/dedicated-server-flow.md \xA72."))},close(){}}}var Um=3e3,Bm=1e4,Hm=15e3;async function Qn(n){let e=n.peerConnection;try{Ha(n,"before the handshake started"),To(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 Km(e,n),To(n);let o=e.localDescription?.sdp??r.sdp;if(!o)throw new h("invalid_sdp","the offer carried no SDP");Oe(o,"offer"),Ba(o,"offer");let i=await Wm(n,o);if(To(n),typeof i?.sdp!="string")throw new h("invalid_sdp","the signaling channel answered without an SDP");return Oe(i.sdp,"answer"),Ba(i.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:i.sdp}),await Jm(t,n),Ha(n,"before the channel opened"),t}catch(t){throw e.close(),Vm(t)}}function Vm(n){return n instanceof h?n:Ka(n)?We():new h("connection_failed",Ja(n),{cause:n})}function Ba(n,e){if(Hn(n))throw new h("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 Wm(n,e){let t=n.exchangeTimeoutMs??Bm,r=Wa(n,t),o=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(i=>{throw i instanceof h?i:Ka(i)?We():new h("signaling_failed",Ja(i),{cause:i})});return zm(o,n,r,()=>r.exhausted?Eo("while the offer was in flight"):new h("timeout",`no answer arrived within ${t}ms`))}function Km(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let o=()=>{t.clearTimeout(a),n.removeEventListener("icegatheringstatechange",i),e.signal?.removeEventListener("abort",o),r();},i=()=>{n.iceGatheringState==="complete"&&o();},a=t.setTimeout(o,e.gatherTimeoutMs??Um);n.addEventListener("icegatheringstatechange",i),e.signal?.addEventListener("abort",o);})}function Jm(n,e){if(e.signal?.aborted)return Promise.reject(We());if(n.readyState==="open")return Promise.resolve();if(n.readyState!=="connecting")return Promise.reject(new h("connection_failed",`the data channel was already '${n.readyState}' when the answer was applied`));let{clock:t}=e,r=e.openTimeoutMs??Hm,o=Wa(e,r);return new Promise((i,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(),i();},d=g=>{s(),a(new h("connection_failed","the data channel failed before it opened",Va(g)===void 0?void 0:{cause:Va(g)}));},m=()=>{s(),a(We());},c=()=>{s(),a(o.exhausted?Eo("while the channel was still opening"):new h("timeout",`the data channel did not open within ${r}ms`));},p=t.setTimeout(c,o.ms);n.addEventListener("open",l),n.addEventListener("close",d),n.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function Wa(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 zm(n,e,t,r){let{clock:o,signal:i}=e;return i?.aborted?Promise.reject(We()):new Promise((a,s)=>{let l=c=>{o.clearTimeout(m),i?.removeEventListener("abort",d),c();},d=()=>l(()=>s(We())),m=o.setTimeout(()=>l(()=>s(r())),t.ms);i?.addEventListener("abort",d),n.then(c=>l(()=>a(c)),c=>l(()=>s(c)));})}function Ha(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw Eo(`already ${e}`)}function Eo(n){return new h("credential_expired",`the join credential ran out ${n} \u2014 poll match status again for a fresh one`)}function To(n){if(n.signal?.aborted)throw We()}function We(){return new h("aborted","the caller aborted the connection attempt")}function Ka(n){return n?.name==="AbortError"}function Va(n){return n?.error}function Ja(n){return n instanceof Error?n.message:String(n)}Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"}));Object.freeze(Object.assign(Object.create(null),{answer:[W("sdp","sdp",N(10240)),U("sessionId","session_id",N(64))],error:[U("code","code",N(64)),U("message","message",N(256))],matchEnded:[U("reason","reason",N(64))]}));function nl(n){let{client:e,clock:t,rooms:r}=n,o=n.signaling??Po,i=n.log??(v=>console.warn(v)),a=new lt({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(v,S)=>{let A=s.get(v)??new Set;A.add(S),s.set(v,A);},d=(v,S)=>{let A=s.get(v);A!==void 0&&(A.delete(S),A.size===0&&s.delete(v));},m=async v=>{if(r.isHost&&!Co(r)&&r.currentRoom?.matchId===void 0){let S=pe(v.clusterTargetId);await r.startMatch({...S===void 0?{}:{clusterTargetId:S},...v.retry===void 0?{}:{retry:v.retry},...v.signal===void 0?{}:{signal:v.signal}});}return el(r.matchConnectionState==="suspended"?await r.reconnectToMatch(Io(v)):await r.awaitMatch(Io(v)))},c=async v=>el(await r.pollMatchStatus(Io(v))),p=async(v,S)=>{let A=false;try{let R=await m(v),H=r.currentRoom?.transports;if(H!==void 0&&!H.includes("webrtc"))throw new h("misconfigured",`the room template offers (${H.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 j=v.peerConnection??tl();A=!0;let V=await Qn({peerConnection:j,signaling:S,clock:t,matchId:R.matchId,credentialExpiresAt:R.credentialExpiresAt,...Zn(v,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),k=null;if(v.presentCredential!==!1)try{k=await Mt({channel:V,clock:t,credential:R.joinCredential,credentialExpiresAt:R.credentialExpiresAt,...Zn(v,"onMessage","signal"),...v.welcomeTimeoutMs===void 0?{}:{ceilingMs:v.welcomeTimeoutMs}});}catch(P){throw we(V),we(j),P}return op(r,R,V,j,S,v.reportDisconnect!==!1,v.reportConnected!==!1,k,{remember:l,forget:d},v.onMatchEnded)}catch(R){throw A&&Za(a,R),we(S),R}},g=async(v,S,A,R,H,j)=>{if(v==="webtransport"){let F=R?.webtransport;if(F===void 0)throw new h("misconfigured","webtransport is not advertised");let B={credential:A.joinCredential,credentialExpiresAt:A.credentialExpiresAt,clock:t};if(typeof F.named_url=="string"&&F.named_url!==""){let re=Math.max(Math.floor(j/2),1e3);try{return await Dt({url:F.named_url,timeoutMs:re,log:i,...B})}catch(le){if(Fn()!==null)throw le;return i(`[gem] webtransport named dial failed (${Dn(le)}); retrying the pinned dial`),Dt({url:F.url,certHashBase64:F.cert_sha256_b64,timeoutMs:re,log:i,...B})}}return Dt({url:F.url,certHashBase64:F.cert_sha256_b64,timeoutMs:j,...B})}if(v==="websocket"){let F=R?.websocket;if(F===void 0)throw new h("misconfigured","websocket is not advertised");return Xr({url:F.url,credential:A.joinCredential,credentialExpiresAt:A.credentialExpiresAt,clock:t,timeoutMs:j})}let V=S.peerConnection??tl(),k,P=await Qn({peerConnection:V,signaling:H,clock:t,matchId:A.matchId,credentialExpiresAt:A.credentialExpiresAt,extraChannels:[{label:Lt,ordered:false,maxRetransmits:0}],onExtraChannel:(F,B)=>{F===Lt&&(k=B);},...Zn(S,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...S.exchangeTimeoutMs===void 0&&S.redial===true?{exchangeTimeoutMs:Qm}:{}}),L;try{L=await Mt({channel:P,clock:t,credential:A.joinCredential,credentialExpiresAt:A.credentialExpiresAt,wire:Gn,heartbeat:!0,...Zn(S,"signal"),...S.welcomeTimeoutMs===void 0?{}:{ceilingMs:S.welcomeTimeoutMs}});}catch(F){throw we(P),we(V),F}let G=L.welcome.heartbeatIntervalMs;return {link:Zr(P,V,k,G===void 0?void 0:{clock:t,intervalMs:G}),welcome:L.welcome,channel:P,peerConnection:V}},y=(v,S,A,R,H)=>{let j=false,V;R.link.onClose(G=>{!j&&v.reportDisconnect!==false&&Ao(r,S.matchId,G),V?.(G);}),v.reportDisconnect!==false&&v.reportConnected!==false&&r.notifyMatchConnected(S.matchId);let k={transport:R.link.transport,send:(G,F)=>R.link.send(G,F),onMessage:G=>R.link.onMessage(G),onClose:G=>{V=G;},close:()=>R.link.close()},P=()=>{j||(j=true,we(R.link),we(H));},L=G=>{if(!j){try{v.onMatchEnded?.(G);}catch{}P();}};return l(S.matchId,L),{matchId:S.matchId,transport:A,link:k,joinCredential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,welcome:R.welcome,...R.channel===void 0?{}:{channel:R.channel},...R.peerConnection===void 0?{}:{peerConnection:R.peerConnection},close(){d(S.matchId,L),P();}}},w=async(v,S)=>{let A=r.currentRoom?.id,R=r.gameId,H=()=>({advert:Gt(r.currentRoom?.settings,v),template:r.currentRoom?.transports??null});if(A===void 0||R===null)return H();try{let j=await e.get(`/v2/games/${encodeURIComponent(R)}/game-rooms/${encodeURIComponent(A)}`,S);return {advert:Gt(j.settings,v),template:st(j.transports)??r.currentRoom?.transports??null}}catch{return H()}},x=(v,S)=>{let A=v??za;return S.length===0?A:A.filter(R=>S.includes(R))},C=async(v,S,A)=>{try{let R=await m(v),{advert:H,template:j}=await w(R.matchId,v.signal),V=x(j,S),k=V.filter(Q=>tp(Q,H)),P=Fn();if(P!==null&&V.includes("webtransport")&&H?.webtransport!==void 0&&i(`[gem] webtransport skipped: ${P} (learned on an earlier dial in this page)`),k.length===0){let Q=j===null?`the default order (${za.join(", ")})`:`the room template's transports (${j.join(", ")||"none"})`;throw new h("misconfigured",`none of ${Q}`+(S.length>0?`, narrowed to (${S.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let L=v.transportAttemptTimeoutMs??Xm,G=()=>v.deadlineAt===void 0?1/0:v.deadlineAt-t.now(),F=Q=>n.signalingReady===void 0||Q<=0?Promise.resolve(!0):n.signalingReady(Q),B=[],re=[];for(let Q of k){if(G()<Xa){i(`[gem] ${Q} rung not tried: the reconnect budget is spent`);break}re.length>0&&R.credentialExpiresAt-t.now()<Qa&&(R=await c(v)),re.push(Q);let K=!1,Se=!1,Re={attempts:0,waitedMs:0};for(;;){if(Q==="webrtc"&&v.redial===!0){let ee=Math.min(Ya,G());await F(ee)||i(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(ee)}ms; offering anyway`);}let De=Math.max(Math.min(L,G()),Xa);try{return y(v,R,Q,await g(Q,v,R,H,A,De),A)}catch(ee){let J=ee instanceof h?ee:new h("connection_failed",ee instanceof Error?ee.message:String(ee),{cause:ee});if(Q==="webrtc"&&Za(a,J),(J.reason==="credential_expired"||J.reason==="credential_reused")&&!K){K=!0,R=await c(v);continue}if(Q==="webrtc"&&J.reason==="signaling_failed"&&J.platformCode===ko&&!Se){Se=!0;let ce=Math.min(Ya,G());if(i(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(ce)}ms for the socket before offering again`),await F(ce))continue}if(J.reason==="join_rate_limited"){let ce=ep(Re,Math.random,G());if(ce!==null){if(Re.attempts+=1,Re.waitedMs+=ce,i(`[gem] ${Q} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ce)}ms before presenting again (retry ${Re.attempts} of ${ol.maxAttempts})`),await Mn(t,ce,v.signal),v.signal?.aborted)throw new h("aborted","the caller aborted while waiting out a join rate limit");R.credentialExpiresAt-t.now()<Qa&&(R=await c(v));continue}}if(Zm.has(J.reason)||J.reason==="credential_expired"||Q==="webrtc"&&rl(J)){i(`[gem] ${Q} rung failed (${J.reason}): ${Dn(J.cause??J)} \u2014 `+(re.length<k.length?`falling through to ${k[re.length]}`:"no rungs left")),B.push(J);break}throw i(`[gem] ${Q} rung refused the session (${J.reason}): ${J.message}`),J}}}let le=B[B.length-1];throw le===void 0?new h("timeout",`the reconnect budget ran out before any transport (${k.join(", ")}) could be tried`):new h(le.reason,`every transport tried (${re.join(", ")}) failed; the last said: ${le.message}`,{cause:B,platformCode:le.platformCode})}catch(R){throw we(A),R}};return {listClusterTargets:async(v={})=>Dr({client:e,...v}),handleMatchEnded(v,S){let A=s.get(v);if(A!==void 0){s.delete(v);for(let R of A)R(S);}},connect:(async(v={})=>{let S=v.signaling??o();return v.transports===void 0?p(v,S):C(v,v.transports,S)})}}var za=["webtransport","webrtc","websocket"],Xm=1e4,Qm=5e3,Ya=3e3,Xa=1e3,Qa=1e4,Zm=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function rl(n){return n.platformCode!==void 0&&xo.has(n.platformCode)}var ol={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function ep(n,e=Math.random,t=1/0){let r=ol;if(n.attempts>=r.maxAttempts)return null;let o=Math.min(r.budgetMs-n.waitedMs,t);if(o<r.initialDelayMs)return null;let i=r.initialDelayMs*r.factor**n.attempts;return Math.min(i+e()*r.jitterMs,o)}function tp(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&$n():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||np(e.websocket.url)}function np(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return un(e)}function Io(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var rp=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Za(n,e){e instanceof h&&(!rp.has(e.reason)&&!rl(e)||n.report([{type:"connection_failures_total",value:1}]));}function op(n,e,t,r,o,i,a,s,l,d){let m=false,c=()=>{m||Ao(n,e.matchId,void 0);};i&&(t.addEventListener("close",c),a&&n.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,t.removeEventListener("close",c),s?.detach(),we(t),we(r),we(o));},g=y=>{if(!m){try{d?.(y);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:t,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:s?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function Co(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function el(n){if(n.status==="failed")throw new h("allocation_failed",`match ${n.matchId} did not come up: ${n.reason}`);if(n.status==="ended")throw new h("match_ended",`match ${n.matchId} ended (${n.reason}) before this side connected.`);if(n.protocol!==Cn)throw new h("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${Cn}' 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 h("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 tl(){let n=globalThis.RTCPeerConnection;if(!n)throw new h("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 we(n){try{n.close();}catch{}}function Zn(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var ip=1e4;function il(n,e){return Mo(n,e)}function Mo(n,e){if(typeof n.serverToken!="function"||typeof n.onServerToken!="function")throw new Error("this runtime delivers no game-server token: host.serverToken/onServerToken are missing. The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let t=a=>({token:a.token,expiresAt:a.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,o=new Ze({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((a,s)=>{let l=e.clock.setTimeout(()=>{r=null,s({reason:"unavailable",retryable:true});},e.timeoutMs??ip);r={resolve:d=>{e.clock.clearTimeout(l),a(d);},reject:s,timer:l};})}),i=n.onServerToken(a=>{let s=t(a),l=r;if(l){r=null,l.resolve(s);return}o.accept(s);});return {source:o,dispose(){i(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var Lo={};$l(Lo,{acceptTransfer:()=>sp,addEntityProgression:()=>ap,adminAction:()=>lp,cancelInventoryTransfer:()=>dp,claimEntityProgressionRewards:()=>cp,closeGameRoom:()=>up,createEntityBatchOrder:()=>mp,createEntityOrder:()=>pp,createSession:()=>gp,deleteEntityGameSetting:()=>yp,deleteEntitySave:()=>fp,deleteSession:()=>hp,executeEntityRecipe:()=>bp,finalizeSaveUpload:()=>vp,getDropRates:()=>_p,getEntityCurrency:()=>wp,getEntityGameSetting:()=>Sp,getEntityInventory:()=>Rp,getEntityInventoryItem:()=>kp,getEntityLeaderboard:()=>xp,getEntityOrder:()=>Ap,getEntityProgression:()=>Pp,getEntityRecipeAvailability:()=>Tp,getEntityRecipeUsage:()=>Ep,getEntitySave:()=>Ip,getEvent:()=>Cp,getGameRoomV2:()=>Mp,getLeaderboard:()=>Op,getPurchaseCatalog:()=>Lp,getResolvedTemplate:()=>Gp,getRoomArgs:()=>Dp,getTransferDetails:()=>$p,ingestAnalyticsEvents:()=>Oo,initiateInventoryTransfer:()=>Fp,invokeFunction:()=>jp,kickPlayer:()=>qp,listChallenges:()=>Np,listEntityGameSettings:()=>Up,listEntityOrders:()=>Bp,listEntityProgressions:()=>Hp,listEntitySaves:()=>Vp,listEvents:()=>Wp,listGameRooms:()=>Kp,listResolvedTemplates:()=>Jp,listTransfers:()=>zp,putEntityGameSetting:()=>Yp,putRoomArgs:()=>Xp,rejectTransfer:()=>Qp,requestSaveUploadUrl:()=>Zp,resetEntityProgression:()=>eg,simulateEntityOrder:()=>tg,transferHostV2:()=>ng,updateGameRoomV2:()=>rg});function b(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 sp(n,e,t){let r=`/v1/inventory/transfers/${b(e)}/accept`;return n.client.post(r,void 0,t?.signal)}async function ap(n,e,t,r,o,i){let a=`/v1/inventory/${b(e)}/${b(t)}/progressions/${b(r)}/add`;return n.client.post(a,o,i?.signal)}async function lp(n,e,t,r){let o=`/v1/voice/sessions/${b(e)}/admin`;return n.client.post(o,t,r?.signal)}async function dp(n,e,t){let r=`/v1/inventory/transfers/${b(e)}/cancel`;return n.client.post(r,void 0,t?.signal)}async function cp(n,e,t,r,o,i){let a=`/v1/inventory/${b(e)}/${b(t)}/progressions/${b(r)}/claim`;return n.client.post(a,o,i?.signal)}async function up(n,e,t){let r=`/v1/games/${b(n.gameId())}/game-rooms/${b(e)}`;return n.client.delete(r,t?.signal)}async function mp(n,e,t,r,o){let i=`/v1/inventory/${b(e)}/${b(t)}/orders/batch`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function pp(n,e,t,r,o){let i=`/v1/inventory/${b(e)}/${b(t)}/orders`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function gp(n,e,t){return n.client.post("/v1/voice/sessions",e,t?.signal)}async function yp(n,e,t,r,o){let i=`/v1/settings/${b(e)}/${b(t)}/${b(r)}`;return n.client.delete(i,o?.signal)}async function fp(n,e,t,r,o){let i=`/v1/saves/${b(e)}/${b(t)}/${b(r)}`;return n.client.delete(i,o?.signal)}async function hp(n,e,t){let r=`/v1/voice/sessions/${b(e)}`;return n.client.delete(r,t?.signal)}async function bp(n,e,t,r,o){let i=`/v1/inventory/${b(e)}/${b(t)}/recipes/execute`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function vp(n,e,t,r,o,i){let a=`/v1/saves/${b(e)}/${b(t)}/${b(r)}/finalize`;return n.client.post(a,o,i?.signal)}async function _p(n,e,t){let r=`/v1/inventory/loot-tables/${b(e)}/drop-rates`;return n.client.get(r,t?.signal)}async function wp(n,e,t,r,o){let i=`/v1/inventory/${b(e)}/${b(t)}/currencies/${b(r)}`;return n.client.get(i,o?.signal)}async function Sp(n,e,t,r,o){let i=`/v1/settings/${b(e)}/${b(t)}/${b(r)}`;return n.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Rp(n,e,t,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),a=`/v1/inventory/${b(e)}/${b(t)}`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function kp(n,e,t,r,o){let i=`/v1/inventory/${b(e)}/${b(t)}/items/${b(r)}`;return n.client.get(i,o?.signal)}async function xp(n,e,t,r,o){let i=new URLSearchParams;o?.bucket_1!==void 0&&i.set("bucket_1",String(o?.bucket_1)),o?.bucket_2!==void 0&&i.set("bucket_2",String(o?.bucket_2)),o?.limit!==void 0&&i.set("limit",String(o?.limit));let a=i.toString(),s=`/v1/leaderboards/${b(e)}/${b(t)}/${b(r)}`+(a?`?${a}`:"");return n.client.get(s,o?.signal)}async function Ap(n,e,t,r,o){let i=`/v1/inventory/${b(e)}/${b(t)}/orders/${b(r)}`;return n.client.get(i,o?.signal)}async function Pp(n,e,t,r,o){let i=`/v1/inventory/${b(e)}/${b(t)}/progressions/${b(r)}`;return n.client.get(i,o?.signal)}async function Tp(n,e,t,r,o,i){let a=`/v1/inventory/${b(e)}/${b(t)}/catalogs/${b(r)}/recipes/${b(o)}/availability`;return n.client.get(a,i?.signal)}async function Ep(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit));let i=o.toString(),a=`/v1/inventory/${b(e)}/${b(t)}/recipe-usage`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function Ip(n,e,t,r,o){let i=`/v1/saves/${b(e)}/${b(t)}/${b(r)}`;return n.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Cp(n,e,t){let r=`/v1/events/${b(e)}`;return n.client.get(r,t?.signal)}async function Mp(n,e,t){let r=`/v2/games/${b(n.gameId())}/game-rooms/${b(e)}`;return n.client.getWithEtag(r,{...t?.signal===void 0?{}:{signal:t.signal},...t?.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}})}async function Op(n,e,t){let r=new URLSearchParams;t?.bucket_1!==void 0&&r.set("bucket_1",String(t?.bucket_1)),t?.bucket_2!==void 0&&r.set("bucket_2",String(t?.bucket_2));let o=r.toString(),i=`/v1/leaderboards/${b(e)}`+(o?`?${o}`:"");return n.client.get(i,t?.signal)}async function Lp(n,e){let t=new URLSearchParams;e?.config_version!==void 0&&t.set("config_version",String(e?.config_version));let r=t.toString(),o="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function Gp(n,e,t){let r=`/v1/game-room-templates/${b(e)}`;return n.client.get(r,t?.signal)}async function Dp(n,e,t){let r=`/v1/games/${b(n.gameId())}/game-rooms/${b(e)}/room-args`;return n.client.get(r,t?.signal)}async function $p(n,e,t){let r=`/v1/inventory/transfers/${b(e)}`;return n.client.get(r,t?.signal)}async function Oo(n,e,t){let r=`/v1/games/${b(n.gameId())}/analytics/events`;return n.client.post(r,e,t?.signal,{replaySafe:true})}async function Fp(n,e,t){return n.client.post("/v1/inventory/transfers",e,t?.signal)}async function jp(n,e,t){return n.client.postBytes("/v1/functions/invoke",e,t?.signal)}async function qp(n,e,t,r){let o=`/v1/games/${b(n.gameId())}/game-rooms/${b(e)}/kick/${b(t)}`;return n.client.post(o,void 0,r?.signal)}async function Np(n,e){let t=new URLSearchParams;e?.periods_back!==void 0&&t.set("periods_back",String(e?.periods_back));let r=t.toString(),o="/v1/challenges"+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function Up(n,e,t,r){let o=`/v1/settings/${b(e)}/${b(t)}`;return n.client.get(o,r?.signal)}async function Bp(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/inventory/${b(e)}/${b(t)}/orders`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function Hp(n,e,t,r){let o=`/v1/inventory/${b(e)}/${b(t)}/progressions`;return n.client.get(o,r?.signal)}async function Vp(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/saves/${b(e)}/${b(t)}`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function Wp(n,e){let t=new URLSearchParams;e?.include_inactive!==void 0&&t.set("include_inactive",String(e?.include_inactive)),e?.limit!==void 0&&t.set("limit",String(e?.limit)),e?.offset!==void 0&&t.set("offset",String(e?.offset));let r=t.toString(),o="/v1/events"+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function Kp(n,e){let t=new URLSearchParams;e?.status!==void 0&&t.set("status",String(e?.status)),e?.game_channel!==void 0&&t.set("game_channel",String(e?.game_channel)),e?.game_room_type!==void 0&&t.set("game_room_type",String(e?.game_room_type)),e?.template_id!==void 0&&t.set("template_id",String(e?.template_id)),e?.template_slug!==void 0&&t.set("template_slug",String(e?.template_slug)),e?.limit!==void 0&&t.set("limit",String(e?.limit)),e?.cursor!==void 0&&t.set("cursor",String(e?.cursor));let r=t.toString(),o=`/v1/games/${b(n.gameId())}/game-rooms`+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function Jp(n,e){return n.client.get("/v1/game-room-templates",e?.signal)}async function zp(n,e){let t=new URLSearchParams;e.entity_type!==void 0&&t.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&t.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&t.set("direction",String(e?.direction)),e?.status!==void 0&&t.set("status",String(e?.status)),e?.cursor!==void 0&&t.set("cursor",String(e?.cursor)),e?.limit!==void 0&&t.set("limit",String(e?.limit));let r=t.toString(),o="/v1/inventory/transfers"+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function Yp(n,e,t,r,o,i){let a=`/v1/settings/${b(e)}/${b(t)}/${b(r)}`;return n.client.put(a,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Xp(n,e,t,r){let o=`/v1/games/${b(n.gameId())}/game-rooms/${b(e)}/room-args`;return n.client.put(o,t,r?.signal)}async function Qp(n,e,t){let r=`/v1/inventory/transfers/${b(e)}/reject`;return n.client.post(r,void 0,t?.signal)}async function Zp(n,e,t,r,o,i){let a=`/v1/saves/${b(e)}/${b(t)}/${b(r)}/upload-url`;return n.client.post(a,o,i?.signal,{replaySafe:true})}async function eg(n,e,t,r,o,i){let a=`/v1/inventory/${b(e)}/${b(t)}/progressions/${b(r)}/reset`;return n.client.post(a,o,i?.signal)}async function tg(n,e,t,r,o){let i=`/v1/inventory/${b(e)}/${b(t)}/orders/simulate`;return n.client.post(i,r,o?.signal)}async function ng(n,e,t,r){let o=`/v2/games/${b(n.gameId())}/game-rooms/${b(e)}/transfer/${b(t)}`;return n.client.post(o,void 0,r?.signal)}async function rg(n,e,t,r){let o=`/v2/games/${b(n.gameId())}/game-rooms/${b(e)}`;return n.client.patch(o,t,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var og=1e4,ig=50,sg=1e3,ag=65536-4*1024,sl=n=>typeof n=="number"?n:0,lg=n=>typeof n=="string"?n:"";function al(){let n=globalThis.crypto;return typeof n?.randomUUID=="function"?n.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.floor(Math.random()*16);return (e==="x"?t:t&3|8).toString(16)})}function dg(n){return n?.retryable===true}function cg(n,e){let t=n??{},r=Array.isArray(t.rejected)?t.rejected.map(o=>{let i=o??{};return {index:sl(i.index),code:lg(i.code)}}):[];return {accepted:sl(t.accepted),rejected:r,dropped:e,duplicate:t.duplicate===true}}function ll(n,e){return {event_uid:n.uid,name:n.name,offset_ms:Math.round(n.atMs)-e,player_id:n.playerId,dimensions:n.dimensions,measures:n.measures}}function dl(n){let e=Math.max(1,Math.floor(n.maxQueue??sg)),t={client:n.client,gameId:()=>n.gameId},r=[],o=0,i=null,a=false,s=false,l=false,d=false,m=w=>{n.log?.(w);},c=()=>{i!==null&&(n.clock.clearTimeout(i),i=null);},p=()=>{i!==null||a||s||(i=n.clock.setTimeout(()=>{i=null,y().catch(()=>{});},og));},g=()=>{let w=Math.min(r.length,100),x=128;for(let C=0;C<w;C+=1){let E=r[C];if(E===void 0)break;if(x+=JSON.stringify(ll(E,0)).length+1,x>ag)return Math.max(1,C)}return w};async function y(w){if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};c();let x=r.splice(0,g()),C=o;o=0;let E=Math.round(n.clock.now()),v={batch_id:al(),sent_at_ms:E,events:x.map(S=>ll(S,E))};s=true;try{let S=await Oo(t,v,w===void 0?void 0:{signal:w}),A=cg(S,C);for(let R of A.rejected)m(`[gem] analytics: an event was refused (${R.code}). See the analytics_events section of your game config.`);return A}catch(S){if(dg(S))for(r=[...x,...r],o+=C;r.length>e;)r.shift(),o+=1;else m(`[gem] analytics: ${x.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(S)}`);throw S}finally{s=false,r.length>0&&p();}}return {track(w,x,C={}){if(a)return;if(typeof w!="string"||w===""){d||(d=true,m(`[gem] analytics: '${x}' was not recorded \u2014 an event from a server has to name the player it is about. A game-server token names no player, so the platform cannot infer one; pass the id from join() or host.players().`));return}if(x.startsWith(Tr)){l||(l=true,m(`[gem] analytics: '${x}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let E={},v={};for(let[S,A]of Object.entries(C))typeof A=="string"?E[S]=A:typeof A=="number"&&Number.isFinite(A)&&(v[S]=A);for(;r.length>=e;)r.shift(),o+=1;r.push({uid:al(),playerId:w,name:x,atMs:n.clock.now(),dimensions:E,measures:v}),r.length>=ig?y().catch(()=>{}):p();},flush:w=>y(w),get pending(){return r.length},dispose(){a=true,c(),r=[],o=0;}}}function ug(n){let e={};for(let[t,r]of Object.entries(Lo))if(typeof r=="function"){let o=r;e[t]=(...i)=>o(n,...i);}return e}function pt(n,e={}){let t=e.clock??ae,r=e.baseUrl??n.apiBaseUrl;if(!r)throw new Error("this runtime names no gem-api host (host.apiBaseUrl is missing). The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let o=Mo(n,{clock:t,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),i=Xn({baseUrl:r,tokenSource:o.source,defaultQuery:{game_id:n.gameId,channel:n.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),a=new Ie({transport:i,clock:t}),s={gameId:n.gameId,channel:n.channel,matchId:n.matchId,...n.gameRoomId===void 0?{}:{gameRoomId:n.gameRoomId}},l=ug({client:a,gameId:()=>s.gameId}),d=s.gameRoomId,m=n.endMatch,c=n.log,p=dl({client:a,clock:t,gameId:s.gameId,...typeof c=="function"?{log:y=>c.call(n,y)}:{}});return {identity:s,client:a,api:l,match:{end:async()=>{if(m===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await m.call(n);}},analytics:p,functions:new Ce(l.invokeFunction),...d===void 0?{}:{room:{get:y=>l.getGameRoomV2(d,y),args:y=>l.getRoomArgs(d,y)}},dispose:()=>{p.dispose(),o.dispose();}}}function Ke(n){return n?.reliable!==false?"reliable":n?.ordered!==false?"ordered":"unreliable"}function gt(n){return {reliable:n==="reliable",ordered:n!=="unreliable"}}function Xt(n){return typeof n=="string"?n:n.slice().buffer}function er(n){if(typeof n=="string")return {data:n,isText:true};if(n instanceof ArrayBuffer)return {data:new Uint8Array(n),isText:false};if(ArrayBuffer.isView(n)){let e=n;return {data:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),isText:false}}return null}var mg=5e3,cl=3e4,ul=2e3,pg=1e4,ml=1;async function pl(n,e){let{session:t,localPlayerId:r}=e;if(!t.isHost)throw new Error("[gem] runListenHost was handed a session this player does not host. The room decides who hosts; gate on `gem.rooms.isHost` \u2014 or call `gem.match.serve()`, which does.");let o=e.log===void 0?f=>console.info(f):e.log,i=f=>o?.(`[gem host] ${f}`),a=typeof n=="function"?n():n,s=Promise.resolve(),l=true,d=false,m=(f,T)=>{l&&(s=s.then(async()=>{if(!d)try{await T();}catch($){i(`the bundle's ${f} handler threw: ${Je($)}. Serving continues.`);}}));},c=true,p,g,y,w=f=>{if(!c)return;c=false,m("leave",()=>a.leave?.(r,{cause:f??"left"}));let T=g;T&&queueMicrotask(()=>T(f));},x={send(f,T){if(!c)return;let $=gt(Ke(T));m("message",()=>a.message?.(r,f,typeof f=="string",{reliable:$.reliable,ordered:$.ordered}));},onMessage(f){p=f;},onClose(f){g=f;},close(){w("closed");}},C=(f,T)=>{if(!c)return;let $=gt(Ke(T));queueMicrotask(()=>{c&&p?.(f,$);});},E=new Map,v=f=>{let T=[];for(let $ of Ee){let Z=f.channels[$];try{Z.binaryType="arraybuffer";}catch{}let ke=gt($),yt=ze=>{let $e=er(ze?.data);$e!==null&&m("message",()=>a.message?.(f.playerId,$e.data,$e.isText,{reliable:ke.reliable,ordered:ke.ordered}));};Z.addEventListener("message",yt),T.push(()=>Z.removeEventListener("message",yt));}E.get(f.playerId)?.forEach($=>$()),E.set(f.playerId,T);},S=f=>{E.get(f)?.forEach(T=>T()),E.delete(f);},A=new Set,R=new Map,H=(f,T,$)=>({playerNumber:f.assignedPeerId,transport:"webrtc_p2p",...T?{rejoin:true}:{},...$?{superseded:true}:{}}),j=f=>{let T=E.has(f.playerId),$=A.has(f.playerId);A.add(f.playerId),v(f),T&&m("leave",()=>a.leave?.(f.playerId,{cause:"superseded"})),m("join",()=>a.join?.(f.playerId,H(f,$,T)));},V=new Set,k=(f,T,$)=>{if(f===r){C(T,$);return}let Z=t.peer(f);if(Z===null){let ke=R.get(f);if(ke!==void 0&&e.clock.now()-ke<ul)return;V.has(f)||(V.add(f),i(`send to '${f}' dropped: no such connected player`));return}Z.send(Xt(T),Ke($));},P={matchId:t.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:f=>e.tokens.subscribe(f),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(f=>f.playerId)??[],players(){let f=c?[r]:[];for(let T of t.peers)f.push(T.playerId);return f},profile(f){let T=e.room()?.members.find($=>$.playerId===f);if(!(!T||T.displayName===void 0))return {displayName:je.toPlain(T.displayName),...T.displayTag===void 0?{}:{displayTag:je.toPlain(T.displayTag)},...T.discriminator===void 0?{}:{discriminator:T.discriminator}}},playerNumber(f){return f===r?ml:t.peer(f)?.assignedPeerId},send(f,T,$){k(f,T,$);},broadcast(f,T){let $=T?.except;c&&r!==$&&C(f,T);for(let Z of t.peers)Z.playerId!==$&&Z.send(Xt(f),Ke(T));},async endMatch(){let f=await De();return f.answer!=="ok"&&i(f.cause),f.answer},kick(f,T){if(f===r){w(T??"kicked");return}t.kick(f).catch($=>{i(`kick of '${f}' failed: ${Je($)}`);});},log(f){i(f);},warn(f){i(`\u26A0 ${f}`);}},L=()=>{},G=new Promise(f=>{L=f;}),F=[],B=null,re=async(f,T)=>{l=false;let $=s.then(async()=>{try{await a.shutdown(f);}catch(Z){i(`the bundle's shutdown threw: ${Je(Z)}`);}});s=$,await $,ce();for(let Z of F.splice(0))Z();for(let Z of [...E.keys()])S(Z);w(T);},le=(f,T)=>B||(B=(async()=>{await re(T,f),t.close(),L();})(),B),Q=()=>B||(B=(async()=>{await re({reason:"signal"},"left"),await t.leave().catch(f=>i(`leaving the match failed: ${Je(f)}`)),L();})(),B),K=()=>B||(B=(async()=>{l=false;let f=await De();f.answer==="ok"?(await re({reason:"match_ended",platform_reason:"explicit"},"match ended"),t.close()):(i(`${f.cause}; leaving instead`),await re({reason:"signal"},"left"),await t.leave().catch(T=>i(`leaving the match failed: ${Je(T)}`))),L();})(),B),Se=null,Re=()=>(Se??=pt(P,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),Se),De=async()=>{try{return await Ui({client:Re().client,gameId:()=>P.gameId},P.matchId,{},{signal:AbortSignal.timeout(mg)}),{answer:"ok"}}catch(f){return f instanceof D&&(f.reason==="forbidden"||f.reason==="not_found")?{answer:f.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${f.reason})`}:{answer:"failed",cause:`ending the match failed: ${Je(f)}`}}},ee=null,J=false,ce=()=>{J=true,ee!==null&&(e.clock.clearTimeout(ee),ee=null);},X=async()=>{if(ee=null,!J){try{await Re().client.post(`/v1/games/${encodeURIComponent(P.gameId)}/matches/${encodeURIComponent(P.matchId)}/heartbeat`,void 0,AbortSignal.timeout(pg));}catch(f){if(f instanceof D&&(f.reason==="forbidden"||f.reason==="not_found")){i(`the platform no longer holds this match under this host (${f.reason}); heartbeats stop`),ce();return}i(`heartbeat failed: ${Je(f)}`);}J||(ee=e.clock.setTimeout(()=>{X();},cl));}},en=()=>{J||ee!==null||(ee=e.clock.setTimeout(()=>{X();},cl));};{let f=L;L=()=>{ce(),Se?.dispose(),Se=null,f();};}let tn=Promise.resolve().then(()=>a.init(P));s=tn.then(()=>{},()=>{}),m("join",()=>a.join?.(r,{playerNumber:ml,transport:"loopback"})),F.push(t.on("peerJoined",j)),F.push(t.on("peerLeft",(f,T)=>{S(f);let $=e.clock.now();for(let[Z,ke]of R)$-ke>=ul&&R.delete(Z);R.set(f,$),V.delete(f),m("leave",()=>a.leave?.(f,{cause:T}));})),F.push(t.on("error",f=>{i(`\u26A0 session error: ${f.message}`);})),F.push(t.on("matchEnded",f=>{B||Go(y,f),le("match ended",{reason:"match_ended",platform_reason:f});})),F.push(t.on("hostChanged",f=>{f!==r&&le("host migrated",{reason:"host_migrated"});}));for(let f of t.peers)j(f);try{await tn,en();}catch(f){l=false,ce(),d=true;for(let T of F.splice(0))T();for(let T of [...E.keys()])S(T);throw t.leave().catch(()=>{}),L(),f}return {matchId:t.matchId,localLink:x,onMatchEnded(f){y=f;},end:K,leave:Q,stop:f=>le(f,{reason:"stopped"}),done:G}}function Go(n,e){try{n?.(e);}catch{}}function Je(n){return n instanceof Error?n.message:String(n)}function Do(n,e){let t=async()=>{throw new h("misconfigured",`this seat is \`${n}\`, not the match's authority: `+(n==="dedicated"?"the platform runs the server, and its bundle ends the match with gem.match.end().":"another player hosts this match."))};return {mode:n,matchId:e,end:t,leave:t,stop:async()=>{}}}function gl(n){let e=new Map,t=n.autoReconnect===true,{rooms:r}=n,o=new Map,i=async s=>{r.isHost&&!Co(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...s.signal===void 0?{}:{signal:s.signal}});let l={...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},a=s=>({...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0?{}:{clusterTargetId:s.clusterTargetId}});return {async serve(s,l={}){let d=await i(l);if(d.protocol!==Ve)return Do("dedicated",d.matchId);let m=n.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return Do("peer",d.matchId);let c=n.identity();if(c===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=m??await n.p2p.connect(a(l)),g=await pl(s,{session:p,clock:n.clock,gameId:c.gameId,channel:c.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:n.apiBaseUrl(),tokens:n.tokens,room:n.room,localPlayerId:p.playerId!==""?p.playerId:c.playerId,...n.log===void 0?{}:{log:n.log},...n.fetch===void 0?{}:{fetch:n.fetch}});return o.set(d.matchId,g),g.done.then(()=>{o.get(d.matchId)===g&&o.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(s={}){let l=await i(s),d=s.onMatchEnded;if(l.protocol===Ve){let g=o.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),hg(l.matchId,g,d);if(r.isHost)throw new Error("[gem] this player hosts the P2P match, so there is no one to connect TO yet. Call gem.match.serve(yourServer) first; connect() then resolves the loopback to your own bundle.");let y=await Ht(),w=async()=>n.p2p.connect({...a(s),certificate:y}),x=await w(),C=vg(x,w,d,E=>{r.notifyMatchDisconnected(E).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),t);return t&&(e.set(x.matchId,{redial:C.redial,abandon:C.abandon}),C.onClosed(()=>{e.get(x.matchId)?.abandon===C.abandon&&e.delete(x.matchId);})),C}let m=async(g=null)=>await n.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:s.transports??[]}),c=await m(),p=bg(c,m,r,t);return t&&(e.set(c.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(c.matchId)?.abandon===p.abandon&&e.delete(c.matchId);})),p},async redialMatch(s,l){let d=e.get(s);return d===void 0?"closed":d.redial(l)},abandonMatch(s,l){e.get(s)?.abandon(l);}}}var yl="link_closed",gg="host_unreachable",yg=new Set(["failed","closed"]);function fg(n){return yg.has(n)?yl:gg}function hg(n,e,t){let r=e.localLink;e.onMatchEnded(t);let o="connected";r.onClose(()=>{o="closed";});let i;return {matchId:n,protocol:"loopback",get state(){return o},send:(a,s)=>r.send(a,s),onMessage:a=>r.onMessage(a),onClose:a=>{i=a,r.onClose(s=>{o="closed",i?.(s);});},close:()=>r.close()}}function bg(n,e,t,r){let o=n.matchId,i=n,a="connected",s,l,d=[],m=false,c=false,p=y=>{if(a!=="closed"){a="closed";for(let w of d.splice(0))w();l?.(y);}},g=y=>{y.link.onMessage((w,x)=>s?.(w,x)),y.link.onClose(w=>{if(y!==i||a==="closed")return;if(m||!r){p(w);return}let x=t.matchSession;if(x.phase==="suspended"&&x.matchId===o){a="suspended";return}p(w);});};return g(n),{matchId:o,protocol:"dedicated",get transport(){return i.transport},get state(){return a},send(y,w){a==="connected"&&i.link.send(y,w);},onMessage(y){s=y;},onClose(y){l=y;},close(){if(a!=="closed"){if(m=true,a==="suspended"){p("closed");return}i.close(),p("closed");}},async redial(y){if(a==="closed"||m)return "closed";if(c)return "connected";c=true;let w;try{w=await e(y===void 0?{}:{deadlineAt:y});}finally{c=false;}return m||a==="closed"?(w.close(),"closed"):(i=w,g(w),a="connected",t.notifyMatchConnected(o),"connected")},abandon(y){a!=="closed"&&(a==="connected"&&i.close(),p(y));},onClosed(y){a==="closed"?y():d.push(y);}}}function vg(n,e,t,r,o,i=false){let a=n.matchId,s=n,l,d,m=[],c=[],p=[],g=false,y=false,w=false,x=false,C="connected",E=k=>{if(g)return;g=true,C="closed";for(let L of m.splice(0))L();for(let L of c.splice(0))L();for(let L of p.splice(0))L();let P=d;P&&queueMicrotask(()=>P(k));},v=k=>{for(let P of m.splice(0))P();for(let P of Ee){let L=k.channels[P];try{L.binaryType="arraybuffer";}catch{}let G=gt(P),F=B=>{let re=er(B?.data);re!==null&&l?.(re.data,G);};L.addEventListener("message",F),m.push(()=>L.removeEventListener("message",F));}},S=()=>s.peer(s.hostPlayerId),A=k=>{if(!(g||s.isHost)&&C!=="suspended"){if(r?.(k),i){C="suspended";return}E(k);}},R=k=>{for(let P of Ee){let L=k.channels[P];if(typeof L.addEventListener!="function")continue;let G=()=>{S()===k&&A(yl);};L.addEventListener("close",G),m.push(()=>L.removeEventListener?.("close",G));}},H=k=>{v(k),R(k),!g&&(C="connected",o?.());},j=k=>{for(let P of c.splice(0))P();c.push(k.on("migrating",()=>{x=true;})),c.push(k.on("hostChanged",P=>{if(x=false,P===k.playerId){E("host_migrated_here");return}let L=S();L!==null&&H(L);})),c.push(k.on("peerJoined",P=>{P.playerId===k.hostPlayerId&&H(P);})),c.push(k.on("matchEnded",P=>{g||Go(t,P),E(P);})),c.push(k.on("peerLeft",(P,L)=>{P===k.hostPlayerId&&A(fg(L));}));};j(s);let V=S();return V!==null&&H(V),{matchId:a,protocol:"p2p",get state(){return C},send(k,P){C==="connected"&&S()?.send(Xt(k),Ke(P));},onMessage(k){l=k;},onClose(k){d=k;},close(){y=true,E("closed"),s.leave().catch(()=>{});},async redial(){if(C==="closed")return "closed";if(C==="connected"||w)return "connected";if(x)throw new O("connection_failed","a host migration is in flight, and it is the way back \u2014 this attempt waits it out rather than tearing down the session the platform is moving");w=true;let k;try{for(let L of m.splice(0))L();for(let L of c.splice(0))L();s.close(),k=await e();}finally{w=false;}if(g)return y?k.leave().catch(()=>{}):k.close(),"closed";s=k,j(s);let P=S();if(P===null)throw s.close(),new O("connection_failed","this peer rejoined the match but the host never answered with a link");return H(P),"connected"},abandon(k){E(k);},onClosed(k){g?k():p.push(k);}}}function $o(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(o=>{let i={},a=l=>{t.delete(r)&&(n.clock.clearTimeout(i.timer),o(l));};t.set(r,a),i.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,o){t.get(r)?.(o);}}}var _g=0;function Ge(){try{return crypto.randomUUID()}catch{let n=Math.random().toString(36).slice(2,10);return `local-${String(++_g)}-${String(Date.now())}-${n}`}}var wg=12e4;function fl(n){let e=false,t=new Map;return {api:{request(r){if(!n.bridge.parentSupports("purchases"))return Promise.resolve({outcome:"unavailable"});if(e)return Promise.resolve({outcome:"declined"});let o=`purchase-${Ge()}`;return new Promise(i=>{let a={},s=d=>{t.delete(o)&&(e=false,n.clock.clearTimeout(a.timer),i(d));};e=true,t.set(o,s),a.timer=n.clock.setTimeout(()=>s({outcome:"unavailable"}),n.timeoutMs??wg);let l=false;try{l=n.bridge.requestPurchase(o,r.kind,r.targetId,r.currencySlug,r.quantity,r.catalogId);}catch{}l||s({outcome:"unavailable"});})}},settle(r){let o=r.outcome==="ok"||r.outcome==="declined"?r.outcome:"unavailable",i=t.get(r.requestId);if(i===void 0){n.onDropped?.(`gem.purchaseResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}if(o!=="ok"){i({outcome:o});return}let a=r.purchaseId;if(a===void 0){n.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),i({outcome:"unavailable"});return}(async()=>{let s;try{s=await n.confirm(a);}catch{s="unknown";}if(s==="granted"){i({outcome:"ok",purchaseId:a});return}s==="absent"&&n.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for purchase "+JSON.stringify(a)),i({outcome:"unavailable"});})();}}}async function hl(n,e){try{return (await Pi(n,e)).granted?"granted":"absent"}catch(t){return t instanceof D&&t.reason==="not_found"?"absent":"unknown"}}var Sg=6e5;function bl(n){let e=null,t=new Map;return {api:{requestSignIn(){if(!n.bridge.parentSupports("signIn"))return Promise.resolve({outcome:"unavailable"});if(e!==null)return e;let r=`signin-${Ge()}`;return e=new Promise(o=>{let i={},a=l=>{t.delete(r)&&(e=null,n.clock.clearTimeout(i.timer),o(l));};t.set(r,a),i.timer=n.clock.setTimeout(()=>{a({outcome:"unavailable"});},n.timeoutMs??Sg);let s=false;try{s=n.bridge.requestSignIn(r);}catch{}s||a({outcome:"unavailable"});}),e}},settle(r){let o=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",i=t.get(r.requestId);if(i===void 0){n.onDropped?.(`gem.signInResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}i({outcome:o});}}}var Rg=18e4,vl=32,kg=/^[a-z0-9_-]+$/;function xg(n){return n==="interstitial"||n==="rewarded"}function _l(n){let e=false,t=new Map;return {api:{requestAd(r){if(!n.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});if(typeof r.placement!="string"||r.placement===""||r.placement.length>vl||!kg.test(r.placement)||!xg(r.format))return n.onDropped?.(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${JSON.stringify(r.placement)}, format ${JSON.stringify(r.format)}. A placement is 1..${String(vl)} characters of a-z, 0-9, '-' and '_' \u2014 the grammar the platform's own ad endpoint accepts \u2014 and a format is 'interstitial' or 'rewarded'. Answering no_ad.`),Promise.resolve({outcome:"no_ad"});let o=`ad-${Ge()}`,i=r.format,a=r.placement;return new Promise(s=>{let l={},d=c=>{t.delete(o)&&(e=false,n.clock.clearTimeout(l.timer),s(c));};e=true,t.set(o,d),l.timer=n.clock.setTimeout(()=>{d({outcome:"unavailable"});},n.timeoutMs??Rg);let m=false;try{m=n.bridge.requestAd(o,a,i);}catch{}m||d({outcome:"no_ad"});})}},settle(r){let o=r.outcome==="shown"||r.outcome==="no_ad"?r.outcome:"unavailable",i=t.get(r.requestId);if(i===void 0){n.onDropped?.(`gem.adResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}i({outcome:o});}}}var Fo=16384;function wl(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:Ag(e)}function Ag(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 o=n.charCodeAt(t+1);o>=56320&&o<=57343?(e+=4,t+=1):e+=3;}else e+=3;}return e}var Pg=1e4,Tg=5e3;function Sl(n){let e=null,t=false,r=[],o=new Map,i=()=>{for(let a of r.splice(0))a();};return {api:{get current(){return e},wait(a=Tg){return t?Promise.resolve(e):new Promise(s=>{let l=()=>{let c=r.indexOf(d);c>=0&&r.splice(c,1);},d=()=>{n.clock.clearTimeout(m),l(),s(e);},m=n.clock.setTimeout(()=>{l(),s(e);},a);r.push(d);})},put(a){if(!n.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let s=wl(a);if(s===null)return n.onDropped?.("gem.deviceSettings.put refused locally: settings must be a plain JSON object (not a primitive, an array, null, or something JSON.stringify cannot take)"),Promise.resolve("unavailable");if(s>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(a)),d=`device-settings-${Ge()}`;return new Promise(m=>{let c={},p=y=>{o.delete(d)&&(n.clock.clearTimeout(c.timer),y==="stored"&&(e=l,t=true,i()),m(y));};o.set(d,p),c.timer=n.clock.setTimeout(()=>p("unavailable"),n.timeoutMs??Pg);let g=false;try{g=n.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(a){let s=a.settings;e=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:null,t=true,i();},settle(a){let s=a.outcome==="stored"||a.outcome==="too_large"?a.outcome:"unavailable",l=o.get(a.requestId);if(l===void 0){n.onDropped?.(`gem.deviceSettings.result (${s}) for an unknown requestId: `+JSON.stringify(a.requestId));return}l(s);}}}function Rl(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function kl(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function Eg(n){let e=n.untrusted,t=ye(e.displayName),r=e.displayTag||e.displayHandle,o=r?ye(r):void 0,i=n.discriminator||n.displayTag,a=i&&/^[0-9]{1,8}$/.test(i)?i:void 0,s=n.avatarIconUrl||n.avatarUrl,l={displayName:t,displayHandle:o??t,badges:(n.badges??[]).map(p=>({itemId:p.itemId,iconUrl:p.iconUrl}))};n.playerId&&(l.playerId=n.playerId),a&&(l.discriminator=a),o&&(l.displayTag=o),s&&(l.avatarIconUrl=l.avatarUrl=s);let d=n.boost,m=(d?.multipliers??[]).map(p=>({currencyId:p.currencyId,currencySlug:p.currencySlug,multiplier:p.multiplierBp/1e4})),c=m.some(p=>p.multiplier>1);return l.boost=c&&d?.expiresInDays?{active:c,multipliers:m,expiresInDays:d.expiresInDays}:{active:c,multipliers:m},l}var Ig=1e4,Qt=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??ae,this.inbound=new bt(this.clock),this.outbound=new bt(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(s=>mr(s,e.origin))||rs(e.origin,this.options.selfOrigin)))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=cn["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let o=e.data;if(!mr(o.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${o.embedder}' but arrived from '${e.origin}'`),false;let i=e.ports?.[0];if(!i)return this.refuse(e,"handshake transferred no MessagePort"),false;let a=os(ln,o.versions);return a===null?(i.onmessage=null,i.postMessage({gem:z,type:"gem.error",code:"version_mismatch",message:`frame supports v${ln.min}..v${ln.max}`}),i.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=i,this.version=a,i.onmessage=s=>this.receive(s.data,s.ports??[]),i.start?.(),this.peerCapabilities=o.capabilities??[],i.postMessage({gem:z,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:z,type:"gem.ready"});}settled(e=Ig){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(t=>{let r=i=>{this.clock.clearTimeout(o),t(i);},o=this.clock.setTimeout(()=>{let i=this.settleWaiters.indexOf(r);i>=0&&this.settleWaiters.splice(i,1),t(this.state);},e);this.settleWaiters.push(r);})}progress(e,t){this.send({gem:z,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:z,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:z,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),true):false}exit(e){this.send(e===void 0?{gem:z,type:"gem.exit"}:{gem:z,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:z,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:z,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:z,type:"gem.audioState",muted:e}),true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let t={gem:z,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:Rl(e.origin.x),y:Rl(e.origin.y)}),this.send(t),true}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:z,type:"gem.frameStats",fps:kl(e.fps,1e3),frameTimeP95Ms:kl(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:z,type:"gem.gameContext",context:e}),true)}signal(e,t,r){this.send({gem:z,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:z,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:z,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,o,i,a){return this.send({gem:z,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:o,...i===void 0?{}:{quantity:i},...a===void 0?{}:{catalogId:a}})}putDeviceSettings(e,t){return this.send({gem:z,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:z,type:"gem.requestAd",requestId:e,placement:t,format:r})}requestSignIn(e){return this.send({gem:z,type:"gem.requestSignIn",requestId:e})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let t of this.settleWaiters.splice(0))t(e);this.options.onStateChange?.(e);}}refuseMalformed(e,t){if(!this.inbound.allow(dn)){this.options.onDropped?.(e,t);return}this.fail(e,t);}dropUnknownType(e){this.inbound.allow(dn)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,t){e.ports?.[0]?.close?.(),this.inbound.allow(dn)&&this.options.onRefused?.(t);}fail(e,t){this.options.onError?.(e,t),this.state==="connected"&&this.port&&this.send({gem:z,type:"gem.error",code:e,...t===void 0?{}:{message:t}});}send(e){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let t=e.type;if(!this.outbound.allow(t))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${t}`),false;let r=cn[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||xl(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 o=cn[r];if(!o)return this.dropUnknownType(r),false;if(!this.inbound.allow(r))return this.fail("rate_limited",`parent exceeded the limit for ${r}`),false;let i=es(r);if(i!==void 0&&!this.options.capabilities?.includes(i))return this.fail("unsupported_capability",`${r} requires the '${i}' capability, which this frame did not advertise`),false;let a=o(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.prefs":this.options.onPrefs?.(s);break;case "gem.cohorts":this.options.onCohorts?.(s);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 xl(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?.(Eg(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.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.signInResult":this.options.onSignInResult?.(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:z,type:"gem.screenshot.denied",reason:e,retryable:t});}};function xl(n){for(let e of n)try{e?.close?.();}catch{}}var Al="https://api.gemarcade.com";function jo(n){let e;try{e=new URL(n);}catch{return "it is not a valid URL"}return e.protocol!=="https:"&&e.protocol!=="http:"?`its scheme is ${e.protocol.replace(":","")}, and only http and https can be used`:e.username!==""||e.password!==""?"it carries credentials in the URL, which `fetch` will not send":e.href.includes("#")?"it carries a fragment. The transport joins the base and the path by concatenation, so the fragment would swallow the path and every request would go to the API root":e.href.includes("?")?"it carries a query string. The transport joins the base and the path by concatenation, so the query would swallow the path and every request would go to the API root":null}var Cg=new Set(["localhost","127.0.0.1","[::1]"]);function Pl(n){let e=jo(n);if(e!==null)return e;let t=new URL(n);return t.protocol==="http:"&&!Cg.has(t.hostname)?"it is a plaintext http address that is not loopback. An embedder may name an https root, or http on localhost for a rig running the whole stack on one machine \u2014 the play token travels on every request to it":null}var Mg=Object.freeze(["https://gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),Og=Al,Tl=8e3,qo=15e3,Lg=9e4,Gg=1/0,Dg=8e3,$g=5e3,Fg=5e3;async function jg(n,e,t,r){if(n.isInRoom)try{await n.leave();}catch{}r?.endSession("session_ended"),e!==null&&e.currentState==="connected"&&e.exit(t);}function Zt(n){let e=null,t=[];return {get current(){return e},set(r){e=r;for(let o of t.splice(0))o(r);},wait(r){return e!==null?Promise.resolve(e):new Promise(o=>{let i=()=>{let l=t.indexOf(a);l>=0&&t.splice(l,1);},a=l=>{n.clearTimeout(s),i(),o(l);},s=n.setTimeout(()=>{i(),o(e);},r);t.push(a);})}}}function V_(n={}){let e=n.clock??ae,t=n.log===void 0?u=>console.info(u):n.log,r=n.baseUrl??void 0;if(r!=null){let u=jo(r);if(u!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${u}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let o=wo();o.mark("sdk created");let i=()=>On(X.gameVersion,n.clientVersion?.gameVersion),a=new It({client:()=>Xe,clock:e,gameId:()=>X.identity?.gameId??null,playerId:()=>X.identity?.playerId??null,environment:()=>{let u=i();return {sdk_version:Ko(),...u===null?{}:{game_version:u}}},...n.analytics===void 0?{}:{options:n.analytics},log:t}),s=u=>{if(u===false)return null;let I=u?.attempts??Gg,q=u?.budgetMs??Lg;return !(I>0)||!(q>0)?null:{attempts:I,budgetMs:q,maxDelayMs:u?.maxDelayMs??Dg}},l=u=>{u.on("created",()=>{o.mark("room created");}),u.on("joined",()=>{o.mark("room joined");}),u.on("matchAllocationStarted",()=>{o.mark("allocation started");}),u.on("matchReady",()=>{o.mark("match ready");}),u.on("matchFailed",()=>{o.mark("match failed");});};if(typeof window>"u")throw new Error("createGem: there is no `window` in this environment, so the SDK has no document to listen on and no embedder to hand it a port. A game runs in a browser; if this is a server-side render or a node process, do not construct the SDK there.");let d=n.allowedEmbedders;if(d!=null&&!Array.isArray(d))throw new Error("createGem: `allowedEmbedders` must be an array of origins, e.g. `['https://my-own-site.example']`. The Gem Arcade is allowed without any entry.");let m=Array.from(d??[]),c=m.filter(u=>typeof u!="string"||!ur(u));if(c.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${c.length===1?"an entry":"entries"} that ${c.length===1?"is":"are"} not an origin: ${c.map(u=>typeof u=="string"?JSON.stringify(u):String(u)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let p=Object.freeze([...new Set([...Mg,...m])]),g=Zt(e),y=Zt(e),w=Zt(e),x=Zt(e),C=n.manageAudio===false?null:Ma(),E=null,v=()=>{E!==null&&(y.current!==null&&y.current.muted===E||K.reportMuted(E));},S=Oa({report:u=>K.reportFrameStats(u)}),A=false,R=$a(()=>Wo,()=>A),H=u=>{let I=A&&!u,q=A!==u;if(A=u,I&&R.close(),!!q)try{n.onDevToolsPermissionChange?.(u);}catch(me){t?.(`[gem] onDevToolsPermissionChange threw: ${me instanceof Error?me.message:String(me)}`),queueMicrotask(()=>{throw me});}},j=r??Og,V=r!==void 0,k,P=u=>(t?.(`[gem] token refused: ${u}`),n.onError?.("internal",u),false),L=(u,I)=>{if(u===void 0)return I!==void 0?P("the embedder named a backend by tag, which this build no longer resolves \u2014 it needs `apiBaseUrl` on `gem.token`. The token was refused rather than sent to the default: silently resolving production is how a development session writes to the live backend."):true;let q=Pl(u);return q!==null?P(`the embedder named an API root that cannot be used: ${q}. Its value is withheld here rather than written to logs.`):k!==void 0&&k!==u?P("the embedder named a different API root than it named on this session\u2019s first token. The address is fixed by the first grant, so a later message cannot repoint a running game; both values are withheld here."):(k=u,V||(j=u),true)},G=window.location?.origin,F=null,B=-1/0,re=2e3,le=new Set,Q=u=>F!==false?Promise.resolve(true):new Promise(I=>{let q=e.setTimeout(()=>{le.delete(me),I(false);},u),me=()=>{e.clearTimeout(q),le.delete(me),I(true);};le.add(me);}),K=new Qt({allowedEmbedders:p,...typeof G=="string"&&G!==""?{selfOrigin:G}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","frameStats","viewport","purchases","deviceSettings","ads","signIn",...n.onFeedbackContext!==void 0?["feedbackContext"]:[]],...n.onRefused===void 0?{}:{onRefused:n.onRefused},...n.onError===void 0?{}:{onError:n.onError},onStateChange:u=>{X.onBridgeState(u),u!=="connected"&&S.setRequested(false),u==="connected"&&(o.mark("bridge connected"),tn(),v(),a.startSession()),n.onStateChange?.(u);},onPlayer:u=>{g.set(u),n.onPlayer?.(u);},onPrefs:u=>{let I={reducedMotion:u.reducedMotion,muted:u.muted,locale:u.locale,showFrameStats:u.showFrameStats===true};y.set(I),C?.setMuted(I.muted),S.setRequested(I.showFrameStats&&K.parentSupports("frameStats")),n.onPrefs?.(I);},onCohorts:u=>{let I=Object.freeze(u.cohorts.map(q=>Object.freeze({experimentId:q.experimentId,variantKey:q.variantKey})));w.set(I),n.onCohorts?.(I);},onViewport:u=>{let I=Object.freeze({insets:Object.freeze({top:u.insets.top,right:u.insets.right,bottom:u.insets.bottom,left:u.insets.left})});x.set(I),Ga(La(),I.insets),n.onViewport?.(I);},onPause:u=>{a.setPaused(u.paused),S.setPaused(u.paused),n.onPause?.(u.paused);},onWillTerminate:u=>{a.endSession(u.reason),n.onWillTerminate?.({reason:u.reason,graceMs:u.graceMs});},onToken:u=>{let I=u.garden;if(H(u.allowDevTools===true),!L(u.apiBaseUrl,I))return;let q=u;X.onToken(q);let me=X.identity;me&&(Re.set(me),De||(De=true,ue.reconcileSeats().catch(()=>{}))),ce.push({token:q.token,expiresAt:q.expiresAt});},onTokenDenied:u=>{H(false),X.onDenied(u);},onScreenshot:(u,I,q)=>{Ea(u,I,q,{...n.onScreenshot===void 0?{}:{handler:n.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{Ia(K,n.onFeedbackContext);},onDevtools:u=>{u==="close"?R.close():u==="open"?R.openFrom("platform").catch(()=>{}):R.isOpen?R.close():R.openFrom("platform").catch(()=>{});},onRoomEvent:u=>ue.handleRoomEvent({event:u.event,roomId:u.roomId,...u.matchId===void 0?{}:{matchId:u.matchId},...u.version===void 0?{}:{version:u.version},...u.reason===void 0?{}:{reason:u.reason},...u.platform===void 0?{}:{platform:u.platform}}),onSeatedEvent:u=>ue.handleSeated(u.roomId),onAutoStartFailedEvent:u=>ue.handleAutoStartFailed(u.roomId,u.code),onSocketState:u=>{let I=F;if(F=u.connected,u.connected)for(let me of [...le])me();if(!u.connected||I===true)return;let q=e.now();q-B<re||(B=q,ue.reconcile().catch(()=>{}));},onSignalEvent:u=>{let I=typeof u.data=="object"&&u.data!==null&&!Array.isArray(u.data)?u.data:{};Qe.handleSignalEvent(u.matchId,u.event,I),u.event==="matchEnded"&&ue.reconcile({matchId:u.matchId,...typeof I.reason=="string"?{reason:I.reason}:{}}).catch(()=>{});},onDedicatedEvent:u=>{u.event==="matchEnded"&&(ft.handleMatchEnded(u.matchId,u.reason),ue.reconcile({matchId:u.matchId,...u.reason===void 0?{}:{reason:u.reason}}).catch(()=>{})),Se.handleEvent(u);},onClusterTarget:u=>ze.accept(u.clusterTargetId,u.clusterTargetIds),onLocalServer:u=>$e.accept(u),onLocalServerDenied:u=>$e.refuse(u),onPartyResult:u=>f.settle(u.requestId,u.partyId),onPurchaseResult:u=>$.settle(u),onDeviceSettings:u=>{Z.receive(u),n.onDeviceSettings?.(Z.api.current);},onDeviceSettingsResult:u=>Z.settle(u),onAdResult:u=>ke.settle(u),onSignInResult:u=>yt.settle(u)}),Se=new Yt({bridge:K}),Re=Zt(e),De=false,ee=new Set,J,ce={current:()=>J,subscribe:u=>(ee.add(u),J!==void 0&&u(J),()=>ee.delete(u)),push:u=>{J=u;for(let I of [...ee])try{I(u);}catch(q){t?.(`[gem] a server-token listener threw: ${q instanceof Error?q.message:String(q)}`);}}},X=ja({bridge:K,clock:e,onStateChange:(u,I)=>{if(u==="ready"){if(o.mark("token ready")){let q=o.marks.find(me=>me.name==="token ready")?.at;a.trackPlatform("gem_boot_ready",q===void 0?{}:{boot_ms:Math.max(0,Math.round(q))});}}else u==="lost"&&(o.mark("token lost"),a.trackPlatform("gem_auth_lost"));n.onAuthStateChange?.(u,I);}}),en=()=>{let u=X.identity;return !u||X.source.currentState==="lost"?null:`${u.playerId}\0${u.gameId}\0${u.channel}`},tn=()=>{o.mark("token requested"),X.source.get().catch(()=>{});},f=$o({bridge:K,clock:e}),T={},$=fl({bridge:K,clock:e,onDropped:u=>n.onError?.("internal",u),confirm:async u=>T.confirm?.(u)??"unknown"}),Z=Sl({bridge:K,clock:e,onDropped:u=>n.onError?.("internal",u)}),ke=_l({bridge:K,clock:e,onDropped:u=>n.onError?.("internal",u)}),yt=bl({bridge:K,clock:e,onDropped:u=>n.onError?.("internal",u)}),ze=$s({bridge:K,clock:e}),$e=Da({bridge:K,clock:e}),tr=u=>{let I=K.handleWindowMessage({data:u.data,origin:u.origin,source:u.source,ports:u.ports});return I&&window.removeEventListener("message",tr),I};window.addEventListener("message",tr);let Ye=xa(window,tr),Ml=Ye?.capture,nr=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];nr?.domInteractive!==void 0&&nr.domInteractive>0&&o.mark("document parsed",nr.domInteractive),Ml?.late&&t?.("[gem] the early-handshake capture installed after this document finished loading, so a handshake posted at iframe load may already have been missed. Load the capture script ahead of everything else in the document.");let rr=n.handshakeWarningMs;rr!==null&&t&&e.setTimeout(()=>{let u=Ye===null?"no capture script ran":`capture: ${Ye.delivered} offer(s) delivered, ${Ye.stale} stale, ${Ye.capture.dropped} evicted${Ye.capture.late?", installed late":""}`;if(K.currentState==="connected"){t(`[gem] handshake connected. boot: ${o.timeline()} \xB7 ${u}`);return}t(`[gem] no completed handshake after ${rr??Tl}ms (bridge state: ${K.currentState}). Either the embedder does not run the gem-web-sdk parent half, its origin is not in this build\u2019s allowedEmbedders, or its handshake fired before this frame\u2019s listener registered. boot: ${o.timeline()} \xB7 `+u);},rr??Tl);let Ol=Xn({get baseUrl(){return j},tokenSource:X.source,get defaultQuery(){let u=X.identity;return u?{game_id:u.gameId,channel:u.channel}:{}}}),Xe=new Ie({transport:Ol,clock:e}),he={client:Xe,gameId:()=>X.identity?.gameId??""};T.confirm=u=>hl(he,u);let Ll=()=>X.identity?.channel??"release",Uo=new Tn(he,Ll),Bo=async u=>(await Uo.load())?.currency(u)?.id??void 0,Ho=Sn(he,Sr,{identity:en,resolveCurrencyId:Bo}),or=async u=>{let I=await Re.wait(u);if(I)return I;throw new se("timeout","no play token arrived over the bridge. Every route a game reaches is scoped by the token, so nothing can proceed without one \u2014 the bridge may not be connected, or the parent may have refused to mint (see onAuthStateChange).")},ir=s(n.autoReconnect),ue=io({client:Xe,clock:e,gameId:()=>X.identity?.gameId??null,playerId:()=>X.identity?.playerId??null,awaitGameId:async()=>(await or(qo)).gameId,resolveParty:f.resolve,resolveClusterTargets:ze.resolveList,refreshClusterTargets:ze.refresh,ensureLocalServer:$e.ensure,...n.clientVersion===void 0?{}:{clientVersion:n.clientVersion},platformGameVersion:()=>X.gameVersion,...n.pollRooms===void 0?{}:{poll:n.pollRooms},...n.recoverStaleMembership===void 0?{}:{recoverStaleMembership:n.recoverStaleMembership},...n.retryAutoStart===void 0?{}:{retryAutoStart:n.retryAutoStart},...n.watchSeats===void 0?{}:{watchSeats:n.watchSeats},...n.seatPollIntervalMs===void 0?{}:{seatPollIntervalMs:n.seatPollIntervalMs},...ir===null?{}:{autoReconnect:{...ir,redial:(u,I)=>sr.redialMatch(u,I),abandon:(u,I)=>sr.abandonMatch(u,I)}}});l(ue),ka({analytics:a,rooms:ue});let Qe=Ra({client:Xe,clock:e,rooms:ue,bridge:K,gameId:()=>X.identity?.gameId??"",baseUrl:()=>j,resolveClusterTarget:ze.resolve,boot:o,...n.log===void 0?{}:{log:n.log}}),Vo=_o(o,t),ft=nl({client:Xe,clock:e,rooms:ue,signaling:()=>Se.channel(),signalingReady:Q,log:t??(()=>{})}),sr=gl({rooms:ue,p2p:{connect:u=>Vo(Qe.connect(u)),session:u=>Qe.session(u)},dedicated:{connect:(u=>Jn(o,"welcome",ft.connect(u),t))},clock:e,identity:()=>X.identity,apiBaseUrl:()=>j,tokens:ce,room:()=>ue.currentRoom,autoReconnect:ir!==null,...n.log===void 0?{}:{log:n.log}}),Gl=async()=>(await or(qo)).playerId,Wo={client:Xe,boot:o,get identity(){return X.identity},awaitIdentity:(u=qo)=>or(u),awaitBridge:u=>K.settled(u),get player(){return g.current},awaitPlayer:(u=$g)=>g.wait(u),me:Ho,characters:new kn(he,void 0,en,Bo),transfers:new An(he,Sr,Ho.inventory),gameConfig:Uo,purchases:$.api,deviceSettings:Z.api,ads:ke.api,account:yt.api,analytics:a,leaderboards:new kt(he),challenges:new wt(he),showcase:new xt(he,Gl),friends:new At(he),platform:new Pt(he),profiles:new Tt(he),functions:new Ce((u,I)=>Li(he,u,I)),get prefs(){return y.current},get cohorts(){return w.current},get viewport(){return x.current},awaitCohorts:(u=Fg)=>w.wait(u),reportMuted:u=>{E=!!u,v();},cueReward:u=>K.cueReward(u),exit:u=>jg(ue,K,u,a),frame:K,devtools:R,rooms:ue,dedicatedServer:{listClusterTargets:u=>ft.listClusterTargets(u),connect:(u=>Jn(o,"welcome",ft.connect(u),t)),handleMatchEnded:(u,I)=>ft.handleMatchEnded(u,I)},p2p:{handleSignalEvent:(u,I,q)=>Qe.handleSignalEvent(u,I,q),session:u=>Qe.session(u),connect:u=>Vo(Qe.connect(u))},match:sr};return Wo}var El="the match has not started yet: the runtime hands over the host at `init`, and this was read before that. Read it from `init` or later \u2014 a bundle that needs a value at module scope is reading it one call too early.";function No(n,e={}){let t=e.clock??ae,r=()=>{let s=n();if(s===null)throw new Error(El);return s},o=null,i=()=>{if(o===null)throw new Error(El);return o};return {server:{get identity(){return i().identity},get client(){return i().client},get api(){return i().api},get match(){return i().match},get analytics(){return i().analytics},get functions(){return i().functions},get room(){return i().room},dispose(){o?.dispose();},get sizeClass(){return r().sizeClass},get roomArgs(){return r().roomArgs},get roster(){return r().roster},players(){return r().players()},profile(s){let d=r().profile?.(s);if(!d)return null;let m=d.displayName;return typeof m!="string"||m===""?null:{displayName:ye(m),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:ye(d.displayTag)}:{},...typeof d.discriminator=="string"?{discriminator:d.discriminator}:{}}},playerNumber(s){return r().playerNumber?.(s)},send(s,l,d){d===void 0?r().send(s,l):r().send(s,l,d);},broadcast(s,l){l===void 0?r().broadcast(s):r().broadcast(s,l);},kick(s,l){l===void 0?r().kick(s):r().kick(s,l);},log(s){r().log(s);},warn(s){r().warn(s);}},attach:()=>{o=pt(r(),{...e,clock:t});}}}function Il(n,e={}){let{server:t,attach:r}=No(()=>n,e);return r(),t}function qg(n){if(n===void 0||typeof n.reason!="string"||n.reason==="")return;let e=n.platform_reason??n.endedReason;return {reason:n.reason,...e===void 0?{}:{endedReason:Me(e)}}}function Cl(n,e={}){return ()=>{let t=null,{server:r,attach:o}=No(()=>t,e),i=n(r),a={async init(s){t=s,o(),await i.init?.();},async shutdown(s){let l=qg(s);try{await i.shutdown?.(l);}finally{r.dispose();}}};return i.join&&(a.join=(s,l)=>i.join?.(s,l)),i.leave&&(a.leave=(s,l)=>i.leave?.(s,l)),i.message&&(a.message=(s,l,d,m)=>i.message?.(s,l,d,m)),a}}
2
- export{Mg as ARCADE_EMBEDDERS,It as AnalyticsApi,se as AuthError,nn as CONDITIONAL_HEADERS,wt as ChallengesApi,Fo as DEVICE_SETTINGS_MAX_BYTES,h as DedicatedServerError,At as FriendsApi,Ce as FunctionsApi,D as GemApiError,Ie as GemClient,de as GemConfigError,Qt as GemFrame,Et as GemFunctionError,oe as GemSaveError,kt as LeaderboardsApi,kr as MAX_PERIODS_BACK,Xc as PLATFORM_EVENTS,Pt as PlatformApi,In as PlatformCurrenciesApi,ge as PlayerText,Tt as ProfilesApi,xt as ShowcaseApi,ne as TransportRefusal,Lt as UNRELIABLE_CHANNEL_LABEL,ye as asPlayerText,wo as createBootTimeline,V_ as createGem,pt as createGemServer,il as createHostTokenSource,Il as createMatchServer,Cl as defineServer,jg as leaveAndExit,ve as mapIdentity,Jn as markOnResolve,Gc as platformIconUrl,Mt as presentJoinCredential,st as readTemplateTransports,Gt as readTransportAdvert,_o as reportOnResolve,ae as systemClock,je as text,rn as toBase64,$n as webTransportAvailable};//# sourceMappingURL=gem-web-sdk.sdk.js.map
1
+ var jl=Object.defineProperty;var Nl=(n,e)=>{for(var t in e)jl(n,t,{get:e[t],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:7.2.0]";function zo(){let n=globalThis.__gemWebSdkVersion;if(typeof n!="string")return "";let e=n.lastIndexOf(":"),t=n.lastIndexOf("]");return e<0||t<=e+1?"":n.slice(e+1,t)}function ql(n,e){return e!==void 0?!e:n==="chain_exhausted"}var tt=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;get currentState(){return this.state}get lastFailure(){return this.failure}async get(){if(this.state==="lost")throw new se(this.failure??"unavailable","the session cannot be renewed");let e=this.seconds();if(this.grant&&e<this.grant.expiresAt-this.renewBefore())return this.grant.token;if(this.grant&&e>=this.grant.chainEndsAt)throw this.enter("lost","chain_exhausted"),new se("chain_exhausted","the token chain reached its ceiling");return this.refresh(this.nextReason())}nextReason(){return this.rejected?"rejected":this.grant?"expiring":"initial"}invalidate(e){e!==void 0&&this.grant!==null&&this.grant.token!==e||this.rejected&&this.grant===null||(this.grant=null,this.generation+=1,this.inFlight=null,this.rejected=true,this.state!=="lost"&&this.enter("pending"));}accept(e){this.state!=="lost"&&(this.grant=e,this.rejected=false,this.enter("ready"));}close(e="unavailable"){this.grant=null,this.generation+=1,this.inFlight=null,this.enter("lost",e);}refresh(e){if(this.inFlight)return this.inFlight;let t=this.generation;this.enter("pending");let r=this.options.request(e).then(o=>{if(t!==this.generation)throw new se("internal","token arrived for a superseded generation");return this.grant=o,this.rejected=false,this.enter("ready"),o.token}).catch(o=>{let i=Ul(o),a=o?.retryable;throw t===this.generation&&this.enter(ql(i,typeof a=="boolean"?a:void 0)?"lost":"degraded",i),o instanceof se?o:new se(i,String(o))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,t){this.failure=t??(e==="ready"?null:this.failure),this.state!==e&&(this.state=e,this.options.onStateChange?.(e,t));}renewBefore(){return this.options.renewBeforeSeconds??60}seconds(){return Math.floor(this.options.clock.now()/1e3)}},se=class n extends Error{constructor(t,r){super(`auth ${t}: ${r}`);this.reason=t;this.name="AuthError";}reason;static isAuthError(t){if(t instanceof n)return true;let r=t;return r?.name==="AuthError"&&typeof r.reason=="string"}};function Ul(n){if(n instanceof se)return n.reason;let e=n?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var ne=class n extends Error{retryable=false;constructor(e){super(e),this.name="TransportRefusal";}static isRefusal(e){if(e instanceof n)return true;let t=e;return t?.name==="TransportRefusal"&&t.retryable===false}},on=["if-match","if-none-match"],Yo=4096;function Bl(n){if(!n)return;let e={};for(let[t,r]of Object.entries(n)){let o=t.toLowerCase();if(!on.includes(o)||r===void 0)continue;let i=typeof r=="string"?Hl(r):r;if(typeof i!="string"||i.length>Yo||!Vl(i))throw new ne(`the ${o} header value cannot be sent \u2014 it is not a string, is longer than ${Yo} characters, or contains a character outside the range an HTTP header value may carry. This is a malformed request, not a server failure; the value is withheld here rather than written to logs.`);i!==""&&(e[o]=i);}return Object.freeze(e)}function Hl(n){let e=o=>o===32||o===9||o===10||o===13,t=0,r=n.length;for(;t<r&&e(n.charCodeAt(t));)t++;for(;r>t&&e(n.charCodeAt(r-1));)r--;return n.slice(t,r)}function Vl(n){for(let e=0;e<n.length;e++){let t=n.charCodeAt(e);if(t!==9&&(t<32||t===127||t>255))return false}return true}function Wl(n){let{bytes:e}=n;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new ne("the raw body is not a Uint8Array, so it cannot be sent as bytes. This is a malformed request, not a server failure.");if(n.body!==void 0)throw new ne("the request carries both a JSON body and a raw body, and only one can be sent. This is a malformed request, not a server failure.");return new Uint8Array(e)}}function Xo(n,e){let t=e.replayUnauthorizedOnce??true;return {async request(r){let o={...r},i=Bl(o.headers),a=Wl(o),s=Object.freeze({...o,headers:i,...a===void 0?{}:{bytes:a}}),l=await e.tokenSource.get(),d=await n(s,l);if(d.status!==401||!t)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),c=await n(s,m);if(c.status===401)throw e.tokenSource.close("unavailable"),new se("unavailable","the server refused a freshly minted token");return c}}}function sn(n){let e=typeof n=="string"?new TextEncoder().encode(n):n;return btoa(Kl(e))}function an(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}function dr(n){return new TextDecoder().decode(an(n))}function Kl(n){let t="";for(let r=0;r<n.length;r+=32768)t+=String.fromCharCode(...n.subarray(r,r+32768));return t}var D=class extends Error{constructor(t,r,o,i,a){super(`${t} (${r}): ${o}`);this.reason=t;this.status=r;this.detail=o;this.retryAfterSeconds=i;this.code=a;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},Zo=new WeakMap;function ei(n){return Zo.get(n)??{}}var Jl=new Set([408,429,500,502,503,504]),zl=6e4;function Yl(n){if(n===void 0)return 2;if(!Number.isInteger(n)||n<0||n>10)throw new ne(`maxRetries must be a whole number between 0 and 10; received ${JSON.stringify(n)}. This is a configuration fault, not a server failure.`);return n}var Ce=class{constructor(e){this.options=e;}options;async get(e,t){return this.send({method:"GET",path:e,signal:t},true)}async getWithEtag(e,t={}){let r=await this.sendRaw({method:"GET",path:e,...t.signal===void 0?{}:{signal:t.signal},...t.ifNoneMatch===void 0?{}:{headers:{"if-none-match":t.ifNoneMatch}}},true),o=r.etag===void 0?{}:{etag:r.etag};return r.status===304?{modified:false,...o}:{modified:true,body:r.body,...o}}async put(e,t,r,o={}){return this.send({method:"PUT",path:e,body:t,signal:r,...vt(o)},o.replaySafe===true)}async post(e,t,r,o={}){return this.send({method:"POST",path:e,body:t,signal:r,...vt(o)},o.replaySafe===true)}async postBytes(e,t,r,o={}){let i=await this.sendRaw({method:"POST",path:e,bytes:t,responseType:"bytes",signal:r,...vt(o)},o.replaySafe===true);return {bytes:Xl(i.body),...i.invocationId===void 0?{}:{invocationId:i.invocationId}}}async patch(e,t,r,o={}){return this.send({method:"PATCH",path:e,body:t,signal:r,...vt(o)},o.replaySafe===true)}async delete(e,t,r={}){return this.send({method:"DELETE",path:e,signal:t,...vt(r)},r.replaySafe===true)}async send(e,t){return (await this.sendRaw(e,t)).body}async sendRaw(e,t){let r=t?Yl(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw Qo(e.signal);for(let i=0;i<r;i++){if(i>0&&await this.backoff(i,o,e.signal),e.signal?.aborted)throw Qo(e.signal);let a;try{a=await this.options.transport.request(e);}catch(l){if(se.isAuthError(l)||ne.isRefusal(l)||e.signal?.aborted||Ql(l))throw l;o=new D("unavailable",0,String(l));continue}if(a.status>=200&&a.status<300||a.status===304)return a;let s=Zl(a);if(!Jl.has(a.status))throw s;o=s;}throw o??new D("unavailable",0,"no attempt was made")}backoff(e,t,r){if(r?.aborted)return Promise.resolve();let o=t?.retryAfterSeconds,i=o!==void 0?o*1e3:2**(e-1)*250,a=2**(e-1)*250,s=Math.min(Math.max(i,a),zl);return new Promise(l=>{let d=this.options.clock,m=false,c=false,p,g=()=>{m||(m=true,c&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,s),c=true,m&&d.clearTimeout(p);})}};function Xl(n){if(n instanceof Uint8Array)return n;if(n==null)return new Uint8Array(0);let e=typeof n=="string"?n:JSON.stringify(n);return new TextEncoder().encode(e)}function vt(n){return {...n.keepalive===void 0?{}:{keepalive:n.keepalive},...n.ifMatch===void 0?{}:{headers:{"if-match":n.ifMatch}}}}function Qo(n){return n.reason!==void 0?n.reason:new DOMException("The operation was aborted.","AbortError")}function Ql(n){let e=n?.name;return e==="AbortError"||e==="TimeoutError"}function Zl(n){let e=td(n),t=rd(n.body),r={...t===void 0?{}:{details:t},...n.invocationId===void 0?{}:{invocationId:n.invocationId}};return Object.keys(r).length>0&&Zo.set(e,r),e}var ed=new Map([["insufficient_funds","insufficient_funds"]]);function td(n){let{status:e,body:t}=n,r=nd(t),o=n.retryAfterSeconds??id(t),i=od(t),a=i===void 0?void 0:ed.get(i);if(a!==void 0)return new D(a,e,r,void 0,i);switch(e){case 304:return new D("not_modified",e,r);case 400:case 422:return new D("invalid",e,r,void 0,i);case 403:return new D("forbidden",e,r,void 0,i);case 404:return new D("not_found",e,r,void 0,i);case 402:return new D("insufficient_funds",e,r,void 0,i);case 409:return new D("conflict",e,r,void 0,i);case 412:return new D("precondition_failed",e,r,void 0,i);case 413:return new D("too_large",e,r,void 0,i);case 429:return new D("rate_limited",e,r,o,i);default:return new D("unavailable",e,r,o,i)}}function nd(n){if(typeof n=="string")return n;let e=n?.message;if(typeof e=="string")return e;let t=n?.error;if(typeof t=="string")return t;let r=t?.message;return typeof r=="string"?r:"no detail"}function rd(n){let t=n?.error?.details;return t===null?void 0:t}function od(n){let t=n?.error?.code;return typeof t=="string"&&t.length>0?t:void 0}function id(n){let e=n?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function _(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 ti(n,e,t){let r=`/v1/inventory/transfers/${_(e)}/accept`;return n.client.post(r,void 0,t?.signal)}async function ni(n,e,t,r,o,i){let a=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/add`;return n.client.post(a,o,i?.signal)}async function ri(n,e,t){let r=`/v1/inventory/transfers/${_(e)}/cancel`;return n.client.post(r,void 0,t?.signal)}async function oi(n,e,t,r,o,i){let a=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/claim`;return n.client.post(a,o,i?.signal)}async function ii(n,e,t){return n.client.post("/v1/characters",e,t?.signal)}async function si(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/orders/batch`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function ai(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/orders`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function li(n,e,t,r,o){let i=`/v1/settings/${_(e)}/${_(t)}/${_(r)}`;return n.client.delete(i,o?.signal)}async function di(n,e,t,r,o){let i=`/v1/saves/${_(e)}/${_(t)}/${_(r)}`;return n.client.delete(i,o?.signal)}async function ci(n,e,t,r){let o=`/v1/showcase/players/${_(e)}/${_(t)}`;return n.client.delete(o,r?.signal)}async function ui(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/recipes/execute`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function mi(n,e,t,r,o,i){let a=`/v1/saves/${_(e)}/${_(t)}/${_(r)}/finalize`;return n.client.post(a,o,i?.signal)}async function pi(n,e,t){let r=`/v1/games/${_(n.gameId())}/config/channels/${_(e)}`;return n.client.getWithEtag(r,{...t?.signal===void 0?{}:{signal:t.signal},...t?.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}})}async function gi(n,e,t){let r=`/v1/characters/${_(e)}`;return n.client.get(r,t?.signal)}async function yi(n,e,t){let r=`/v1/inventory/loot-tables/${_(e)}/drop-rates`;return n.client.get(r,t?.signal)}async function fi(n,e,t,r,o){let i=`/v1/settings/${_(e)}/${_(t)}/${_(r)}`;return n.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function hi(n,e,t,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),a=`/v1/inventory/${_(e)}/${_(t)}`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function bi(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/items/${_(r)}`;return n.client.get(i,o?.signal)}async function vi(n,e,t,r,o){let i=new URLSearchParams;o?.bucket_1!==void 0&&i.set("bucket_1",String(o?.bucket_1)),o?.bucket_2!==void 0&&i.set("bucket_2",String(o?.bucket_2)),o?.limit!==void 0&&i.set("limit",String(o?.limit));let a=i.toString(),s=`/v1/leaderboards/${_(e)}/${_(t)}/${_(r)}`+(a?`?${a}`:"");return n.client.get(s,o?.signal)}async function _i(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/orders/${_(r)}`;return n.client.get(i,o?.signal)}async function wi(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}`;return n.client.get(i,o?.signal)}async function Si(n,e,t,r,o,i){let a=`/v1/inventory/${_(e)}/${_(t)}/catalogs/${_(r)}/recipes/${_(o)}/availability`;return n.client.get(a,i?.signal)}async function Ri(n,e,t,r){let o=new URLSearchParams;o.set("limit",String(r?.limit));let i=o.toString(),a=`/v1/inventory/${_(e)}/${_(t)}/recipe-usage`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function cr(n,e,t,r,o){let i=`/v1/saves/${_(e)}/${_(t)}/${_(r)}`;return n.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function ki(n,e,t){let r=new URLSearchParams;t?.bucket_1!==void 0&&r.set("bucket_1",String(t?.bucket_1)),t?.bucket_2!==void 0&&r.set("bucket_2",String(t?.bucket_2));let o=r.toString(),i=`/v1/leaderboards/${_(e)}/friends`+(o?`?${o}`:"");return n.client.get(i,t?.signal)}async function xi(n,e,t){let r=`/v1/showcase/friends/${_(e)}`;return n.client.get(r,t?.signal)}async function Ai(n,e,t){let r=new URLSearchParams;t?.bucket_1!==void 0&&r.set("bucket_1",String(t?.bucket_1)),t?.bucket_2!==void 0&&r.set("bucket_2",String(t?.bucket_2));let o=r.toString(),i=`/v1/leaderboards/${_(e)}`+(o?`?${o}`:"");return n.client.get(i,t?.signal)}async function ln(n,e){return n.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function Pi(n,e,t){let r=`/v1/profiles/players/${_(e)}`;return n.client.get(r,t?.signal)}async function Ti(n,e){let t=new URLSearchParams;e?.config_version!==void 0&&t.set("config_version",String(e?.config_version));let r=t.toString(),o="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function Ei(n,e,t){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${_(e)}`;return n.client.get(r,t?.signal)}async function Ii(n,e,t,r){let o=`/v1/showcase/players/${_(e)}/${_(t)}`;return n.client.get(o,r?.signal)}async function Ci(n,e){return n.client.get("/v1/characters/slots",e?.signal)}async function Mi(n,e,t){let r=`/v1/inventory/transfers/${_(e)}`;return n.client.get(r,t?.signal)}async function Oi(n,e,t){let r=`/v1/games/${_(n.gameId())}/analytics/events`;return n.client.post(r,e,t?.signal,{...t?.keepalive===void 0?{}:{keepalive:t.keepalive},replaySafe:true})}async function Li(n,e,t){return n.client.post("/v1/inventory/transfers",e,t?.signal)}async function Gi(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/platform-funded-game-inventory-purchases`;return n.client.post(i,r,o?.signal)}async function Di(n,e,t){return n.client.postBytes("/v1/functions/invoke",e,t?.signal)}async function $i(n,e){let t=new URLSearchParams;e?.periods_back!==void 0&&t.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&t.set("player_id",String(e?.player_id));let r=t.toString(),o="/v1/challenges"+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function Fi(n,e){return n.client.get("/v1/characters",e?.signal)}async function ji(n,e,t,r){let o=`/v1/settings/${_(e)}/${_(t)}`;return n.client.get(o,r?.signal)}async function Ni(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/inventory/${_(e)}/${_(t)}/orders`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function qi(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/saves/${_(e)}/${_(t)}`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function Ui(n,e){let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",String(e?.limit)),e?.cursor!==void 0&&t.set("cursor",String(e?.cursor));let r=t.toString(),o="/v1/friends"+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function Bi(n,e){let t=new URLSearchParams;e.entity_type!==void 0&&t.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&t.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&t.set("direction",String(e?.direction)),e?.status!==void 0&&t.set("status",String(e?.status)),e?.cursor!==void 0&&t.set("cursor",String(e?.cursor)),e?.limit!==void 0&&t.set("limit",String(e?.limit));let r=t.toString(),o="/v1/inventory/transfers"+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function Hi(n,e,t,r){let o=`/v1/games/${_(n.gameId())}/matches/${_(e)}/end`;return n.client.post(o,t,r?.signal)}async function Vi(n,e,t,r,o,i){let a=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/max`;return n.client.post(a,o,i?.signal)}async function Wi(n,e,t,r,o,i){let a=`/v1/settings/${_(e)}/${_(t)}/${_(r)}`;return n.client.put(a,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Ki(n,e,t,r,o){let i=`/v1/showcase/players/${_(e)}/${_(t)}`;return n.client.put(i,r,o?.signal)}async function Ji(n,e,t){let r=`/v1/inventory/transfers/${_(e)}/reject`;return n.client.post(r,void 0,t?.signal)}async function zi(n,e,t,r){let o=`/v1/characters/${_(e)}`;return n.client.patch(o,t,r?.signal)}async function Yi(n,e,t,r,o,i){let a=`/v1/saves/${_(e)}/${_(t)}/${_(r)}/upload-url`;return n.client.post(a,o,i?.signal,{replaySafe:true})}async function Xi(n,e,t,r,o,i){let a=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/reset`;return n.client.post(a,o,i?.signal)}async function Qi(n,e,t){let r=`/v1/characters/${_(e)}`;return n.client.delete(r,t?.signal)}var z="gem-web-bridge",cn={min:1,max:1},nt=65536,Zi=8,dn=5e3,es=1024;function mr(n){return Object.freeze(Object.assign(Object.create(null),n))}var ts=mr({"gem.handshake":30,"gem.handshake.accept":5,"gem.token":30,"gem.token.denied":30,"gem.player":12,"gem.pause":120,"gem.prefs":60,"gem.cohorts":12,"gem.viewport":60,"gem.deviceSettings":12,"gem.willTerminate":10,"gem.roomEvent":120,"gem.socketState":12,"gem.seatedEvent":60,"gem.autoStartFailedEvent":30,"gem.signalEvent":1800,"gem.dedicatedEvent":120,"gem.partyResult":30,"gem.clusterTarget":12,"gem.devtools":30,"gem.screenshot":6,"gem.screenshot.denied":12,"gem.requestContext":12,"gem.gameContext":12,"gem.signal":1200,"gem.dedicatedOffer":60,"gem.partyRequest":12,"gem.ready":5,"gem.progress":600,"gem.requestToken":12,"gem.requestLocalServer":6,"gem.localServer":30,"gem.localServer.denied":30,"gem.exit":5,"gem.openExternal":6,"gem.requestFullscreen":30,"gem.audioState":120,"gem.rewardCue":60,"gem.frameStats":120,"gem.error":60,"gem.requestPurchase":12,"gem.purchaseResult":30,"gem.deviceSettings.put":30,"gem.deviceSettings.result":30,"gem.requestAd":6,"gem.adResult":12,"gem.requestSignIn":6,"gem.signInResult":12,__malformed:60}),un="__malformed";var sd=mr({"gem.requestAd":"ads","gem.adResult":"ads","gem.requestSignIn":"signIn","gem.signInResult":"signIn","gem.requestPurchase":"purchases","gem.purchaseResult":"purchases","gem.devtools":"devtools","gem.screenshot":"screenshot","gem.screenshot.denied":"screenshot","gem.requestContext":"feedbackContext","gem.gameContext":"feedbackContext","gem.roomEvent":"rooms","gem.signal":"p2p","gem.signalEvent":"p2p","gem.dedicatedOffer":"dedicated","gem.dedicatedEvent":"dedicated","gem.clusterTarget":"clusterTarget","gem.partyRequest":"parties","gem.partyResult":"parties","gem.autoStartFailedEvent":"autoStartFailure","gem.seatedEvent":"partySeating","gem.socketState":"socketState","gem.audioState":"audioState","gem.rewardCue":"rewardCue","gem.frameStats":"frameStats","gem.viewport":"viewport","gem.requestLocalServer":"localHost","gem.localServer":"localHost","gem.localServer.denied":"localHost","gem.cohorts":"cohorts","gem.deviceSettings":"deviceSettings","gem.deviceSettings.put":"deviceSettings","gem.deviceSettings.result":"deviceSettings"}),ad=Object.freeze([["gem.asyncOpponents.","asyncOpponents"]]);function ns(n){let e=sd[n];if(e!==void 0)return e;for(let[t,r]of ad)if(n.startsWith(t))return r}function pr(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 ld(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 dd(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function cd(n){return /^[a-z_]+$/.test(n)}function ur(n,e,t){if(e>Zi)return `nesting deeper than ${Zi}`;if(++t.nodes>dn)return `more than ${dn} values`;if(t.bytes>nt)return `over the ${nt} 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 o=n;if(t.seen.has(o))return "a repeated or cyclic object reference";if(t.seen.add(o),Array.isArray(n)){if(n.length>es)return `an array of ${n.length} entries, over the ${es} limit`;t.bytes+=2;for(let s of n){let l=ur(s,e+1,t);if(l)return l}return null}let i=Object.getPrototypeOf(n);if(i!==Object.prototype&&i!==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>dn)return `more than ${dn} values`;if(t.bytes+=s.length*3+4,t.bytes>nt)return `over the ${nt} byte limit`;let l=ur(a[s],e+1,t);if(l)return l}return null}function ud(n){let e={nodes:0,bytes:0,seen:new Set},t=ur(n,0,e);return t?`message contains ${t}`:e.bytes>nt?`message is over the ${nt} byte limit`:null}var md={origin:[pr,"not a well-formed origin"],url:[ld,"not a safe absolute http(s) URL"],bcp47:[dd,"not a well-formed BCP 47 tag"],code:[cd,"not a code of lower-case letters and underscores"]};function rs(n,e,t){for(let r of e){let o=t===""?r.n:`${t}.${r.n}`,i=n[r.n];if(i==null){if(r.o)continue;return `${o}: required`}let a=os(i,r,o);if(a)return a}return null}function os(n,e,t){switch(e.k){case "string":{if(typeof n!="string")return `${t}: expected string`;if(n.length>e.max)return `${t}: exceeds ${e.max} characters`;if(e.f){let[r,o]=md[e.f];if(!r(n))return `${t}: ${o}`}return null}case "int":return typeof n!="number"||!Number.isInteger(n)?`${t}: expected integer`:n<e.lo||n>e.hi?`${t}: out of range ${e.lo}..${e.hi}`:null;case "boolean":return typeof n=="boolean"?null:`${t}: expected boolean`;case "enum":{let r=e.v;return r.includes(n)?null:`${t}: not one of ${r.join("|")}`}case "object":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected object`:rs(n,e.fs,t);case "json":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected a plain object`:null;case "array":{if(!Array.isArray(n))return `${t}: expected array`;if(n.length>e.max)return `${t}: exceeds ${e.max} items`;let r=e.it,o=`${t}[]`;for(let i of n){if(i==null){if(r.o)continue;return `${o}: required`}let a=os(i,r,o);if(a)return a}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}function M(n,e){return t=>{let r=ud(t);if(r)return r;if(typeof t!="object"||t===null||Array.isArray(t))return "message: expected object";let o=t;return o.gem!==z?"gem: wrong protocol marker":o.type!==n?`type: expected ${n}`:rs(o,e,"")}}var pd=M("gem.handshake",[{n:"versions",k:"object",fs:[{n:"min",k:"int",lo:1,hi:1e3},{n:"max",k:"int",lo:1,hi:1e3}]},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}},{n:"embedder",k:"string",max:2048,f:"origin"}]),gd=M("gem.handshake.accept",[{n:"v",k:"int",lo:1,hi:1e3},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}}]),yd=M("gem.token",[{n:"token",k:"string",max:4096},{n:"requestId",k:"string",o:1,max:64},{n:"generation",k:"int",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"string",o:1,max:512,f:"url"},{n:"playerId",k:"string",max:64},{n:"gameId",k:"string",max:64},{n:"channel",k:"enum",v:["dev","test","release"]},{n:"gameVersion",k:"string",o:1,max:64},{n:"expiresAt",k:"int",lo:0,hi:4102444800},{n:"chainEndsAt",k:"int",lo:0,hi:4102444800},{n:"allowDevTools",k:"boolean",o:1}]),fd=M("gem.token.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:36e5},{n:"reason",k:"enum",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"string",max:64}]),hd=M("gem.player",[{n:"untrusted",k:"object",fs:[{n:"displayName",k:"string",max:64},{n:"displayTag",k:"string",o:1,max:80},{n:"displayHandle",k:"string",max:80}]},{n:"playerId",k:"string",o:1,max:64},{n:"discriminator",k:"string",o:1,max:8},{n:"avatarIconUrl",k:"string",o:1,max:2048,f:"url"},{n:"badges",k:"array",o:1,max:2,it:{n:"",k:"object",fs:[{n:"itemId",k:"string",max:64},{n:"iconUrl",k:"string",max:2048,f:"url"}]}},{n:"displayTag",k:"string",max:8},{n:"avatarUrl",k:"string",o:1,max:2048,f:"url"},{n:"boost",k:"object",o:1,fs:[{n:"multipliers",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"currencyId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"multiplierBp",k:"int",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"int",o:1,lo:1,hi:7}]}]),bd=M("gem.pause",[{n:"paused",k:"boolean"}]),vd=M("gem.prefs",[{n:"reducedMotion",k:"boolean"},{n:"muted",k:"boolean"},{n:"showFrameStats",k:"boolean",o:1},{n:"locale",k:"string",max:35,f:"bcp47"}]),_d=M("gem.cohorts",[{n:"cohorts",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"experimentId",k:"string",max:36},{n:"variantKey",k:"string",max:32}]}}]),wd=M("gem.viewport",[{n:"insets",k:"object",fs:[{n:"top",k:"int",lo:0,hi:4096},{n:"right",k:"int",lo:0,hi:4096},{n:"bottom",k:"int",lo:0,hi:4096},{n:"left",k:"int",lo:0,hi:4096}]}]),Sd=M("gem.deviceSettings",[{n:"settings",k:"json",o:1}]),Rd=M("gem.willTerminate",[{n:"reason",k:"enum",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"int",lo:0,hi:6e4}]),kd=M("gem.roomEvent",[{n:"event",k:"enum",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"string",max:64},{n:"matchId",k:"string",o:1,max:64},{n:"version",k:"int",o:1,lo:0,hi:2147483647},{n:"reason",k:"string",o:1,max:64},{n:"platform",k:"enum",o:1,v:["universal","mobile"]}]),xd=M("gem.socketState",[{n:"connected",k:"boolean"},{n:"reason",k:"enum",o:1,v:["connecting","dropped","watchdog","terminal"]}]),Ad=M("gem.seatedEvent",[{n:"roomId",k:"string",max:64}]),Pd=M("gem.autoStartFailedEvent",[{n:"roomId",k:"string",max:64},{n:"code",k:"string",max:64}]),Td=M("gem.signalEvent",[{n:"event",k:"enum",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Ed=M("gem.dedicatedEvent",[{n:"event",k:"enum",v:["answer","error","matchEnded"]},{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",o:1,max:10240},{n:"sessionId",k:"string",o:1,max:64},{n:"code",k:"string",o:1,max:64},{n:"message",k:"string",o:1,max:256},{n:"reason",k:"string",o:1,max:64}]),Id=M("gem.partyResult",[{n:"requestId",k:"string",max:64},{n:"partyId",k:"string",o:1,max:64}]),Cd=M("gem.clusterTarget",[{n:"clusterTargetId",k:"string",max:64},{n:"clusterTargetIds",k:"array",o:1,max:3,it:{n:"",k:"string",max:64}}]),Md=M("gem.devtools",[{n:"action",k:"enum",v:["open","close","toggle"]}]),Od=M("gem.screenshot",[{n:"maxWidth",k:"int",lo:1,hi:7680},{n:"maxHeight",k:"int",lo:1,hi:4320}]),Ld=M("gem.screenshot.denied",[{n:"reason",k:"enum",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"boolean"}]),Gd=M("gem.requestContext",[]),Dd=M("gem.gameContext",[{n:"context",k:"json"}]),$d=M("gem.signal",[{n:"signal",k:"enum",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Fd=M("gem.dedicatedOffer",[{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",max:10240},{n:"intent",k:"enum",v:["initial","ice_restart","full_reconnect"]}]),jd=M("gem.partyRequest",[{n:"requestId",k:"string",max:64}]),Nd=M("gem.ready",[]),qd=M("gem.progress",[{n:"loaded",k:"int",lo:0,hi:1099511627776},{n:"total",k:"int",lo:0,hi:1099511627776}]),Ud=M("gem.requestToken",[{n:"requestId",k:"string",max:64},{n:"reason",k:"enum",v:["initial","expiring","rejected"]}]),Bd=M("gem.requestLocalServer",[{n:"requestId",k:"string",max:64},{n:"gameRoomId",k:"string",max:64}]),Hd=M("gem.localServer",[{n:"requestId",k:"string",max:64},{n:"serverId",k:"string",o:1,max:128}]),Vd=M("gem.localServer.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"reason",k:"enum",v:["refused","unavailable"]}]),Wd=M("gem.exit",[{n:"reason",k:"string",o:1,max:64}]),Kd=M("gem.openExternal",[{n:"url",k:"string",max:2048,f:"url"}]),Jd=M("gem.requestFullscreen",[{n:"enabled",k:"boolean"}]),zd=M("gem.audioState",[{n:"muted",k:"boolean"}]),Yd=M("gem.rewardCue",[{n:"currencySlug",k:"string",max:32},{n:"expected",k:"int",o:1,lo:1,hi:1e9},{n:"origin",k:"object",o:1,fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384}]}]),Xd=M("gem.frameStats",[{n:"fps",k:"int",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"int",lo:0,hi:1e5}]),Qd=M("gem.error",[{n:"code",k:"enum",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"string",o:1,max:256}]),Zd=M("gem.requestPurchase",[{n:"requestId",k:"string",max:64},{n:"purchaseKind",k:"enum",v:["item","recipe"]},{n:"targetId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"quantity",k:"int",o:1,lo:1,hi:10},{n:"catalogId",k:"string",o:1,max:64}]),ec=M("gem.purchaseResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["ok","declined","unavailable"]},{n:"reason",k:"string",o:1,max:64,f:"code"},{n:"purchaseId",k:"string",o:1,max:64}]),tc=M("gem.deviceSettings.put",[{n:"requestId",k:"string",max:64},{n:"settings",k:"json"}]),nc=M("gem.deviceSettings.result",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["stored","too_large","unavailable"]}]),rc=M("gem.requestAd",[{n:"requestId",k:"string",max:64},{n:"placement",k:"string",max:32},{n:"format",k:"enum",v:["interstitial","rewarded"]}]),oc=M("gem.adResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["shown","no_ad","unavailable"]}]),ic=M("gem.requestSignIn",[{n:"requestId",k:"string",max:64}]),sc=M("gem.signInResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["signed_in","declined","unavailable"]}]),mn=mr({"gem.handshake":pd,"gem.handshake.accept":gd,"gem.token":yd,"gem.token.denied":fd,"gem.player":hd,"gem.pause":bd,"gem.prefs":vd,"gem.cohorts":_d,"gem.viewport":wd,"gem.deviceSettings":Sd,"gem.willTerminate":Rd,"gem.roomEvent":kd,"gem.socketState":xd,"gem.seatedEvent":Ad,"gem.autoStartFailedEvent":Pd,"gem.signalEvent":Td,"gem.dedicatedEvent":Ed,"gem.partyResult":Id,"gem.clusterTarget":Cd,"gem.devtools":Md,"gem.screenshot":Od,"gem.screenshot.denied":Ld,"gem.requestContext":Gd,"gem.gameContext":Dd,"gem.signal":$d,"gem.dedicatedOffer":Fd,"gem.partyRequest":jd,"gem.ready":Nd,"gem.progress":qd,"gem.requestToken":Ud,"gem.requestLocalServer":Bd,"gem.localServer":Hd,"gem.localServer.denied":Vd,"gem.exit":Wd,"gem.openExternal":Kd,"gem.requestFullscreen":Jd,"gem.audioState":zd,"gem.rewardCue":Yd,"gem.frameStats":Xd,"gem.error":Qd,"gem.requestPurchase":Zd,"gem.purchaseResult":ec,"gem.deviceSettings.put":tc,"gem.deviceSettings.result":nc,"gem.requestAd":rc,"gem.adResult":oc,"gem.requestSignIn":ic,"gem.signInResult":sc});var ae={now:()=>Date.now(),setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n)},_t=class{constructor(e=ae){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let t=ts[e];if(t===void 0)return false;let r=this.clock.now(),o=this.lastRefill.get(e)??r,i=this.tokens.get(e)??t,a=Math.max(0,r-o),s=Math.min(t,i+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 gr(n,e){return n.toLowerCase()===e.toLowerCase()}function pn(n){let e=n.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function is(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:pn(t.hostname)&&pn(r.hostname)}function ss(n,e){if(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 gn=class{constructor(e,t){this.inventory=e;this.resolveCurrencyId=t;}inventory;resolveCurrencyId;async list(e={}){return (await this.inventory.snapshot({buckets:e.buckets})).currencies.data.map(r=>({currencyId:r.currencyId,total:r.total,...r.buckets===void 0?{}:{buckets:r.buckets}}))}async get(e,t={}){let o=(await this.inventory.snapshot({buckets:t.buckets})).currencies.data,i=o.find(s=>s.currencyId===e),a;return !i&&this.resolveCurrencyId&&(a=await this.resolveCurrencyId(e).catch(()=>{}),a!==void 0&&(i=o.find(s=>s.currencyId===a))),{currencyId:i?i.currencyId:a??e,total:i?i.total:null,...i?.buckets===void 0?{}:{buckets:i.buckets}}}};function fr(n){let e=Array.isArray(n.achievements)?n.achievements:[],t=[];for(let r of e){let o=r??{};typeof o.id!="string"||o.id===""||typeof o.threshold!="number"||!Number.isFinite(o.threshold)||t.push({id:o.id,threshold:o.threshold,points:typeof o.points=="number"?o.points:0,hidden:o.hidden===true,...typeof o.unlocked_at=="number"&&Number.isFinite(o.unlocked_at)?{unlockedAt:o.unlocked_at}:{},...o.revoked===true?{revoked:true}:{}});}return {...t.length>0?{achievements:t}:{},...n.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var as="inventory",rt=n=>typeof n=="number"?n:0,wt=n=>typeof n=="string"?n:"";function yr(n,e){let t=n??{},r=typeof t.next_cursor=="string"?t.next_cursor:void 0;return {data:Array.isArray(t.data)?t.data.map(e):[],...r===void 0?{}:{nextCursor:r}}}function ls(n){let e=n??{};return {itemDefinitionId:wt(e.item_definition_id),instanceId:wt(e.instance_id),quantity:rt(e.quantity),acquiredAt:rt(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function ac(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0;return {currencies:yr(e.currencies,r=>{let o=r??{},i=Array.isArray(o.buckets)?o.buckets.map(a=>{let s=a??{};return {bucket:wt(s.bucket),balance:rt(s.balance)}}):void 0;return {currencyId:wt(o.currency_id),total:rt(o.total),...i===void 0?{}:{buckets:i}}}),items:yr(e.items,ls),progressions:yr(e.progressions,r=>{let o=r??{};return {progressionDefinitionId:wt(o.progression_definition_id),currentValue:rt(o.current_value),completionCount:rt(o.completion_count),isCompleted:o.is_completed===true,...fr(o)}}),...t===void 0?{}:{etag:t}}}var yn=class{constructor(e,t,r){this.api=e;this.entity=t;this.cache=r;}api;entity;cache;snapshot(e={}){let t=e.buckets?`${as}#buckets`:as;return this.cache.read(t,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,t){let r=await this.snapshot();if(r.items.nextCursor===void 0){let i=r.items.data.filter(a=>a.itemDefinitionId===e);if(i.length>0)return i}let o=await bi(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return Array.isArray(o)?o.map(ls):[]}page(e){return this.fetch(e)}refresh(){this.invalidate();}onChanged(e){return this.cache.onInvalidate(e)}invalidate(){this.cache.invalidate();}async fetch(e){let t=await hi(this.api,this.entity.type,this.entity.id,{...e.includeBuckets?{include_buckets:true}:{},...e.currencyCursor===void 0?{}:{currency_cursor:e.currencyCursor},...e.itemCursor===void 0?{}:{item_cursor:e.itemCursor},...e.progressionCursor===void 0?{}:{progression_cursor:e.progressionCursor},...e.currencyLimit===void 0?{}:{currency_limit:e.currencyLimit},...e.itemLimit===void 0?{}:{item_limit:e.itemLimit},...e.progressionLimit===void 0?{}:{progression_limit:e.progressionLimit},...e.signal===void 0?{}:{signal:e.signal}});return ac(t)}};var lc={unknown_currency:1,currency_not_in_game_payable:1,not_purchasable:1,no_price_in_currency:1,busy:1,cancelled:1,insufficient_funds:1,price_mismatch:1,config_version_stale:1,platform_currency_unavailable:1,not_available:1,recipe_locked:1,recipe_on_cooldown:1,recipe_max_uses_exceeded:1,item_max_stack_exceeded:1,recipe_costs_unmet:1,quantity_invalid:1,error:1},dc=new Set(Object.keys(lc));function ds(n){return typeof n=="string"&&dc.has(n)?n:"error"}var Me=class extends RangeError{constructor(t,r){super(r);this.code=t;this.name="PurchaseRefusal";}code;retryable=false};var te=n=>typeof n=="string"?n:"",cc=n=>typeof n=="string"?n:te(n&&typeof n=="object"?n.type:void 0),xe=n=>typeof n=="number"?n:0;function uc(n){let e=n??{};return {prerequisiteType:te(e.prerequisite_type),referenceId:te(e.reference_id),required:xe(e.required),current:xe(e.current)}}function St(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0;return {orderId:te(e.order_id),status:te(e.status),...t===void 0?{}:{etag:t}}}function fn(){return crypto.randomUUID()}var mc="recipe-usage",cs=100;function hn(n){let e=n??{};switch(e.type){case "currency":return {kind:"currency",currencyId:te(e.currency_id),bucket:te(e.bucket),delta:xe(e.delta),balanceAfter:xe(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:te(e.item_definition_id),instanceId:te(e.instance_id),delta:xe(e.delta),quantityAfter:xe(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:te(e.progression_definition_id),delta:xe(e.delta),valueAfter:xe(e.value_after),completed:e.completed===true};default:return {kind:"other",type:te(e.type)}}}function pc(n){let e=n??{},t=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:te(e.entry_id),...t===void 0?{}:{rarityTier:t},rollNumber:xe(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(hn):[]}}function gc(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(pc):void 0;return {orderId:te(e.order_id),status:te(e.status),...t===void 0?{}:{etag:t},granted:Array.isArray(e.granted)?e.granted.map(hn):[],consumed:Array.isArray(e.consumed)?e.consumed.map(hn):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(hn):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function yc(n){let e=n??{},t=e.price??{};return {payment:"platform_currency",orderId:te(e.target_order_id)||te(e.source_order_id),status:te(e.status),purchaseId:te(e.purchase_id),sourceOrderId:te(e.source_order_id),price:{currencyId:te(t.platform_currency_id),amount:xe(t.price)}}}function fc(n){let e=n??{},t=typeof e.last_used_at=="string"?e.last_used_at:void 0,r=typeof e.cooldown_expires_at=="string"?e.cooldown_expires_at:void 0;return {recipeId:te(e.recipe_id),useCount:typeof e.use_count=="number"?e.use_count:0,isOnCooldown:e.is_on_cooldown===true,...t===void 0?{}:{lastUsedAt:t},...r===void 0?{}:{cooldownExpiresAt:r}}}function us(n){switch(n.type){case "currency_grant":case "currency_consume":return {type:n.type,currency_id:n.currencyId,amount:n.amount};default:return {type:n.type,item_definition_id:n.itemDefinitionId,quantity:n.quantity}}}var bn=class{constructor(e,t,r){this.api=e;this.entity=t;this.cache=r;}api;entity;cache;async create(e,t={}){let r=await this.write(()=>ai(this.api,this.entity.type,this.entity.id,{operations:e.map(us),source:t.source??"play",nonce:fn()},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}));return St(r)}async createMany(e,t={}){return this.write(()=>si(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(us),nonce:fn()})),source:t.source??"play"},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}))}async recipeAvailability(e,t,r){let i=await Si(this.api,this.entity.type,this.entity.id,e,t,r===void 0?{}:{signal:r})??{},a=typeof i.uses_remaining=="number"?i.uses_remaining:void 0,s=typeof i.cooldown_expires_at=="string"?i.cooldown_expires_at:void 0,l=Array.isArray(i.lock_reasons)?i.lock_reasons.map(uc):[];return {canExecute:i.can_execute===true,locked:i.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(i.reasons)?i.reasons.map(d=>cc(d)):[],...a===void 0?{}:{usesRemaining:a},...s===void 0?{}:{cooldownExpiresAt:s}}}async recipeUsageAll(){return this.cache.read(mc,[],async()=>{let t=await Ri(this.api,this.entity.type,this.entity.id,{limit:cs})??{},r=Array.isArray(t.usages)?t.usages:[];return {usages:r.map(fc),truncated:r.length>=cs}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,t={}){if(e.payment.kind==="configured"){let c=e,p=await this.write(()=>ui(this.api,this.entity.type,this.entity.id,{catalog_id:c.catalogId,recipe_id:c.targetId,game_id:this.api.gameId(),nonce:fn()},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}));return {payment:"configured",...gc(p)}}if(this.entity.type!=="players"||this.entity.id!=="me")throw new TypeError("platform-currency purchases are available only on gem.me.mutations");let[r,o]=await Promise.all([Ti(this.api,t.signal===void 0?{}:{signal:t.signal}),ln(this.api,t.signal===void 0?{}:{signal:t.signal})]),i=e.payment.currencySlug.toLowerCase(),a=o.currencies.find(c=>c.currency_id.toLowerCase()===i||c.slug.toLowerCase()===i);if(a===void 0){let c=o.currencies.map(p=>p.slug);throw new Me("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${c.length===0?"none":c.join(", ")}`)}let s=e.kind==="item"?r.items.find(c=>c.item_id===e.targetId):r.recipes.find(c=>c.recipe_id===e.targetId&&c.catalog_id===e.catalogId);if(s===void 0)throw new Me("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=s.platform_prices.find(c=>c.platform_currency_id===a.currency_id);if(l===void 0){let c=g=>o.currencies.find(y=>y.currency_id===g)?.slug??g,p=s.platform_prices.map(g=>`${c(g.platform_currency_id)} ${g.price}`);throw new Me("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${a.slug} price. It is priced in: ${p.length===0?"nothing":p.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new Me("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>Gi(this.api,this.entity.type,this.entity.id,{purchase_kind:e.kind,target_id:e.targetId,...e.kind==="recipe"?{catalog_id:e.catalogId}:{},quantity:d,expected_price:{platform_currency_id:a.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:fn(),confirmation:"none"},t.signal===void 0?{}:{signal:t.signal}));return yc(m)}async executeRecipe(e,t,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:t,payment:{kind:"configured"}},r)}async addProgression(e,t,r){let o=await this.write(()=>ni(this.api,this.entity.type,this.entity.id,e,{amount:t,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return St(o)}async maxProgression(e,t,r){let o=await this.write(()=>Vi(this.api,this.entity.type,this.entity.id,e,{value:t,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return St(o)}async claimProgression(e,t){let r=await this.write(()=>oi(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},t===void 0?{}:{signal:t}));return St(r)}async resetProgression(e,t){let r=await this.write(()=>Xi(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},t===void 0?{}:{signal:t}));return St(r)}async write(e){return this.cache.invalidate(),e()}};var hr=n=>typeof n=="string"?n:"",hc=n=>typeof n=="number"?n:0;function ms(n){let e=n??{};return {orderId:hr(e.order_id),status:hr(e.status),source:hr(e.source),createdAt:hc(e.created_at)}}var vn=class{constructor(e,t){this.api=e;this.entity=t;}api;entity;async list(e={}){let r=await Ni(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}})??{},o=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {data:Array.isArray(r.orders)?r.orders.map(ms):[],...o===void 0?{}:{nextCursor:o}}}async get(e,t){let r=await _i(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return ms(r)}};var ps=n=>typeof n=="number"?n:0,bc=n=>typeof n=="string"?n:"";function vc(n){let e=n??{};return {progressionDefinitionId:bc(e.progression_definition_id),currentValue:ps(e.current_value),completionCount:ps(e.completion_count),isCompleted:e.is_completed===true,...fr(e)}}var _n=class{constructor(e,t,r){this.api=e;this.entity=t;this.inventory=r;}api;entity;inventory;async list(){return (await this.inventory.snapshot()).progressions.data}async get(e,t){let o=(await this.inventory.snapshot()).progressions.data.find(i=>i.progressionDefinitionId===e);if(o&&o.achievementsUnavailable!==true)return o;try{let i=await wi(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return vc(i)}catch{return o??null}}};var wn=class{constructor(e,t){this.clock=e;this.identity=t;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,t,r,o){this.rebind();let i=t.length===0,a=i?e:e+"\0"+t.join("\0"),s=this.slots.get(a);if(s){let c=s.filledAt;if(c!==void 0&&(o===void 0||this.clock.now()-c<=o))return Promise.resolve(s.value);if(s.inFlight)return s.inFlight}let l=s??{};this.slots.set(a,l);let d=this.generation,m=r().then(c=>(i&&this.generation===d&&(l.value=c,l.filledAt=this.clock.now()),c)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(a)===l&&this.slots.delete(a));});return l.inFlight=m,m}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function br(n){let e=o=>new RegExp(`<${o}>([^<]{0,300})</${o}>`).exec(n)?.[1]?.trim()||void 0,t=[e("Code"),e("AuthenticationErrorDetail")??e("Message")].filter(Boolean);if(t.length>0)return t.join(" \u2014 ");let r=n.trim();return r?r.slice(0,300):""}async function vr(n){try{let e=br(await n.text());return e?`Storage said: ${e}`:""}catch{return ""}}var oe=class extends Error{constructor(t,r){super(r);this.reason=t;this.name="GemSaveError";}reason},_c=3e4,gs="the save payload could not reach storage. From a browser this is almost always the storage account's CORS rule, which the platform owns and your game cannot change. If every save fails this way, report it rather than working around it",wc=/^[A-Za-z0-9_]{1,64}$/;function Ae(n){let e=n.length===0?"a save key cannot be empty":n.length>64?`it is ${n.length} characters; a save key is at most 64`:n.startsWith("_")||n.startsWith("$")?`it begins with ${JSON.stringify(n[0])}, and \`_\` and \`$\` are reserved prefixes`:"a save key is ASCII letters, digits and underscores only \u2014 no hyphens, spaces or other punctuation, unlike a template slug";if(!wc.test(n)||n.startsWith("_"))throw new TypeError(`${JSON.stringify(n)} is not a usable save key: ${e}.`);return n}function ys(n,e){let t=new AbortController,r=AbortSignal.timeout(e),o=()=>t.abort(r.reason),i=()=>t.abort(n?.reason);return n?.aborted?t.abort(n.reason):(r.addEventListener("abort",o,{once:true}),n?.addEventListener("abort",i,{once:true})),{signal:t.signal,release:()=>{r.removeEventListener("abort",o),n?.removeEventListener("abort",i);}}}function _r(n,e){return n.aborted&&e?.aborted!==true}var Sc=new Set(["x-ms-blob-type"]),Rc=/^[ -~]+$/;function kc(n,e){if(n==null)return {};if(typeof n!="object"||Array.isArray(n))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} described its upload headers as ${Array.isArray(n)?"a list":typeof n}, which is not a set of headers.`);let t={};for(let[r,o]of Object.entries(n)){let i=r.toLowerCase();if(!Sc.has(i))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} asked the upload to send ${JSON.stringify(r)}, which this SDK does not put on a storage request. Report it \u2014 a platform that needs a new upload header needs an SDK release too.`);if(typeof o!="string"||!Rc.test(o))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} gave header ${JSON.stringify(r)} a value that is not usable as one.`);if(i in t)throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(i)} twice.`);t[i]=o;}return t}function wr(n){let e=typeof n.metadata=="object"&&n.metadata!==null&&!Array.isArray(n.metadata)?n.metadata:void 0;return {key:n.key,sizeBytes:n.size_bytes,etag:n.etag,...e===void 0?{}:{metadata:e},createdAt:n.created_at,updatedAt:n.updated_at}}function Sr(n){return n?.reason==="not_found"}var Sn=class{constructor(e,t,r={}){this.api=e;this.entity=t;this.options=r;}api;entity;options;async put(e,t,r={}){let o;try{o=JSON.stringify(t);}catch(i){throw new oe("save_malformed",`save ${JSON.stringify(e)} could not be serialised to JSON: ${String(i)}. Retrying stores the same unserialisable value.`)}if(o===void 0)throw new oe("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(o),{...r,contentType:"application/json"})}async putBytes(e,t,r={}){let o=r.contentType??"application/octet-stream",i=this.budget(r.timeoutMs),a=ys(r.signal,i);try{let s=await Yi(this.api,this.entity.type,this.entity.id,Ae(e),{size_bytes:t.byteLength,content_type:o,...r.metadata===void 0?{}:{metadata:r.metadata}},{signal:a.signal});if(typeof s.upload_url!="string"||typeof s.session_id!="string")throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=kc(s.upload_headers,e),d,m=this.options.fetch??globalThis.fetch.bind(globalThis);try{d=await m(s.upload_url,{method:"PUT",headers:{"content-type":o,...l},body:t,credentials:"omit",signal:a.signal});}catch(c){throw _r(a.signal,r.signal)?this.timeout("upload",i):new oe("upload_failed",`${gs} for PUT. Underlying error: ${c}`)}if(!d.ok){let c=await vr(d);throw new oe("upload_failed",d.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+c:`the save upload answered ${d.status}. `+(d.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+c)}return wr(await mi(this.api,this.entity.type,this.entity.id,Ae(e),{session_id:s.session_id},{signal:a.signal}))}catch(s){throw this.rethrow(s,r.signal,a.signal,"save",i)}finally{a.release();}}async get(e,t={}){let r=await this.getBytes(e,t);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(o){throw new oe("save_malformed",`the stored save ${JSON.stringify(e)} is not JSON, so put() did not write it. Read it with getBytes() and decode it yourself. Underlying error: ${o}`)}}async getBytes(e,t={}){let r=this.budget(t.timeoutMs),o=ys(t.signal,r);try{let i;try{let l=await cr(this.api,this.entity.type,this.entity.id,Ae(e),{signal:o.signal});if(!l.modified)return null;i=l.body;}catch(l){if(Sr(l))return null;throw l}if(typeof i.download_url!="string")throw new oe("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let a=this.options.fetch??globalThis.fetch.bind(globalThis),s;try{s=await a(i.download_url,{credentials:"omit",signal:o.signal});}catch(l){throw _r(o.signal,t.signal)?this.timeout("download",r):new oe("download_failed",`${gs} for GET. Underlying error: ${l}`)}if(!s.ok){let l=await vr(s);throw new oe("download_failed",`the save download answered ${s.status}. `+(s.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+l)}return new Uint8Array(await s.arrayBuffer())}catch(i){throw this.rethrow(i,t.signal,o.signal,"load",r)}finally{o.release();}}async describe(e,t={}){try{let r=await cr(this.api,this.entity.type,this.entity.id,Ae(e),{...t.signal===void 0?{}:{signal:t.signal},...t.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}});return r.modified?wr(r.body):null}catch(r){if(Sr(r))return null;throw r}}async list(e={}){let t=await qi(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}}),r=t.next_cursor;return {saves:(t.data??[]).map(wr),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,t){try{await di(this.api,this.entity.type,this.entity.id,Ae(e),{...t===void 0?{}:{signal:t}});}catch(r){if(!Sr(r))throw r}}budget(e){return e??this.options.timeoutMs??_c}timeout(e,t){return new oe("save_timeout",`the save ${e} did not finish within ${t}ms`)}rethrow(e,t,r,o,i){return e instanceof oe?e:_r(r,t)?this.timeout(o,i):e}};function xc(n){try{return dr(n)}catch{return n}}function Rr(n,e){let t=n??{},r=typeof t.etag=="string"?t.etag:e;return {key:typeof t.key=="string"?t.key:"",value:typeof t.value=="string"?xc(t.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof t.updated_at=="number"?t.updated_at:0}}var Rn=class{constructor(e,t){this.api=e;this.entity=t;}api;entity;async list(e){let r=(await ji(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(o=>Rr(o)):[]}async get(e,t={}){try{let r=await fi(this.api,this.entity.type,this.entity.id,e,{...t.signal===void 0?{}:{signal:t.signal},...t.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}});return r.modified?Rr(r.body,r.etag):null}catch(r){if(fs(r))return null;throw r}}async put(e,t,r={}){let o=await Wi(this.api,this.entity.type,this.entity.id,e,{value:sn(t)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return Rr(o)}async delete(e,t){try{await li(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});}catch(r){if(!fs(r))throw r}}};function fs(n){return n?.reason==="not_found"}function kn(n,e,t={}){let r=new wn(ae,t.identity);t.onInventoryChanged&&r.onInvalidate(t.onInventoryChanged);let o=new yn(n,e,r);return {settings:new Rn(n,e),inventory:o,saves:new Sn(n,e,t.saves??{}),currencies:new gn(o,t.resolveCurrencyId),mutations:new bn(n,e,r),orders:new vn(n,e),progressions:new _n(n,e,o)}}var kr={type:"players",id:"me"};var Ne=n=>typeof n=="string"?n:"",ot=n=>typeof n=="number"?n:0;function xn(n,e){let t=e??{},r=Ne(t.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...n(r),id:r,playerId:Ne(t.player_id),gameId:Ne(t.game_id),channel:Ne(t.channel)||"release",name:Ne(t.name),slotIndex:ot(t.slot_index),isActive:t.is_active!==false,createdAt:Ne(t.created_at),updatedAt:Ne(t.updated_at)}}var An=class{constructor(e,t,r,o){this.api=e;this.saves=t;this.identity=r;this.resolveCurrencyId=o;}api;saves;identity;resolveCurrencyId;scopes=new Map;scope=e=>{let t=this.scopes.get(e);return t||(t=kn(this.api,{type:"characters",id:e},{saves:this.saves,identity:this.identity,resolveCurrencyId:this.resolveCurrencyId}),this.scopes.set(e,t)),t};async list(e){let r=(await Fi(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(o=>xn(this.scope,o)):[]}async get(e,t){let r=await gi(this.api,e,t===void 0?{}:{signal:t});return xn(this.scope,r)}async create(e){let t=await ii(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return xn(this.scope,t)}async update(e,t,r){let o=await zi(this.api,e,{name:t},r===void 0?{}:{signal:r});return xn(this.scope,o)}async delete(e,t){await Qi(this.api,e,t===void 0?{}:{signal:t});}async slots(e){let r=await Ci(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:ot(r?.total_slots),availableSlots:ot(r?.available_slots),activeCharacterCount:ot(r?.active_character_count),defaultMaxSlots:ot(r?.default_max_slots),purchasedExtraSlots:ot(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var ge=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 ye(n){return new ge(n)}var qe={toPlain(n){return ge.unwrap(n)},compare(n,e,t){let r=n instanceof ge?ge.unwrap(n):n,o=e instanceof ge?ge.unwrap(e):e,i;try{i=new Intl.Collator(t);}catch{i=new Intl.Collator;}return i.compare(r,o)},equals(n,e){let t=n instanceof ge?ge.unwrap(n):n,r=e instanceof ge?ge.unwrap(e):e;return t.normalize("NFC")===r.normalize("NFC")}};var it=n=>typeof n=="string"?n:"";function Pn(n){let e=n??{},t=typeof e.message=="string"&&e.message.length>0?e.message:void 0,r=typeof e.resolved_at=="string"?e.resolved_at:void 0;return {id:it(e.transfer_id),status:it(e.status),sourceEntityId:it(e.source_entity_id),targetEntityId:it(e.target_entity_id),...t===void 0?{}:{message:ye(t)},createdAt:it(e.created_at),expiresAt:it(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function Ac(){return crypto.randomUUID()}var Tn=class{constructor(e,t,r){this.api=e;this.self=t;this.inventory=r;}api;self;inventory;async initiate(e){this.inventory.invalidate();let t=await Li(this.api,{source_entity_type:this.self.type,source_entity_id:this.self.id,target_entity_type:e.to.type,target_entity_id:e.to.id,items:(e.items??[]).map(r=>({item_definition_id:r.itemDefinitionId,quantity:r.quantity})),currencies:(e.currencies??[]).map(r=>({currency_id:r.currencyId,amount:r.amount})),...e.message===void 0?{}:{message:e.message},nonce:Ac()},e.signal===void 0?{}:{signal:e.signal});return Pn(t)}async list(e={}){let r=await Bi(this.api,{entity_type:this.self.type,entity_id:this.self.id,...e.direction===void 0?{}:{direction:e.direction},...e.status===void 0?{}:{status:e.status},...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit},...e.signal===void 0?{}:{signal:e.signal}})??{},o=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {transfers:Array.isArray(r.transfers)?r.transfers.map(Pn):[],...o===void 0?{}:{nextCursor:o}}}async get(e,t){let r=await Mi(this.api,e,t===void 0?{}:{signal:t});return Pn(r)}async accept(e,t){return this.resolve(()=>ti(this.api,e,t===void 0?{}:{signal:t}))}async reject(e,t){return this.resolve(()=>Ji(this.api,e,t===void 0?{}:{signal:t}))}async cancel(e,t){return this.resolve(()=>ri(this.api,e,t===void 0?{}:{signal:t}))}async resolve(e){return this.inventory.invalidate(),Pn(await e())}};var Pc=n=>typeof n=="string"?n:"",Tc=n=>typeof n=="string"&&n?n:void 0,Ec=n=>typeof n=="number"?n:void 0;function hs(n){let e=new Map(n.map(r=>[r.id,r])),t=new Map(n.filter(r=>r.slug).map(r=>[r.slug,r]));return r=>e.get(r)??t.get(r)??null}function Ic(n){if(typeof n!="object"||n===null||Array.isArray(n))throw new de("config_malformed",`the config document is ${n===null?"null":typeof n}, expected a JSON object`);let e=n,t=l=>{let d=e[l];if(d==null)return [];if(!Array.isArray(d))throw new de("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=Ec(e.version);if(r===void 0)throw new de("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let o=(l,d,m)=>{let c=Pc(l.id);if(!c)throw new de("config_malformed",`${d}[${m}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return c},i=t("items");i.forEach((l,d)=>o(l??{},"items",d));let a=t("currencies");a.forEach((l,d)=>o(l??{},"currencies",d));let s=n;return {...s,version:r,hash:typeof s.hash=="string"?s.hash:"",items:i,currencies:a,catalogs:t("catalogs"),loot_tables:t("loot_tables"),affix_pools:t("affix_pools"),progressions:t("progressions"),game_room_templates:t("game_room_templates"),kv:typeof s.kv=="object"&&s.kv!==null&&!Array.isArray(s.kv)?s.kv:{},item:hs(i),currency:hs(a)}}var de=class extends Error{constructor(t,r){super(r);this.reason=t;this.name="GemConfigError";}reason},bs=10*1024*1024,vs=15e3,_s=new Set(["dev","test","release"]);function Cc(n){if(!_s.has(n))throw new de("config_channel_unknown",`the play token names channel "${n}", which is not one of ${[..._s].join(", ")}. gem-api would reject the assignment read.`);return n}var En=n=>typeof n=="number"?n:0,xr=n=>typeof n=="string"?n:"";function Mc(n){let e=n??{},t=Array.isArray(e.entries)?e.entries.map(r=>{let o=r??{},i=typeof o.rarity_tier=="string"?o.rarity_tier:void 0;return {entryId:xr(o.entry_id),weight:En(o.weight),dropRate:En(o.drop_rate),...i===void 0?{}:{rarityTier:i}}}):[];return {lootTableId:xr(e.loot_table_id),name:xr(e.name),rollCount:En(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:En(e.total_weight),entries:t}}var In=class{constructor(e,t,r={}){this.api=e;this.channel=t;this.options=r;}api;channel;options;loaded=null;inFlight=null;generation=0;dropRatesByConfig=new WeakMap;load(){if(this.loaded)return Promise.resolve(this.loaded);if(this.inFlight)return this.inFlight;let e=this.generation,t=this.fetchConfig().then(r=>(this.generation===e&&(this.loaded=r),r)).finally(()=>{this.inFlight===t&&(this.inFlight=null);});return this.inFlight=t,t}refresh(){this.loaded=null,this.inFlight=null,this.generation+=1;}async dropRates(e,t){let r=await this.load();if(r===null)throw new de("config_channel_unknown",`dropRates(${e}) needs a loaded config, and this session's channel has none`);let o=this.dropRatesByConfig.get(r);o===void 0&&(o=new Map,this.dropRatesByConfig.set(r,o));let i=o.get(e);if(i!==void 0)return i;let a=(async()=>{let s=await yi(this.api,e,t===void 0?{}:{signal:t});return Mc(s)})().catch(s=>{throw o?.get(e)===a&&o.delete(e),s});return o.set(e,a),a}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??vs),t;try{let l=await pi(this.api,Cc(this.channel()),{signal:e});if(!l.modified)throw new de("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");t=l.body;}catch(l){if(l instanceof de)throw l;if(l?.reason==="not_found")return null;throw l}let r=Tc(t.config_url);if(r===void 0)return null;let o=this.options.fetch??globalThis.fetch.bind(globalThis),i;try{i=await o(r,{credentials:"omit",signal:e});}catch(l){throw e.aborted?new de("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??vs}ms`):new de("config_unreachable",`could not fetch the game config document. From a browser this is almost always the storage CORS rule: the storage account must allow this game origin for GET. It is NOT a CSP problem \u2014 game origins carry no fetch directives by design. Underlying error: ${String(l)}`)}if(!i.ok){let l=await i.text().then(d=>br(d)).catch(()=>"");throw new de("config_unreachable",`the config document answered ${i.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let a=await i.text();if(a.length>bs)throw new de("config_too_large",`the config document is ${a.length} bytes, over the ${bs} cap`);let s;try{s=JSON.parse(a);}catch(l){throw new de("config_malformed",`config document is not JSON: ${String(l)}`)}return Ic(s)}};var Ar=400,Pe=n=>typeof n=="string"?n:"",Oc=/(?:Z|[+-]\d{2}:?\d{2})$/i;function ws(n){let e=Pe(n);if(!Oc.test(e))return 0;let t=Date.parse(e);return Number.isFinite(t)?Math.floor(t/1e3):0}var Lc=/^[0-9a-f]{1,64}$/,Gc=/^[0-9a-f]{16}$/,Dc=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,$c=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function Fc(n){let e=Pe(n),t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return;let[r,o,i]=[Number(t[1]),Number(t[2]),Number(t[3])],a=new Date(Date.UTC(r,o-1,i));return a.getUTCFullYear()===r&&a.getUTCMonth()===o-1&&a.getUTCDate()===i?e:void 0}var jc=4096,Nc=new TextEncoder;function qc(n){let e=Pe(n.challenge_data),t=Pe(n.challenge_data_hash);return e===""||!Gc.test(t)?{}:Nc.encode(e).length>jc?{}:{data:e,dataHash:t}}function Uc(n){let e=n??{},t=ws(e.period_start_at),r=ws(e.period_ends_at);if(t===0||r===0)return;let o=Pe(e.slug),i=Pe(e.seed),a=Fc(e.period_local_date),s=Pe(e.boundary),l=Pe(e.reset_time);return {id:Pe(e.progression_definition_id),...o===""?{}:{slug:o},window:Pe(e.window),periodStartAt:t,periodEndsAt:r,...a===void 0?{}:{periodLocalDate:a},boundary:Dc.test(s)?s:"",resetTime:$c.test(l)?l:"",seed:Lc.test(i)?i:"",...qc(e)}}var Rt=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:t}=e;if(t!==void 0&&(!Number.isInteger(t)||t<0||t>Ar))throw new TypeError(`periodsBack must be an integer between 0 and ${Ar}, got ${String(t)}`);let o=await $i(this.#e,{...t===void 0?{}:{periods_back:t},...e.signal===void 0?{}:{signal:e.signal}})??{};return Array.isArray(o.challenges)?o.challenges.map(Uc).filter(i=>i!==void 0):[]}};function Ue(n){return typeof n=="string"&&n!==""?n:void 0}var Ss=new Set(["localhost","127.0.0.1","[::1]"]);function Pr(n){let e=Ue(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:"&&Ss.has(t.hostname)))return e}function Bc(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=t??{},o=Ue(r.item_id),i=Pr(r.icon_url);o!==void 0&&i!==void 0&&e.push({itemId:o,iconUrl:i});}return e}function ve(n){let e=n??{},t=Ue(e.player_id),r=Ue(e.display_name),o=Ue(e.discriminator),i=Ue(e.display_tag),a=Ue(e.avatar_icon_id),s=Pr(e.avatar_icon_url);return {...t===void 0?{}:{playerId:t},...r===void 0?{}:{displayName:ye(r)},...o===void 0?{}:{discriminator:o},...i===void 0?{}:{displayTag:ye(i)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},badges:Bc(e.badges)}}var Hc=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Vc(n){if(n===void 0)return;let e=Pr(n);if(e===void 0)return;let t=new URL(e);return Ss.has(t.hostname)||Hc.has(t.origin)?e:void 0}var Rs=100,kt=n=>typeof n=="string"?n:"",st=n=>typeof n=="number"?n:0,xt=n=>typeof n=="string"?n:void 0,Wc=n=>typeof n=="number"?n:void 0,As={player:"players",character:"characters"};function Kc(n,e){let t=n??{},r=xt(t.entity_id),o=typeof t.entity_type=="string"&&Object.hasOwn(As,t.entity_type)?t.entity_type:void 0,i=Ps(t.stats),a=t.properties!==null&&typeof t.properties=="object"?t.properties:void 0,s=e?t.is_viewer===true:void 0;return {...ve(t),rank:st(t.rank),occurredAt:st(t.occurred_at),...s===void 0?{}:{isViewer:s},...r===void 0?{}:{entityId:r},...o===void 0?{}:{entityType:o},...i===void 0?{}:{stats:i},...a===void 0?{}:{properties:a}}}function ks(n,e){let t=n??{},r=xt(t.bucket_1),o=xt(t.bucket_2),i=Wc(t.update_frequency_seconds);return {leaderboardType:kt(t.leaderboard_type),runType:kt(t.run_type),...r===void 0?{}:{bucket1:r},...o===void 0?{}:{bucket2:o},entries:Array.isArray(t.entries)?t.entries.map(a=>Kc(a,e)):[],generatedAt:st(t.generated_at),...i===void 0?{}:{updateFrequencySeconds:i}}}function xs(n){if(n===null||typeof n!="object"||Array.isArray(n))return;let e=n;if(!Number.isFinite(e.rank))return;let t=Ps(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:st(e.occurred_at),...t===void 0?{}:{stats:t},...r===void 0?{}:{properties:r}}}function Ps(n){if(n===null||typeof n!="object")return;let e={};for(let[t,r]of Object.entries(n))typeof r=="number"&&(e[t]=r);return e}function Jc(n,e,t){let r=n??{},o=xt(r.bucket_1),i=xt(r.bucket_2);return {leaderboardType:kt(r.leaderboard_type),runType:kt(r.run_type),entityType:e,entityId:t,...o===void 0?{}:{bucket1:o},...i===void 0?{}:{bucket2:i},entries:Array.isArray(r.entries)?r.entries.map(xs).filter(a=>a!==void 0):[],personalBest:xs(r.personal_best)??null,totalRuns:st(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:st(r.generated_at)}}var At=class{#e;constructor(e){this.#e=e;}async get(e,t={}){let r=await Ai(this.#e,e,{...t.bucket1===void 0?{}:{bucket_1:t.bucket1},...t.bucket2===void 0?{}:{bucket_2:t.bucket2},...t.signal===void 0?{}:{signal:t.signal}});return ks(r,false)}async friends(e,t={}){let r=await ki(this.#e,e,{...t.bucket1===void 0?{}:{bucket_1:t.bucket1},...t.bucket2===void 0?{}:{bucket_2:t.bucket2},...t.signal===void 0?{}:{signal:t.signal}});return ks(r,true)}async mine(e,t={}){return this.#i(e,"player","me",t)}async character(e,t,r={}){return this.#i(e,"character",t,r)}async#i(e,t,r,o){if(o.limit!==void 0){let{limit:s}=o;if(!Number.isInteger(s)||s<1||s>Rs)throw new TypeError(`limit must be an integer between 1 and ${Rs}, got ${String(s)}`)}let i=await vi(this.#e,e,As[t],r,{...o.bucket1===void 0?{}:{bucket_1:o.bucket1},...o.bucket2===void 0?{}:{bucket_2:o.bucket2},...o.limit===void 0?{}:{limit:o.limit},...o.signal===void 0?{}:{signal:o.signal}}),a=t==="player"&&r==="me"&&kt((i??{}).entity_id)||r;return Jc(i,t,a)}};var Cn=n=>typeof n=="string"?n:"",Tr=n=>typeof n=="number"?n:0;function Ts(n){let e=n??{};return {playerId:Cn(e.player_id),key:Cn(e.key),value:e.value,updatedAt:Tr(e.updated_at)}}function zc(n){let e=n??{};return {...ve(e),playerId:Cn(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:Tr(e.updated_at)}}function Yc(n){return n?.reason==="not_found"}var Pt=class{constructor(e,t){this.api=e;this.selfPlayerId=t;}api;selfPlayerId;async friends(e,t={}){let o=await xi(this.api,Ae(e),{...t.signal===void 0?{}:{signal:t.signal}})??{};return {key:Cn(o.key),entries:Array.isArray(o.entries)?o.entries.map(zc):[],generatedAt:Tr(o.generated_at)}}async of(e,t,r={}){try{return Ts(await Ii(this.api,e,Ae(t),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(o){if(Yc(o))return null;throw o}}async set(e,t,r={}){if(Ae(e),t===void 0)throw new TypeError(`showcase value for ${JSON.stringify(e)} is undefined, which is not JSON. Use clear() to remove one.`);try{JSON.stringify(t);}catch(i){throw new TypeError(`showcase value for ${JSON.stringify(e)} could not be serialised to JSON: ${String(i)}.`,{cause:i})}let o=await this.selfPlayerId();return Ts(await Ki(this.api,o,e,{value:t},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,t={}){let r=await this.selfPlayerId();await ci(this.api,r,Ae(e),{...t.signal===void 0?{}:{signal:t.signal}});}};var Es=n=>typeof n=="string"?n:void 0;function Xc(n){let e=n??{};return {...ve(e),playerId:Es(e.player_id)??""}}function Qc(n){let e=n??{},t=e.has_more===true?Es(e.next_cursor):void 0;return {friends:Array.isArray(e.data)?e.data.map(Xc):[],...t===void 0?{}:{nextCursor:t}}}var Tt=class{#e;constructor(e){this.#e=e;}async list(e={}){let t=await Ui(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Qc(t)}};var Is=n=>typeof n=="string"?n:void 0;function Zc(n){let e=n??{},t=Is(e.currency_id);if(t===void 0||t==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Is(e.slug)??"",currencyId:t,balance:r,access:e.access==="spend"?"spend":"read"}}var Mn=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await ln(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=Zc(i);a!==void 0&&o.push(a);}return o}},Et=class{currencies;constructor(e){this.currencies=new Mn(e);}};var Er=n=>typeof n=="string"?n:"",Cs=n=>typeof n=="number"?n:0;function eu(n){let e=n??{};return {key:Er(e.key),visibility:Er(e.visibility),value:e.value,updatedAt:Cs(e.updated_at)}}function tu(n){let e=n??{};return {...ve(e),playerId:Er(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(eu):[],generatedAt:Cs(e.generated_at)}}function nu(n){return n?.reason==="not_found"}var It=class{#e;constructor(e){this.#e=e;}async of(e,t={}){try{return tu(await Pi(this.#e,e,{...t.signal===void 0?{}:{signal:t.signal}}))}catch(r){if(nu(r))return null;throw r}}};var ru=new Map([["function_error",false],["function_failed",false],["function_timeout",false],["function_not_published",false],["function_input_too_large",false],["functions_not_configured",false],["forbidden",false],["function_capacity_unavailable",true],["function_host_unreachable",true],["function_host_error",true],["rate_limited",true],["service_unavailable",true]]),Ct=class extends D{constructor(e,t){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,t);}get retryable(){return (this.code===void 0?void 0:ru.get(this.code))??super.retryable}},Oe=class{#e;constructor(e){this.#e=e;}async invoke(e,t={}){let r=ou(e),o;try{o=await this.#e(r,t.signal===void 0?{}:{signal:t.signal});}catch(i){throw i instanceof D?su(i):i}return iu(o)}};function ou(n){if(n instanceof ArrayBuffer)return new Uint8Array(n);if(ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);let e;try{e=JSON.stringify(n);}catch(t){throw new ne(`the function input could not be serialised to JSON: ${String(t)}. Pass bytes, or a value JSON can carry. This is a bug in the call, not a server failure.`)}if(e===void 0)throw new ne(`the function input is ${typeof n}, which JSON cannot carry. Pass bytes \u2014 an empty Uint8Array for no input \u2014 or a JSON value. This is a bug in the call, not a server failure.`);return new TextEncoder().encode(e)}function iu(n){let{bytes:e}=n,t=()=>new TextDecoder("utf-8",{fatal:true}).decode(e);return {bytes:e,...n.invocationId===void 0?{}:{invocationId:n.invocationId},text:t,json:()=>JSON.parse(t())}}function su(n){let{details:e,invocationId:t}=ei(n),o=e?.untrusted?.message,i=e?.reason;return new Ct(n,{...t===void 0?{}:{invocationId:t},...n.code==="function_error"&&typeof o=="string"?{functionMessage:o}:{},...n.code==="function_failed"&&typeof i=="string"?{failure:i}:{}})}var au=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],Ir="gem_";function Ms(n){return n.startsWith(Ir)}var Os=1e4,lu=50,du=500,cu=65536-4*1024,uu=24*1024;function Ls(n){let e={},t={};for(let[r,o]of Object.entries(n))typeof o=="string"?e[r]=o:typeof o=="number"&&Number.isFinite(o)&&(t[r]=o);return {dimensions:e,measures:t}}var Gs=n=>typeof n=="number"?n:0,mu=n=>typeof n=="string"?n:"";function Ds(n=0){return {accepted:0,rejected:[],dropped:n,duplicate:false}}function pu(n,e){let t=n??{},r=Array.isArray(t.rejected)?t.rejected.map(o=>{let i=o??{};return {index:Gs(i.index),code:mu(i.code)}}):[];return {accepted:Gs(t.accepted),rejected:r,dropped:e,duplicate:t.duplicate===true}}function $s(){let n=globalThis.crypto;return typeof n?.randomUUID=="function"?n.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.floor(Math.random()*16);return (e==="x"?t:t&3|8).toString(16)})}function gu(n){return n?.retryable===true}var Mt=class{#e;#i;#b;#u;#t=[];#m={};#r=0;#o=null;#p=false;#g=false;#y=false;#n=false;#f=null;#s=null;#a=false;#v=false;#_=false;constructor(e){this.#e=e,this.#i=e.options?.enabled!==false,this.#b=Math.max(Os,e.options?.flushIntervalMs??Os),this.#u=Math.max(1,Math.floor(e.options?.maxQueue??du));}track(e,t={}){if(!(!this.#i||this.#n)){if(Ms(e)){this.#_||(this.#_=true,this.#c(`[gem] analytics: '${e}' was not recorded \u2014 the gem_ prefix is reserved for the platform's own events, which the SDK emits for you. Name your event something else.`));return}this.#w(e,Ls({...this.#m,...t}));}}setContext(e){this.#m={...this.#m,...e};}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){let t=this.#A();if(t===null||t==="")return this.#t.length>0&&!this.#v&&(this.#v=true,this.#c("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),Ds();if(this.#S(),this.#t.length===0)return Ds();let r=e.keepalive===true;this.#d();let o=this.#t.splice(0,this.#k(r)),i=this.#r;this.#r=0;let a=Math.round(this.#e.clock.now()),s={batch_id:$s(),sent_at_ms:a,events:o.map(d=>Fs(d,a))},l={client:this.#e.client(),gameId:()=>t};this.#y=true;try{let d=await Oi(l,s,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=pu(d,i);return this.#x(m),m}catch(d){throw gu(d)?this.#R(o,i):this.#c(`[gem] analytics: ${o.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#y=false,this.#t.length>0&&this.#l();}}trackPlatform(e,t={}){this.#n||this.#w(e,Ls(t));}startSession(){this.#n||this.#s!==null||(this.#s=this.#e.clock.now(),this.#a=false,this.trackPlatform("gem_session_start"));}endSession(e){if(this.#n||this.#a)return;this.#a=true;let t=this.#s;this.trackPlatform("gem_session_end",{reason:e,...t===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-t))}}),this.#h({keepalive:true});}setPaused(e){this.#n||e===this.#p||(this.#p=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#d():this.#t.length>0&&this.#l());}setHidden(e){this.#n||e===this.#g||(this.#g=e,e?this.#d():this.#t.length>0&&this.#l());}dispose(){this.#n=true,this.#d(),this.#t=[],this.#r=0;}get pending(){return this.#t.length}#w(e,t){let{dimensions:r,measures:o}=t;for(this.#S();this.#t.length>=this.#u;)this.#t.shift(),this.#r+=1;this.#t.push({uid:$s(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:o}),this.#t.length>=lu?this.#h():this.#l();}#h(e={}){this.flush(e).catch(()=>{});}#R(e,t){for(this.#t=[...e,...this.#t],this.#r+=t;this.#t.length>this.#u;)this.#t.shift(),this.#r+=1;}#k(e){let t=e?uu:cu,r=Math.min(this.#t.length,100),o=128;for(let i=0;i<r;i+=1){let a=this.#t[i];if(a===void 0)break;if(o+=JSON.stringify(Fs(a,0)).length+1,o>t)return Math.max(1,i)}return r}#l(){this.#o!==null||this.#p||this.#g||this.#n||this.#y||(this.#o=this.#e.clock.setTimeout(()=>{this.#o=null,this.#h();},this.#b));}#d(){this.#o!==null&&(this.#e.clock.clearTimeout(this.#o),this.#o=null);}#S(){let e=this.#P();e===null||e===""||(this.#f!==null&&this.#f!==e&&(this.#t=[],this.#r=0,this.#s=null,this.#a=false),this.#f=e);}#x(e){for(let t of e.rejected)this.#c(`[gem] analytics: an event was refused (${t.code}). `+yu(t.code));}#c(e){let t=this.#e.log;t!==null&&(t===void 0?console.warn(e):t(e));}#A(){try{return this.#e.gameId()}catch{return null}}#P(){try{return this.#e.playerId()}catch{return null}}};function Fs(n,e){return {event_uid:n.uid,name:n.name,offset_ms:Math.round(n.atMs)-e,dimensions:n.dimensions,measures:n.measures}}function yu(n){switch(n){case "analytics_not_declared":return "This channel has no analytics_events section at all \u2014 promote a game config that declares one. The gem_* events in the same batch were still recorded.";case "unknown_event":return "This channel declares a set of events and this name is not in it \u2014 check the spelling, or declare it in analytics_events.";case "unknown_dimension":return "A string property on this event is not declared as one of its dimensions.";case "missing_dimension":return "A dimension this event declares was not supplied.";case "dimension_value_not_declared":return "A dimension value is outside the closed set the config declares for it.";case "unknown_measure":return "A numeric property on this event is not declared as one of its measures.";case "measure_wrong_type":return "A measure was the wrong shape \u2014 an int measure refuses a fractional value.";case "source_not_permitted":return "This event is declared for the server only, so a client may not emit it.";default:return "See the analytics_events section of your game config."}}function pe(n){if(typeof n!="string")return;let e=n.trim();return e.length===0?void 0:e}function Ot(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=pe(t);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var fu=2e3,hu=5e3;function Ns(n){let e=[],t=false,r=null,o=new Map,i=()=>{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??fu);});return r={promise:s,settle:a},s};return {resolveList:i,resolve(){return e.length>0||t||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):i().then(a=>a[0])},refresh(a){return !js(e,a)||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(s=>{let l=null,d=m=>{o.delete(d)&&(n.clock.clearTimeout(l),s(m));};o.set(d,a),l=n.clock.setTimeout(()=>d(e),n.refreshTimeoutMs??hu);})},accept(a,s){let l=Ot(s),d=pe(a),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[c,p]of [...o])js(m,p)||c(m);}}}}function js(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var bu=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),h=class extends Error{constructor(t,r,o){super(`${t}: ${r}`,o);this.reason=t;this.name="DedicatedServerError",this.retryable=bu.has(t),this.platformCode=o?.platformCode;}reason;retryable;platformCode};var qs=["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"],vu=new Set(qs);function Le(n){return typeof n=="string"&&vu.has(n)?n:"unknown"}var On="webrtc_dedicated",Lr=["universal","mobile","web"];var _u="p2p_unavailable",wu="capacity_unavailable",Su=2,Us=3e4,Bs=1e3,Hs=2e4;async function Gr(n){let e=pe(n.clusterTargetId),t=n.nextClusterTarget,r=0,o=n.clock??ae,i=n.retry??{},a=i.budgetMs??Us,s=i.maxDelayMs??Hs,l=i.initialDelayMs??Bs,d=o.now(),m=d+a,c=0;for(;;){c++;try{let p=await jr(n.signal,"while allocating",()=>n.client.post(`${Ks(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!Ru(p)||a<=0)throw p;if(p.status===503&&p.code===_u)throw new h("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===wu?r+1:0,t!==void 0&&r>=Su){let C=t;t=void 0;let E=pe(await C());E!==void 0&&(e=E,r=0);}let g=Math.min(s,l*2**(c-1)),y=Math.min(s,(p.retryAfterSeconds??0)*1e3),x=Math.max(g/2,y)+Math.random()*(g/2);if(o.now()+x>m)throw ku(n,p,c,o.now()-d,a);if(i.onWaiting?.({attempt:c,elapsedMs:o.now()-d,budgetMs:a,nextAttemptInMs:x,status:p.status,message:p.message}),await Ln(o,x,n.signal),n.signal?.aborted)throw Or("while waiting to allocate")}}}function Ru(n){return n instanceof D?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function ku(n,e,t,r,o){let i=`${t} attempt${t===1?"":"s"} over ${r}ms of a ${o}ms budget`;return e.status===429?new h("start_rate_limited",`the platform was still limiting match starts for room ${n.roomId} after ${i}: ${e.message}`,{cause:e}):new h("no_server_ready",`the platform had no server ready for room ${n.roomId} after ${i}: ${e.message}`,{cause:e})}var xu=12e4,Au=1e3;async function Dr(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??Au,o=n.timeoutMs??xu,i=e.now()+o,a=Vs(n),s={seen:n.knownToExist===true};for(;;){let l=await Ws(n,a,s);if(l.outcome!==null)return l.outcome;if(e.now()+r>i)throw new h("timeout",`match ${t} was still ${l.status} after ${o}ms`);await Ln(e,r,n.signal);}}async function $r(n){return (await Ws(n,Vs(n),{seen:n.knownToExist===true})).outcome}function Vs(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${Ks(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function Ws(n,e,t){let{matchId:r}=n,o=n.clock.now(),i;try{i=await jr(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(a){if(a instanceof D&&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,i.status==="ready")return {status:"ready",outcome:Pu(r,i,o)};if(i.status==="failed"){let a=i.ended_reason;return typeof a=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Le(a)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:i.failure_reason??"unknown"}}}return {status:i.status,outcome:null}}async function Fr(n){let e=await jr(n.signal,"while listing cluster targets",()=>n.client.get("/v1/ping/targets",n.signal)),t=[];for(let r of e.targets??[]){let o=r?.cluster_target_id;typeof o!="string"||o.length===0||t.push({id:o,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return t}async function jr(n,e,t){if(n?.aborted)throw Or(e);try{return await t()}catch(r){throw n?.aborted?Or(e,r):r}}function Or(n,e){return new h("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function Pu(n,e,t){let r=e.join_credential,o=e.expires_in_seconds,i=typeof r=="string"&&typeof o=="number";return {status:"ready",matchId:n,protocol:e.protocol??"unknown",...i?{joinCredential:r,credentialExpiresAt:t+o*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function Ks(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function Ln(n,e,t){return t?.aborted?Promise.resolve():new Promise(r=>{let o=()=>{n.clearTimeout(i),t?.removeEventListener("abort",o),r();},i=n.setTimeout(o,e);t?.addEventListener("abort",o);})}function Js(n){return typeof n=="string"&&n.trim()!==""}function Gn(n,e){return Js(n)?n.trim():Js(e)?e:null}var Dn="0.1.0-beta",zs="0-beta",at="web",Tu=/^(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 Eu(n){let e=Tu.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function Ys(n,e){let t=Iu(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:Dn};let o=Eu(r);if(o===null)throw new h("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 '${Dn}' for it.`);if(o!==zs)throw new h("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${o}', and '${zs}' 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 '${o}' 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 '${Dn}' for it.`);return {...n,platform:t,engineVersion:r}}function Iu(n,e){if(n===void 0||n===at)return at;if(!Lr.includes(n))throw new h("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${Lr.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${at}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${at}' 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.`),at}var Cu="join",Mu="welcome",Ou="rejected",Xs=25e3,Lu=1e3,Nr=1;function qr(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var Gu={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 Ur(n){let e=typeof n=="string"?n:"unknown";return new h(Gu[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function Lt(n){let{channel:e,clock:t}=n;return new Promise((r,o)=>{let i=false,a=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??Xs),s=t.setTimeout(()=>w(new h("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,Lu)),l=x=>{let C=x.data;if(typeof C!="string"){c(C);return}let E;try{E=JSON.parse(C);}catch{c(C);return}if(i){c(C);return}if(E.t===Mu){let v=qr(E.heartbeat_interval);y({...typeof E.player_id=="string"?{playerId:E.player_id}:{},...typeof E.match_id=="string"?{matchId:E.match_id}:{},...v===void 0?{}:{heartbeatIntervalMs:v}});return}if(E.t===Ou){w(Ur(E.reason));return}c(C);},d=()=>{w(new h("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{w(new h("aborted","the caller aborted during the join exchange"));},c=x=>{i&&n.onMessage?.(x);},p=()=>{t.clearTimeout(s),e.removeEventListener("close",d),n.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=x=>{i=true,p(),n.onMessage===void 0&&g(),r({welcome:x,detach:g});},w=x=>{i||(i=true,p(),g(),o(x));};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:Cu,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:Nr}:{}}));}catch(x){w(new h("connection_failed",`the join frame could not be sent on the open channel: ${String(x)}`,{cause:x}));}})}var Be=1,Gt=2,Br=4,Wr=8,Du=2,$u=1e3,Kr="heartbeat timeout",Dt="gem-uu",$n=2,Zs="gem_transports";function lt(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!Fu(r)||e.includes(r)||e.push(r);}return e}function Fu(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function $t(n,e){if(typeof n!="object"||n===null)return null;let t=n[Zs];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 Fn(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var ea=new TextEncoder,ta=new TextDecoder;function Jr(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function zr(n){let e=0;return n?.reliable===false&&(e|=Be),n?.ordered===false&&(e|=Gt),e}function Yr(n){return {reliable:(n&Be)===0,ordered:(n&Gt)===0}}var Xr={reliable:true,ordered:true};function na(n){return JSON.stringify({t:"join",credential:n,wire:$n,heartbeat:Nr})}function ra(n){let e;try{e=JSON.parse(n);}catch{throw new h("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let t=qr(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"?Ur(e.reason):new h("join_refused","the server answered the join out of protocol")}function jn(){return typeof globalThis.WebTransport=="function"&&Qr===null}function Nn(){return Qr}var Qr=null;var Qs="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function ju(n){let e=an(n);if(e.byteLength!==32)throw new h("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var Hr=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 i=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(i===0||i>1<<20)throw new h("connection_failed",`a control-stream record claims ${i} bytes`);if(this.buffered.byteLength<4+i)break;let a=this.buffered.slice(4,4+i);this.buffered=this.buffered.slice(4+i),r.push({flags:a[0]??0,payload:a.slice(1)});}return r}};function Vr(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 Ft(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 h("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:ju(n.certHashBase64)}]});}let r=t,o=s=>{try{r.close();}catch{}throw s},i=r.datagrams;(i?.readable===void 0||i.writable===void 0)&&(Qr=Qs,o(new h("connection_failed",`${Qs}; the rung is skipped for the rest of this page (a reload probes again)`)));let a=new Promise((s,l)=>{setTimeout(()=>l(new h("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 o(new h("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(Vr(Br,ea.encode(na(n.credential))));let c=new Hr,p=d.readable.getReader(),g;for(;g===void 0;){let y=await Promise.race([p.read(),a]);if(y.done||y.value===void 0)return o(new h("connection_failed","the control stream closed before the join was answered"));for(let w of c.push(y.value)){g=ra(ta.decode(w.payload));break}}return {link:Nu(r,m,p,c,n.log??(y=>console.warn(y)),ia(g,n.clock)),welcome:g}}catch(s){return o(s)}}function Nu(n,e,t,r,o,i){let a,s,l=false,d=y=>{if(!l){l=true,m.stop();try{n.close();}catch{}s?.(y);}},m=eo(i,()=>d(Kr)),c=(y,w)=>{m.heard(),(y&Wr)===0&&a!==void 0&&((y&Br)!==0?a(ta.decode(w),Xr):a(w,Yr(y)));};(async()=>{try{for(;;){let y=await t.read();if(y.done||y.value===void 0)break;for(let w of r.push(y.value))c(w.flags,w.payload);}}catch{}d("stream closed");})();let p,g;try{let y=n.datagrams;if(y?.readable!==void 0&&y.writable!==void 0){let w=y.readable.getReader();g=y.writable.getWriter(),p=y,(async()=>{try{for(;;){let x=await w.read();if(x.done||x.value===void 0)break;let C=x.value;C.byteLength!==0&&c((C[0]??0)|Be|Gt,C.slice(1));}}catch{}})();}else o("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(y){p=void 0,g=void 0,o(`[gem] webtransport datagram lane unusable (${Fn(y)}); unreliable sends ride the stream`);}return n.closed.then(y=>d(oa(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,w){if(l)return;if(typeof y=="string"){e.write(Vr(Br,ea.encode(y))).catch(()=>d("write failed"));return}let x=zr(w);if((x&Be)!==0&&g!==void 0){let C=Jr(x,y),E=p?.maxDatagramSize;if(E===void 0||C.byteLength<=E){g.write(C).catch(()=>{});return}}e.write(Vr(x,y)).catch(()=>d("write failed"));},onMessage(y){a=y;},onClose(y){s=y;},close(){d("closed");}}}function Zr(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webSocket;if(t===void 0){let o=globalThis.WebSocket;if(o===void 0)return Promise.reject(new h("connection_failed","this environment has no WebSocket"));t=new o(n.url);}let r=t;return r.binaryType="arraybuffer",new Promise((o,i)=>{let a=false,s=setTimeout(()=>{a||(a=true,r.close(),i(new h("timeout","websocket did not come up in time")));},e),l=g=>{a||(a=true,clearTimeout(s),r.close(),i(g));},d=()=>{r.send(na(n.credential));},m=g=>{if(a)return;if(typeof g.data!="string"){l(new h("join_refused","the server sent binary before answering the join"));return}let y;try{y=ra(g.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),o({link:qu(r,ia(y,n.clock)),welcome:y});},c=()=>{l(new h("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new h("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 oa(n){return typeof n=="string"&&n.length>0?n:void 0}function ia(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function eo(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,$u)*Du,o=t.now(),i=null,a=()=>{i=null;let s=t.now()-o;if(s>=r){e();return}i=t.setTimeout(a,r-s);};return i=t.setTimeout(a,r),{heard:()=>{o=t.now();},stop:()=>{i!==null&&(t.clearTimeout(i),i=null);}}}function qu(n,e){let t,r,o=false,i=s=>{if(!o){o=true,a.stop();try{n.close();}catch{}r?.(s);}},a=eo(e,()=>i(Kr));return n.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){t?.(s.data,Xr);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&Wr)===0&&t?.(l.slice(1),Yr(d));})),n.addEventListener("close",(s=>i(oa(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!o){if(typeof s=="string"){n.send(s);return}n.send(Jr(zr(l),s));}},onMessage(s){t=s;},onClose(s){r=s;},close(){i("closed");}}}function to(n,e,t,r){let o,i,a=false,s=t,l=c=>{if(!a){a=true,d.stop();try{n.close();}catch{}try{e.close();}catch{}i?.(c);}},d=eo(r,()=>l(Kr)),m=(c,p)=>{if(d.heard(),typeof c=="string"){o?.(c,Xr);return}let g=new Uint8Array(c);if(g.byteLength===0)return;let y=g[0]??0;(y&Wr)===0&&o?.(g.slice(1),Yr(y|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,Be|Gt))),c.addEventListener("close",(()=>{s=void 0;}));}return {transport:"webrtc",send(c,p){if(a)return;if(typeof c=="string"){n.send(c);return}let g=zr(p),y=Jr(g,c);if((g&Be)!==0&&s!==void 0&&s.readyState==="open"){s.send(y);return}n.send(y);},onMessage(c){o=c;},onClose(c){i=c;},close(){l("closed");}}}function oo(n){if(typeof n!="object"||n===null)return;let e={};for(let[t,r]of Object.entries(n)){let o=no(r);o!==void 0&&(e[t]=o);}return e}function io(n){if(Array.isArray(n))return n.map(Uu).filter(e=>!!e)}function no(n){if(ro(n)||Array.isArray(n)&&n.every(ro))return n}function ro(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function Uu(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=no(e.fixed),r=no(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},...dt("description",Bu(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(ro)?{allowed:e.allowed}:{},...dt("min",jt(e.min)),...dt("max",jt(e.max)),...dt("minItems",jt(e.min_items)),...dt("maxItems",jt(e.max_items)),...dt("maxLength",jt(e.max_length))}}function Bu(n){return typeof n=="string"&&n.length>0?n:void 0}function jt(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function dt(n,e){return e===void 0?{}:{[n]:e}}function Ee(n){let e=n??{},t=Y(e.id)??Y(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(sa):[];return {id:t,gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Te(e.max_players)??0,memberCount:Te(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,..._e("joinCode",Y(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},..._e("roomArgs",oo(e.room_args)),..._e("roomArgsTemplate",io(e.room_args_template)),gameChannel:Y(e.game_channel)??"release",..._e("region",Y(e.region)),..._e("clusterTargetId",Y(e.cluster_target_id)),..._e("matchId",Y(e.match_id)),version:Te(e.version)??0,..._e("templateId",Y(e.template_id)),roomType:Y(e.game_room_type)??"Standard",..._e("transports",lt(e.transports)??void 0),createdAt:Te(e.created_at)??0,updatedAt:Te(e.updated_at)??0,..._e("startedAt",Te(e.started_at))}}function sa(n){let e=n??{};return {...ve(e),playerId:Y(e.player_id)??"",isReady:e.is_ready===true,role:Y(e.role)??"member",joinedAt:Te(e.joined_at)??0,..._e("groupId",Y(e.group_id)),..._e("platform",Y(e.platform))}}function qn(n){let e=n??{};return {id:Y(e.id)??Y(e.game_room_id)??"",gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Te(e.max_players)??0,memberCount:Te(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Y(e.game_channel)??"release",roomType:Y(e.game_room_type)??"Standard",createdAt:Te(e.created_at)??0}}function Y(n){return typeof n=="string"&&n.length>0?n:void 0}function Te(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function _e(n,e){return e===void 0?{}:{[n]:e}}var Nt=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(o=>({rooms:(o.game_rooms??[]).map(qn),...typeof o.next_cursor=="string"?{nextCursor:o.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(qn)}))}create(e,t,r){return Hu(e.maxPlayers),this.options.client.post(this.baseV2(),{name:e.name,...e.isPublic===void 0?{}:{is_public:e.isPublic},...e.settings===void 0?{}:{settings:e.settings},...e.region===void 0?{}:{region:e.region},...r===void 0?{}:{cluster_target_id:r},...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.partyId===void 0?{}:{party_id:e.partyId},...e.roomArgs===void 0?{}:{room_args:e.roomArgs},...Un(t)},e.signal).then(Ee)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(Ee)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...Un(r)},t.signal).then(Ee)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...Un(r)},t.signal).then(Ee)}quickJoin(e,t,r=[]){return this.options.client.post(`${this.baseV2()}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...Un(t)},e.signal).then(Ee)}leave(e,t,r,o=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:t},r,{keepalive:o}).then(()=>{})}close(e,t){return this.options.client.delete(this.roomV1(e),t).then(()=>{})}update(e,t){return this.options.client.patch(this.roomV2(e),{...t.name===void 0?{}:{name:t.name},...t.maxPlayers===void 0?{}:{max_players:t.maxPlayers},...t.isPublic===void 0?{}:{is_public:t.isPublic},...t.settings===void 0?{}:{settings:t.settings},...t.roomArgs===void 0?{}:{room_args:t.roomArgs}},t.signal).then(Ee)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(Ee)}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(Ee)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function Un(n){return {platform:n.platform,game_version:n.gameVersion,engine_version:n.engineVersion}}function Hu(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 qt=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 o=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(t)&&this.retainedMatch===o&&t(o);});}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,((...o)=>{r(),t(...o);}));return r}emit(e,...t){e==="matchReady"&&(this.retainedMatch=t[0]);let r=this.listeners.get(e);if(r)for(let o of [...r])o(...t);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};function Vu(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var Wu=1e3,Ku=3e3,Ju=6e4,zu=2,aa=new Set(["game_room_closed","game_room_gone"]),Yu=12e4,Xu=5e3,Qu=new Set(["invalid_cluster_target","capacity_unavailable"]);function ao(n){return new so(n)}var so=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Nt({client:e.client,gameId:()=>this.requireGameId()}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new qt;api;room=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create");let t=this.clusterTargets(),r=await this.attachParty(e),o=await this.run("create",async()=>{let i=await t;return this.api.create(r,this.version("create"),i[0]).catch(async a=>{let s=await this.afterRefusedClusters(a,i);if(s[0]===void 0||s[0]===i[0])throw a;return this.api.create(r,this.version("create"),s[0])})});return this.enter(o,"created"),o}async join(e,t={}){this.assertNotInRoom("join");let r=await this.attachParty(t),o=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(o,"joined"),o}async joinByCode(e,t={}){this.assertNotInRoom("joinByCode");let r=await this.attachParty(t),o=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(o,"joined"),o}async quickJoin(e){this.assertNotInRoom("quickJoin");let t=this.clusterTargets(),r=await this.attachParty(e),o=a=>this.api.quickJoin(r,this.version("quickJoin"),a).catch(s=>this.retryPastStaleMembership(s,r,a)),i=await this.run("quickJoin",async()=>{let a=await t;return o(a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||em(l,a))throw s;return o(l)})});return this.enter(i,"joined"),i}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,o=()=>this.run("leave",()=>this.api.leave(t.id,e.asGroup!==false,e.signal,r));if(r){let i=o();this.track(this.notifyLeavingMatch({keepalive:true})),await i;}else await this.notifyLeavingMatch(),await o();this.exit(),this.emitter.emit("left");}async leaveAll(e){let t=await this.myRooms(e),r=[];for(let o of t)try{await this.run("leaveAll",()=>this.api.leave(o.id,!0,e)),r.push(o.id),this.room?.id===o.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(o){if(o instanceof D&&o.reason==="not_found"){let i=this.heldMatchId;if(i!==null){let a=await this.askWhyEnded(i,e);this.endMatch(i,a??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",o),o}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 o=await this.askWhyEnded(r,e);o!==null&&this.endMatch(r,o,t.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,t){let r=this.room;if(r===null)return null;let o=this.takeHint(e),i;try{i=await this.track(this.onceGameIdKnown(()=>$r({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 D&&a.reason==="not_found"?o??null:(this.reportError("reconcile",a),null)}return i===null?null:i.status==="ready"?(this.seenMatches.add(e),null):i.status==="failed"?(this.settleFailed(i.matchId,i.reason),null):i.reason==="unknown"&&o!==null?o:i.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=Le(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"),o=await this.run("setReady",()=>this.api.setReady(r.id,e,t));return this.apply(o),o}async kick(e,t){let r=this.requireRoom("kick"),o=await this.run("kick",()=>this.api.kick(r.id,e,t));return this.apply(o),o}async transferHost(e,t){let r=this.requireRoom("transferHost"),o=await this.run("transferHost",()=>this.api.transferHost(r.id,e,t));return this.apply(o),o}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 h("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 o=pe(t.clusterTargetId),i=o??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),a=i??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let s=(m,c)=>Gr({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...o===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(i,[a]).catch(async m=>{if(o!==void 0||!da(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 h("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),o=await this.run("pollMatchStatus",()=>this.chase(t.id,r,e));return this.settleOutcome(o)}chase(e,t,r){return Dr({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 h("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!aa.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new h("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 o={matchId:e,cause:t,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=o,this.track(this.reconnectStep(o));}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(!He()){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<Wu){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(Vu(e.attempt,t.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!He()){this.park(e,()=>this.reconnectAttempt(e));return}let t=this.options.autoReconnect,r=this.room;if(t===void 0||r===null)return;let o=null;try{o=await this.track(this.onceGameIdKnown(()=>$r({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(i){this.reportError("reconcile",i);}if(this.reconnecting(e)){if(o?.status==="ended"){this.endMatch(o.matchId,o.reason,!aa.has(o.reason)),this.track(this.reconcile().catch(()=>{}));return}if(o?.status==="failed"){this.abandonReconnect(e.matchId,o.reason),this.settleFailed(o.matchId,o.reason);return}if(o?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(o);let i;try{i=await t.redial(e.matchId,e.deadlineAt);}catch(a){this.reportError("reconcile",a),i="failed";}if(e.done||this.reconnect!==e)return;if(i==="closed"){this.finishReconnect();return}if(i==="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 h("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 h("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 h("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:t},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let t=this.heldMatchId;if(t!==null)try{await this.api.leaveMatch(t,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,t){let r=this.emitter.on(e,t);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}handleRoomEvent(e){if(this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let t=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(t).catch(()=>{}));}handleAutoStartFailed(e,t){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 o=new AbortController;this.autoStartRetry=o,this.track(this.requestStart({signal:o.signal},false).then(()=>{},i=>{o.signal.aborted||this.reportError("startMatch",i);}).finally(()=>{this.autoStartRetry===o&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!Qu.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){this.disposed||!this.watchingSeats||this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}async reconcileSeats(){if(this.disposed||!this.watchingSeats)return;let e;try{e=await this.myRooms();}catch{return}let t=new Set;for(let r of e)r.status!=="closed"&&(t.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])t.has(r)||this.reported.delete(r);}async reportSeat(e){let t=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||t===null||!r.members.some(o=>o.playerId===t)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.seatPollMs>0&&He())){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(),!!He())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of Bn)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.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 Bn)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??Xu}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new h("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=Gn(this.options.platformGameVersion?.(),t?.gameVersion);if(r===null)throw new h("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 Ys({...t,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return Ot(await this.options.resolveClusterTargets());let e=pe(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,t){return !da(e)||t.length===0?[]:Ot(await this.options.refreshClusterTargets?.(t)??[])}async nextCluster(e,t=false){let r=a=>a.find(s=>!e.includes(s)),o=await this.clusterTargets(),i=r(o);return i!==void 0||!t?i:r(Ot(await this.options.refreshClusterTargets?.(o)??[]))}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 D)||e.reason!=="conflict")throw e;if(this.options.recoverStaleMembership===false)throw new D(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 o;try{o=await this.leaveAll(t.signal);}catch{throw new D(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(o.length===0)throw new D(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 h("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}requireRoom(e){if(this.room===null)throw new h("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 D?{operation:e,code:t.status,reason:t.reason,message:t.message,retryable:t.retryable}:{operation:e,code:0,reason:t instanceof h?t.reason:"unavailable",message:t instanceof Error?t.message:String(t),retryable:false};this.emitter.emit("error",r);}track(e){return this.inFlight.push(e),e}enter(e,t){this.room=e,this.abortFollow(),this.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])),o=new Map(e.members.map(s=>[s.playerId,s])),i=this.playerId();for(let s of o.keys())r.has(s)||this.emitter.emit("memberJoined",s);for(let s of r.keys())if(!o.has(s)){if(s===i){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",s);}for(let[s,l]of o){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=Zu(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(o=>{if(!r.signal.aborted)try{this.settleOutcome(o);}catch{}}).catch(o=>{r.signal.aborted||this.reportError("pollMatchStatus",o);}).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??Yu;return new Promise((o,i)=>{let a=c=>{s(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),c();},s=this.emitter.on("matchAllocationStarted",c=>a(()=>o(c))),l=this.emitter.on("matchFailed",(c,p)=>a(()=>i(new h("allocation_failed",`match ${c} did not come up: ${p}`)))),d=()=>a(()=>i(new h("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>a(()=>i(new h("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??Ku}pushedInterval(){return this.options.pushedPollIntervalMs??Ju}pushed(){return this.options.clock.now()-this.lastPushAt<zu*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=t=>{t?.persisted!==true&&this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{}));},e.addEventListener("pagehide",this.unloadListener));}};function He(){let n=globalThis.document;return n?.visibilityState===void 0||n.visibilityState==="visible"}var Bn=["visibilitychange","focus","pageshow","online"];function Zu(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||la(n)!==la(e)}function la(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function da(n){return n instanceof D&&n.code==="invalid_cluster_target"}function em(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var tm=["p2p","dedicated","unknown"],lo=["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 ct=class{constructor(e){this.options=e;}options;async post(e,t){let r=this.options.gameId();if(r===null||r==="")return;let o=nm(e,this.options.transport,(this.options.now??Date.now)());o.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:o},t);}report(e){this.post(e).catch(()=>{});}};function nm(n,e,t){let r=Math.floor(t/1e3);return n.filter(o=>lo.includes(o.type)).slice(0,100).map(o=>{let i=rm(o.transport??e);return {event_type:o.type,timestamp:r,...i===void 0?{}:{transport:i},data:o.value===void 0?{}:{value:o.value}}})}function rm(n){if(n!==void 0)return tm.includes(n)?n:"unknown"}var Ut=class{constructor(e){this.options=e;this.reporter=new ct({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,t,r){let o=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:t},r);return {credential:Hn(o.credential)??"",hostFingerprint:Hn(o.host_fingerprint)??"",hostEpoch:Vn(o.host_epoch)??0,expiresAt:(Vn(o.expires_at)??0)*1e3}}async turnLease(e,t,r){let o=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:t},r),i=[];for(let l of Array.isArray(o.ice_servers)?o.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);m.length!==0&&i.push({urls:m,username:Hn(d.username)??"",credential:Hn(d.credential)??""});}let a=Vn(o.expires_at),s=Vn(o.ttl_seconds);return {iceServers:i,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 Hn(n){return typeof n=="string"&&n.length>0?n:void 0}function Vn(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var om=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),O=class extends Error{constructor(t,r,o){super(`${t}: ${r}`,o);this.reason=t;this.name="P2pError",this.retryable=om.has(t);}reason;retryable};var ca=10240,ua=2048,im=new TextEncoder;function ma(n){return im.encode(n).length}function Ge(n,e){let t=o=>{throw new h("invalid_sdp",`the ${e} ${o}`)},r=ma(n);r>=ca&&t(`is ${r} bytes, over the ${ca} 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 o of n.split(/\r\n|\n/)){let i=ma(o);i>ua&&t(`has a ${i}-byte line, over the ${ua} limit`);}}function Wn(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 Kn=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,((...o)=>{r(),t(...o);}));return r}emit(e,...t){let r=this.listeners.get(e);if(r)for(let o of [...r])o(...t);}clear(){this.listeners.clear();}};var sm=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function ut(n){let e=null;for(let t of n.split(/\r\n|\n/)){if(!t.startsWith("a=fingerprint:"))continue;let r=Jn(t.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function Jn(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 sm.test(r)?r:null}function Bt(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 co=5e3,am=12e4+co,lm=1024,dm=6e4,cm=1e4,pa=64*1024,ga=5;function uo(n){let e=new Map,t=-1/0,r=null,o=(()=>{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}`}})(),i=()=>{let s=n.subtle??globalThis.crypto?.subtle;if(!s)throw new O("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(!o.ok)throw new O("keys_unavailable",o.reason);let s=n.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await s(o.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(cm)});}catch{throw new O("keys_unavailable",`the JWKS endpoint at ${o.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new O("keys_unavailable",`the JWKS endpoint answered ${o.shown} with an error`);let d;try{let p=await l.text();if(p.length>pa)throw new O("keys_unavailable",`the JWKS endpoint at ${o.shown} answered with more than ${pa} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof O?p:new O("keys_unavailable",`the JWKS endpoint at ${o.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>ga)throw new O("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${ga} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=i();for(let p of m){let g=p;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.kid.length===0))try{let y=await c.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,y);}catch{}}};return {async key(s){let l=e.get(s);if(l)return l;if(!o.ok)throw new O("keys_unavailable",o.reason);if(r)return await r,e.get(s)??null;let d=n.now();if(!Number.isFinite(d))throw new O("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<dm?null:(t=d,r??=a().finally(()=>{r=null;}),await r,e.get(s)??null)}}}var Ht=class{seen=new Map;admit(e,t){for(let[r,o]of this.seen)o<=t&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=lm){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+am),true}};function fa(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}function ya(n){try{let e=new TextDecoder().decode(fa(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function mo(n,e,t,r,o){let i=G=>{throw new O("peer_unauthenticated",`the peer's join credential is not usable: ${G}`)},a=n.split(".");a.length!==3&&i("it is not a three-part JWT");let[s,l,d]=a,m=ya(s);m===null&&i("its header does not decode"),m.alg!=="RS256"&&i(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&i(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let c=m.kid;(typeof c!="string"||c.length===0)&&i("it names no key");let p=await t.key(c);p===null&&i("it was signed by a key this build cannot resolve");let g=o.subtle??globalThis.crypto?.subtle;g||i("this environment has no WebCrypto");let y=new TextEncoder().encode(`${s}.${l}`),w;try{w=fa(d);}catch{i("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,w,y)||i("its signature does not verify");let C=ya(l);C===null&&i("its payload does not decode");let E=C,v=G=>typeof E[G]=="string"?E[G]:"",S=G=>typeof E[G]=="number"&&Number.isFinite(E[G])?E[G]:NaN;v("iss")!==o.issuer&&i("it was issued by someone else"),v("aud")!==`${o.issuer}/p2p-match`&&i("its audience is not this platform"),v("match_id")!==e.matchId&&i("it is for another match"),v("game_id")!==e.gameId&&i("it is for another game");let A=S("exp")*1e3,R=S("nbf")*1e3;(!Number.isFinite(A)||e.now>A+co)&&i("it has expired"),Number.isFinite(R)&&e.now<R-co&&i("it is not valid yet");let H=v("role");H!=="host"&&H!=="client"&&i("it names no usable role");let j=S("host_epoch");j!==e.hostEpoch&&i("it names a different host epoch");let V=Jn(v("fingerprint"));V===null&&i("its fingerprint claim is malformed"),Bt(V,e.peerFingerprint)||i("it was issued for a different certificate than this connection used");let k=Jn(v("host_fingerprint"));k===null&&i("its host fingerprint claim is malformed"),Bt(k,e.hostFingerprint)||i("it was issued against a different host certificate");let P=v("jti");P.length===0&&i("it carries no jti, so replay cannot be detected"),r.admit(P,e.now)||i("it has already been used");let L=v("sub");return L.length===0&&i("it names no player"),{playerId:L.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:j,role:H,fingerprint:V,hostFingerprint:k,jti:P,expiresAt:A}}function po(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 go(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 yo(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function fo(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 ha(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 ba(n){switch(n){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var Vt=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 ho={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}},Ie=["reliable","ordered","unreliable"];function bo(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 Wt(){let n=globalThis.RTCPeerConnection;return n?.generateCertificate?n.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var _a=1,ym=3e4,wa=2e3,fm=5e3,Sa=6e4,hm=8,_o=class{constructor(e=hm){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;}},bm=new _o,vm=8,_m=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),Jt=class{constructor(e){this.options=e;this.keys=e.keys??uo({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Kn;links=new Map;replays=new Ht;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=_a+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??ym;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),o=pe(this.options.clusterTargetId);if(o!==void 0)try{let s=await this.options.api.turnLease(this.options.matchId,o,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: ${vo(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 i=this.options.clock.setTimeout(()=>{this.fail(new O("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 O("aborted","the caller aborted while connecting"));e?.aborted?a():e?.addEventListener("abort",a);try{await r;}finally{this.options.clock.clearTimeout(i),e?.removeEventListener("abort",a),this.ready=null;}}async kick(e){if(!this.isHost)throw new O("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=ie(e.playerId),r=ie(e.hostPlayerId),o=zn(e.hostEpoch);if(!(t===null||r===null||o===null)&&(this.mark("signaling hello"),this.localPlayerId=t,this.migration===null&&(this.migration=new Vt(t,r,o)),!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,_a),o=await r.connection.createOffer();await r.connection.setLocalDescription(o);let i=r.connection.localDescription?.sdp??o.sdp;if(!i)throw new O("invalid_sdp","the browser produced an offer with no SDP");Ge(i,"offer"),this.refuseMedia(i,"offer"),this.options.signaling.offer(i,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,o=r===void 0?null:ut(r);if(o===null)throw new O("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let i=this.options.credentialPacing??bm,a=()=>this.closed||e!==this.credentialGeneration,s=fm;for(;;){let l=i.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,a))return;i.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,o);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=wa;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,Sa)),c=Math.min(Math.max(c,wa),Sa);}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=ie(e.fromPlayerId),r=ie(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=vm){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 o=ie(e.sessionId);if(o!==null&&this.answeredSessions.get(t)===o)return;Ge(r,"offer"),this.refuseMedia(r,"offer");let i=ut(r);if(i===null)throw new O("invalid_sdp",`the offer from ${t} carries no usable fingerprint`);this.mark("offer received"),o!==null&&this.answeredSessions.set(t,o);let a=this.links.get(t);a&&this.dropLink(a,"resignalled",false);let s=this.openLink(t,this.nextPeerId++);s.remoteFingerprint=i,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 O("invalid_sdp","the browser produced an answer with no SDP");Ge(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=ie(e.fromPlayerId),r=ie(e.sdp);if(t===null||r===null)return;let o=this.links.get(this.hostPlayerId);if(!o||t!==this.hostPlayerId)return;Ge(r,"answer"),this.refuseMedia(r,"answer");let i=ut(r);if(i===null)throw new O("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),o.remoteFingerprint=i,o.pendingAnswer=r,this.hostVerified(o)&&await this.applyAnswer(o,r);}hostVerified(e){let t=this.credential;return t===null||e.remoteFingerprint===null?false:Bt(t.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new O("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=ie(e.fromPlayerId),r=ie(e.candidate);if(t===null||r===null)return;let o=this.links.get(t);if(!o)return;let i=ie(e.sdpMid),a=zn(e.sdpMLineIndex)??zn(e.sdpMLineIndexAlt),s={candidate:r,...i===null?{}:{sdpMid:i},...a===null?{}:{sdpMLineIndex:a}};if(o.connection.remoteDescription===null){o.pendingCandidates.length<64&&o.pendingCandidates.push(s);return}await o.connection.addIceCandidate(s);}onPeerLeft(e){let t=ie(e.playerId);if(t===null)return;let r=ie(e.reason)??"left";if(t===this.localPlayerId){this.fail(new O("kicked",`this player was removed from the match (${r})`)),this.close();return}let o=this.links.get(t);o&&this.dropLink(o,r,true);}async onMigration(e){let t=ie(e.hostPlayerId),r=zn(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let o=this.migration.apply({hostPlayerId:t,hostEpoch:r,...ie(e.reason)===null?{}:{reason:ie(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(i=>typeof i=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(o.kind!=="duplicate"){if(o.kind==="completed"){this.emitter.emit("hostChanged",t,r);return}if(o.kind==="refused"){this.report_(new O("migration_failed",o.why));return}for(let i of [...this.links.values()])this.dropLink(i,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",t,r),o.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 O("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=ie(e.reason)??"ended";this.ended=t,this.emitter.emit("matchEnded",t),this.ready!==null&&this.fail(new O("match_ended",`the match ended: ${t}`)),this.close();}onSignalingError(e){let t=ie(e.code)??"unknown",r=ie(e.message)??"the platform refused a signaling message";this.report_(new O("signaling_failed",`${t}: ${r}`));}openLink(e,t){let o=(this.options.peerConnectionFactory??bo)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),i={};for(let p of Ie){let g=o.createDataChannel(p,ho[p]);g.binaryType="arraybuffer",i[p]=g;}let a={playerId:e,assignedPeerId:t,connection:o,channels:i,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},s=p=>{let g=p.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},l=()=>this.onIceState(a),d=()=>this.onConnectionState(a),m=p=>{this.onHandshakeMessage(a,p.data).catch(g=>this.report_(g));},c=()=>{this.onReliableOpen(a).catch(p=>this.report_(p));};return o.addEventListener("icecandidate",s),o.addEventListener("iceconnectionstatechange",l),o.addEventListener("connectionstatechange",d),i.reliable.addEventListener("open",c),i.reliable.addEventListener("message",m),a.detachHandshake=()=>{i.reliable.removeEventListener("open",c),i.reliable.removeEventListener("message",m);},a.detachAll=()=>{a.detachHandshake(),o.removeEventListener("icecandidate",s),o.removeEventListener("iceconnectionstatechange",l),o.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 O("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 O("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(po({jwt:t.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,t){if(!(t instanceof ArrayBuffer))return;let r=fo(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 O(ba(r.reason),ha(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 o=ut(e.connection.localDescription?.sdp??"");if(o===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 i;try{i=await mo(t,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:o,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(a){let s=a instanceof O&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",vo(a)),s&&this.fail(a);return}if(i.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${i.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(i.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(go({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,t,r,o){this.warn(`refused to admit ${e.playerId}: ${o}`);try{e.channels.reliable.send(yo(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 o of Ie)Ra(e.channels[o]);Ra(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 O?e:new O("connection_failed",vo(e),{cause:e}));}count(e){this.counted||!_m.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(Wn(e))throw new O("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 ie(n){return typeof n=="string"&&n.length>0?n:null}function zn(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function vo(n){return n instanceof Error?n.message:String(n)}function Ra(n){try{n.close();}catch{}}var wm=100,Sm=50,zt=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,o){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??wm)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:t,...r===void 0?{}:{sdpMid:r},...o===void 0?{}:{sdpMLineIndex:o}}),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 O("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new O("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see public-docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId:t,candidate:r,sdpMid:o,sdpMLineIndex:i}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:t,candidate:r,...o===void 0?{}:{sdpMid:o},...i===void 0?{}:{sdpMLineIndex:i}});}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??Sm));}};function q(n){return e=>typeof e=="string"&&e.length>0&&e.length<=n?e:void 0}function De(n,e){return t=>typeof t=="number"&&Number.isInteger(t)&&t>=n&&t<=e?t:void 0}function mt(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function ka(n){return typeof n=="boolean"?n:void 0}var fe=q(64),Yt=De(0,2147483647);function wo(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(e.length>=64)break;let r=fe(t);typeof r=="string"&&e.push(r);}return e}function W(n,e,t){return {to:n,from:e,read:t,required:true}}function U(n,e,t){return {to:n,from:e,read:t,required:false}}var xm=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=mt("disconnected","failed","closed")(e.iceState),r=De(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}}};Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[W("sdp","sdp",q(10240)),W("signaling_intent","intent",mt("initial","ice_restart","full_reconnect")),U("sdp_hash","sdpHash",q(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[W("peer_id","peerId",fe),W("sdp","sdp",q(10240)),W("assigned_peer_id","assignedPeerId",De(0,4294967295)),U("sdp_hash","sdpHash",q(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[W("peer_id","peerId",fe),W("candidate","candidate",q(512)),U("sdp_mid","sdpMid",q(64)),U("sdp_mline_index","sdpMLineIndex",De(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[W("host_epoch","hostEpoch",Yt)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[W("host_epoch","hostEpoch",Yt),U("evidence","evidence",xm)]}}));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"}));Object.freeze(Object.assign(Object.create(null),{hello:[W("playerId","player_id",fe),W("hostPlayerId","host_player_id",fe),W("hostEpoch","host_epoch",Yt),U("members","members",wo)],offer:[W("fromPlayerId","from_player_id",fe),W("sdp","sdp",q(10240)),U("sessionId","signaling_session_id",q(128)),U("sdpHash","sdp_hash",q(128)),U("iceUfrag","ice_ufrag",q(64)),U("intent","signaling_intent",mt("initial","ice_restart","full_reconnect"))],answer:[W("fromPlayerId","from_player_id",fe),W("sdp","sdp",q(10240)),U("sessionId","signaling_session_id",q(128)),U("sdpHash","sdp_hash",q(128)),U("iceUfrag","ice_ufrag",q(64)),U("assignedPeerId","assigned_peer_id",De(0,4294967295))],ice:[W("fromPlayerId","from_player_id",fe),W("candidate","candidate",q(512)),U("sdpMid","sdp_mid",q(64)),U("sdpMLineIndex","sdp_m_line_index",De(0,255)),U("sdpMLineIndexAlt","sdp_mline_index",De(0,255))],peerJoined:[W("playerId","player_id",fe)],peerLeft:[W("playerId","player_id",fe),U("reason","reason",q(64))],migration:[W("hostPlayerId","new_host_player_id",fe),W("hostEpoch","host_epoch",Yt),U("reason","reason",q(64)),U("kickedPlayerIds","kicked_player_ids",wo),U("migrationComplete","migration_complete",ka)],matchEnded:[U("reason","reason",q(64))],error:[U("code","code",q(64)),U("message","message",q(256))]}));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"}));var We="webrtc_p2p";function Aa(n){let e=new Ut({client:n.client,gameId:n.gameId}),t=new Map;return {handleSignalEvent(r,o,i){t.get(r)?.handleSignal(o,i);},session(r){return t.get(r)??null},async connect(r={}){if(n.bridge===null)throw new O("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See public-docs/p2p-and-parties.md \xA72.");let o=pe(r.clusterTargetId),i=o??pe(await n.resolveClusterTarget?.());n.rooms.isHost&&n.rooms.currentMatch===null&&n.rooms.currentRoom?.matchId===void 0&&await n.rooms.startMatch({...o===void 0?{}:{clusterTargetId:o},...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!==We)throw new O("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${We}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new zt({bridge:n.bridge,matchId:a.matchId,clock:n.clock}),l=new Jt({api:e,clock:n.clock,matchId:a.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:s,...i===void 0?{}:{clusterTargetId:i},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Wt(),...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 Pa(n){let{analytics:e,rooms:t}=n,r=n.target??globalThis,o=n.document??globalThis.document,i=[];if(typeof r.addEventListener=="function"){let s=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",s),i.push(()=>r.removeEventListener?.("pagehide",s));let l=()=>e.setHidden(!He());for(let d of Bn)r.addEventListener(d,l),i.push(()=>r.removeEventListener?.(d,l));typeof o?.addEventListener=="function"&&(o.addEventListener("resume",l),i.push(()=>o.removeEventListener?.("resume",l))),e.setHidden(!He());}let a=new Map;return i.push(t.on("matchReady",s=>{let l=s.protocol===We?"p2p":"dedicated";a.set(s.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),i.push(t.on("matchEnded",s=>{let l=a.get(s.matchId);l!==void 0&&(a.delete(s.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let s of i.splice(0))try{s();}catch{}a.clear();}}async function Yn(n,e,t,r){let o=await t;return n.mark(e)&&r&&r(`[gem] boot: ${n.timeline()}`),o}function So(n,e){let t=false;return async r=>{let o=await r;return !t&&e&&(t=true,e(`[gem] boot: ${n.timeline()}`)),o}}function Ro(n={}){let e=n.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),t=[],r=new Set;return {marks:t,mark(o,i){return r.has(o)?false:(r.add(o),t.push({name:o,at:i??e()}),true)},timeline(){let o=[...t].sort((i,a)=>i.at-a.at);return o.map((i,a)=>{let s=o[a-1],l=s===void 0?"":` (+${Math.round(i.at-s.at)}ms)`;return `${i.name}@${Math.round(i.at)}ms${l}`}).join(" \u2192 ")}}}var Am="GemWebSdkHandshake";var Pm=()=>Date.now();function Ta(n,e,t={}){let r=n[Am];if(r===void 0)return null;let o=t.ttlMs??9500,i=t.now??Pm,a=r.events.splice(0),s=r.times?.splice(0),l=0,d=0,m=false,c=i()-o;for(let p=a.length-1;p>=0;p--){let g=s?.[p];if(g!==void 0&&g<c){d+=1;continue}if(l+=1,e(a[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}var ko=false;async function Ma(n,e,t,r){if(ko){e.close(),t("busy",true);return}ko=true;let o=null;try{let i=await Em(n,r);if(typeof i=="string"){e.close(),t(i,Tm(i));return}o=i;let s=await(r.encodeRef??(l=>Om(l,r)))(o);if(o.close(),o=null,s===null){e.close(),t("failed",!0);return}if(s.size>Mm){e.close(),t("too_large",!1);return}e.postMessage(s);}catch(i){e.close(),t("failed",true),console.error("[gem] screenshot capture failed",i);}finally{ko=false,o?.close();}}function Tm(n){switch(n){case "no_source":case "busy":case "failed":return true;case "not_wired":case "unsupported":case "unreadable":case "tainted":case "too_large":case "declined":return false}}async function Em(n,e){if(e.handler){let i=await e.handler(n);return i===null?"declined":Ea(i,n)}if(!e.useDefaultStrategy)return "not_wired";let t=e.documentRef??globalThis.document;if(!t)return "no_source";let r=Cm(t);if(!r)return "no_source";let o=Im(r);if(o!==null)return o;try{return Ea(await createImageBitmap(r),n)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}function Im(n){let e;try{e=n.getContext("webgl2")??n.getContext("webgl");}catch{return "unreadable"}if(e){let t=e.getContextAttributes();return !t||t.preserveDrawingBuffer!==true?"unsupported":null}try{if(n.getContext("2d"))return null}catch{return "unreadable"}return "unreadable"}function Cm(n){let e=null,t=0;for(let r of Array.from(n.querySelectorAll("canvas"))){let o=r.width*r.height;o<=0||r.clientWidth<=0||r.clientHeight<=0||o>t&&(e=r,t=o);}return e}async function Ea(n,e){let{maxWidth:t,maxHeight:r}=e;if(n.width<=t&&n.height<=r)return n;let o=Math.min(t/n.width,r/n.height),i=Math.max(1,Math.floor(n.width*o)),a=Math.max(1,Math.floor(n.height*o));try{let s=await createImageBitmap(n,{resizeWidth:i,resizeHeight:a,resizeQuality:"high"});return n.close(),s}catch{return n.close(),"too_large"}}var Mm=8*1024*1024,Ia="image/webp",Ca=.92;async function Om(n,e){try{if(typeof OffscreenCanvas=="function"){let i=new OffscreenCanvas(n.width,n.height),a=i.getContext("2d");if(a){a.drawImage(n,0,0);let s=await i.convertToBlob({type:Ia,quality:Ca});if(s&&s.size>0)return s}}}catch{}let t=e.documentRef??globalThis.document;if(!t)return null;let r=t.createElement("canvas");r.width=n.width,r.height=n.height;let o=r.getContext("2d");return !o||(o.drawImage(n,0,0),typeof r.toBlob!="function")?null:await new Promise(i=>{r.toBlob(a=>i(a),Ia,Ca);})}async function Oa(n,e){if(!e)return;let t;try{t=await Lm(e);}catch(r){console.error("[gem] onFeedbackContext threw; sending the report without context",r);return}if(t!=null){if(typeof t!="object"||Array.isArray(t)){console.error("[gem] onFeedbackContext must return a plain object or null; got",t);return}n.sendGameContext(t);}}function Lm(n){return new Promise((e,t)=>{let r=false,o=setTimeout(()=>{r||(r=true,console.warn("[gem] onFeedbackContext did not answer within 1000ms; sending the report without context. Gather cheaply, or keep a snapshot."),e(null));},1e3);(async()=>n())().then(i=>{r||(r=true,clearTimeout(o),e(i??null));},i=>{r||(r=true,clearTimeout(o),t(i instanceof Error?i:new Error(String(i))));});})}var La=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function Ga(n=globalThis){let t=n[La];if(t!==void 0)return t;let r=false,o=()=>r,i=[],a=Gm(n,o);a!==null&&i.push(a);let s=Dm(n,o);s!==null&&i.push(s);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let c of i)c();}}};return Object.defineProperty(n,La,{value:l,configurable:true}),l}function Gm(n,e){let t=n.AudioNode?.prototype,r=n.AudioDestinationNode;if(t===void 0||r===void 0)return null;let o=n.OfflineAudioContext,i=t.connect,a=t.disconnect,s=new Map,l=m=>{let c=m.gain,p=m.context.currentTime;c.cancelScheduledValues(p),e()?c.setValueAtTime(0,p):c.setTargetAtTime(1,p,.01);},d=m=>{let c=m.context;if(o!==void 0&&c instanceof o)return null;let p=s.get(c);return p===void 0&&(p=c.createGain(),p.gain.value=e()?0:1,i.call(p,m),s.set(c,p)),p};return t.connect=function(...c){let[p,...g]=c;if(p instanceof r){let y;try{y=d(p);}catch{y=null;}if(y!==null)return i.call(this,y,...g),p}return i.apply(this,c)},t.disconnect=function(...c){let[p,...g]=c;if(p instanceof r){let y=s.get(p.context);if(y!==void 0&&y!==this)try{return a.call(this,y,...g)}catch{}}return a.apply(this,c)},()=>{for(let[m,c]of s){if(m.state==="closed"){s.delete(m);continue}try{l(c);}catch{}}}}function Dm(n,e){let t=n.HTMLMediaElement;if(t===void 0)return null;let r=t.prototype,o=Object.getOwnPropertyDescriptor(r,"muted"),i=o?.get,a=o?.set;if(i===void 0||a===void 0)return null;let s=r.play,l=new WeakMap,d=new WeakSet,m=new Set,c=p=>{l.has(p)||l.set(p,!!i.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),a.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:o?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!i.call(this):p},set(p){l.set(this,!!p),c(this);}}),r.play=function(){try{c(this);}catch{}return s.call(this)},n.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof t)try{c(g);}catch{}},true),()=>{for(let p of m){let g=p.deref();if(g===void 0){m.delete(p);continue}try{a.call(g,(l.get(g)??!1)||e());}catch{}}}}function Da(n){let e=n.windowMs??1e3,t=n.realm??globalThis,r=false,o=false,i=false,a=null,s=null,l=null,d=[],m=()=>r&&!o&&!i,c=()=>{s=null,l=null,d=[];},p=w=>{if(a=null,!m()){c();return}if(l!==null&&d.push(w-l),l=w,s===null)s=w;else {let x=w-s;x>=e&&d.length>0&&(n.report($m(d,x)),s=w,d=[]);}g();},g=()=>{let w=t.requestAnimationFrame;typeof w=="function"&&(a=w.call(t,p));},y=()=>{if(m()){a===null&&(c(),g());return}a!==null&&(t.cancelAnimationFrame?.call(t,a),a=null),c();};return {setRequested(w){r=w,y();},setPaused(w){o=w,y();},get running(){return a!==null},dispose(){i=true,y();}}}function $m(n,e){let t=[...n].sort((o,i)=>o-i),r=Math.max(1,Math.ceil(t.length*.95));return {fps:n.length*1e3/e,frameTimeP95Ms:t[r-1]}}var Xn=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function $a(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function Fa(n,e){n!==null&&(n.style.setProperty(Xn.top,`${e.top}px`),n.style.setProperty(Xn.right,`${e.right}px`),n.style.setProperty(Xn.bottom,`${e.bottom}px`),n.style.setProperty(Xn.left,`${e.left}px`));}var Fm=3e4,Qn=class extends Error{retryable;reason;constructor(e,t,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=t;}};function ja(n){let e=n.clock??ae,t=n.timeoutMs??Fm,r=new Map,o=new Map,i=0,a=s=>{let l=r.get(s);return l?(r.delete(s),o.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return n.bridge.parentSupports("localHost")},ensure(s){if(!n.bridge.parentSupports("localHost"))return Promise.resolve();let l=o.get(s);if(l)return l;let d=new Promise((m,c)=>{let p=`ls${++i}`,g=e.setTimeout(()=>{r.delete(p),o.delete(s),c(new Qn("timeout",true,`the embedder did not answer a local-server request for room ${s} within ${String(t)}ms`));},t);r.set(p,{room:s,resolve:m,reject:c,timer:g}),n.bridge.requestLocalServer(p,s)||(a(p),m());});return o.set(s,d),d.catch(()=>{}),d},accept(s){a(s.requestId)?.resolve();},refuse(s){let l=a(s.requestId);l&&l.reject(new Qn(s.reason,s.retryable,s.reason==="refused"?`the platform refused to let this machine serve room ${l.room}. Check that you are signed in as a developer on this game, that the room is on the dev or test channel, and that you host it.`:`this machine could not start a server for room ${l.room}. Your development tool has the reason.`));}}}var Xt={url:"https://downloads.indiegems.games/sdk/v7.2.0/gem-web-sdk.devtools.min.js",integrity:"sha384-d9NeDj7YDz0gLG+x1BVeR/fZmFjkkpJd37aUY80PjX+/gCV2mE2deJPhIvk5bv5Z"};var gt=null;function jm(){return gt!==null||(gt=new Promise((n,e)=>{let t=document.createElement("script");t.src=Xt.url,t.integrity=Xt.integrity,t.crossOrigin="anonymous",t.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){gt=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${Xt.url} is not a gem-web-sdk devtools build.`));return}n(r);},t.onerror=()=>{gt=null,e(new Error(`gem devtools: could not load ${Xt.url}. Either the network refused it or its Subresource Integrity check failed, or the CDN did not answer the CORS preflight this request needs \u2014 SRI is only checkable on bytes the page may read. A locally rebuilt SDK is the commonest cause: it produces panel bytes that do not match the hash compiled into this build.`));},document.head.append(t);})),gt}function Na(n,e){let t=null,r=0;async function o(i){if(t!==null)return true;let a=++r;if(!e())return false;let s=await jm();return !e()||a!==r?false:(t!==null||(t=s.mount(n(),{openedBy:i,text:qe,onDismiss:()=>{t?.unmount(),t=null;}})),true)}return {get isOpen(){return t!==null},close(){r+=1,t?.unmount(),t=null;},open:()=>o("game"),openFrom:o}}var Nm=1e4,qa={reason:"unavailable",retryable:false};function Ua(n){let e=new Map,t=null,r=null,o=0,i=(d,m)=>{m.timer=n.clock.setTimeout(()=>{e.delete(d),m.reject({reason:"timeout",retryable:true});},n.timeoutMs??Nm);},a=(d,m)=>{let c=s(d);c&&m(c);},s=d=>{let m=e.get(d);return m?(e.delete(d),n.clock.clearTimeout(m.timer),m):null},l=new tt({clock:n.clock,onStateChange:n.onStateChange,request:d=>new Promise((m,c)=>{let p=n.bridge.currentState;if(p==="refused"||p==="closed"){c(qa);return}let g=`t${++o}`,y={resolve:m,reject:c,reason:d,timer:null,held:p!=="connected"};e.set(g,y),i(g,y),y.held||n.bridge.requestToken(g,d);})});return {source:l,onToken(d){let m={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(t={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){a(d.requestId,c=>c.resolve(m));return}l.accept(m);},onDenied(d){a(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,c]of e)c.held&&(c.held=false,n.clock.clearTimeout(c.timer),i(m,c),n.bridge.requestToken(m,c.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])a(m,c=>c.reject(qa));},get identity(){return t},get gameVersion(){return r}}}function qm(n){let e=n.lastIndexOf("@");return (e===-1?n:`***@${n.slice(e+1)}`).slice(0,200)}var Um=new Set(on);function Bm(n){if(!n)return {};let e={};for(let[t,r]of Object.entries(n))Um.has(t.toLowerCase())&&(e[t.toLowerCase()]=r);return e}function Zn(n){let e=n.fetch??globalThis.fetch.bind(globalThis);return Xo(async(t,r)=>{let o;try{o=new URL(n.baseUrl.replace(/\/+$/,""));}catch{throw new ne("the configured baseUrl is not a valid URL. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure.")}let i;try{i=new URL(o.href.replace(/\/+$/,"")+t.path);}catch{throw new ne(`${JSON.stringify(typeof t.path=="string"?qm(t.path):"(a non-string path)")} does not form a valid URL against ${o.protocol}//${o.host}. This is a malformed request, not a server failure.`)}if(i.protocol!==o.protocol||i.host!==o.host)throw new ne(`${JSON.stringify(i.pathname)} resolves to ${i.protocol}//${i.host}, not ${o.protocol}//${o.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(i.username!==""||i.password!==""){let g=o.username!==""||o.password!=="",y=i.username!==o.username||i.password!==o.password,w=g?y?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new ne(`the ${w} puts credentials in the URL, which cannot be fetched (${t.method} ${i.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[g,y]of Object.entries(n.defaultQuery??{}))i.searchParams.has(g)||i.searchParams.set(g,y);let a=t.bytes,s=t.bytes===void 0?void 0:"application/octet-stream";try{t.body!==void 0&&(a=JSON.stringify(t.body),s="application/json");}catch(g){throw new ne(`the body of ${t.method} ${JSON.stringify(i.pathname)} could not be serialised to JSON: ${String(g)}. This is a bug in the request, not a server failure \u2014 retrying sends the same unserialisable value.`)}let l=await e(i.toString(),{method:t.method,headers:{authorization:`Bearer ${r}`,...s===void 0?{}:{"content-type":s},...Bm(t.headers)},body:a,signal:t.signal,...t.keepalive===void 0?{}:{keepalive:t.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(t.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let m=l.headers.get("etag"),c=Hm(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...c===void 0?{}:{retryAfterSeconds:c},...p===null||p===""?{}:{invocationId:p}}},n)}function Hm(n){if(n===null)return;let e=n.trim();if(!/^\d+$/.test(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0}var Vm=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),Ao="embedder_relay_unavailable",Wm="embedder_no_relay",Km=new Set([Ao]),Po=new Set([Wm]),Qt=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new xo(this)}handleEvent(e){let t=this.pending.get(e.matchId);if(t!==void 0){if(e.event==="matchEnded"){t.refuse(new h("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 h("signaling_failed","the parent relayed an answer with no SDP in it"));return}t.settle({sdp:e.sdp});return}t.refuse(Jm(e.code,e.message));}}register(e,t){this.pending.get(e)?.refuse(new h("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 h("signaling_unavailable","this game is not running inside a page that holds the player's notification socket, so there is nothing to carry an offer. Dedicated signaling needs that socket and only the page can hold one \u2014 see public-docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new h("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See public-docs/dedicated-server-flow.md \xA72.");return e}};function Jm(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new h(zm(n),r,{platformCode:n})}function zm(n){return n===void 0||Km.has(n)?"signaling_failed":Po.has(n)?"offer_refused":Vm.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var xo=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,t){if(this.closed)return Promise.reject(new h("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(o){return Promise.reject(o)}return t?.aborted?Promise.reject(new h("aborted","the caller aborted before the offer was sent")):new Promise((o,i)=>{let a=()=>{s(),i(new h("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(),o(d);},refuse:d=>{s(),i(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 h?d:new h("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var Ba="match_ended:",Ha="server_shutdown:",Va="kicked:",Ym=123;function Xm(n){if(typeof n!="string"||n.length===0||n.length>Ym)return {kind:"other"};if(n.startsWith(Ba)){let e=Le(n.slice(Ba.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(Ha)?{kind:"server_shutdown",cause:n.slice(Ha.length)}:n.startsWith(Va)?{kind:"kicked",detail:n.slice(Va.length)}:{kind:"other"}}function To(n,e,t){let r=Xm(t),o=r.kind==="kicked"?"kicked":"link_closed";n.notifyMatchDisconnected(o).catch(()=>{}),r.kind==="match_ended"&&n.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}function Eo(){return {exchange(){return Promise.reject(new h("signaling_unavailable","no signaling channel is wired. The exchange rides the notification WebSocket, and POST /v1/ws/ticket accepts only account credentials \u2014 a game frame holds a game-scoped token and cannot mint one \u2014 so it has to be relayed by the page embedding this game. Run inside a parent that advertises `dedicated`, or pass your own `signaling` implementation. See public-docs/dedicated-server-flow.md \xA72."))},close(){}}}var Qm=3e3,Zm=1e4,ep=15e3;async function er(n){let e=n.peerConnection;try{Ka(n,"before the handshake started"),Io(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 rp(e,n),Io(n);let o=e.localDescription?.sdp??r.sdp;if(!o)throw new h("invalid_sdp","the offer carried no SDP");Ge(o,"offer"),Wa(o,"offer");let i=await np(n,o);if(Io(n),typeof i?.sdp!="string")throw new h("invalid_sdp","the signaling channel answered without an SDP");return Ge(i.sdp,"answer"),Wa(i.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:i.sdp}),await op(t,n),Ka(n,"before the channel opened"),t}catch(t){throw e.close(),tp(t)}}function tp(n){return n instanceof h?n:Ya(n)?Ke():new h("connection_failed",Xa(n),{cause:n})}function Wa(n,e){if(Wn(n))throw new h("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 np(n,e){let t=n.exchangeTimeoutMs??Zm,r=za(n,t),o=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(i=>{throw i instanceof h?i:Ya(i)?Ke():new h("signaling_failed",Xa(i),{cause:i})});return ip(o,n,r,()=>r.exhausted?Co("while the offer was in flight"):new h("timeout",`no answer arrived within ${t}ms`))}function rp(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let o=()=>{t.clearTimeout(a),n.removeEventListener("icegatheringstatechange",i),e.signal?.removeEventListener("abort",o),r();},i=()=>{n.iceGatheringState==="complete"&&o();},a=t.setTimeout(o,e.gatherTimeoutMs??Qm);n.addEventListener("icegatheringstatechange",i),e.signal?.addEventListener("abort",o);})}function op(n,e){if(e.signal?.aborted)return Promise.reject(Ke());if(n.readyState==="open")return Promise.resolve();if(n.readyState!=="connecting")return Promise.reject(new h("connection_failed",`the data channel was already '${n.readyState}' when the answer was applied`));let{clock:t}=e,r=e.openTimeoutMs??ep,o=za(e,r);return new Promise((i,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(),i();},d=g=>{s(),a(new h("connection_failed","the data channel failed before it opened",Ja(g)===void 0?void 0:{cause:Ja(g)}));},m=()=>{s(),a(Ke());},c=()=>{s(),a(o.exhausted?Co("while the channel was still opening"):new h("timeout",`the data channel did not open within ${r}ms`));},p=t.setTimeout(c,o.ms);n.addEventListener("open",l),n.addEventListener("close",d),n.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function za(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 ip(n,e,t,r){let{clock:o,signal:i}=e;return i?.aborted?Promise.reject(Ke()):new Promise((a,s)=>{let l=c=>{o.clearTimeout(m),i?.removeEventListener("abort",d),c();},d=()=>l(()=>s(Ke())),m=o.setTimeout(()=>l(()=>s(r())),t.ms);i?.addEventListener("abort",d),n.then(c=>l(()=>a(c)),c=>l(()=>s(c)));})}function Ka(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw Co(`already ${e}`)}function Co(n){return new h("credential_expired",`the join credential ran out ${n} \u2014 poll match status again for a fresh one`)}function Io(n){if(n.signal?.aborted)throw Ke()}function Ke(){return new h("aborted","the caller aborted the connection attempt")}function Ya(n){return n?.name==="AbortError"}function Ja(n){return n?.error}function Xa(n){return n instanceof Error?n.message:String(n)}Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"}));Object.freeze(Object.assign(Object.create(null),{answer:[W("sdp","sdp",q(10240)),U("sessionId","session_id",q(64))],error:[U("code","code",q(64)),U("message","message",q(256))],matchEnded:[U("reason","reason",q(64))]}));function il(n){let{client:e,clock:t,rooms:r}=n,o=n.signaling??Eo,i=n.log??(v=>console.warn(v)),a=new ct({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(v,S)=>{let A=s.get(v)??new Set;A.add(S),s.set(v,A);},d=(v,S)=>{let A=s.get(v);A!==void 0&&(A.delete(S),A.size===0&&s.delete(v));},m=async v=>{if(r.isHost&&!Oo(r)&&r.currentRoom?.matchId===void 0){let S=pe(v.clusterTargetId);await r.startMatch({...S===void 0?{}:{clusterTargetId:S},...v.retry===void 0?{}:{retry:v.retry},...v.signal===void 0?{}:{signal:v.signal}});}return rl(r.matchConnectionState==="suspended"?await r.reconnectToMatch(Mo(v)):await r.awaitMatch(Mo(v)))},c=async v=>rl(await r.pollMatchStatus(Mo(v))),p=async(v,S)=>{let A=false;try{let R=await m(v),H=r.currentRoom?.transports;if(H!==void 0&&!H.includes("webrtc"))throw new h("misconfigured",`the room template offers (${H.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 j=v.peerConnection??ol();A=!0;let V=await er({peerConnection:j,signaling:S,clock:t,matchId:R.matchId,credentialExpiresAt:R.credentialExpiresAt,...tr(v,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),k=null;if(v.presentCredential!==!1)try{k=await Lt({channel:V,clock:t,credential:R.joinCredential,credentialExpiresAt:R.credentialExpiresAt,...tr(v,"onMessage","signal"),...v.welcomeTimeoutMs===void 0?{}:{ceilingMs:v.welcomeTimeoutMs}});}catch(P){throw we(V),we(j),P}return gp(r,R,V,j,S,v.reportDisconnect!==!1,v.reportConnected!==!1,k,{remember:l,forget:d},v.onMatchEnded)}catch(R){throw A&&nl(a,R),we(S),R}},g=async(v,S,A,R,H,j)=>{if(v==="webtransport"){let F=R?.webtransport;if(F===void 0)throw new h("misconfigured","webtransport is not advertised");let B={credential:A.joinCredential,credentialExpiresAt:A.credentialExpiresAt,clock:t};if(typeof F.named_url=="string"&&F.named_url!==""){let re=Math.max(Math.floor(j/2),1e3);try{return await Ft({url:F.named_url,timeoutMs:re,log:i,...B})}catch(le){if(Nn()!==null)throw le;return i(`[gem] webtransport named dial failed (${Fn(le)}); retrying the pinned dial`),Ft({url:F.url,certHashBase64:F.cert_sha256_b64,timeoutMs:re,log:i,...B})}}return Ft({url:F.url,certHashBase64:F.cert_sha256_b64,timeoutMs:j,...B})}if(v==="websocket"){let F=R?.websocket;if(F===void 0)throw new h("misconfigured","websocket is not advertised");return Zr({url:F.url,credential:A.joinCredential,credentialExpiresAt:A.credentialExpiresAt,clock:t,timeoutMs:j})}let V=S.peerConnection??ol(),k,P=await er({peerConnection:V,signaling:H,clock:t,matchId:A.matchId,credentialExpiresAt:A.credentialExpiresAt,extraChannels:[{label:Dt,ordered:false,maxRetransmits:0}],onExtraChannel:(F,B)=>{F===Dt&&(k=B);},...tr(S,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...S.exchangeTimeoutMs===void 0&&S.redial===true?{exchangeTimeoutMs:lp}:{}}),L;try{L=await Lt({channel:P,clock:t,credential:A.joinCredential,credentialExpiresAt:A.credentialExpiresAt,wire:$n,heartbeat:!0,...tr(S,"signal"),...S.welcomeTimeoutMs===void 0?{}:{ceilingMs:S.welcomeTimeoutMs}});}catch(F){throw we(P),we(V),F}let G=L.welcome.heartbeatIntervalMs;return {link:to(P,V,k,G===void 0?void 0:{clock:t,intervalMs:G}),welcome:L.welcome,channel:P,peerConnection:V}},y=(v,S,A,R,H)=>{let j=false,V;R.link.onClose(G=>{!j&&v.reportDisconnect!==false&&To(r,S.matchId,G),V?.(G);}),v.reportDisconnect!==false&&v.reportConnected!==false&&r.notifyMatchConnected(S.matchId);let k={transport:R.link.transport,send:(G,F)=>R.link.send(G,F),onMessage:G=>R.link.onMessage(G),onClose:G=>{V=G;},close:()=>R.link.close()},P=()=>{j||(j=true,we(R.link),we(H));},L=G=>{if(!j){try{v.onMatchEnded?.(G);}catch{}P();}};return l(S.matchId,L),{matchId:S.matchId,transport:A,link:k,joinCredential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,welcome:R.welcome,...R.channel===void 0?{}:{channel:R.channel},...R.peerConnection===void 0?{}:{peerConnection:R.peerConnection},close(){d(S.matchId,L),P();}}},w=async(v,S)=>{let A=r.currentRoom?.id,R=r.gameId,H=()=>({advert:$t(r.currentRoom?.settings,v),template:r.currentRoom?.transports??null});if(A===void 0||R===null)return H();try{let j=await e.get(`/v2/games/${encodeURIComponent(R)}/game-rooms/${encodeURIComponent(A)}`,S);return {advert:$t(j.settings,v),template:lt(j.transports)??r.currentRoom?.transports??null}}catch{return H()}},x=(v,S)=>{let A=v??Qa;return S.length===0?A:A.filter(R=>S.includes(R))},C=async(v,S,A)=>{try{let R=await m(v),{advert:H,template:j}=await w(R.matchId,v.signal),V=x(j,S),k=V.filter(Q=>up(Q,H)),P=Nn();if(P!==null&&V.includes("webtransport")&&H?.webtransport!==void 0&&i(`[gem] webtransport skipped: ${P} (learned on an earlier dial in this page)`),k.length===0){let Q=j===null?`the default order (${Qa.join(", ")})`:`the room template's transports (${j.join(", ")||"none"})`;throw new h("misconfigured",`none of ${Q}`+(S.length>0?`, narrowed to (${S.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let L=v.transportAttemptTimeoutMs??ap,G=()=>v.deadlineAt===void 0?1/0:v.deadlineAt-t.now(),F=Q=>n.signalingReady===void 0||Q<=0?Promise.resolve(!0):n.signalingReady(Q),B=[],re=[];for(let Q of k){if(G()<el){i(`[gem] ${Q} rung not tried: the reconnect budget is spent`);break}re.length>0&&R.credentialExpiresAt-t.now()<tl&&(R=await c(v)),re.push(Q);let K=!1,Se=!1,Re={attempts:0,waitedMs:0};for(;;){if(Q==="webrtc"&&v.redial===!0){let ee=Math.min(Za,G());await F(ee)||i(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(ee)}ms; offering anyway`);}let Fe=Math.max(Math.min(L,G()),el);try{return y(v,R,Q,await g(Q,v,R,H,A,Fe),A)}catch(ee){let J=ee instanceof h?ee:new h("connection_failed",ee instanceof Error?ee.message:String(ee),{cause:ee});if(Q==="webrtc"&&nl(a,J),(J.reason==="credential_expired"||J.reason==="credential_reused")&&!K){K=!0,R=await c(v);continue}if(Q==="webrtc"&&J.reason==="signaling_failed"&&J.platformCode===Ao&&!Se){Se=!0;let ce=Math.min(Za,G());if(i(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(ce)}ms for the socket before offering again`),await F(ce))continue}if(J.reason==="join_rate_limited"){let ce=cp(Re,Math.random,G());if(ce!==null){if(Re.attempts+=1,Re.waitedMs+=ce,i(`[gem] ${Q} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ce)}ms before presenting again (retry ${Re.attempts} of ${al.maxAttempts})`),await Ln(t,ce,v.signal),v.signal?.aborted)throw new h("aborted","the caller aborted while waiting out a join rate limit");R.credentialExpiresAt-t.now()<tl&&(R=await c(v));continue}}if(dp.has(J.reason)||J.reason==="credential_expired"||Q==="webrtc"&&sl(J)){i(`[gem] ${Q} rung failed (${J.reason}): ${Fn(J.cause??J)} \u2014 `+(re.length<k.length?`falling through to ${k[re.length]}`:"no rungs left")),B.push(J);break}throw i(`[gem] ${Q} rung refused the session (${J.reason}): ${J.message}`),J}}}let le=B[B.length-1];throw le===void 0?new h("timeout",`the reconnect budget ran out before any transport (${k.join(", ")}) could be tried`):new h(le.reason,`every transport tried (${re.join(", ")}) failed; the last said: ${le.message}`,{cause:B,platformCode:le.platformCode})}catch(R){throw we(A),R}};return {listClusterTargets:async(v={})=>Fr({client:e,...v}),handleMatchEnded(v,S){let A=s.get(v);if(A!==void 0){s.delete(v);for(let R of A)R(S);}},connect:(async(v={})=>{let S=v.signaling??o();return v.transports===void 0?p(v,S):C(v,v.transports,S)})}}var Qa=["webtransport","webrtc","websocket"],ap=1e4,lp=5e3,Za=3e3,el=1e3,tl=1e4,dp=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function sl(n){return n.platformCode!==void 0&&Po.has(n.platformCode)}var al={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function cp(n,e=Math.random,t=1/0){let r=al;if(n.attempts>=r.maxAttempts)return null;let o=Math.min(r.budgetMs-n.waitedMs,t);if(o<r.initialDelayMs)return null;let i=r.initialDelayMs*r.factor**n.attempts;return Math.min(i+e()*r.jitterMs,o)}function up(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&jn():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||mp(e.websocket.url)}function mp(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return pn(e)}function Mo(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var pp=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function nl(n,e){e instanceof h&&(!pp.has(e.reason)&&!sl(e)||n.report([{type:"connection_failures_total",value:1}]));}function gp(n,e,t,r,o,i,a,s,l,d){let m=false,c=()=>{m||To(n,e.matchId,void 0);};i&&(t.addEventListener("close",c),a&&n.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,t.removeEventListener("close",c),s?.detach(),we(t),we(r),we(o));},g=y=>{if(!m){try{d?.(y);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:t,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:s?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function Oo(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function rl(n){if(n.status==="failed")throw new h("allocation_failed",`match ${n.matchId} did not come up: ${n.reason}`);if(n.status==="ended")throw new h("match_ended",`match ${n.matchId} ended (${n.reason}) before this side connected.`);if(n.protocol!==On)throw new h("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${On}' 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 h("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 ol(){let n=globalThis.RTCPeerConnection;if(!n)throw new h("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 we(n){try{n.close();}catch{}}function tr(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var yp=1e4;function ll(n,e){return Lo(n,e)}function Lo(n,e){if(typeof n.serverToken!="function"||typeof n.onServerToken!="function")throw new Error("this runtime delivers no game-server token: host.serverToken/onServerToken are missing. The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let t=a=>({token:a.token,expiresAt:a.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,o=new tt({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((a,s)=>{let l=e.clock.setTimeout(()=>{r=null,s({reason:"unavailable",retryable:true});},e.timeoutMs??yp);r={resolve:d=>{e.clock.clearTimeout(l),a(d);},reject:s,timer:l};})}),i=n.onServerToken(a=>{let s=t(a),l=r;if(l){r=null,l.resolve(s);return}o.accept(s);});return {source:o,dispose(){i(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var Do={};Nl(Do,{acceptTransfer:()=>fp,addEntityProgression:()=>hp,adminAction:()=>bp,cancelInventoryTransfer:()=>vp,claimEntityProgressionRewards:()=>_p,closeGameRoom:()=>wp,createEntityBatchOrder:()=>Sp,createEntityOrder:()=>Rp,createSession:()=>kp,deleteEntityGameSetting:()=>xp,deleteEntitySave:()=>Ap,deleteSession:()=>Pp,executeEntityRecipe:()=>Tp,finalizeSaveUpload:()=>Ep,getDropRates:()=>Ip,getEntityCurrency:()=>Cp,getEntityGameSetting:()=>Mp,getEntityInventory:()=>Op,getEntityInventoryItem:()=>Lp,getEntityLeaderboard:()=>Gp,getEntityOrder:()=>Dp,getEntityProgression:()=>$p,getEntityRecipeAvailability:()=>Fp,getEntityRecipeUsage:()=>jp,getEntitySave:()=>Np,getEvent:()=>qp,getGameRoomV2:()=>Up,getLeaderboard:()=>Bp,getPurchaseCatalog:()=>Hp,getResolvedTemplate:()=>Vp,getRoomArgs:()=>Wp,getTransferDetails:()=>Kp,ingestAnalyticsEvents:()=>Go,initiateInventoryTransfer:()=>Jp,invokeFunction:()=>zp,kickPlayer:()=>Yp,listChallenges:()=>Xp,listEntityGameSettings:()=>Qp,listEntityOrders:()=>Zp,listEntityProgressions:()=>eg,listEntitySaves:()=>tg,listEvents:()=>ng,listGameRooms:()=>rg,listResolvedTemplates:()=>og,listTransfers:()=>ig,putEntityGameSetting:()=>sg,putRoomArgs:()=>ag,rejectTransfer:()=>lg,requestSaveUploadUrl:()=>dg,resetEntityProgression:()=>cg,simulateEntityOrder:()=>ug,transferHostV2:()=>mg,updateGameRoomV2:()=>pg});function b(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 fp(n,e,t){let r=`/v1/inventory/transfers/${b(e)}/accept`;return n.client.post(r,void 0,t?.signal)}async function hp(n,e,t,r,o,i){let a=`/v1/inventory/${b(e)}/${b(t)}/progressions/${b(r)}/add`;return n.client.post(a,o,i?.signal)}async function bp(n,e,t,r){let o=`/v1/voice/sessions/${b(e)}/admin`;return n.client.post(o,t,r?.signal)}async function vp(n,e,t){let r=`/v1/inventory/transfers/${b(e)}/cancel`;return n.client.post(r,void 0,t?.signal)}async function _p(n,e,t,r,o,i){let a=`/v1/inventory/${b(e)}/${b(t)}/progressions/${b(r)}/claim`;return n.client.post(a,o,i?.signal)}async function wp(n,e,t){let r=`/v1/games/${b(n.gameId())}/game-rooms/${b(e)}`;return n.client.delete(r,t?.signal)}async function Sp(n,e,t,r,o){let i=`/v1/inventory/${b(e)}/${b(t)}/orders/batch`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Rp(n,e,t,r,o){let i=`/v1/inventory/${b(e)}/${b(t)}/orders`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function kp(n,e,t){return n.client.post("/v1/voice/sessions",e,t?.signal)}async function xp(n,e,t,r,o){let i=`/v1/settings/${b(e)}/${b(t)}/${b(r)}`;return n.client.delete(i,o?.signal)}async function Ap(n,e,t,r,o){let i=`/v1/saves/${b(e)}/${b(t)}/${b(r)}`;return n.client.delete(i,o?.signal)}async function Pp(n,e,t){let r=`/v1/voice/sessions/${b(e)}`;return n.client.delete(r,t?.signal)}async function Tp(n,e,t,r,o){let i=`/v1/inventory/${b(e)}/${b(t)}/recipes/execute`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Ep(n,e,t,r,o,i){let a=`/v1/saves/${b(e)}/${b(t)}/${b(r)}/finalize`;return n.client.post(a,o,i?.signal)}async function Ip(n,e,t){let r=`/v1/inventory/loot-tables/${b(e)}/drop-rates`;return n.client.get(r,t?.signal)}async function Cp(n,e,t,r,o){let i=`/v1/inventory/${b(e)}/${b(t)}/currencies/${b(r)}`;return n.client.get(i,o?.signal)}async function Mp(n,e,t,r,o){let i=`/v1/settings/${b(e)}/${b(t)}/${b(r)}`;return n.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Op(n,e,t,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),a=`/v1/inventory/${b(e)}/${b(t)}`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function Lp(n,e,t,r,o){let i=`/v1/inventory/${b(e)}/${b(t)}/items/${b(r)}`;return n.client.get(i,o?.signal)}async function Gp(n,e,t,r,o){let i=new URLSearchParams;o?.bucket_1!==void 0&&i.set("bucket_1",String(o?.bucket_1)),o?.bucket_2!==void 0&&i.set("bucket_2",String(o?.bucket_2)),o?.limit!==void 0&&i.set("limit",String(o?.limit));let a=i.toString(),s=`/v1/leaderboards/${b(e)}/${b(t)}/${b(r)}`+(a?`?${a}`:"");return n.client.get(s,o?.signal)}async function Dp(n,e,t,r,o){let i=`/v1/inventory/${b(e)}/${b(t)}/orders/${b(r)}`;return n.client.get(i,o?.signal)}async function $p(n,e,t,r,o){let i=`/v1/inventory/${b(e)}/${b(t)}/progressions/${b(r)}`;return n.client.get(i,o?.signal)}async function Fp(n,e,t,r,o,i){let a=`/v1/inventory/${b(e)}/${b(t)}/catalogs/${b(r)}/recipes/${b(o)}/availability`;return n.client.get(a,i?.signal)}async function jp(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit));let i=o.toString(),a=`/v1/inventory/${b(e)}/${b(t)}/recipe-usage`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function Np(n,e,t,r,o){let i=`/v1/saves/${b(e)}/${b(t)}/${b(r)}`;return n.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function qp(n,e,t){let r=`/v1/events/${b(e)}`;return n.client.get(r,t?.signal)}async function Up(n,e,t){let r=`/v2/games/${b(n.gameId())}/game-rooms/${b(e)}`;return n.client.getWithEtag(r,{...t?.signal===void 0?{}:{signal:t.signal},...t?.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}})}async function Bp(n,e,t){let r=new URLSearchParams;t?.bucket_1!==void 0&&r.set("bucket_1",String(t?.bucket_1)),t?.bucket_2!==void 0&&r.set("bucket_2",String(t?.bucket_2));let o=r.toString(),i=`/v1/leaderboards/${b(e)}`+(o?`?${o}`:"");return n.client.get(i,t?.signal)}async function Hp(n,e){let t=new URLSearchParams;e?.config_version!==void 0&&t.set("config_version",String(e?.config_version));let r=t.toString(),o="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function Vp(n,e,t){let r=`/v1/game-room-templates/${b(e)}`;return n.client.get(r,t?.signal)}async function Wp(n,e,t){let r=`/v1/games/${b(n.gameId())}/game-rooms/${b(e)}/room-args`;return n.client.get(r,t?.signal)}async function Kp(n,e,t){let r=`/v1/inventory/transfers/${b(e)}`;return n.client.get(r,t?.signal)}async function Go(n,e,t){let r=`/v1/games/${b(n.gameId())}/analytics/events`;return n.client.post(r,e,t?.signal,{replaySafe:true})}async function Jp(n,e,t){return n.client.post("/v1/inventory/transfers",e,t?.signal)}async function zp(n,e,t){return n.client.postBytes("/v1/functions/invoke",e,t?.signal)}async function Yp(n,e,t,r){let o=`/v1/games/${b(n.gameId())}/game-rooms/${b(e)}/kick/${b(t)}`;return n.client.post(o,void 0,r?.signal)}async function Xp(n,e){let t=new URLSearchParams;e?.periods_back!==void 0&&t.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&t.set("player_id",String(e?.player_id));let r=t.toString(),o="/v1/challenges"+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function Qp(n,e,t,r){let o=`/v1/settings/${b(e)}/${b(t)}`;return n.client.get(o,r?.signal)}async function Zp(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/inventory/${b(e)}/${b(t)}/orders`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function eg(n,e,t,r){let o=`/v1/inventory/${b(e)}/${b(t)}/progressions`;return n.client.get(o,r?.signal)}async function tg(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/saves/${b(e)}/${b(t)}`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function ng(n,e){let t=new URLSearchParams;e?.include_inactive!==void 0&&t.set("include_inactive",String(e?.include_inactive)),e?.limit!==void 0&&t.set("limit",String(e?.limit)),e?.offset!==void 0&&t.set("offset",String(e?.offset));let r=t.toString(),o="/v1/events"+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function rg(n,e){let t=new URLSearchParams;e?.status!==void 0&&t.set("status",String(e?.status)),e?.game_channel!==void 0&&t.set("game_channel",String(e?.game_channel)),e?.game_room_type!==void 0&&t.set("game_room_type",String(e?.game_room_type)),e?.template_id!==void 0&&t.set("template_id",String(e?.template_id)),e?.template_slug!==void 0&&t.set("template_slug",String(e?.template_slug)),e?.limit!==void 0&&t.set("limit",String(e?.limit)),e?.cursor!==void 0&&t.set("cursor",String(e?.cursor));let r=t.toString(),o=`/v1/games/${b(n.gameId())}/game-rooms`+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function og(n,e){return n.client.get("/v1/game-room-templates",e?.signal)}async function ig(n,e){let t=new URLSearchParams;e.entity_type!==void 0&&t.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&t.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&t.set("direction",String(e?.direction)),e?.status!==void 0&&t.set("status",String(e?.status)),e?.cursor!==void 0&&t.set("cursor",String(e?.cursor)),e?.limit!==void 0&&t.set("limit",String(e?.limit));let r=t.toString(),o="/v1/inventory/transfers"+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function sg(n,e,t,r,o,i){let a=`/v1/settings/${b(e)}/${b(t)}/${b(r)}`;return n.client.put(a,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ag(n,e,t,r){let o=`/v1/games/${b(n.gameId())}/game-rooms/${b(e)}/room-args`;return n.client.put(o,t,r?.signal)}async function lg(n,e,t){let r=`/v1/inventory/transfers/${b(e)}/reject`;return n.client.post(r,void 0,t?.signal)}async function dg(n,e,t,r,o,i){let a=`/v1/saves/${b(e)}/${b(t)}/${b(r)}/upload-url`;return n.client.post(a,o,i?.signal,{replaySafe:true})}async function cg(n,e,t,r,o,i){let a=`/v1/inventory/${b(e)}/${b(t)}/progressions/${b(r)}/reset`;return n.client.post(a,o,i?.signal)}async function ug(n,e,t,r,o){let i=`/v1/inventory/${b(e)}/${b(t)}/orders/simulate`;return n.client.post(i,r,o?.signal)}async function mg(n,e,t,r){let o=`/v2/games/${b(n.gameId())}/game-rooms/${b(e)}/transfer/${b(t)}`;return n.client.post(o,void 0,r?.signal)}async function pg(n,e,t,r){let o=`/v2/games/${b(n.gameId())}/game-rooms/${b(e)}`;return n.client.patch(o,t,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var gg=1e4,yg=50,fg=1e3,hg=65536-4*1024,dl=n=>typeof n=="number"?n:0,bg=n=>typeof n=="string"?n:"";function cl(){let n=globalThis.crypto;return typeof n?.randomUUID=="function"?n.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.floor(Math.random()*16);return (e==="x"?t:t&3|8).toString(16)})}function vg(n){return n?.retryable===true}function _g(n,e){let t=n??{},r=Array.isArray(t.rejected)?t.rejected.map(o=>{let i=o??{};return {index:dl(i.index),code:bg(i.code)}}):[];return {accepted:dl(t.accepted),rejected:r,dropped:e,duplicate:t.duplicate===true}}function ul(n,e){return {event_uid:n.uid,name:n.name,offset_ms:Math.round(n.atMs)-e,player_id:n.playerId,dimensions:n.dimensions,measures:n.measures}}function ml(n){let e=Math.max(1,Math.floor(n.maxQueue??fg)),t={client:n.client,gameId:()=>n.gameId},r=[],o=0,i=null,a=false,s=false,l=false,d=false,m=w=>{n.log?.(w);},c=()=>{i!==null&&(n.clock.clearTimeout(i),i=null);},p=()=>{i!==null||a||s||(i=n.clock.setTimeout(()=>{i=null,y().catch(()=>{});},gg));},g=()=>{let w=Math.min(r.length,100),x=128;for(let C=0;C<w;C+=1){let E=r[C];if(E===void 0)break;if(x+=JSON.stringify(ul(E,0)).length+1,x>hg)return Math.max(1,C)}return w};async function y(w){if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};c();let x=r.splice(0,g()),C=o;o=0;let E=Math.round(n.clock.now()),v={batch_id:cl(),sent_at_ms:E,events:x.map(S=>ul(S,E))};s=true;try{let S=await Go(t,v,w===void 0?void 0:{signal:w}),A=_g(S,C);for(let R of A.rejected)m(`[gem] analytics: an event was refused (${R.code}). See the analytics_events section of your game config.`);return A}catch(S){if(vg(S))for(r=[...x,...r],o+=C;r.length>e;)r.shift(),o+=1;else m(`[gem] analytics: ${x.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(S)}`);throw S}finally{s=false,r.length>0&&p();}}return {track(w,x,C={}){if(a)return;if(typeof w!="string"||w===""){d||(d=true,m(`[gem] analytics: '${x}' was not recorded \u2014 an event from a server has to name the player it is about. A game-server token names no player, so the platform cannot infer one; pass the id from join() or host.players().`));return}if(x.startsWith(Ir)){l||(l=true,m(`[gem] analytics: '${x}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let E={},v={};for(let[S,A]of Object.entries(C))typeof A=="string"?E[S]=A:typeof A=="number"&&Number.isFinite(A)&&(v[S]=A);for(;r.length>=e;)r.shift(),o+=1;r.push({uid:cl(),playerId:w,name:x,atMs:n.clock.now(),dimensions:E,measures:v}),r.length>=yg?y().catch(()=>{}):p();},flush:w=>y(w),get pending(){return r.length},dispose(){a=true,c(),r=[],o=0;}}}function wg(n){let e={};for(let[t,r]of Object.entries(Do))if(typeof r=="function"){let o=r;e[t]=(...i)=>o(n,...i);}return e}function yt(n,e={}){let t=e.clock??ae,r=e.baseUrl??n.apiBaseUrl;if(!r)throw new Error("this runtime names no gem-api host (host.apiBaseUrl is missing). The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let o=Lo(n,{clock:t,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),i=Zn({baseUrl:r,tokenSource:o.source,defaultQuery:{game_id:n.gameId,channel:n.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),a=new Ce({transport:i,clock:t}),s={gameId:n.gameId,channel:n.channel,matchId:n.matchId,...n.gameRoomId===void 0?{}:{gameRoomId:n.gameRoomId}},l=wg({client:a,gameId:()=>s.gameId}),d=s.gameRoomId,m=n.endMatch,c=n.log,p=ml({client:a,clock:t,gameId:s.gameId,...typeof c=="function"?{log:y=>c.call(n,y)}:{}});return {identity:s,client:a,api:l,match:{end:async()=>{if(m===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await m.call(n);}},analytics:p,functions:new Oe(l.invokeFunction),...d===void 0?{}:{room:{get:y=>l.getGameRoomV2(d,y),args:y=>l.getRoomArgs(d,y)}},dispose:()=>{p.dispose(),o.dispose();}}}function Je(n){return n?.reliable!==false?"reliable":n?.ordered!==false?"ordered":"unreliable"}function ft(n){return {reliable:n==="reliable",ordered:n!=="unreliable"}}function Zt(n){return typeof n=="string"?n:n.slice().buffer}function nr(n){if(typeof n=="string")return {data:n,isText:true};if(n instanceof ArrayBuffer)return {data:new Uint8Array(n),isText:false};if(ArrayBuffer.isView(n)){let e=n;return {data:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),isText:false}}return null}var Sg=5e3,pl=3e4,gl=2e3,Rg=1e4,yl=1;async function fl(n,e){let{session:t,localPlayerId:r}=e;if(!t.isHost)throw new Error("[gem] runListenHost was handed a session this player does not host. The room decides who hosts; gate on `gem.rooms.isHost` \u2014 or call `gem.match.serve()`, which does.");let o=e.log===void 0?f=>console.info(f):e.log,i=f=>o?.(`[gem host] ${f}`),a=typeof n=="function"?n():n,s=Promise.resolve(),l=true,d=false,m=(f,T)=>{l&&(s=s.then(async()=>{if(!d)try{await T();}catch($){i(`the bundle's ${f} handler threw: ${ze($)}. Serving continues.`);}}));},c=true,p,g,y,w=f=>{if(!c)return;c=false,m("leave",()=>a.leave?.(r,{cause:f??"left"}));let T=g;T&&queueMicrotask(()=>T(f));},x={send(f,T){if(!c)return;let $=ft(Je(T));m("message",()=>a.message?.(r,f,typeof f=="string",{reliable:$.reliable,ordered:$.ordered}));},onMessage(f){p=f;},onClose(f){g=f;},close(){w("closed");}},C=(f,T)=>{if(!c)return;let $=ft(Je(T));queueMicrotask(()=>{c&&p?.(f,$);});},E=new Map,v=f=>{let T=[];for(let $ of Ie){let Z=f.channels[$];try{Z.binaryType="arraybuffer";}catch{}let ke=ft($),ht=Xe=>{let je=nr(Xe?.data);je!==null&&m("message",()=>a.message?.(f.playerId,je.data,je.isText,{reliable:ke.reliable,ordered:ke.ordered}));};Z.addEventListener("message",ht),T.push(()=>Z.removeEventListener("message",ht));}E.get(f.playerId)?.forEach($=>$()),E.set(f.playerId,T);},S=f=>{E.get(f)?.forEach(T=>T()),E.delete(f);},A=new Set,R=new Map,H=(f,T,$)=>({playerNumber:f.assignedPeerId,transport:"webrtc_p2p",...T?{rejoin:true}:{},...$?{superseded:true}:{}}),j=f=>{let T=E.has(f.playerId),$=A.has(f.playerId);A.add(f.playerId),v(f),T&&m("leave",()=>a.leave?.(f.playerId,{cause:"superseded"})),m("join",()=>a.join?.(f.playerId,H(f,$,T)));},V=new Set,k=(f,T,$)=>{if(f===r){C(T,$);return}let Z=t.peer(f);if(Z===null){let ke=R.get(f);if(ke!==void 0&&e.clock.now()-ke<gl)return;V.has(f)||(V.add(f),i(`send to '${f}' dropped: no such connected player`));return}Z.send(Zt(T),Je($));},P={matchId:t.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:f=>e.tokens.subscribe(f),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(f=>f.playerId)??[],players(){let f=c?[r]:[];for(let T of t.peers)f.push(T.playerId);return f},profile(f){let T=e.room()?.members.find($=>$.playerId===f);if(!(!T||T.displayName===void 0))return {displayName:qe.toPlain(T.displayName),...T.displayTag===void 0?{}:{displayTag:qe.toPlain(T.displayTag)},...T.discriminator===void 0?{}:{discriminator:T.discriminator}}},playerNumber(f){return f===r?yl:t.peer(f)?.assignedPeerId},send(f,T,$){k(f,T,$);},broadcast(f,T){let $=T?.except;c&&r!==$&&C(f,T);for(let Z of t.peers)Z.playerId!==$&&Z.send(Zt(f),Je(T));},async endMatch(){let f=await Fe();return f.answer!=="ok"&&i(f.cause),f.answer},kick(f,T){if(f===r){w(T??"kicked");return}t.kick(f).catch($=>{i(`kick of '${f}' failed: ${ze($)}`);});},log(f){i(f);},warn(f){i(`\u26A0 ${f}`);}},L=()=>{},G=new Promise(f=>{L=f;}),F=[],B=null,re=async(f,T)=>{l=false;let $=s.then(async()=>{try{await a.shutdown(f);}catch(Z){i(`the bundle's shutdown threw: ${ze(Z)}`);}});s=$,await $,ce();for(let Z of F.splice(0))Z();for(let Z of [...E.keys()])S(Z);w(T);},le=(f,T)=>B||(B=(async()=>{await re(T,f),t.close(),L();})(),B),Q=()=>B||(B=(async()=>{await re({reason:"signal"},"left"),await t.leave().catch(f=>i(`leaving the match failed: ${ze(f)}`)),L();})(),B),K=()=>B||(B=(async()=>{l=false;let f=await Fe();f.answer==="ok"?(await re({reason:"match_ended",platform_reason:"explicit"},"match ended"),t.close()):(i(`${f.cause}; leaving instead`),await re({reason:"signal"},"left"),await t.leave().catch(T=>i(`leaving the match failed: ${ze(T)}`))),L();})(),B),Se=null,Re=()=>(Se??=yt(P,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),Se),Fe=async()=>{try{return await Hi({client:Re().client,gameId:()=>P.gameId},P.matchId,{},{signal:AbortSignal.timeout(Sg)}),{answer:"ok"}}catch(f){return f instanceof D&&(f.reason==="forbidden"||f.reason==="not_found")?{answer:f.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${f.reason})`}:{answer:"failed",cause:`ending the match failed: ${ze(f)}`}}},ee=null,J=false,ce=()=>{J=true,ee!==null&&(e.clock.clearTimeout(ee),ee=null);},X=async()=>{if(ee=null,!J){try{await Re().client.post(`/v1/games/${encodeURIComponent(P.gameId)}/matches/${encodeURIComponent(P.matchId)}/heartbeat`,void 0,AbortSignal.timeout(Rg));}catch(f){if(f instanceof D&&(f.reason==="forbidden"||f.reason==="not_found")){i(`the platform no longer holds this match under this host (${f.reason}); heartbeats stop`),ce();return}i(`heartbeat failed: ${ze(f)}`);}J||(ee=e.clock.setTimeout(()=>{X();},pl));}},nn=()=>{J||ee!==null||(ee=e.clock.setTimeout(()=>{X();},pl));};{let f=L;L=()=>{ce(),Se?.dispose(),Se=null,f();};}let rn=Promise.resolve().then(()=>a.init(P));s=rn.then(()=>{},()=>{}),m("join",()=>a.join?.(r,{playerNumber:yl,transport:"loopback"})),F.push(t.on("peerJoined",j)),F.push(t.on("peerLeft",(f,T)=>{S(f);let $=e.clock.now();for(let[Z,ke]of R)$-ke>=gl&&R.delete(Z);R.set(f,$),V.delete(f),m("leave",()=>a.leave?.(f,{cause:T}));})),F.push(t.on("error",f=>{i(`\u26A0 session error: ${f.message}`);})),F.push(t.on("matchEnded",f=>{B||$o(y,f),le("match ended",{reason:"match_ended",platform_reason:f});})),F.push(t.on("hostChanged",f=>{f!==r&&le("host migrated",{reason:"host_migrated"});}));for(let f of t.peers)j(f);try{await rn,nn();}catch(f){l=false,ce(),d=true;for(let T of F.splice(0))T();for(let T of [...E.keys()])S(T);throw t.leave().catch(()=>{}),L(),f}return {matchId:t.matchId,localLink:x,onMatchEnded(f){y=f;},end:K,leave:Q,stop:f=>le(f,{reason:"stopped"}),done:G}}function $o(n,e){try{n?.(e);}catch{}}function ze(n){return n instanceof Error?n.message:String(n)}function Fo(n,e){let t=async()=>{throw new h("misconfigured",`this seat is \`${n}\`, not the match's authority: `+(n==="dedicated"?"the platform runs the server, and its bundle ends the match with gem.match.end().":"another player hosts this match."))};return {mode:n,matchId:e,end:t,leave:t,stop:async()=>{}}}function hl(n){let e=new Map,t=n.autoReconnect===true,{rooms:r}=n,o=new Map,i=async s=>{r.isHost&&!Oo(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...s.signal===void 0?{}:{signal:s.signal}});let l={...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},a=s=>({...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0?{}:{clusterTargetId:s.clusterTargetId}});return {async serve(s,l={}){let d=await i(l);if(d.protocol!==We)return Fo("dedicated",d.matchId);let m=n.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return Fo("peer",d.matchId);let c=n.identity();if(c===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=m??await n.p2p.connect(a(l)),g=await fl(s,{session:p,clock:n.clock,gameId:c.gameId,channel:c.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:n.apiBaseUrl(),tokens:n.tokens,room:n.room,localPlayerId:p.playerId!==""?p.playerId:c.playerId,...n.log===void 0?{}:{log:n.log},...n.fetch===void 0?{}:{fetch:n.fetch}});return o.set(d.matchId,g),g.done.then(()=>{o.get(d.matchId)===g&&o.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(s={}){let l=await i(s),d=s.onMatchEnded;if(l.protocol===We){let g=o.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),Pg(l.matchId,g,d);if(r.isHost)throw new Error("[gem] this player hosts the P2P match, so there is no one to connect TO yet. Call gem.match.serve(yourServer) first; connect() then resolves the loopback to your own bundle.");let y=await Wt(),w=async()=>n.p2p.connect({...a(s),certificate:y}),x=await w(),C=Eg(x,w,d,E=>{r.notifyMatchDisconnected(E).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),t);return t&&(e.set(x.matchId,{redial:C.redial,abandon:C.abandon}),C.onClosed(()=>{e.get(x.matchId)?.abandon===C.abandon&&e.delete(x.matchId);})),C}let m=async(g=null)=>await n.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:s.transports??[]}),c=await m(),p=Tg(c,m,r,t);return t&&(e.set(c.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(c.matchId)?.abandon===p.abandon&&e.delete(c.matchId);})),p},async redialMatch(s,l){let d=e.get(s);return d===void 0?"closed":d.redial(l)},abandonMatch(s,l){e.get(s)?.abandon(l);}}}var bl="link_closed",kg="host_unreachable",xg=new Set(["failed","closed"]);function Ag(n){return xg.has(n)?bl:kg}function Pg(n,e,t){let r=e.localLink;e.onMatchEnded(t);let o="connected";r.onClose(()=>{o="closed";});let i;return {matchId:n,protocol:"loopback",get state(){return o},send:(a,s)=>r.send(a,s),onMessage:a=>r.onMessage(a),onClose:a=>{i=a,r.onClose(s=>{o="closed",i?.(s);});},close:()=>r.close()}}function Tg(n,e,t,r){let o=n.matchId,i=n,a="connected",s,l,d=[],m=false,c=false,p=y=>{if(a!=="closed"){a="closed";for(let w of d.splice(0))w();l?.(y);}},g=y=>{y.link.onMessage((w,x)=>s?.(w,x)),y.link.onClose(w=>{if(y!==i||a==="closed")return;if(m||!r){p(w);return}let x=t.matchSession;if(x.phase==="suspended"&&x.matchId===o){a="suspended";return}p(w);});};return g(n),{matchId:o,protocol:"dedicated",get transport(){return i.transport},get state(){return a},send(y,w){a==="connected"&&i.link.send(y,w);},onMessage(y){s=y;},onClose(y){l=y;},close(){if(a!=="closed"){if(m=true,a==="suspended"){p("closed");return}i.close(),p("closed");}},async redial(y){if(a==="closed"||m)return "closed";if(c)return "connected";c=true;let w;try{w=await e(y===void 0?{}:{deadlineAt:y});}finally{c=false;}return m||a==="closed"?(w.close(),"closed"):(i=w,g(w),a="connected",t.notifyMatchConnected(o),"connected")},abandon(y){a!=="closed"&&(a==="connected"&&i.close(),p(y));},onClosed(y){a==="closed"?y():d.push(y);}}}function Eg(n,e,t,r,o,i=false){let a=n.matchId,s=n,l,d,m=[],c=[],p=[],g=false,y=false,w=false,x=false,C="connected",E=k=>{if(g)return;g=true,C="closed";for(let L of m.splice(0))L();for(let L of c.splice(0))L();for(let L of p.splice(0))L();let P=d;P&&queueMicrotask(()=>P(k));},v=k=>{for(let P of m.splice(0))P();for(let P of Ie){let L=k.channels[P];try{L.binaryType="arraybuffer";}catch{}let G=ft(P),F=B=>{let re=nr(B?.data);re!==null&&l?.(re.data,G);};L.addEventListener("message",F),m.push(()=>L.removeEventListener("message",F));}},S=()=>s.peer(s.hostPlayerId),A=k=>{if(!(g||s.isHost)&&C!=="suspended"){if(r?.(k),i){C="suspended";return}E(k);}},R=k=>{for(let P of Ie){let L=k.channels[P];if(typeof L.addEventListener!="function")continue;let G=()=>{S()===k&&A(bl);};L.addEventListener("close",G),m.push(()=>L.removeEventListener?.("close",G));}},H=k=>{v(k),R(k),!g&&(C="connected",o?.());},j=k=>{for(let P of c.splice(0))P();c.push(k.on("migrating",()=>{x=true;})),c.push(k.on("hostChanged",P=>{if(x=false,P===k.playerId){E("host_migrated_here");return}let L=S();L!==null&&H(L);})),c.push(k.on("peerJoined",P=>{P.playerId===k.hostPlayerId&&H(P);})),c.push(k.on("matchEnded",P=>{g||$o(t,P),E(P);})),c.push(k.on("peerLeft",(P,L)=>{P===k.hostPlayerId&&A(Ag(L));}));};j(s);let V=S();return V!==null&&H(V),{matchId:a,protocol:"p2p",get state(){return C},send(k,P){C==="connected"&&S()?.send(Zt(k),Je(P));},onMessage(k){l=k;},onClose(k){d=k;},close(){y=true,E("closed"),s.leave().catch(()=>{});},async redial(){if(C==="closed")return "closed";if(C==="connected"||w)return "connected";if(x)throw new O("connection_failed","a host migration is in flight, and it is the way back \u2014 this attempt waits it out rather than tearing down the session the platform is moving");w=true;let k;try{for(let L of m.splice(0))L();for(let L of c.splice(0))L();s.close(),k=await e();}finally{w=false;}if(g)return y?k.leave().catch(()=>{}):k.close(),"closed";s=k,j(s);let P=S();if(P===null)throw s.close(),new O("connection_failed","this peer rejoined the match but the host never answered with a link");return H(P),"connected"},abandon(k){E(k);},onClosed(k){g?k():p.push(k);}}}function jo(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(o=>{let i={},a=l=>{t.delete(r)&&(n.clock.clearTimeout(i.timer),o(l));};t.set(r,a),i.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,o){t.get(r)?.(o);}}}var Ig=0;function $e(){try{return crypto.randomUUID()}catch{let n=Math.random().toString(36).slice(2,10);return `local-${String(++Ig)}-${String(Date.now())}-${n}`}}var Cg=12e4;function Ye(n,e){return {outcome:n,reason:e}}function vl(n){let e=false,t=new Map;return {api:{request(r){if(!n.bridge.parentSupports("purchases"))return Promise.resolve(Ye("unavailable","error"));if(e)return Promise.resolve(Ye("declined","busy"));let o=`purchase-${$e()}`;return new Promise(i=>{let a={},s=d=>{t.delete(o)&&(e=false,n.clock.clearTimeout(a.timer),i(d));};e=true,t.set(o,s),a.timer=n.clock.setTimeout(()=>s(Ye("unavailable","error")),n.timeoutMs??Cg);let l=false;try{l=n.bridge.requestPurchase(o,r.kind,r.targetId,r.currencySlug,r.quantity,r.catalogId);}catch{}l||s(Ye("unavailable","error"));})}},settle(r){let o=r.outcome==="ok"||r.outcome==="declined"?r.outcome:"unavailable",i=t.get(r.requestId);if(i===void 0){n.onDropped?.(`gem.purchaseResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}if(o!=="ok"){i(Ye(o,ds(r.reason)));return}let a=r.purchaseId;if(a===void 0){n.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),i(Ye("unavailable","error"));return}(async()=>{let s;try{s=await n.confirm(a);}catch{s="unknown";}if(s==="granted"){i({outcome:"ok",purchaseId:a});return}s==="absent"&&n.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for purchase "+JSON.stringify(a)),i(Ye("unavailable","error"));})();}}}async function _l(n,e){try{return (await Ei(n,e)).granted?"granted":"absent"}catch(t){return t instanceof D&&t.reason==="not_found"?"absent":"unknown"}}var Mg=6e5;function wl(n){let e=null,t=new Map;return {api:{requestSignIn(){if(!n.bridge.parentSupports("signIn"))return Promise.resolve({outcome:"unavailable"});if(e!==null)return e;let r=`signin-${$e()}`;return e=new Promise(o=>{let i={},a=l=>{t.delete(r)&&(e=null,n.clock.clearTimeout(i.timer),o(l));};t.set(r,a),i.timer=n.clock.setTimeout(()=>{a({outcome:"unavailable"});},n.timeoutMs??Mg);let s=false;try{s=n.bridge.requestSignIn(r);}catch{}s||a({outcome:"unavailable"});}),e}},settle(r){let o=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",i=t.get(r.requestId);if(i===void 0){n.onDropped?.(`gem.signInResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}i({outcome:o});}}}var Og=18e4,Sl=32,Lg=/^[a-z0-9_-]+$/;function Gg(n){return n==="interstitial"||n==="rewarded"}function Rl(n){let e=false,t=new Map;return {api:{requestAd(r){if(!n.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});if(typeof r.placement!="string"||r.placement===""||r.placement.length>Sl||!Lg.test(r.placement)||!Gg(r.format))return n.onDropped?.(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${JSON.stringify(r.placement)}, format ${JSON.stringify(r.format)}. A placement is 1..${String(Sl)} characters of a-z, 0-9, '-' and '_' \u2014 the grammar the platform's own ad endpoint accepts \u2014 and a format is 'interstitial' or 'rewarded'. Answering no_ad.`),Promise.resolve({outcome:"no_ad"});let o=`ad-${$e()}`,i=r.format,a=r.placement;return new Promise(s=>{let l={},d=c=>{t.delete(o)&&(e=false,n.clock.clearTimeout(l.timer),s(c));};e=true,t.set(o,d),l.timer=n.clock.setTimeout(()=>{d({outcome:"unavailable"});},n.timeoutMs??Og);let m=false;try{m=n.bridge.requestAd(o,a,i);}catch{}m||d({outcome:"no_ad"});})}},settle(r){let o=r.outcome==="shown"||r.outcome==="no_ad"?r.outcome:"unavailable",i=t.get(r.requestId);if(i===void 0){n.onDropped?.(`gem.adResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}i({outcome:o});}}}var No=16384;function kl(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:Dg(e)}function Dg(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 o=n.charCodeAt(t+1);o>=56320&&o<=57343?(e+=4,t+=1):e+=3;}else e+=3;}return e}var $g=1e4,Fg=5e3;function xl(n){let e=null,t=false,r=[],o=new Map,i=()=>{for(let a of r.splice(0))a();};return {api:{get current(){return e},wait(a=Fg){return t?Promise.resolve(e):new Promise(s=>{let l=()=>{let c=r.indexOf(d);c>=0&&r.splice(c,1);},d=()=>{n.clock.clearTimeout(m),l(),s(e);},m=n.clock.setTimeout(()=>{l(),s(e);},a);r.push(d);})},put(a){if(!n.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let s=kl(a);if(s===null)return n.onDropped?.("gem.deviceSettings.put refused locally: settings must be a plain JSON object (not a primitive, an array, null, or something JSON.stringify cannot take)"),Promise.resolve("unavailable");if(s>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(a)),d=`device-settings-${$e()}`;return new Promise(m=>{let c={},p=y=>{o.delete(d)&&(n.clock.clearTimeout(c.timer),y==="stored"&&(e=l,t=true,i()),m(y));};o.set(d,p),c.timer=n.clock.setTimeout(()=>p("unavailable"),n.timeoutMs??$g);let g=false;try{g=n.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(a){let s=a.settings;e=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:null,t=true,i();},settle(a){let s=a.outcome==="stored"||a.outcome==="too_large"?a.outcome:"unavailable",l=o.get(a.requestId);if(l===void 0){n.onDropped?.(`gem.deviceSettings.result (${s}) for an unknown requestId: `+JSON.stringify(a.requestId));return}l(s);}}}function Al(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function Pl(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function jg(n){let e=n.untrusted,t=ye(e.displayName),r=e.displayTag||e.displayHandle,o=r?ye(r):void 0,i=n.discriminator||n.displayTag,a=i&&/^[0-9]{1,8}$/.test(i)?i:void 0,s=n.avatarIconUrl||n.avatarUrl,l={displayName:t,displayHandle:o??t,badges:(n.badges??[]).map(p=>({itemId:p.itemId,iconUrl:p.iconUrl}))};n.playerId&&(l.playerId=n.playerId),a&&(l.discriminator=a),o&&(l.displayTag=o),s&&(l.avatarIconUrl=l.avatarUrl=s);let d=n.boost,m=(d?.multipliers??[]).map(p=>({currencyId:p.currencyId,currencySlug:p.currencySlug,multiplier:p.multiplierBp/1e4})),c=m.some(p=>p.multiplier>1);return l.boost=c&&d?.expiresInDays?{active:c,multipliers:m,expiresInDays:d.expiresInDays}:{active:c,multipliers:m},l}var Ng=1e4,en=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??ae,this.inbound=new _t(this.clock),this.outbound=new _t(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(s=>gr(s,e.origin))||is(e.origin,this.options.selfOrigin)))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=mn["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let o=e.data;if(!gr(o.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${o.embedder}' but arrived from '${e.origin}'`),false;let i=e.ports?.[0];if(!i)return this.refuse(e,"handshake transferred no MessagePort"),false;let a=ss(cn,o.versions);return a===null?(i.onmessage=null,i.postMessage({gem:z,type:"gem.error",code:"version_mismatch",message:`frame supports v${cn.min}..v${cn.max}`}),i.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=i,this.version=a,i.onmessage=s=>this.receive(s.data,s.ports??[]),i.start?.(),this.peerCapabilities=o.capabilities??[],i.postMessage({gem:z,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:z,type:"gem.ready"});}settled(e=Ng){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(t=>{let r=i=>{this.clock.clearTimeout(o),t(i);},o=this.clock.setTimeout(()=>{let i=this.settleWaiters.indexOf(r);i>=0&&this.settleWaiters.splice(i,1),t(this.state);},e);this.settleWaiters.push(r);})}progress(e,t){this.send({gem:z,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:z,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:z,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),true):false}exit(e){this.send(e===void 0?{gem:z,type:"gem.exit"}:{gem:z,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:z,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:z,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:z,type:"gem.audioState",muted:e}),true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let t={gem:z,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:Al(e.origin.x),y:Al(e.origin.y)}),this.send(t),true}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:z,type:"gem.frameStats",fps:Pl(e.fps,1e3),frameTimeP95Ms:Pl(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:z,type:"gem.gameContext",context:e}),true)}signal(e,t,r){this.send({gem:z,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:z,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:z,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,o,i,a){return this.send({gem:z,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:o,...i===void 0?{}:{quantity:i},...a===void 0?{}:{catalogId:a}})}putDeviceSettings(e,t){return this.send({gem:z,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:z,type:"gem.requestAd",requestId:e,placement:t,format:r})}requestSignIn(e){return this.send({gem:z,type:"gem.requestSignIn",requestId:e})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let t of this.settleWaiters.splice(0))t(e);this.options.onStateChange?.(e);}}refuseMalformed(e,t){if(!this.inbound.allow(un)){this.options.onDropped?.(e,t);return}this.fail(e,t);}dropUnknownType(e){this.inbound.allow(un)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,t){e.ports?.[0]?.close?.(),this.inbound.allow(un)&&this.options.onRefused?.(t);}fail(e,t){this.options.onError?.(e,t),this.state==="connected"&&this.port&&this.send({gem:z,type:"gem.error",code:e,...t===void 0?{}:{message:t}});}send(e){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let t=e.type;if(!this.outbound.allow(t))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${t}`),false;let r=mn[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||Tl(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 o=mn[r];if(!o)return this.dropUnknownType(r),false;if(!this.inbound.allow(r))return this.fail("rate_limited",`parent exceeded the limit for ${r}`),false;let i=ns(r);if(i!==void 0&&!this.options.capabilities?.includes(i))return this.fail("unsupported_capability",`${r} requires the '${i}' capability, which this frame did not advertise`),false;let a=o(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.prefs":this.options.onPrefs?.(s);break;case "gem.cohorts":this.options.onCohorts?.(s);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 Tl(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?.(jg(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.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.signInResult":this.options.onSignInResult?.(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:z,type:"gem.screenshot.denied",reason:e,retryable:t});}};function Tl(n){for(let e of n)try{e?.close?.();}catch{}}var El="https://api.gemarcade.com";function qo(n){let e;try{e=new URL(n);}catch{return "it is not a valid URL"}return e.protocol!=="https:"&&e.protocol!=="http:"?`its scheme is ${e.protocol.replace(":","")}, and only http and https can be used`:e.username!==""||e.password!==""?"it carries credentials in the URL, which `fetch` will not send":e.href.includes("#")?"it carries a fragment. The transport joins the base and the path by concatenation, so the fragment would swallow the path and every request would go to the API root":e.href.includes("?")?"it carries a query string. The transport joins the base and the path by concatenation, so the query would swallow the path and every request would go to the API root":null}var qg=new Set(["localhost","127.0.0.1","[::1]"]);function Il(n){let e=qo(n);if(e!==null)return e;let t=new URL(n);return t.protocol==="http:"&&!qg.has(t.hostname)?"it is a plaintext http address that is not loopback. An embedder may name an https root, or http on localhost for a rig running the whole stack on one machine \u2014 the play token travels on every request to it":null}var Ug=Object.freeze(["https://gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),Bg=El,Cl=8e3,Uo=15e3,Hg=9e4,Vg=1/0,Wg=8e3,Kg=5e3,Jg=5e3;async function zg(n,e,t,r){if(n.isInRoom)try{await n.leave();}catch{}r?.endSession("session_ended"),e!==null&&e.currentState==="connected"&&e.exit(t);}function tn(n){let e=null,t=[];return {get current(){return e},set(r){e=r;for(let o of t.splice(0))o(r);},wait(r){return e!==null?Promise.resolve(e):new Promise(o=>{let i=()=>{let l=t.indexOf(a);l>=0&&t.splice(l,1);},a=l=>{n.clearTimeout(s),i(),o(l);},s=n.setTimeout(()=>{i(),o(e);},r);t.push(a);})}}}function ow(n={}){let e=n.clock??ae,t=n.log===void 0?u=>console.info(u):n.log,r=n.baseUrl??void 0;if(r!=null){let u=qo(r);if(u!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${u}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let o=Ro();o.mark("sdk created");let i=()=>Gn(X.gameVersion,n.clientVersion?.gameVersion),a=new Mt({client:()=>Ze,clock:e,gameId:()=>X.identity?.gameId??null,playerId:()=>X.identity?.playerId??null,environment:()=>{let u=i();return {sdk_version:zo(),...u===null?{}:{game_version:u}}},...n.analytics===void 0?{}:{options:n.analytics},log:t}),s=u=>{if(u===false)return null;let I=u?.attempts??Vg,N=u?.budgetMs??Hg;return !(I>0)||!(N>0)?null:{attempts:I,budgetMs:N,maxDelayMs:u?.maxDelayMs??Wg}},l=u=>{u.on("created",()=>{o.mark("room created");}),u.on("joined",()=>{o.mark("room joined");}),u.on("matchAllocationStarted",()=>{o.mark("allocation started");}),u.on("matchReady",()=>{o.mark("match ready");}),u.on("matchFailed",()=>{o.mark("match failed");});};if(typeof window>"u")throw new Error("createGem: there is no `window` in this environment, so the SDK has no document to listen on and no embedder to hand it a port. A game runs in a browser; if this is a server-side render or a node process, do not construct the SDK there.");let d=n.allowedEmbedders;if(d!=null&&!Array.isArray(d))throw new Error("createGem: `allowedEmbedders` must be an array of origins, e.g. `['https://my-own-site.example']`. The Gem Arcade is allowed without any entry.");let m=Array.from(d??[]),c=m.filter(u=>typeof u!="string"||!pr(u));if(c.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${c.length===1?"an entry":"entries"} that ${c.length===1?"is":"are"} not an origin: ${c.map(u=>typeof u=="string"?JSON.stringify(u):String(u)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let p=Object.freeze([...new Set([...Ug,...m])]),g=tn(e),y=tn(e),w=tn(e),x=tn(e),C=n.manageAudio===false?null:Ga(),E=null,v=()=>{E!==null&&(y.current!==null&&y.current.muted===E||K.reportMuted(E));},S=Da({report:u=>K.reportFrameStats(u)}),A=false,R=Na(()=>Jo,()=>A),H=u=>{let I=A&&!u,N=A!==u;if(A=u,I&&R.close(),!!N)try{n.onDevToolsPermissionChange?.(u);}catch(me){t?.(`[gem] onDevToolsPermissionChange threw: ${me instanceof Error?me.message:String(me)}`),queueMicrotask(()=>{throw me});}},j=r??Bg,V=r!==void 0,k,P=u=>(t?.(`[gem] token refused: ${u}`),n.onError?.("internal",u),false),L=(u,I)=>{if(u===void 0)return I!==void 0?P("the embedder named a backend by tag, which this build no longer resolves \u2014 it needs `apiBaseUrl` on `gem.token`. The token was refused rather than sent to the default: silently resolving production is how a development session writes to the live backend."):true;let N=Il(u);return N!==null?P(`the embedder named an API root that cannot be used: ${N}. Its value is withheld here rather than written to logs.`):k!==void 0&&k!==u?P("the embedder named a different API root than it named on this session\u2019s first token. The address is fixed by the first grant, so a later message cannot repoint a running game; both values are withheld here."):(k=u,V||(j=u),true)},G=window.location?.origin,F=null,B=-1/0,re=2e3,le=new Set,Q=u=>F!==false?Promise.resolve(true):new Promise(I=>{let N=e.setTimeout(()=>{le.delete(me),I(false);},u),me=()=>{e.clearTimeout(N),le.delete(me),I(true);};le.add(me);}),K=new en({allowedEmbedders:p,...typeof G=="string"&&G!==""?{selfOrigin:G}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","frameStats","viewport","purchases","deviceSettings","ads","signIn",...n.onFeedbackContext!==void 0?["feedbackContext"]:[]],...n.onRefused===void 0?{}:{onRefused:n.onRefused},...n.onError===void 0?{}:{onError:n.onError},onStateChange:u=>{X.onBridgeState(u),u!=="connected"&&S.setRequested(false),u==="connected"&&(o.mark("bridge connected"),rn(),v(),a.startSession()),n.onStateChange?.(u);},onPlayer:u=>{g.set(u),n.onPlayer?.(u);},onPrefs:u=>{let I={reducedMotion:u.reducedMotion,muted:u.muted,locale:u.locale,showFrameStats:u.showFrameStats===true};y.set(I),C?.setMuted(I.muted),S.setRequested(I.showFrameStats&&K.parentSupports("frameStats")),n.onPrefs?.(I);},onCohorts:u=>{let I=Object.freeze(u.cohorts.map(N=>Object.freeze({experimentId:N.experimentId,variantKey:N.variantKey})));w.set(I),n.onCohorts?.(I);},onViewport:u=>{let I=Object.freeze({insets:Object.freeze({top:u.insets.top,right:u.insets.right,bottom:u.insets.bottom,left:u.insets.left})});x.set(I),Fa($a(),I.insets),n.onViewport?.(I);},onPause:u=>{a.setPaused(u.paused),S.setPaused(u.paused),n.onPause?.(u.paused);},onWillTerminate:u=>{a.endSession(u.reason),n.onWillTerminate?.({reason:u.reason,graceMs:u.graceMs});},onToken:u=>{let I=u.garden;if(H(u.allowDevTools===true),!L(u.apiBaseUrl,I))return;let N=u;X.onToken(N);let me=X.identity;me&&(Re.set(me),Fe||(Fe=true,ue.reconcileSeats().catch(()=>{}))),ce.push({token:N.token,expiresAt:N.expiresAt});},onTokenDenied:u=>{H(false),X.onDenied(u);},onScreenshot:(u,I,N)=>{Ma(u,I,N,{...n.onScreenshot===void 0?{}:{handler:n.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{Oa(K,n.onFeedbackContext);},onDevtools:u=>{u==="close"?R.close():u==="open"?R.openFrom("platform").catch(()=>{}):R.isOpen?R.close():R.openFrom("platform").catch(()=>{});},onRoomEvent:u=>ue.handleRoomEvent({event:u.event,roomId:u.roomId,...u.matchId===void 0?{}:{matchId:u.matchId},...u.version===void 0?{}:{version:u.version},...u.reason===void 0?{}:{reason:u.reason},...u.platform===void 0?{}:{platform:u.platform}}),onSeatedEvent:u=>ue.handleSeated(u.roomId),onAutoStartFailedEvent:u=>ue.handleAutoStartFailed(u.roomId,u.code),onSocketState:u=>{let I=F;if(F=u.connected,u.connected)for(let me of [...le])me();if(!u.connected||I===true)return;let N=e.now();N-B<re||(B=N,ue.reconcile().catch(()=>{}));},onSignalEvent:u=>{let I=typeof u.data=="object"&&u.data!==null&&!Array.isArray(u.data)?u.data:{};et.handleSignalEvent(u.matchId,u.event,I),u.event==="matchEnded"&&ue.reconcile({matchId:u.matchId,...typeof I.reason=="string"?{reason:I.reason}:{}}).catch(()=>{});},onDedicatedEvent:u=>{u.event==="matchEnded"&&(bt.handleMatchEnded(u.matchId,u.reason),ue.reconcile({matchId:u.matchId,...u.reason===void 0?{}:{reason:u.reason}}).catch(()=>{})),Se.handleEvent(u);},onClusterTarget:u=>Xe.accept(u.clusterTargetId,u.clusterTargetIds),onLocalServer:u=>je.accept(u),onLocalServerDenied:u=>je.refuse(u),onPartyResult:u=>f.settle(u.requestId,u.partyId),onPurchaseResult:u=>$.settle(u),onDeviceSettings:u=>{Z.receive(u),n.onDeviceSettings?.(Z.api.current);},onDeviceSettingsResult:u=>Z.settle(u),onAdResult:u=>ke.settle(u),onSignInResult:u=>ht.settle(u)}),Se=new Qt({bridge:K}),Re=tn(e),Fe=false,ee=new Set,J,ce={current:()=>J,subscribe:u=>(ee.add(u),J!==void 0&&u(J),()=>ee.delete(u)),push:u=>{J=u;for(let I of [...ee])try{I(u);}catch(N){t?.(`[gem] a server-token listener threw: ${N instanceof Error?N.message:String(N)}`);}}},X=Ua({bridge:K,clock:e,onStateChange:(u,I)=>{if(u==="ready"){if(o.mark("token ready")){let N=o.marks.find(me=>me.name==="token ready")?.at;a.trackPlatform("gem_boot_ready",N===void 0?{}:{boot_ms:Math.max(0,Math.round(N))});}}else u==="lost"&&(o.mark("token lost"),a.trackPlatform("gem_auth_lost"));n.onAuthStateChange?.(u,I);}}),nn=()=>{let u=X.identity;return !u||X.source.currentState==="lost"?null:`${u.playerId}\0${u.gameId}\0${u.channel}`},rn=()=>{o.mark("token requested"),X.source.get().catch(()=>{});},f=jo({bridge:K,clock:e}),T={},$=vl({bridge:K,clock:e,onDropped:u=>n.onError?.("internal",u),confirm:async u=>T.confirm?.(u)??"unknown"}),Z=xl({bridge:K,clock:e,onDropped:u=>n.onError?.("internal",u)}),ke=Rl({bridge:K,clock:e,onDropped:u=>n.onError?.("internal",u)}),ht=wl({bridge:K,clock:e,onDropped:u=>n.onError?.("internal",u)}),Xe=Ns({bridge:K,clock:e}),je=ja({bridge:K,clock:e}),rr=u=>{let I=K.handleWindowMessage({data:u.data,origin:u.origin,source:u.source,ports:u.ports});return I&&window.removeEventListener("message",rr),I};window.addEventListener("message",rr);let Qe=Ta(window,rr),Gl=Qe?.capture,or=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];or?.domInteractive!==void 0&&or.domInteractive>0&&o.mark("document parsed",or.domInteractive),Gl?.late&&t?.("[gem] the early-handshake capture installed after this document finished loading, so a handshake posted at iframe load may already have been missed. Load the capture script ahead of everything else in the document.");let ir=n.handshakeWarningMs;ir!==null&&t&&e.setTimeout(()=>{let u=Qe===null?"no capture script ran":`capture: ${Qe.delivered} offer(s) delivered, ${Qe.stale} stale, ${Qe.capture.dropped} evicted${Qe.capture.late?", installed late":""}`;if(K.currentState==="connected"){t(`[gem] handshake connected. boot: ${o.timeline()} \xB7 ${u}`);return}t(`[gem] no completed handshake after ${ir??Cl}ms (bridge state: ${K.currentState}). Either the embedder does not run the gem-web-sdk parent half, its origin is not in this build\u2019s allowedEmbedders, or its handshake fired before this frame\u2019s listener registered. boot: ${o.timeline()} \xB7 `+u);},ir??Cl);let Dl=Zn({get baseUrl(){return j},tokenSource:X.source,get defaultQuery(){let u=X.identity;return u?{game_id:u.gameId,channel:u.channel}:{}}}),Ze=new Ce({transport:Dl,clock:e}),he={client:Ze,gameId:()=>X.identity?.gameId??""};T.confirm=u=>_l(he,u);let $l=()=>X.identity?.channel??"release",Ho=new In(he,$l),Vo=async u=>(await Ho.load())?.currency(u)?.id??void 0,Wo=kn(he,kr,{identity:nn,resolveCurrencyId:Vo}),sr=async u=>{let I=await Re.wait(u);if(I)return I;throw new se("timeout","no play token arrived over the bridge. Every route a game reaches is scoped by the token, so nothing can proceed without one \u2014 the bridge may not be connected, or the parent may have refused to mint (see onAuthStateChange).")},ar=s(n.autoReconnect),ue=ao({client:Ze,clock:e,gameId:()=>X.identity?.gameId??null,playerId:()=>X.identity?.playerId??null,awaitGameId:async()=>(await sr(Uo)).gameId,resolveParty:f.resolve,resolveClusterTargets:Xe.resolveList,refreshClusterTargets:Xe.refresh,ensureLocalServer:je.ensure,...n.clientVersion===void 0?{}:{clientVersion:n.clientVersion},platformGameVersion:()=>X.gameVersion,...n.pollRooms===void 0?{}:{poll:n.pollRooms},...n.recoverStaleMembership===void 0?{}:{recoverStaleMembership:n.recoverStaleMembership},...n.retryAutoStart===void 0?{}:{retryAutoStart:n.retryAutoStart},...n.watchSeats===void 0?{}:{watchSeats:n.watchSeats},...n.seatPollIntervalMs===void 0?{}:{seatPollIntervalMs:n.seatPollIntervalMs},...ar===null?{}:{autoReconnect:{...ar,redial:(u,I)=>lr.redialMatch(u,I),abandon:(u,I)=>lr.abandonMatch(u,I)}}});l(ue),Pa({analytics:a,rooms:ue});let et=Aa({client:Ze,clock:e,rooms:ue,bridge:K,gameId:()=>X.identity?.gameId??"",baseUrl:()=>j,resolveClusterTarget:Xe.resolve,boot:o,...n.log===void 0?{}:{log:n.log}}),Ko=So(o,t),bt=il({client:Ze,clock:e,rooms:ue,signaling:()=>Se.channel(),signalingReady:Q,log:t??(()=>{})}),lr=hl({rooms:ue,p2p:{connect:u=>Ko(et.connect(u)),session:u=>et.session(u)},dedicated:{connect:(u=>Yn(o,"welcome",bt.connect(u),t))},clock:e,identity:()=>X.identity,apiBaseUrl:()=>j,tokens:ce,room:()=>ue.currentRoom,autoReconnect:ar!==null,...n.log===void 0?{}:{log:n.log}}),Fl=async()=>(await sr(Uo)).playerId,Jo={client:Ze,boot:o,get identity(){return X.identity},awaitIdentity:(u=Uo)=>sr(u),awaitBridge:u=>K.settled(u),get player(){return g.current},awaitPlayer:(u=Kg)=>g.wait(u),me:Wo,characters:new An(he,void 0,nn,Vo),transfers:new Tn(he,kr,Wo.inventory),gameConfig:Ho,purchases:$.api,deviceSettings:Z.api,ads:ke.api,account:ht.api,analytics:a,leaderboards:new At(he),challenges:new Rt(he),showcase:new Pt(he,Fl),friends:new Tt(he),platform:new Et(he),profiles:new It(he),functions:new Oe((u,I)=>Di(he,u,I)),get prefs(){return y.current},get cohorts(){return w.current},get viewport(){return x.current},awaitCohorts:(u=Jg)=>w.wait(u),reportMuted:u=>{E=!!u,v();},cueReward:u=>K.cueReward(u),exit:u=>zg(ue,K,u,a),frame:K,devtools:R,rooms:ue,dedicatedServer:{listClusterTargets:u=>bt.listClusterTargets(u),connect:(u=>Yn(o,"welcome",bt.connect(u),t)),handleMatchEnded:(u,I)=>bt.handleMatchEnded(u,I)},p2p:{handleSignalEvent:(u,I,N)=>et.handleSignalEvent(u,I,N),session:u=>et.session(u),connect:u=>Ko(et.connect(u))},match:lr};return Jo}var Ml="the match has not started yet: the runtime hands over the host at `init`, and this was read before that. Read it from `init` or later \u2014 a bundle that needs a value at module scope is reading it one call too early.";function Bo(n,e={}){let t=e.clock??ae,r=()=>{let s=n();if(s===null)throw new Error(Ml);return s},o=null,i=()=>{if(o===null)throw new Error(Ml);return o};return {server:{get identity(){return i().identity},get client(){return i().client},get api(){return i().api},get match(){return i().match},get analytics(){return i().analytics},get functions(){return i().functions},get room(){return i().room},dispose(){o?.dispose();},get sizeClass(){return r().sizeClass},get roomArgs(){return r().roomArgs},get roster(){return r().roster},players(){return r().players()},profile(s){let d=r().profile?.(s);if(!d)return null;let m=d.displayName;return typeof m!="string"||m===""?null:{displayName:ye(m),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:ye(d.displayTag)}:{},...typeof d.discriminator=="string"?{discriminator:d.discriminator}:{}}},playerNumber(s){return r().playerNumber?.(s)},send(s,l,d){d===void 0?r().send(s,l):r().send(s,l,d);},broadcast(s,l){l===void 0?r().broadcast(s):r().broadcast(s,l);},kick(s,l){l===void 0?r().kick(s):r().kick(s,l);},log(s){r().log(s);},warn(s){r().warn(s);}},attach:()=>{o=yt(r(),{...e,clock:t});}}}function Ol(n,e={}){let{server:t,attach:r}=Bo(()=>n,e);return r(),t}function Yg(n){if(n===void 0||typeof n.reason!="string"||n.reason==="")return;let e=n.platform_reason??n.endedReason;return {reason:n.reason,...e===void 0?{}:{endedReason:Le(e)}}}function Ll(n,e={}){return ()=>{let t=null,{server:r,attach:o}=Bo(()=>t,e),i=n(r),a={async init(s){t=s,o(),await i.init?.();},async shutdown(s){let l=Yg(s);try{await i.shutdown?.(l);}finally{r.dispose();}}};return i.join&&(a.join=(s,l)=>i.join?.(s,l)),i.leave&&(a.leave=(s,l)=>i.leave?.(s,l)),i.message&&(a.message=(s,l,d,m)=>i.message?.(s,l,d,m)),a}}
2
+ export{Ug as ARCADE_EMBEDDERS,Mt as AnalyticsApi,se as AuthError,on as CONDITIONAL_HEADERS,Rt as ChallengesApi,No as DEVICE_SETTINGS_MAX_BYTES,h as DedicatedServerError,Tt as FriendsApi,Oe as FunctionsApi,D as GemApiError,Ce as GemClient,de as GemConfigError,en as GemFrame,Ct as GemFunctionError,oe as GemSaveError,At as LeaderboardsApi,Ar as MAX_PERIODS_BACK,au as PLATFORM_EVENTS,Et as PlatformApi,Mn as PlatformCurrenciesApi,ge as PlayerText,It as ProfilesApi,Me as PurchaseRefusal,Pt as ShowcaseApi,ne as TransportRefusal,Dt as UNRELIABLE_CHANNEL_LABEL,ye as asPlayerText,Ro as createBootTimeline,ow as createGem,yt as createGemServer,ll as createHostTokenSource,Ol as createMatchServer,Ll as defineServer,zg as leaveAndExit,ve as mapIdentity,Yn as markOnResolve,Vc as platformIconUrl,Lt as presentJoinCredential,lt as readTemplateTransports,$t as readTransportAdvert,So as reportOnResolve,ae as systemClock,qe as text,sn as toBase64,jn as webTransportAvailable};//# sourceMappingURL=gem-web-sdk.sdk.js.map
3
3
  //# sourceMappingURL=gem-web-sdk.sdk.js.map