@indiegems/gem-web-sdk 10.1.1 → 10.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 sc=Object.defineProperty;var lc=(n,e)=>{for(var t in e)sc(n,t,{get:e[t],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:10.1.1]";function Do(){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 dc(n,e){return e!==void 0?!e:n==="chain_exhausted"}var at=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 oe(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 oe("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(i=>{if(t!==this.generation)throw new oe("internal","token arrived for a superseded generation");return this.grant=i,this.rejected=false,this.enter("ready"),i.token}).catch(i=>{let o=cc(i),s=i?.retryable;throw t===this.generation&&this.enter(dc(o,typeof s=="boolean"?s:void 0)?"lost":"degraded",o),i instanceof oe?i:new oe(o,String(i))}).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)}},oe=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 cc(n){if(n instanceof oe)return n.reason;let e=n?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var ie=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}},vn=["if-match","if-none-match"],Fo=4096;function uc(n){if(!n)return;let e={};for(let[t,r]of Object.entries(n)){let i=t.toLowerCase();if(!vn.includes(i)||r===void 0)continue;let o=typeof r=="string"?mc(r):r;if(typeof o!="string"||o.length>Fo||!pc(o))throw new ie(`the ${i} header value cannot be sent \u2014 it is not a string, is longer than ${Fo} 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.`);o!==""&&(e[i]=o);}return Object.freeze(e)}function mc(n){let e=i=>i===32||i===9||i===10||i===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 pc(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 gc(n){let{bytes:e}=n;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new ie("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 ie("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 $o(n,e){let t=e.replayUnauthorizedOnce??true;return {async request(r){let i={...r},o=uc(i.headers),s=gc(i),a=Object.freeze({...i,headers:o,...s===void 0?{}:{bytes:s}}),l=await e.tokenSource.get(),d=await n(a,l);if(d.status!==401||!t)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),u=await n(a,m);if(u.status===401)throw e.tokenSource.close("unavailable"),new oe("unavailable","the server refused a freshly minted token");return u}}}function _n(n){let e=typeof n=="string"?new TextEncoder().encode(n):n;return btoa(yc(e))}function wn(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 Mr(n){return new TextDecoder().decode(wn(n))}function yc(n){let t="";for(let r=0;r<n.length;r+=32768)t+=String.fromCharCode(...n.subarray(r,r+32768));return t}var L=class extends Error{constructor(t,r,i,o,s){super(`${t} (${r}): ${i}`);this.reason=t;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=s;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},jo=new WeakMap;function No(n){return jo.get(n)??{}}var fc=new Set([408,429,500,502,503,504]),hc=6e4;function bc(n){if(n===void 0)return 2;if(!Number.isInteger(n)||n<0||n>10)throw new ie(`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 Ge=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),i=r.etag===void 0?{}:{etag:r.etag};return r.status===304?{modified:false,...i}:{modified:true,body:r.body,...i}}async put(e,t,r,i={}){return this.send({method:"PUT",path:e,body:t,signal:r,...xt(i)},i.replaySafe===true)}async post(e,t,r,i={}){return this.send({method:"POST",path:e,body:t,signal:r,...xt(i)},i.replaySafe===true)}async postBytes(e,t,r,i={}){let o=await this.sendRaw({method:"POST",path:e,bytes:t,responseType:"bytes",signal:r,...xt(i)},i.replaySafe===true);return {bytes:vc(o.body),...o.invocationId===void 0?{}:{invocationId:o.invocationId}}}async patch(e,t,r,i={}){return this.send({method:"PATCH",path:e,body:t,signal:r,...xt(i)},i.replaySafe===true)}async delete(e,t,r={}){return this.send({method:"DELETE",path:e,signal:t,...xt(r)},r.replaySafe===true)}async send(e,t){return (await this.sendRaw(e,t)).body}async sendRaw(e,t){let r=t?bc(this.options.maxRetries)+1:1,i=null;if(e.signal?.aborted)throw qo(e.signal);for(let o=0;o<r;o++){if(o>0&&await this.backoff(o,i,e.signal),e.signal?.aborted)throw qo(e.signal);let s;try{s=await this.options.transport.request(e);}catch(l){if(oe.isAuthError(l)||ie.isRefusal(l)||e.signal?.aborted||_c(l))throw l;i=new L("unavailable",0,String(l));continue}if(s.status>=200&&s.status<300||s.status===304)return s;let a=wc(s);if(!fc.has(s.status))throw a;i=a;}throw i??new L("unavailable",0,"no attempt was made")}backoff(e,t,r){if(r?.aborted)return Promise.resolve();let i=t?.retryAfterSeconds,o=i!==void 0?i*1e3:2**(e-1)*250,s=2**(e-1)*250,a=Math.min(Math.max(o,s),hc);return new Promise(l=>{let d=this.options.clock,m=false,u=false,p,g=()=>{m||(m=true,u&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,a),u=true,m&&d.clearTimeout(p);})}};function vc(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 xt(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 _c(n){let e=n?.name;return e==="AbortError"||e==="TimeoutError"}function wc(n){let e=Rc(n),t=xc(n.body),r={...t===void 0?{}:{details:t},...n.invocationId===void 0?{}:{invocationId:n.invocationId}};return Object.keys(r).length>0&&jo.set(e,r),e}var Sc=new Map([["insufficient_funds","insufficient_funds"]]);function Rc(n){let{status:e,body:t}=n,r=kc(t),i=n.retryAfterSeconds??Pc(t),o=Ac(t),s=o===void 0?void 0:Sc.get(o);if(s!==void 0)return new L(s,e,r,void 0,o);switch(e){case 304:return new L("not_modified",e,r);case 400:case 422:return new L("invalid",e,r,void 0,o);case 403:return new L("forbidden",e,r,void 0,o);case 404:return new L("not_found",e,r,void 0,o);case 402:return new L("insufficient_funds",e,r,void 0,o);case 409:return new L("conflict",e,r,void 0,o);case 412:return new L("precondition_failed",e,r,void 0,o);case 413:return new L("too_large",e,r,void 0,o);case 429:return new L("rate_limited",e,r,i,o);default:return new L("unavailable",e,r,i,o)}}function kc(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 xc(n){let t=n?.error?.details;return t===null?void 0:t}function Ac(n){let t=n?.error?.code;return typeof t=="string"&&t.length>0?t:void 0}function Pc(n){let e=n?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function v(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 Uo(n,e,t){let r=`/v1/inventory/transfers/${v(e)}/accept`;return n.client.post(r,void 0,t?.signal)}async function Bo(n,e,t,r,i,o){let s=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}/add`;return n.client.post(s,i,o?.signal)}async function Vo(n,e,t){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return n.client.post(r,void 0,t?.signal)}async function Ho(n,e,t){let r=`/v1/games/${v(n.gameId())}/matchmaking/tickets/${v(e)}`;return n.client.delete(r,t?.signal)}async function Wo(n,e,t,r,i,o){let s=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}/claim`;return n.client.post(s,i,o?.signal)}async function Ko(n,e,t){return n.client.post("/v1/characters",e,t?.signal)}async function Jo(n,e,t,r,i){let o=`/v1/inventory/${v(e)}/${v(t)}/orders/batch`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function zo(n,e,t,r,i){let o=`/v1/inventory/${v(e)}/${v(t)}/orders`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Yo(n,e,t){let r=`/v1/games/${v(n.gameId())}/matchmaking/tickets`;return n.client.post(r,e,t?.signal)}async function Xo(n,e,t,r,i){let o=`/v1/settings/${v(e)}/${v(t)}/${v(r)}`;return n.client.delete(o,i?.signal)}async function Qo(n,e,t,r,i){let o=`/v1/saves/${v(e)}/${v(t)}/${v(r)}`;return n.client.delete(o,i?.signal)}async function Zo(n,e,t,r){let i=`/v1/showcase/players/${v(e)}/${v(t)}`;return n.client.delete(i,r?.signal)}async function ea(n,e,t,r,i){let o=`/v1/inventory/${v(e)}/${v(t)}/recipes/execute`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ta(n,e,t,r,i,o){let s=`/v1/saves/${v(e)}/${v(t)}/${v(r)}/finalize`;return n.client.post(s,i,o?.signal)}async function na(n,e,t){let r=`/v1/games/${v(n.gameId())}/config/channels/${v(e)}`;return n.client.getWithEtag(r,{...t?.signal===void 0?{}:{signal:t.signal},...t?.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}})}async function ra(n,e,t){let r=`/v1/characters/${v(e)}`;return n.client.get(r,t?.signal)}async function ia(n,e,t){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return n.client.get(r,t?.signal)}async function oa(n,e,t,r,i){let o=`/v1/settings/${v(e)}/${v(t)}/${v(r)}`;return n.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function aa(n,e,t,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),s=`/v1/inventory/${v(e)}/${v(t)}`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function sa(n,e,t,r,i){let o=`/v1/inventory/${v(e)}/${v(t)}/items/${v(r)}`;return n.client.get(o,i?.signal)}async function la(n,e,t,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let s=o.toString(),a=`/v1/leaderboards/${v(e)}/${v(t)}/${v(r)}`+(s?`?${s}`:"");return n.client.get(a,i?.signal)}async function da(n,e,t,r,i){let o=`/v1/inventory/${v(e)}/${v(t)}/orders/${v(r)}`;return n.client.get(o,i?.signal)}async function ca(n,e,t,r,i){let o=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}`;return n.client.get(o,i?.signal)}async function ua(n,e,t,r,i,o){let s=`/v1/inventory/${v(e)}/${v(t)}/catalogs/${v(r)}/recipes/${v(i)}/availability`;return n.client.get(s,o?.signal)}async function ma(n,e,t,r){let i=new URLSearchParams;i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${v(e)}/${v(t)}/recipe-usage`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function Or(n,e,t,r,i){let o=`/v1/saves/${v(e)}/${v(t)}/${v(r)}`;return n.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function pa(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)),t?.periods_back!==void 0&&r.set("periods_back",String(t?.periods_back)),t?.period!==void 0&&r.set("period",String(t?.period)),t?.player_id!==void 0&&r.set("player_id",String(t?.player_id));let i=r.toString(),o=`/v1/leaderboards/${v(e)}/friends`+(i?`?${i}`:"");return n.client.get(o,t?.signal)}async function ga(n,e,t){let r=`/v1/showcase/friends/${v(e)}`;return n.client.get(r,t?.signal)}async function ya(n,e,t){let r=`/v1/inbox/friend-challenges/${v(e)}`;return n.client.get(r,t?.signal)}async function fa(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)),t?.periods_back!==void 0&&r.set("periods_back",String(t?.periods_back)),t?.period!==void 0&&r.set("period",String(t?.period)),t?.player_id!==void 0&&r.set("player_id",String(t?.player_id));let i=r.toString(),o=`/v1/leaderboards/${v(e)}`+(i?`?${i}`:"");return n.client.get(o,t?.signal)}async function ha(n,e){let t=`/v1/games/${v(n.gameId())}/players/me/earn-allowance`;return n.client.get(t,e?.signal)}async function Sn(n,e){return n.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function ba(n,e,t){let r=`/v1/profiles/players/${v(e)}`;return n.client.get(r,t?.signal)}async function va(n,e){let t=new URLSearchParams;e?.config_version!==void 0&&t.set("config_version",String(e?.config_version));let r=t.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function _a(n,e,t){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${v(e)}`;return n.client.get(r,t?.signal)}async function wa(n,e,t,r){let i=`/v1/showcase/players/${v(e)}/${v(t)}`;return n.client.get(i,r?.signal)}async function Sa(n,e){return n.client.get("/v1/characters/slots",e?.signal)}async function Ra(n,e,t){let r=`/v1/inventory/transfers/${v(e)}`;return n.client.get(r,t?.signal)}async function ka(n,e,t){let r=`/v1/games/${v(n.gameId())}/matchmaking/tickets/${v(e)}/heartbeat`;return n.client.post(r,void 0,t?.signal)}async function xa(n,e,t){let r=`/v1/games/${v(n.gameId())}/analytics/events`;return n.client.post(r,e,t?.signal,{...t?.keepalive===void 0?{}:{keepalive:t.keepalive},replaySafe:true})}async function Aa(n,e,t){return n.client.post("/v1/inventory/transfers",e,t?.signal)}async function Pa(n,e,t,r,i){let o=`/v1/inventory/${v(e)}/${v(t)}/platform-funded-game-inventory-purchases`;return n.client.post(o,r,i?.signal)}async function Ea(n,e,t){return n.client.postBytes("/v1/functions/invoke",e,t?.signal)}async function Ta(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(),i="/v1/challenges"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Ia(n,e){return n.client.get("/v1/characters",e?.signal)}async function Ca(n,e,t,r){let i=`/v1/settings/${v(e)}/${v(t)}`;return n.client.get(i,r?.signal)}async function Ma(n,e,t,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/inventory/${v(e)}/${v(t)}/orders`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function Oa(n,e,t,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/saves/${v(e)}/${v(t)}`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function La(n,e){let t=new URLSearchParams;e?.cursor!==void 0&&t.set("cursor",String(e?.cursor)),e?.limit!==void 0&&t.set("limit",String(e?.limit));let r=t.toString(),i="/v1/inbox/friend-challenges"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Ga(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(),i="/v1/friends"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Da(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(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Fa(n,e,t){let r=`/v1/inbox/friend-challenges/${v(e)}/answered`;return n.client.post(r,void 0,t?.signal)}async function $a(n,e,t,r){let i=`/v1/games/${v(n.gameId())}/matches/${v(e)}/end`;return n.client.post(i,t,r?.signal)}async function qa(n,e,t,r,i,o){let s=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}/max`;return n.client.post(s,i,o?.signal)}async function ja(n,e,t,r,i,o){let s=`/v1/settings/${v(e)}/${v(t)}/${v(r)}`;return n.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Na(n,e,t,r,i){let o=`/v1/showcase/players/${v(e)}/${v(t)}`;return n.client.put(o,r,i?.signal)}async function Ua(n,e,t,r,i){let o=`/v1/inventory/${v(e)}/${v(t)}/rewarded-placements/${v(r)}/availability`;return n.client.get(o,i?.signal)}async function Ba(n,e,t){let r=`/v1/inventory/transfers/${v(e)}/reject`;return n.client.post(r,void 0,t?.signal)}async function Va(n,e,t,r){let i=`/v1/characters/${v(e)}`;return n.client.patch(i,t,r?.signal)}async function Ha(n,e,t,r,i,o){let s=`/v1/saves/${v(e)}/${v(t)}/${v(r)}/upload-url`;return n.client.post(s,i,o?.signal,{replaySafe:true})}async function Wa(n,e,t,r,i,o){let s=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}/reset`;return n.client.post(s,i,o?.signal)}async function Ka(n,e,t){let r=`/v1/characters/${v(e)}`;return n.client.delete(r,t?.signal)}var U="gem-web-bridge",kn={min:1,max:1},st=65536,Ja=8,Rn=5e3,za=1024;function Gr(n){return Object.freeze(Object.assign(Object.create(null),n))}var Ya=Gr({"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.earnAllowanceChanged":30,"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.engaged":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.walletDisplay":60,"gem.menu":60,"gem.menuSelect":60,"gem.requestShare":6,"gem.vibrate":600,"gem.frameStats":120,"gem.portraitBorders":60,"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,"gem.requestFriendChallenge":12,"gem.friendChallengeResult":30,__malformed:60}),xn="__malformed";var Ec=Gr({"gem.requestAd":"ads","gem.adResult":"ads","gem.requestSignIn":"signIn","gem.signInResult":"signIn","gem.requestPurchase":"purchases","gem.purchaseResult":"purchases","gem.requestFriendChallenge":"friendChallenges","gem.friendChallengeResult":"friendChallenges","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.portraitBorders":"portraitBorders","gem.engaged":"engagement","gem.viewport":"viewport","gem.walletDisplay":"walletDisplay","gem.requestLocalServer":"localHost","gem.localServer":"localHost","gem.localServer.denied":"localHost","gem.cohorts":"cohorts","gem.earnAllowanceChanged":"earnAllowance","gem.deviceSettings":"deviceSettings","gem.deviceSettings.put":"deviceSettings","gem.deviceSettings.result":"deviceSettings","gem.requestShare":"share","gem.vibrate":"vibration","gem.menu":"gameMenu","gem.menuSelect":"gameMenu"}),Tc=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"]]);function Xa(n){let e=Ec[n];if(e!==void 0)return e;for(let[t,r]of Tc)if(n.startsWith(t))return r}function Dr(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 Ic(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 Cc(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function Mc(n){return /^[a-z_]+$/.test(n)}function Lr(n,e,t){if(e>Ja)return `nesting deeper than ${Ja}`;if(++t.nodes>Rn)return `more than ${Rn} values`;if(t.bytes>st)return `over the ${st} byte limit`;if(n==null)return t.bytes+=4,null;let r=typeof n;if(r==="boolean")return t.bytes+=5,null;if(r==="number")return t.bytes+=8,null;if(r==="string")return t.bytes+=n.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let i=n;if(t.seen.has(i))return "a repeated or cyclic object reference";if(t.seen.add(i),Array.isArray(n)){if(n.length>za)return `an array of ${n.length} entries, over the ${za} limit`;t.bytes+=2;for(let a of n){let l=Lr(a,e+1,t);if(l)return l}return null}let o=Object.getPrototypeOf(n);if(o!==Object.prototype&&o!==null)return "a value that is not a plain object";t.bytes+=2;let s=n;for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;if(++t.nodes>Rn)return `more than ${Rn} values`;if(t.bytes+=a.length*3+4,t.bytes>st)return `over the ${st} byte limit`;let l=Lr(s[a],e+1,t);if(l)return l}return null}function Oc(n){let e={nodes:0,bytes:0,seen:new Set},t=Lr(n,0,e);return t?`message contains ${t}`:e.bytes>st?`message is over the ${st} byte limit`:null}var Lc={origin:[Dr,"not a well-formed origin"],url:[Ic,"not a safe absolute http(s) URL"],bcp47:[Cc,"not a well-formed BCP 47 tag"],code:[Mc,"not a code of lower-case letters and underscores"]};function Qa(n,e,t){for(let r of e){let i=t===""?r.n:`${t}.${r.n}`,o=n[r.n];if(o==null){if(r.o)continue;return `${i}: required`}let s=Za(o,r,i);if(s)return s}return null}function Za(n,e,t){switch(e.k){case "s":{if(typeof n!="string")return `${t}: expected string`;if(n.length>e.max)return `${t}: exceeds ${e.max} characters`;if(e.f){let[r,i]=Lc[e.f];if(!r(n))return `${t}: ${i}`}return null}case "i":return typeof n!="number"||!Number.isInteger(n)?`${t}: expected integer`:n<e.lo||n>e.hi?`${t}: out of range ${e.lo}..${e.hi}`:null;case "b":return typeof n=="boolean"?null:`${t}: expected boolean`;case "e":{let r=e.v;return r.includes(n)?null:`${t}: not one of ${r.join("|")}`}case "o":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected object`:Qa(n,e.fs,t);case "j":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected a plain object`:null;case "a":{if(!Array.isArray(n))return `${t}: expected array`;if(n.length>e.max)return `${t}: exceeds ${e.max} items`;let r=e.it,i=`${t}[]`;for(let o of n){if(o==null){if(r.o)continue;return `${i}: required`}let s=Za(o,r,i);if(s)return s}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}function P(n,e){return t=>{let r=Oc(t);if(r)return r;if(typeof t!="object"||t===null||Array.isArray(t))return "message: expected object";let i=t;return i.gem!==U?"gem: wrong protocol marker":i.type!==n?`type: expected ${n}`:Qa(i,e,"")}}var Gc=P("gem.handshake",[{n:"versions",k:"o",fs:[{n:"min",k:"i",lo:1,hi:1e3},{n:"max",k:"i",lo:1,hi:1e3}]},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}},{n:"embedder",k:"s",max:2048,f:"origin"},{n:"unbidden",k:"b",o:1}]),Dc=P("gem.handshake.accept",[{n:"v",k:"i",lo:1,hi:1e3},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}}]),Fc=P("gem.token",[{n:"token",k:"s",max:4096},{n:"requestId",k:"s",o:1,max:64},{n:"generation",k:"i",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"s",o:1,max:512,f:"url"},{n:"playerId",k:"s",max:64},{n:"gameId",k:"s",max:64},{n:"channel",k:"e",v:["dev","test","release"]},{n:"gameVersion",k:"s",o:1,max:64},{n:"expiresAt",k:"i",lo:0,hi:4102444800},{n:"chainEndsAt",k:"i",lo:0,hi:4102444800},{n:"allowDevTools",k:"b",o:1}]),$c=P("gem.token.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:36e5},{n:"reason",k:"e",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"s",max:64}]),qc=P("gem.player",[{n:"untrusted",k:"o",fs:[{n:"displayName",k:"s",max:64},{n:"displayTag",k:"s",o:1,max:80},{n:"displayHandle",k:"s",max:80}]},{n:"playerId",k:"s",o:1,max:64},{n:"discriminator",k:"s",o:1,max:8},{n:"avatarIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"badges",k:"a",o:1,max:2,it:{n:"",k:"o",fs:[{n:"itemId",k:"s",max:64},{n:"iconUrl",k:"s",max:2048,f:"url"}]}},{n:"displayTag",k:"s",max:8},{n:"avatarUrl",k:"s",o:1,max:2048,f:"url"},{n:"boost",k:"o",o:1,fs:[{n:"multipliers",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"currencyId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"multiplierBp",k:"i",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"i",o:1,lo:1,hi:7}]}]),jc=P("gem.pause",[{n:"paused",k:"b"}]),Nc=P("gem.prefs",[{n:"reducedMotion",k:"b"},{n:"muted",k:"b"},{n:"showFrameStats",k:"b",o:1},{n:"locale",k:"s",max:35,f:"bcp47"},{n:"recommended",k:"o",o:1,fs:[{n:"volume",k:"i",lo:0,hi:100},{n:"batterySaver",k:"b"},{n:"keyboardLayout",k:"e",v:["wasd","arrows"]},{n:"gamepadConfirm",k:"e",v:["south","east"]},{n:"vibration",k:"b"}]}]),Uc=P("gem.cohorts",[{n:"cohorts",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"experimentId",k:"s",max:36},{n:"variantKey",k:"s",max:32}]}}]),Bc=P("gem.earnAllowanceChanged",[]),Vc=P("gem.viewport",[{n:"insets",k:"o",fs:[{n:"top",k:"i",lo:0,hi:4096},{n:"right",k:"i",lo:0,hi:4096},{n:"bottom",k:"i",lo:0,hi:4096},{n:"left",k:"i",lo:0,hi:4096}]},{n:"reserved",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384},{n:"width",k:"i",lo:0,hi:16384},{n:"height",k:"i",lo:0,hi:16384}]}}]),Hc=P("gem.deviceSettings",[{n:"settings",k:"j",o:1}]),Wc=P("gem.willTerminate",[{n:"reason",k:"e",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"i",lo:0,hi:6e4}]),Kc=P("gem.roomEvent",[{n:"event",k:"e",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"s",max:64},{n:"matchId",k:"s",o:1,max:64},{n:"version",k:"i",o:1,lo:0,hi:2147483647},{n:"reason",k:"s",o:1,max:64},{n:"platform",k:"e",o:1,v:["universal","mobile"]}]),Jc=P("gem.socketState",[{n:"connected",k:"b"},{n:"reason",k:"e",o:1,v:["connecting","dropped","watchdog","terminal"]}]),zc=P("gem.seatedEvent",[{n:"roomId",k:"s",max:64}]),Yc=P("gem.autoStartFailedEvent",[{n:"roomId",k:"s",max:64},{n:"code",k:"s",max:64}]),Xc=P("gem.signalEvent",[{n:"event",k:"e",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}]),Qc=P("gem.dedicatedEvent",[{n:"event",k:"e",v:["answer","error","matchEnded"]},{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",o:1,max:10240},{n:"sessionId",k:"s",o:1,max:64},{n:"code",k:"s",o:1,max:64},{n:"message",k:"s",o:1,max:256},{n:"reason",k:"s",o:1,max:64}]),Zc=P("gem.partyResult",[{n:"requestId",k:"s",max:64},{n:"partyId",k:"s",o:1,max:64}]),eu=P("gem.clusterTarget",[{n:"clusterTargetId",k:"s",max:64},{n:"clusterTargetIds",k:"a",o:1,max:3,it:{n:"",k:"s",max:64}}]),tu=P("gem.devtools",[{n:"action",k:"e",v:["open","close","toggle"]}]),nu=P("gem.screenshot",[{n:"maxWidth",k:"i",lo:1,hi:7680},{n:"maxHeight",k:"i",lo:1,hi:4320}]),ru=P("gem.screenshot.denied",[{n:"reason",k:"e",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"b"}]),iu=P("gem.requestContext",[]),ou=P("gem.gameContext",[{n:"context",k:"j"}]),au=P("gem.signal",[{n:"signal",k:"e",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}]),su=P("gem.dedicatedOffer",[{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",max:10240},{n:"intent",k:"e",v:["initial","ice_restart","full_reconnect"]}]),lu=P("gem.partyRequest",[{n:"requestId",k:"s",max:64}]),du=P("gem.ready",[]),cu=P("gem.engaged",[]),uu=P("gem.progress",[{n:"loaded",k:"i",lo:0,hi:1099511627776},{n:"total",k:"i",lo:0,hi:1099511627776}]),mu=P("gem.requestToken",[{n:"requestId",k:"s",max:64},{n:"reason",k:"e",v:["initial","expiring","rejected"]}]),pu=P("gem.requestLocalServer",[{n:"requestId",k:"s",max:64},{n:"gameRoomId",k:"s",max:64}]),gu=P("gem.localServer",[{n:"requestId",k:"s",max:64},{n:"serverId",k:"s",o:1,max:128}]),yu=P("gem.localServer.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"reason",k:"e",v:["refused","unavailable"]}]),fu=P("gem.exit",[{n:"reason",k:"s",o:1,max:64}]),hu=P("gem.openExternal",[{n:"url",k:"s",max:2048,f:"url"}]),bu=P("gem.requestFullscreen",[{n:"enabled",k:"b"}]),vu=P("gem.audioState",[{n:"muted",k:"b"}]),_u=P("gem.rewardCue",[{n:"currencySlug",k:"s",max:32},{n:"expected",k:"i",o:1,lo:1,hi:1e9},{n:"origin",k:"o",o:1,fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384}]}]),wu=P("gem.walletDisplay",[{n:"visible",k:"b"},{n:"currencies",k:"a",o:1,max:8,it:{n:"",k:"s",max:64}},{n:"score",k:"b",o:1}]),Su=P("gem.menu",[{n:"settings",k:"b"},{n:"items",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"id",k:"s",max:32},{n:"label",k:"s",max:40}]}}]),Ru=P("gem.menuSelect",[{n:"entry",k:"e",v:["settings","item"]},{n:"id",k:"s",o:1,max:32}]),ku=P("gem.requestShare",[{n:"params",k:"a",max:16,it:{n:"",k:"o",fs:[{n:"key",k:"s",max:64},{n:"value",k:"s",max:512}]}}]),xu=P("gem.vibrate",[{n:"pattern",k:"a",max:99,it:{n:"",k:"i",lo:0,hi:1e4}}]),Au=P("gem.frameStats",[{n:"fps",k:"i",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"i",lo:0,hi:1e5}]),Pu=P("gem.portraitBorders",[{n:"name",k:"s",o:1,max:40}]),Eu=P("gem.error",[{n:"code",k:"e",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"s",o:1,max:256}]),Tu=P("gem.requestPurchase",[{n:"requestId",k:"s",max:64},{n:"purchaseKind",k:"e",v:["item","recipe"]},{n:"targetId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"quantity",k:"i",o:1,lo:1,hi:10},{n:"catalogId",k:"s",o:1,max:64}]),Iu=P("gem.purchaseResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["ok","declined","unavailable"]},{n:"reason",k:"s",o:1,max:64,f:"code"},{n:"purchaseId",k:"s",o:1,max:64}]),Cu=P("gem.deviceSettings.put",[{n:"requestId",k:"s",max:64},{n:"settings",k:"j"}]),Mu=P("gem.deviceSettings.result",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["stored","too_large","unavailable"]}]),Ou=P("gem.requestAd",[{n:"requestId",k:"s",max:64},{n:"placement",k:"s",max:32},{n:"format",k:"e",v:["interstitial","rewarded"]}]),Lu=P("gem.adResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["shown","no_ad","unavailable"]}]),Gu=P("gem.requestSignIn",[{n:"requestId",k:"s",max:64}]),Du=P("gem.signInResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["signed_in","declined","unavailable"]}]),Fu=P("gem.requestFriendChallenge",[{n:"requestId",k:"s",max:64},{n:"playerId",k:"s",max:64},{n:"template",k:"s",max:64},{n:"params",k:"j",o:1}]),$u=P("gem.friendChallengeResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"s",o:1,max:64},{n:"param",k:"s",o:1,max:64},{n:"channel",k:"s",o:1,max:16},{n:"configVersion",k:"i",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:864e5},{n:"detail",k:"s",o:1,max:300}]),An=Gr({"gem.handshake":Gc,"gem.handshake.accept":Dc,"gem.token":Fc,"gem.token.denied":$c,"gem.player":qc,"gem.pause":jc,"gem.prefs":Nc,"gem.cohorts":Uc,"gem.earnAllowanceChanged":Bc,"gem.viewport":Vc,"gem.deviceSettings":Hc,"gem.willTerminate":Wc,"gem.roomEvent":Kc,"gem.socketState":Jc,"gem.seatedEvent":zc,"gem.autoStartFailedEvent":Yc,"gem.signalEvent":Xc,"gem.dedicatedEvent":Qc,"gem.partyResult":Zc,"gem.clusterTarget":eu,"gem.devtools":tu,"gem.screenshot":nu,"gem.screenshot.denied":ru,"gem.requestContext":iu,"gem.gameContext":ou,"gem.signal":au,"gem.dedicatedOffer":su,"gem.partyRequest":lu,"gem.ready":du,"gem.engaged":cu,"gem.progress":uu,"gem.requestToken":mu,"gem.requestLocalServer":pu,"gem.localServer":gu,"gem.localServer.denied":yu,"gem.exit":fu,"gem.openExternal":hu,"gem.requestFullscreen":bu,"gem.audioState":vu,"gem.rewardCue":_u,"gem.walletDisplay":wu,"gem.menu":Su,"gem.menuSelect":Ru,"gem.requestShare":ku,"gem.vibrate":xu,"gem.frameStats":Au,"gem.portraitBorders":Pu,"gem.error":Eu,"gem.requestPurchase":Tu,"gem.purchaseResult":Iu,"gem.deviceSettings.put":Cu,"gem.deviceSettings.result":Mu,"gem.requestAd":Ou,"gem.adResult":Lu,"gem.requestSignIn":Gu,"gem.signInResult":Du,"gem.requestFriendChallenge":Fu,"gem.friendChallengeResult":$u});var le={now:()=>Date.now(),setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n)},At=class{constructor(e=le){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let t=Ya[e];if(t===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??t,s=Math.max(0,r-i),a=Math.min(t,o+s*t/6e4);return a<1?(this.tokens.set(e,a),this.lastRefill.set(e,r),false):(this.tokens.set(e,a-1),this.lastRefill.set(e,r),true)}};function Fr(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 es(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 ts(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 En=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 i=(await this.inventory.snapshot({buckets:t.buckets})).currencies.data,o=i.find(a=>a.currencyId===e),s;return !o&&this.resolveCurrencyId&&(s=await this.resolveCurrencyId(e).catch(()=>{}),s!==void 0&&(o=i.find(a=>a.currencyId===s))),{currencyId:o?o.currencyId:s??e,total:o?o.total:null,...o?.buckets===void 0?{}:{buckets:o.buckets}}}};function qr(n){let e=Array.isArray(n.achievements)?n.achievements:[],t=[];for(let r of e){let i=r??{};typeof i.id!="string"||i.id===""||typeof i.threshold!="number"||!Number.isFinite(i.threshold)||t.push({id:i.id,threshold:i.threshold,points:typeof i.points=="number"?i.points:0,hidden:i.hidden===true,...typeof i.unlocked_at=="number"&&Number.isFinite(i.unlocked_at)?{unlockedAt:i.unlocked_at}:{},...i.revoked===true?{revoked:true}:{}});}return {...t.length>0?{achievements:t}:{},...n.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var ns="inventory",lt=n=>typeof n=="number"?n:0,Pt=n=>typeof n=="string"?n:"";function $r(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 rs(n){let e=n??{};return {itemDefinitionId:Pt(e.item_definition_id),instanceId:Pt(e.instance_id),quantity:lt(e.quantity),acquiredAt:lt(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function qu(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0;return {currencies:$r(e.currencies,r=>{let i=r??{},o=Array.isArray(i.buckets)?i.buckets.map(s=>{let a=s??{};return {bucket:Pt(a.bucket),balance:lt(a.balance)}}):void 0;return {currencyId:Pt(i.currency_id),total:lt(i.total),...o===void 0?{}:{buckets:o}}}),items:$r(e.items,rs),progressions:$r(e.progressions,r=>{let i=r??{};return {progressionDefinitionId:Pt(i.progression_definition_id),currentValue:lt(i.current_value),completionCount:lt(i.completion_count),isCompleted:i.is_completed===true,...qr(i)}}),...t===void 0?{}:{etag:t}}}var Tn=class{constructor(e,t,r){this.api=e;this.entity=t;this.cache=r;}api;entity;cache;snapshot(e={}){let t=e.buckets?`${ns}#buckets`:ns;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 o=r.items.data.filter(s=>s.itemDefinitionId===e);if(o.length>0)return o}let i=await sa(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return Array.isArray(i)?i.map(rs):[]}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 aa(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 qu(t)}};var ju={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},Nu=new Set(Object.keys(ju));function is(n){return typeof n=="string"&&Nu.has(n)?n:"error"}var De=class extends RangeError{constructor(t,r){super(r);this.code=t;this.name="PurchaseRefusal";}code;retryable=false};var Q=n=>typeof n=="string"?n:"",Uu=n=>typeof n=="string"?n:Q(n&&typeof n=="object"?n.type:void 0),xe=n=>typeof n=="number"?n:0;function Bu(n){let e=n??{};return {prerequisiteType:Q(e.prerequisite_type),referenceId:Q(e.reference_id),required:xe(e.required),current:xe(e.current)}}function Et(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0;return {orderId:Q(e.order_id),status:Q(e.status),...t===void 0?{}:{etag:t}}}function In(){return crypto.randomUUID()}var Vu="recipe-usage",os=100;function Cn(n){let e=n??{};switch(e.type){case "currency":return {kind:"currency",currencyId:Q(e.currency_id),bucket:Q(e.bucket),delta:xe(e.delta),balanceAfter:xe(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:Q(e.item_definition_id),instanceId:Q(e.instance_id),delta:xe(e.delta),quantityAfter:xe(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:Q(e.progression_definition_id),delta:xe(e.delta),valueAfter:xe(e.value_after),completed:e.completed===true};default:return {kind:"other",type:Q(e.type)}}}function Hu(n){let e=n??{},t=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:Q(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(Cn):[]}}function Wu(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(Hu):void 0;return {orderId:Q(e.order_id),status:Q(e.status),...t===void 0?{}:{etag:t},granted:Array.isArray(e.granted)?e.granted.map(Cn):[],consumed:Array.isArray(e.consumed)?e.consumed.map(Cn):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(Cn):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function Ku(n){let e=n??{},t=e.price??{};return {payment:"platform_currency",orderId:Q(e.target_order_id)||Q(e.source_order_id),status:Q(e.status),purchaseId:Q(e.purchase_id),sourceOrderId:Q(e.source_order_id),price:{currencyId:Q(t.platform_currency_id),amount:xe(t.price)}}}function Ju(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:Q(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 as(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 Mn=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(()=>zo(this.api,this.entity.type,this.entity.id,{operations:e.map(as),source:t.source??"play",nonce:In()},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}));return Et(r)}async createMany(e,t={}){return this.write(()=>Jo(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(as),nonce:In()})),source:t.source??"play"},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}))}async recipeAvailability(e,t,r){let o=await ua(this.api,this.entity.type,this.entity.id,e,t,r===void 0?{}:{signal:r})??{},s=typeof o.uses_remaining=="number"?o.uses_remaining:void 0,a=typeof o.cooldown_expires_at=="string"?o.cooldown_expires_at:void 0,l=Array.isArray(o.lock_reasons)?o.lock_reasons.map(Bu):[];return {canExecute:o.can_execute===true,locked:o.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(o.reasons)?o.reasons.map(d=>Uu(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(Vu,[],async()=>{let t=await ma(this.api,this.entity.type,this.entity.id,{limit:os})??{},r=Array.isArray(t.usages)?t.usages:[];return {usages:r.map(Ju),truncated:r.length>=os}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,t={}){if(e.payment.kind==="configured"){let u=e,p=await this.write(()=>ea(this.api,this.entity.type,this.entity.id,{catalog_id:u.catalogId,recipe_id:u.targetId,game_id:this.api.gameId(),nonce:In()},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}));return {payment:"configured",...Wu(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,i]=await Promise.all([va(this.api,t.signal===void 0?{}:{signal:t.signal}),Sn(this.api,t.signal===void 0?{}:{signal:t.signal})]),o=e.payment.currencySlug.toLowerCase(),s=i.currencies.find(u=>u.currency_id.toLowerCase()===o||u.slug.toLowerCase()===o);if(s===void 0){let u=i.currencies.map(p=>p.slug);throw new De("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${u.length===0?"none":u.join(", ")}`)}let a=e.kind==="item"?r.items.find(u=>u.item_id===e.targetId):r.recipes.find(u=>u.recipe_id===e.targetId&&u.catalog_id===e.catalogId);if(a===void 0)throw new De("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=a.platform_prices.find(u=>u.platform_currency_id===s.currency_id);if(l===void 0){let u=g=>i.currencies.find(y=>y.currency_id===g)?.slug??g,p=a.platform_prices.map(g=>`${u(g.platform_currency_id)} ${g.price}`);throw new De("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${s.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 De("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>Pa(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:s.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:In(),confirmation:"none"},t.signal===void 0?{}:{signal:t.signal}));return Ku(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 i=await this.write(()=>Bo(this.api,this.entity.type,this.entity.id,e,{amount:t,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Et(i)}async maxProgression(e,t,r){let i=await this.write(()=>qa(this.api,this.entity.type,this.entity.id,e,{value:t,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Et(i)}async claimProgression(e,t){let r=await this.write(()=>Wo(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},t===void 0?{}:{signal:t}));return Et(r)}async resetProgression(e,t){let r=await this.write(()=>Wa(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},t===void 0?{}:{signal:t}));return Et(r)}async write(e){return this.cache.invalidate(),e()}};var jr=n=>typeof n=="string"?n:"",zu=n=>typeof n=="number"?n:0;function ss(n){let e=n??{};return {orderId:jr(e.order_id),status:jr(e.status),source:jr(e.source),createdAt:zu(e.created_at)}}var On=class{constructor(e,t){this.api=e;this.entity=t;}api;entity;async list(e={}){let r=await Ma(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}})??{},i=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {data:Array.isArray(r.orders)?r.orders.map(ss):[],...i===void 0?{}:{nextCursor:i}}}async get(e,t){let r=await da(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return ss(r)}};var ls=n=>typeof n=="number"?n:0,Yu=n=>typeof n=="string"?n:"";function Xu(n){let e=n??{};return {progressionDefinitionId:Yu(e.progression_definition_id),currentValue:ls(e.current_value),completionCount:ls(e.completion_count),isCompleted:e.is_completed===true,...qr(e)}}var Ln=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 i=(await this.inventory.snapshot()).progressions.data.find(o=>o.progressionDefinitionId===e);if(i&&i.achievementsUnavailable!==true)return i;try{let o=await ca(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return Xu(o)}catch{return i??null}}};var Gn=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,i){this.rebind();let o=t.length===0,s=o?e:e+"\0"+t.join("\0"),a=this.slots.get(s);if(a){let u=a.filledAt;if(u!==void 0&&(i===void 0||this.clock.now()-u<=i))return Promise.resolve(a.value);if(a.inFlight)return a.inFlight}let l=a??{};this.slots.set(s,l);let d=this.generation,m=r().then(u=>(o&&this.generation===d&&(l.value=u,l.filledAt=this.clock.now()),u)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(s)===l&&this.slots.delete(s));});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 Nr(n){let e=i=>new RegExp(`<${i}>([^<]{0,300})</${i}>`).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 Ur(n){try{let e=Nr(await n.text());return e?`Storage said: ${e}`:""}catch{return ""}}var ae=class extends Error{constructor(t,r){super(r);this.reason=t;this.name="GemSaveError";}reason},Qu=3e4,ds="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",Zu=/^[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(!Zu.test(n)||n.startsWith("_"))throw new TypeError(`${JSON.stringify(n)} is not a usable save key: ${e}.`);return n}function cs(n,e){let t=new AbortController,r=AbortSignal.timeout(e),i=()=>t.abort(r.reason),o=()=>t.abort(n?.reason);return n?.aborted?t.abort(n.reason):(r.addEventListener("abort",i,{once:true}),n?.addEventListener("abort",o,{once:true})),{signal:t.signal,release:()=>{r.removeEventListener("abort",i),n?.removeEventListener("abort",o);}}}function Br(n,e){return n.aborted&&e?.aborted!==true}var em=new Set(["x-ms-blob-type"]),tm=/^[ -~]+$/;function nm(n,e){if(n==null)return {};if(typeof n!="object"||Array.isArray(n))throw new ae("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,i]of Object.entries(n)){let o=r.toLowerCase();if(!em.has(o))throw new ae("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 i!="string"||!tm.test(i))throw new ae("save_malformed",`the grant for save ${JSON.stringify(e)} gave header ${JSON.stringify(r)} a value that is not usable as one.`);if(o in t)throw new ae("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(o)} twice.`);t[o]=i;}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 Hr(n){return n?.reason==="not_found"}var Dn=class{constructor(e,t,r={}){this.api=e;this.entity=t;this.options=r;}api;entity;options;async put(e,t,r={}){let i;try{i=JSON.stringify(t);}catch(o){throw new ae("save_malformed",`save ${JSON.stringify(e)} could not be serialised to JSON: ${String(o)}. Retrying stores the same unserialisable value.`)}if(i===void 0)throw new ae("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(i),{...r,contentType:"application/json"})}async putBytes(e,t,r={}){let i=r.contentType??"application/octet-stream",o=this.budget(r.timeoutMs),s=cs(r.signal,o);try{let a=await Ha(this.api,this.entity.type,this.entity.id,Ae(e),{size_bytes:t.byteLength,content_type:i,...r.metadata===void 0?{}:{metadata:r.metadata}},{signal:s.signal});if(typeof a.upload_url!="string"||typeof a.session_id!="string")throw new ae("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=nm(a.upload_headers,e),d,m=this.options.fetch??globalThis.fetch.bind(globalThis);try{d=await m(a.upload_url,{method:"PUT",headers:{"content-type":i,...l},body:t,credentials:"omit",signal:s.signal});}catch(u){throw Br(s.signal,r.signal)?this.timeout("upload",o):new ae("upload_failed",`${ds} for PUT. Underlying error: ${u}`)}if(!d.ok){let u=await Ur(d);throw new ae("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. "+u:`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. ":"")+u)}return Vr(await ta(this.api,this.entity.type,this.entity.id,Ae(e),{session_id:a.session_id},{signal:s.signal}))}catch(a){throw this.rethrow(a,r.signal,s.signal,"save",o)}finally{s.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(i){throw new ae("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: ${i}`)}}async getBytes(e,t={}){let r=this.budget(t.timeoutMs),i=cs(t.signal,r);try{let o;try{let l=await Or(this.api,this.entity.type,this.entity.id,Ae(e),{signal:i.signal});if(!l.modified)return null;o=l.body;}catch(l){if(Hr(l))return null;throw l}if(typeof o.download_url!="string")throw new ae("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let s=this.options.fetch??globalThis.fetch.bind(globalThis),a;try{a=await s(o.download_url,{credentials:"omit",signal:i.signal});}catch(l){throw Br(i.signal,t.signal)?this.timeout("download",r):new ae("download_failed",`${ds} for GET. Underlying error: ${l}`)}if(!a.ok){let l=await Ur(a);throw new ae("download_failed",`the save download answered ${a.status}. `+(a.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 a.arrayBuffer())}catch(o){throw this.rethrow(o,t.signal,i.signal,"load",r)}finally{i.release();}}async describe(e,t={}){try{let r=await Or(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(Hr(r))return null;throw r}}async list(e={}){let t=await Oa(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 Qo(this.api,this.entity.type,this.entity.id,Ae(e),{...t===void 0?{}:{signal:t}});}catch(r){if(!Hr(r))throw r}}budget(e){return e??this.options.timeoutMs??Qu}timeout(e,t){return new ae("save_timeout",`the save ${e} did not finish within ${t}ms`)}rethrow(e,t,r,i,o){return e instanceof ae?e:Br(r,t)?this.timeout(i,o):e}};function rm(n){try{return Mr(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"?rm(t.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof t.updated_at=="number"?t.updated_at:0}}var Fn=class{constructor(e,t){this.api=e;this.entity=t;}api;entity;async list(e){let r=(await Ca(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(i=>Wr(i)):[]}async get(e,t={}){try{let r=await oa(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(us(r))return null;throw r}}async put(e,t,r={}){let i=await ja(this.api,this.entity.type,this.entity.id,e,{value:_n(t)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return Wr(i)}async delete(e,t){try{await Xo(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});}catch(r){if(!us(r))throw r}}};function us(n){return n?.reason==="not_found"}function $n(n,e,t={}){let r=new Gn(le,t.identity);t.onInventoryChanged&&r.onInvalidate(t.onInventoryChanged);let i=new Tn(n,e,r);return {settings:new Fn(n,e),inventory:i,saves:new Dn(n,e,t.saves??{}),currencies:new En(i,t.resolveCurrencyId),mutations:new Mn(n,e,r),orders:new On(n,e),progressions:new Ln(n,e,i)}}var Kr={type:"players",id:"me"};var Ne=n=>typeof n=="string"?n:"",dt=n=>typeof n=="number"?n:0;function qn(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:dt(t.slot_index),isActive:t.is_active!==false,createdAt:Ne(t.created_at),updatedAt:Ne(t.updated_at)}}var jn=class{constructor(e,t,r,i){this.api=e;this.saves=t;this.identity=r;this.resolveCurrencyId=i;}api;saves;identity;resolveCurrencyId;scopes=new Map;scope=e=>{let t=this.scopes.get(e);return t||(t=$n(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 Ia(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(i=>qn(this.scope,i)):[]}async get(e,t){let r=await ra(this.api,e,t===void 0?{}:{signal:t});return qn(this.scope,r)}async create(e){let t=await Ko(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return qn(this.scope,t)}async update(e,t,r){let i=await Va(this.api,e,{name:t},r===void 0?{}:{signal:r});return qn(this.scope,i)}async delete(e,t){await Ka(this.api,e,t===void 0?{}:{signal:t});}async slots(e){let r=await Sa(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:dt(r?.total_slots),availableSlots:dt(r?.available_slots),activeCharacterCount:dt(r?.active_character_count),defaultMaxSlots:dt(r?.default_max_slots),purchasedExtraSlots:dt(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var ye=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 he(n){return new ye(n)}var Ue={toPlain(n){return ye.unwrap(n)},compare(n,e,t){let r=n instanceof ye?ye.unwrap(n):n,i=e instanceof ye?ye.unwrap(e):e,o;try{o=new Intl.Collator(t);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(n,e){let t=n instanceof ye?ye.unwrap(n):n,r=e instanceof ye?ye.unwrap(e):e;return t.normalize("NFC")===r.normalize("NFC")}};var ct=n=>typeof n=="string"?n:"";function Nn(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:ct(e.transfer_id),status:ct(e.status),sourceEntityId:ct(e.source_entity_id),targetEntityId:ct(e.target_entity_id),...t===void 0?{}:{message:he(t)},createdAt:ct(e.created_at),expiresAt:ct(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function im(){return crypto.randomUUID()}var Un=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 Aa(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:im()},e.signal===void 0?{}:{signal:e.signal});return Nn(t)}async list(e={}){let r=await Da(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}})??{},i=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {transfers:Array.isArray(r.transfers)?r.transfers.map(Nn):[],...i===void 0?{}:{nextCursor:i}}}async get(e,t){let r=await Ra(this.api,e,t===void 0?{}:{signal:t});return Nn(r)}async accept(e,t){return this.resolve(()=>Uo(this.api,e,t===void 0?{}:{signal:t}))}async reject(e,t){return this.resolve(()=>Ba(this.api,e,t===void 0?{}:{signal:t}))}async cancel(e,t){return this.resolve(()=>Vo(this.api,e,t===void 0?{}:{signal:t}))}async resolve(e){return this.inventory.invalidate(),Nn(await e())}};var om=n=>typeof n=="string"?n:"",am=n=>typeof n=="string"&&n?n:void 0,sm=n=>typeof n=="number"?n:void 0;function ms(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 lm(n){if(typeof n!="object"||n===null||Array.isArray(n))throw new ce("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 ce("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=sm(e.version);if(r===void 0)throw new ce("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let i=(l,d,m)=>{let u=om(l.id);if(!u)throw new ce("config_malformed",`${d}[${m}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return u},o=t("items");o.forEach((l,d)=>i(l??{},"items",d));let s=t("currencies");s.forEach((l,d)=>i(l??{},"currencies",d));let a=n;return {...a,version:r,hash:typeof a.hash=="string"?a.hash:"",items:o,currencies:s,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 a.kv=="object"&&a.kv!==null&&!Array.isArray(a.kv)?a.kv:{},item:ms(o),currency:ms(s)}}var ce=class extends Error{constructor(t,r){super(r);this.reason=t;this.name="GemConfigError";}reason},ps=10*1024*1024,gs=15e3,ys=new Set(["dev","test","release"]);function dm(n){if(!ys.has(n))throw new ce("config_channel_unknown",`the play token names channel "${n}", which is not one of ${[...ys].join(", ")}. gem-api would reject the assignment read.`);return n}var Bn=n=>typeof n=="number"?n:0,Jr=n=>typeof n=="string"?n:"";function cm(n){let e=n??{},t=Array.isArray(e.entries)?e.entries.map(r=>{let i=r??{},o=typeof i.rarity_tier=="string"?i.rarity_tier:void 0;return {entryId:Jr(i.entry_id),weight:Bn(i.weight),dropRate:Bn(i.drop_rate),...o===void 0?{}:{rarityTier:o}}}):[];return {lootTableId:Jr(e.loot_table_id),name:Jr(e.name),rollCount:Bn(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Bn(e.total_weight),entries:t}}var Vn=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 ce("config_channel_unknown",`dropRates(${e}) needs a loaded config, and this session's channel has none`);let i=this.dropRatesByConfig.get(r);i===void 0&&(i=new Map,this.dropRatesByConfig.set(r,i));let o=i.get(e);if(o!==void 0)return o;let s=(async()=>{let a=await ia(this.api,e,t===void 0?{}:{signal:t});return cm(a)})().catch(a=>{throw i?.get(e)===s&&i.delete(e),a});return i.set(e,s),s}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??gs),t;try{let l=await na(this.api,dm(this.channel()),{signal:e});if(!l.modified)throw new ce("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");t=l.body;}catch(l){if(l instanceof ce)throw l;if(l?.reason==="not_found")return null;throw l}let r=am(t.config_url);if(r===void 0)return null;let i=this.options.fetch??globalThis.fetch.bind(globalThis),o;try{o=await i(r,{credentials:"omit",signal:e});}catch(l){throw e.aborted?new ce("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??gs}ms`):new ce("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(!o.ok){let l=await o.text().then(d=>Nr(d)).catch(()=>"");throw new ce("config_unreachable",`the config document answered ${o.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let s=await o.text();if(s.length>ps)throw new ce("config_too_large",`the config document is ${s.length} bytes, over the ${ps} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new ce("config_malformed",`config document is not JSON: ${String(l)}`)}return lm(a)}};var fs=400,Pe=n=>typeof n=="string"?n:"",um=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Be(n){let e=Pe(n);if(!um.test(e))return 0;let t=Date.parse(e);return Number.isFinite(t)?Math.floor(t/1e3):0}var mm=/^[0-9a-f]{1,64}$/,pm=/^[0-9a-f]{16}$/,gm=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,ym=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function zr(n){let e=Pe(n),t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return;let[r,i,o]=[Number(t[1]),Number(t[2]),Number(t[3])],s=new Date(Date.UTC(r,i-1,o));return s.getUTCFullYear()===r&&s.getUTCMonth()===i-1&&s.getUTCDate()===o?e:void 0}var fm=4096,hm=new TextEncoder;function bm(n){let e=Pe(n.challenge_data),t=Pe(n.challenge_data_hash);return e===""||!pm.test(t)?{}:hm.encode(e).length>fm?{}:{data:e,dataHash:t}}function vm(n){let e=n??{},t=Be(e.period_start_at),r=Be(e.period_ends_at);if(t===0||r===0)return;let i=Pe(e.slug),o=Pe(e.seed),s=zr(e.period_local_date),a=Pe(e.boundary),l=Pe(e.reset_time);return {id:Pe(e.progression_definition_id),...i===""?{}:{slug:i},window:Pe(e.window),periodStartAt:t,periodEndsAt:r,...s===void 0?{}:{periodLocalDate:s},boundary:gm.test(a)?a:"",resetTime:ym.test(l)?l:"",seed:mm.test(o)?o:"",...bm(e)}}function ut(n){if(n!==void 0&&(!Number.isInteger(n)||n<0||n>400))throw new TypeError(`periodsBack must be an integer between 0 and 400, got ${String(n)}`)}function Hn(n){let e=n??{};return Array.isArray(e.challenges)?e.challenges.map(vm).filter(t=>t!==void 0):[]}var Tt=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:t}=e;ut(t);let r=await Ta(this.#e,{...t===void 0?{}:{periods_back:t},...e.signal===void 0?{}:{signal:e.signal}});return Hn(r)}};function Ve(n){return typeof n=="string"&&n!==""?n:void 0}var hs=new Set(["localhost","127.0.0.1","[::1]"]);function Yr(n){let e=Ve(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:"&&hs.has(t.hostname)))return e}function _m(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=t??{},i=Ve(r.item_id),o=Yr(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function we(n){let e=n??{},t=Ve(e.player_id),r=Ve(e.display_name),i=Ve(e.discriminator),o=Ve(e.display_tag),s=Ve(e.avatar_icon_id),a=Yr(e.avatar_icon_url);return {...t===void 0?{}:{playerId:t},...r===void 0?{}:{displayName:he(r)},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:he(o)},...s===void 0?{}:{avatarIconId:s},...a===void 0?{}:{avatarIconUrl:a},badges:_m(e.badges)}}var wm=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Sm(n){if(n===void 0)return;let e=Yr(n);if(e===void 0)return;let t=new URL(e);return hs.has(t.hostname)||wm.has(t.origin)?e:void 0}var bs=100,ws=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function Xr(n){let{periodsBack:e,period:t,playerId:r}=n;if(ut(e),e!==void 0&&t!==void 0)throw new TypeError("pass periodsBack or period, not both");if(t!==void 0&&(typeof t!="string"||!ws.test(t)))throw new TypeError(`period must be a period id such as 2026-10-02 (a result's period.id), got ${String(t)}`);if(r!==void 0&&(typeof r!="string"||r===""))throw new TypeError("playerId must be a player id");return {...e===void 0?{}:{periods_back:e},...t===void 0?{}:{period:t},...r===void 0?{}:{player_id:r}}}function Ss(n){let e=typeof n.period_id=="string"?n.period_id:"";if(!ws.test(e))return;let t=zr(n.period_local_date),r=Be(n.period_start_at),i=Be(n.period_ends_at),o=r>0&&i>0;return {id:e,...t===void 0?{}:{localDate:t},...o?{startAt:r,endsAt:i}:{},opensAt:Be(n.opens_at),closesAt:Be(n.closes_at),final:n.final===true}}var It=n=>typeof n=="string"?n:"",mt=n=>typeof n=="number"?n:0,Ct=n=>typeof n=="string"?n:void 0,Rm=n=>typeof n=="number"?n:void 0,Rs={player:"players",character:"characters"};function km(n,e){let t=n??{},r=Ct(t.entity_id),i=typeof t.entity_type=="string"&&Object.hasOwn(Rs,t.entity_type)?t.entity_type:void 0,o=ks(t.stats),s=t.properties!==null&&typeof t.properties=="object"?t.properties:void 0,a=e?t.is_viewer===true:void 0;return {...we(t),rank:mt(t.rank),occurredAt:mt(t.occurred_at),...a===void 0?{}:{isViewer:a},...r===void 0?{}:{entityId:r},...i===void 0?{}:{entityType:i},...o===void 0?{}:{stats:o},...s===void 0?{}:{properties:s}}}function vs(n,e){let t=n??{},r=Ct(t.bucket_1),i=Ct(t.bucket_2),o=Rm(t.update_frequency_seconds),s=Ss(t);return {leaderboardType:It(t.leaderboard_type),runType:It(t.run_type),...r===void 0?{}:{bucket1:r},...i===void 0?{}:{bucket2:i},entries:Array.isArray(t.entries)?t.entries.map(a=>km(a,e)):[],generatedAt:mt(t.generated_at),...o===void 0?{}:{updateFrequencySeconds:o},...s===void 0?{}:{period:s}}}function _s(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:mt(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 xm(n,e,t){let r=n??{},i=Ct(r.bucket_1),o=Ct(r.bucket_2),s=Ss(r);return {leaderboardType:It(r.leaderboard_type),runType:It(r.run_type),entityType:e,entityId:t,...i===void 0?{}:{bucket1:i},...o===void 0?{}:{bucket2:o},entries:Array.isArray(r.entries)?r.entries.map(_s).filter(a=>a!==void 0):[],personalBest:_s(r.personal_best)??null,totalRuns:mt(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:mt(r.generated_at),...s===void 0?{}:{period:s}}}var Mt=class{#e;constructor(e){this.#e=e;}async get(e,t={}){let r=Xr(t),i=await fa(this.#e,e,{...r,...t.bucket1===void 0?{}:{bucket_1:t.bucket1},...t.bucket2===void 0?{}:{bucket_2:t.bucket2},...t.signal===void 0?{}:{signal:t.signal}});return vs(i,false)}async friends(e,t={}){let r=Xr(t),i=await pa(this.#e,e,{...r,...t.bucket1===void 0?{}:{bucket_1:t.bucket1},...t.bucket2===void 0?{}:{bucket_2:t.bucket2},...t.signal===void 0?{}:{signal:t.signal}});return vs(i,true)}async mine(e,t={}){return this.#n(e,"player","me",t)}async character(e,t,r={}){return this.#n(e,"character",t,r)}async#n(e,t,r,i){if(i.limit!==void 0){let{limit:l}=i;if(!Number.isInteger(l)||l<1||l>bs)throw new TypeError(`limit must be an integer between 1 and ${bs}, got ${String(l)}`)}let o=Xr(i),s=await la(this.#e,e,Rs[t],r,{...o,...i.bucket1===void 0?{}:{bucket_1:i.bucket1},...i.bucket2===void 0?{}:{bucket_2:i.bucket2},...i.limit===void 0?{}:{limit:i.limit},...i.signal===void 0?{}:{signal:i.signal}}),a=t==="player"&&r==="me"&&It((s??{}).entity_id)||r;return xm(s,t,a)}};var Wn=n=>typeof n=="string"?n:"",Qr=n=>typeof n=="number"?n:0;function xs(n){let e=n??{};return {playerId:Wn(e.player_id),key:Wn(e.key),value:e.value,updatedAt:Qr(e.updated_at)}}function Am(n){let e=n??{};return {...we(e),playerId:Wn(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:Qr(e.updated_at)}}function Pm(n){return n?.reason==="not_found"}var Ot=class{constructor(e,t){this.api=e;this.selfPlayerId=t;}api;selfPlayerId;async friends(e,t={}){let i=await ga(this.api,Ae(e),{...t.signal===void 0?{}:{signal:t.signal}})??{};return {key:Wn(i.key),entries:Array.isArray(i.entries)?i.entries.map(Am):[],generatedAt:Qr(i.generated_at)}}async of(e,t,r={}){try{return xs(await wa(this.api,e,Ae(t),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(i){if(Pm(i))return null;throw i}}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(o){throw new TypeError(`showcase value for ${JSON.stringify(e)} could not be serialised to JSON: ${String(o)}.`,{cause:o})}let i=await this.selfPlayerId();return xs(await Na(this.api,i,e,{value:t},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,t={}){let r=await this.selfPlayerId();await Zo(this.api,r,Ae(e),{...t.signal===void 0?{}:{signal:t.signal}});}};var Em="gemChallenge",As=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ps(n){if(!(typeof n!="string"||n===""))try{return new URLSearchParams(n).get(Em)??void 0}catch{return}}var He=class extends L{constructor(e,t={}){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="FriendChallengeError";for(let[r,i]of Object.entries(t))i!==void 0&&Object.assign(this,{[r]:i});}},Kn=n=>typeof n=="string"?n:void 0;function Es(n){let e=n??{};return {...we(e),playerId:Kn(e.player_id)??""}}function Ts(n){let e=n.has_more===true?Kn(n.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function Tm(n){let e=n??{};return {friends:Array.isArray(e.data)?e.data.map(Es):[],...Ts(e)}}var Zr=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0;function Im(n){return typeof n!="object"||n===null||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).filter(e=>typeof e[1]=="string"||typeof e[1]=="number"&&Number.isFinite(e[1])))}function Is(n){let e=n??{},t=Zr(e.opened_at),r=Zr(e.answered_at);return {id:Kn(e.item_id)??"",from:Es(e.sender),template:Kn(e.template)??"",params:Im(e.params),createdAt:Zr(e.created_at)??0,...t===void 0?{}:{openedAt:t},...r===void 0?{}:{answeredAt:r}}}function Cm(n){let e=n??{};return {challenges:Array.isArray(e.data)?e.data.map(Is):[],...Ts(e)}}function Mm(n){let e=n;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var Lt=class{#e;#n;#o;constructor(e,t={}){this.#e=e,this.#n=t.challenge,this.#o=t.launchedChallengeId;}async list(e={}){let t=await Ga(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Tm(t)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let t=await La(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Cm(t)}async launchedChallenge(e={}){let t=this.#o;if(t===void 0||!As.test(t))return null;try{return Is(await ya(this.#e,t,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(Mm(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!As.test(e))throw new L("invalid",400,"id must be a FriendChallenge.id, as gem.friends.launchedChallenge() or inbox() returned it",void 0,"bad_request");await Fa(this.#e,e);}};var Om=0;function Ee(){try{return crypto.randomUUID()}catch{let n=Math.random().toString(36).slice(2,10);return `local-${String(++Om)}-${String(Date.now())}-${n}`}}var Lm=12e4,Cs=8,Gm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Dm=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Gt(n,e,t={}){return new He(new L("invalid",400,e,void 0,n),t)}function Fm(n){if(typeof n!="object"||n===null||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function $m(n){let{playerId:e,template:t,params:r}=n??{};if(typeof e!="string"||!Gm.test(e))return {error:Gt("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof t!="string"||!Dm.test(t))return {error:Gt("unknown_template","template must be a friend_challenge_templates key from this game's config")};if(r===void 0)return {playerId:e,template:t,params:void 0};if(!Fm(r))return {error:Gt("param_invalid","params must be a plain object of strings and integers")};let i={},o=Object.keys(r);for(let s of o){let a=r[s];if(typeof a=="string"||typeof a=="number"&&Number.isSafeInteger(a)){Object.defineProperty(i,s,{value:a,enumerable:true,writable:true,configurable:true});continue}return {error:Gt("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return o.length>Cs?{error:Gt("param_undeclared",`params has ${String(o.length)} keys; a template declares at most ${String(Cs)}`)}:{playerId:e,template:t,params:i}}function qm(n){switch(n.outcome){case "accepted":case "cancelled":case "refused":case "unavailable":return {outcome:{outcome:n.outcome}};case "rate_limited":{let e=n.retryAfterMs,t=typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.ceil(e/1e3):void 0;return {error:new He(new L("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",t,"rate_limited"))}}case "invalid":{let e=typeof n.code=="string"?n.code:void 0,t=typeof n.detail=="string"&&n.detail!==""?n.detail:e??"the friend challenge request was refused as invalid";return {error:new He(new L("invalid",400,t,void 0,e),{...typeof n.param=="string"?{param:n.param}:{},...typeof n.channel=="string"?{channel:n.channel}:{},...typeof n.configVersion=="number"?{configVersion:n.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function jm(n){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(n.outcome)?n.outcome:"unknown"}function Ms(n){let e=new Map;return {challenge(t){if(!n.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=$m(t);if("error"in r)return Promise.reject(r.error);let i=`challenge-${Ee()}`;return new Promise((o,s)=>{let a={},l=m=>{e.delete(i)&&(n.clock.clearTimeout(a.timer),"error"in m?s(m.error):o(m.outcome));};e.set(i,l),a.timer=n.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},n.timeoutMs??Lm);let d=false;try{d=n.bridge.requestFriendChallenge(i,r.playerId,r.template,r.params);}catch{}d||l({outcome:{outcome:"unavailable"}});})},settle(t){let r=e.get(t.requestId);if(r===void 0){n.onDropped?.(`gem.friendChallengeResult (${jm(t)}) for an unknown requestId: `+JSON.stringify(t.requestId));return}r(qm(t));}}}var Jn=n=>typeof n=="string"?n:void 0;function Nm(n){let e=n??{},t=Jn(e.currency_id);if(t===void 0||t==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Jn(e.slug)??"",currencyId:t,balance:r,access:e.access==="spend"?"spend":"read"}}var zn=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await Sn(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=Nm(o);s!==void 0&&i.push(s);}return i}},ei=n=>typeof n=="number"&&Number.isFinite(n)&&n>=0?Math.floor(n):0;function Um(n){let e=n??{},t=Jn(e.currency_id);if(t===void 0||t==="")return;let r=ei(e.limit),i=Math.min(ei(e.earned),r),o=Math.min(ei(e.remaining),r-i),s=e.period_days,a=typeof s=="number"&&Number.isInteger(s)&&s>=1?s:1,l=e.resets_at,d=typeof l=="number"&&Number.isFinite(l)&&l>0?Math.round(l*1e3):void 0;return {currencySlug:Jn(e.currency_slug)??"",currencyId:t,limit:r,earned:i,remaining:o,period:e.period==="day"?"day":"window",periodDays:a,...d===void 0?{}:{resetsAt:d}}}function Os(n){let e=new Set,t=r=>{n?.(`[gem] an earnAllowance 'changed' listener threw: ${r instanceof Error?r.message:String(r)}`);};return {on(r){return e.add(r),()=>{e.delete(r);}},emit(){for(let r of [...e])try{let i=r();typeof i?.then=="function"&&i.then(void 0,t);}catch(i){t(i);}}}}var Yn=class{#e;#n;#o;constructor(e,t,r){this.#e=e,this.#n=t,this.#o=r;}async get(e={}){let r=(await ha(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=Um(o);s!==void 0&&i.push(s);}return i}on(e,t){return e!=="changed"?(this.#o?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#n?.on(t)??(()=>{})}},Dt=class{currencies;earnAllowance;constructor(e,t,r){this.currencies=new zn(e),this.earnAllowance=new Yn(e,t,r);}};var ti=n=>typeof n=="string"?n:"",Ls=n=>typeof n=="number"?n:0;function Bm(n){let e=n??{};return {key:ti(e.key),visibility:ti(e.visibility),value:e.value,updatedAt:Ls(e.updated_at)}}function Vm(n){let e=n??{};return {...we(e),playerId:ti(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Bm):[],generatedAt:Ls(e.generated_at)}}function Hm(n){return n?.reason==="not_found"}var Ft=class{#e;constructor(e){this.#e=e;}async of(e,t={}){try{return Vm(await ba(this.#e,e,{...t.signal===void 0?{}:{signal:t.signal}}))}catch(r){if(Hm(r))return null;throw r}}};var Wm=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]]),$t=class extends L{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:Wm.get(this.code))??super.retryable}},Fe=class{#e;constructor(e){this.#e=e;}async invoke(e,t={}){let r=Km(e),i;try{i=await this.#e(r,t.signal===void 0?{}:{signal:t.signal});}catch(o){throw o instanceof L?zm(o):o}return Jm(i)}};function Km(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 ie(`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 ie(`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 Jm(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 zm(n){let{details:e,invocationId:t}=No(n),i=e?.untrusted?.message,o=e?.reason;return new $t(n,{...t===void 0?{}:{invocationId:t},...n.code==="function_error"&&typeof i=="string"?{functionMessage:i}:{},...n.code==="function_failed"&&typeof o=="string"?{failure:o}:{}})}var Ym=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],ni="gem_";function Gs(n){return n.startsWith(ni)}var Ds=1e4,Fs=50,Xm=500,Qm=65536-4*1024,Zm=24*1024;function $s(n){let e={},t={};for(let[r,i]of Object.entries(n))typeof i=="string"?e[r]=i:typeof i=="number"&&Number.isFinite(i)&&(t[r]=i);return {dimensions:e,measures:t}}var qs=n=>typeof n=="number"?n:0,ep=n=>typeof n=="string"?n:"";function ri(n=0){return {accepted:0,rejected:[],dropped:n,duplicate:false}}function tp(n,e){let t=n??{},r=Array.isArray(t.rejected)?t.rejected.map(i=>{let o=i??{};return {index:qs(o.index),code:ep(o.code)}}):[];return {accepted:qs(t.accepted),rejected:r,dropped:e,duplicate:t.duplicate===true}}function ii(){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 np(n){return n?.retryable===true}var qt=class{#e;#n;#o;#y;#t=[];#f={};#a=0;#s=null;#h=false;#b=false;#v=false;#r=false;#_=null;#l=null;#d=false;#i=false;#m=false;#w=false;#S=false;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#o=Math.max(Ds,e.options?.flushIntervalMs??Ds),this.#y=Math.max(1,Math.floor(e.options?.maxQueue??Xm));}track(e,t={}){if(!(!this.#n||this.#r)){if(Gs(e)){this.#S||(this.#S=true,this.#g(`[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.#R(e,$s({...this.#f,...t}));}}setContext(e){this.#f={...this.#f,...e};}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#i)return ri();let t=this.#E();if(t===null||t==="")return this.#t.length>0&&!this.#w&&(this.#w=true,this.#g("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),ri();if(this.#k(),this.#t.length===0)return ri();let r=e.keepalive===true;this.#u();let i=this.#t.splice(0,this.#A(r)),o=this.#a;this.#a=0;let s=Math.round(this.#e.clock.now()),a={batch_id:ii(),sent_at_ms:s,events:i.map(d=>js(d,s))},l={client:this.#e.client(),gameId:()=>t};this.#v=true;try{let d=await xa(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=tp(d,o);return this.#P(m),m}catch(d){throw np(d)?this.#x(i,o):this.#g(`[gem] analytics: ${i.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#v=false,this.#t.length>0&&this.#c();}}trackPlatform(e,t={}){this.#r||this.#i&&(e==="gem_pause"||e==="gem_resume")||this.#R(e,$s(t));}hold(){this.#r||this.#l!==null||(this.#i=true,this.#u());}release(){if(!this.#i||this.#r)return;this.#i=false;let e=this.#e.clock.now(),t=this.#t.map(r=>({...r,atMs:e}));this.#t=t,this.#m&&(this.#m=false,this.#l=e,this.#d=false,this.#t.unshift({uid:ii(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=Fs?this.#p():this.#t.length>0&&this.#c();}get held(){return this.#i}startSession(){if(!(this.#r||this.#l!==null)){if(this.#i){this.#m=true;return}this.#l=this.#e.clock.now(),this.#d=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#d)return;if(this.#d=true,this.#i){this.#m=false,this.#t=[],this.#a=0;return}let t=this.#l;this.trackPlatform("gem_session_end",{reason:e,...t===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-t))}}),this.#p({keepalive:true});}setPaused(e){this.#r||e===this.#h||(this.#h=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#t.length>0&&this.#c());}setHidden(e){this.#r||e===this.#b||(this.#b=e,e?this.#u():this.#t.length>0&&this.#c());}dispose(){this.#r=true,this.#u(),this.#t=[],this.#a=0;}get pending(){return this.#t.length}#R(e,t){let{dimensions:r,measures:i}=t;for(this.#k();this.#t.length>=this.#y;)this.#t.shift(),this.#a+=1;this.#t.push({uid:ii(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:i}),this.#t.length>=Fs?this.#p():this.#c();}#p(e={}){this.flush(e).catch(()=>{});}#x(e,t){for(this.#t=[...e,...this.#t],this.#a+=t;this.#t.length>this.#y;)this.#t.shift(),this.#a+=1;}#A(e){let t=e?Zm:Qm,r=Math.min(this.#t.length,100),i=128;for(let o=0;o<r;o+=1){let s=this.#t[o];if(s===void 0)break;if(i+=JSON.stringify(js(s,0)).length+1,i>t)return Math.max(1,o)}return r}#c(){this.#s!==null||this.#h||this.#b||this.#i||this.#r||this.#v||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#p();},this.#o));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#k(){let e=this.#T();e===null||e===""||(this.#_!==null&&this.#_!==e&&(this.#t=[],this.#a=0,this.#l=null,this.#d=false),this.#_=e);}#P(e){for(let t of e.rejected)this.#g(`[gem] analytics: an event was refused (${t.code}). `+rp(t.code));}#g(e){let t=this.#e.log;t!==null&&(t===void 0?console.warn(e):t(e));}#E(){try{return this.#e.gameId()}catch{return null}}#T(){try{return this.#e.playerId()}catch{return null}}};function js(n,e){return {event_uid:n.uid,name:n.name,offset_ms:Math.round(n.atMs)-e,dimensions:n.dimensions,measures:n.measures}}function rp(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 jt(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 ip=2e3,op=5e3;function Us(n){let e=[],t=false,r=null,i=new Map,o=()=>{if(e.length>0)return Promise.resolve(e);if(t)return Promise.resolve([]);if(!n.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let s,a=new Promise(l=>{let d=false,m=null;s=u=>{d||(d=true,r=null,n.clock.clearTimeout(m),l(u));},m=n.clock.setTimeout(()=>{t=true,s([]);},n.timeoutMs??ip);});return r={promise:a,settle:s},a};return {resolveList:o,resolve(){return e.length>0||t||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(s=>s[0])},refresh(s){return !Ns(e,s)||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=m=>{i.delete(d)&&(n.clock.clearTimeout(l),a(m));};i.set(d,s),l=n.clock.setTimeout(()=>d(e),n.refreshTimeoutMs??op);})},accept(s,a){let l=jt(a),d=pe(s),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[u,p]of [...i])Ns(m,p)||u(m);}}}}function Ns(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var ap=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),_=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="DedicatedServerError",this.retryable=ap.has(t),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var Bs=["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"],sp=new Set(Bs);function $e(n){return typeof n=="string"&&sp.has(n)?n:"unknown"}var Xn="webrtc_dedicated",li=["universal","mobile","web"];var lp="p2p_unavailable",dp="capacity_unavailable",cp=2,Vs=3e4,Hs=1e3,Ws=2e4;async function di(n){let e=pe(n.clusterTargetId),t=n.nextClusterTarget,r=0,i=n.clock??le,o=n.retry??{},s=o.budgetMs??Vs,a=o.maxDelayMs??Ws,l=o.initialDelayMs??Hs,d=i.now(),m=d+s,u=0;for(;;){u++;try{let p=await pi(n.signal,"while allocating",()=>n.client.post(`${zs(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!up(p)||s<=0)throw p;if(p.status===503&&p.code===lp)throw new _("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===dp?r+1:0,t!==void 0&&r>=cp){let A=t;t=void 0;let I=pe(await A());I!==void 0&&(e=I,r=0);}let g=Math.min(a,l*2**(u-1)),y=Math.min(a,(p.retryAfterSeconds??0)*1e3),S=Math.max(g/2,y)+Math.random()*(g/2);if(i.now()+S>m)throw mp(n,p,u,i.now()-d,s);if(o.onWaiting?.({attempt:u,elapsedMs:i.now()-d,budgetMs:s,nextAttemptInMs:S,status:p.status,message:p.message}),await Qn(i,S,n.signal),n.signal?.aborted)throw si("while waiting to allocate")}}}function up(n){return n instanceof L?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function mp(n,e,t,r,i){let o=`${t} attempt${t===1?"":"s"} over ${r}ms of a ${i}ms budget`;return e.status===429?new _("start_rate_limited",`the platform was still limiting match starts for room ${n.roomId} after ${o}: ${e.message}`,{cause:e}):new _("no_server_ready",`the platform had no server ready for room ${n.roomId} after ${o}: ${e.message}`,{cause:e})}var pp=12e4,gp=1e3;async function ci(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??gp,i=n.timeoutMs??pp,o=e.now()+i,s=Ks(n),a={seen:n.knownToExist===true};for(;;){let l=await Js(n,s,a);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new _("timeout",`match ${t} was still ${l.status} after ${i}ms`);await Qn(e,r,n.signal);}}async function ui(n){return (await Js(n,Ks(n),{seen:n.knownToExist===true})).outcome}function Ks(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${zs(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function Js(n,e,t){let{matchId:r}=n,i=n.clock.now(),o;try{o=await pi(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(s){if(s instanceof L&&s.reason==="not_found")return {status:"not_found",outcome:t.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(t.seen=true,o.status==="ready")return {status:"ready",outcome:yp(r,o,i)};if(o.status==="failed"){let s=o.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:$e(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function mi(n){let e=await pi(n.signal,"while listing cluster targets",()=>n.client.get("/v1/ping/targets",n.signal)),t=[];for(let r of e.targets??[]){let i=r?.cluster_target_id;typeof i!="string"||i.length===0||t.push({id:i,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return t}async function pi(n,e,t){if(n?.aborted)throw si(e);try{return await t()}catch(r){throw n?.aborted?si(e,r):r}}function si(n,e){return new _("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function yp(n,e,t){let r=e.join_credential,i=e.expires_in_seconds,o=typeof r=="string"&&typeof i=="number";return {status:"ready",matchId:n,protocol:e.protocol??"unknown",...o?{joinCredential:r,credentialExpiresAt:t+i*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function zs(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function Qn(n,e,t){return t?.aborted?Promise.resolve():new Promise(r=>{let i=()=>{n.clearTimeout(o),t?.removeEventListener("abort",i),r();},o=n.setTimeout(i,e);t?.addEventListener("abort",i);})}function Ys(n){return typeof n=="string"&&n.trim()!==""}function Zn(n,e){return Ys(n)?n.trim():Ys(e)?e:null}var er="0.1.0-beta",Xs="0-beta",pt="web",fp=/^(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 hp(n){let e=fp.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function Qs(n,e){let t=bp(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:er};let i=hp(r);if(i===null)throw new _("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 '${er}' for it.`);if(i!==Xs)throw new _("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${Xs}' is the only line a web dedicated-server fleet runs. gem-api uses the line \u2014 the semver major plus any prerelease tag \u2014 verbatim as the fleet's label selector, so a match on '${i}' would match nothing and be reported as a capacity shortfall rather than as this. Omit engineVersion: a browser game has no engine version of its own, and the SDK reports '${er}' for it.`);return {...n,platform:t,engineVersion:r}}function bp(n,e){if(n===void 0||n===pt)return pt;if(!li.includes(n))throw new _("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${li.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${pt}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${pt}' 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.`),pt}function Nt(n){let e=n??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let t=e.heartbeat_interval_seconds;return {id:e.ticket_id,status:typeof e.status=="string"?e.status:"queued",...typeof e.reason=="string"?{reason:e.reason}:{},...typeof e.game_room_id=="string"?{roomId:e.game_room_id}:{},partySize:typeof e.party_size=="number"?e.party_size:1,queuedAt:Zs(e.queued_at),expiresAt:Zs(e.expires_at),heartbeatIntervalSeconds:typeof t=="number"&&t>0?t:0}}function Zs(n){if(typeof n!="string")return 0;let e=Date.parse(n);return Number.isFinite(e)?Math.floor(e/1e3):0}var vp=3,el=1e3,tr=class{constructor(e){this.options=e;this.snapshot=e.first;let t=new Promise((o,s)=>{this.resolve=o,this.reject=s;});t.catch(()=>{});let r=()=>this.snapshot,i=()=>this.status;this.ticket={get id(){return r().id},get status(){return i()},get partySize(){return r().partySize},get queuedAt(){return r().queuedAt},get expiresAt(){return r().expiresAt},outcome:t,cancel:()=>(this.requestCancel(),t)};}options;ticket;snapshot;status="queued";timer=null;busy=false;again=false;cancelRequested=false;soon=false;misses=0;settled=false;resolve;reject;start(){this.apply(this.snapshot);}poke(){this.settled||(this.soon=true,!this.busy&&(this.clearTimer(),this.tick()));}abandon(e=false){this.settled||(this.options.cancel(this.snapshot.id,e).catch(()=>{}),this.settle({status:"cancelled",reason:"requested"}));}requestCancel(){this.settled||(this.cancelRequested=true,this.trigger());}trigger(){if(this.busy){this.again=true;return}this.clearTimer(),this.tick();}schedule(e=false){if(this.settled)return;this.clearTimer();let t=e?el:Math.max(el,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},t);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,t=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){t=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(t);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof L&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<vp){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let t=e instanceof L&&e.code==="matchmaking_unavailable";this.settle({status:t?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let t=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:t});}catch(t){this.busy=false,this.fail(t);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};var _p="join",wp="welcome",Sp="rejected",tl=25e3,Rp=1e3,gi=1;function yi(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var kp={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 fi(n){let e=typeof n=="string"?n:"unknown";return new _(kp[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function Ut(n){let{channel:e,clock:t}=n;return new Promise((r,i)=>{let o=false,s=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??tl),a=t.setTimeout(()=>w(new _("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(s,Rp)),l=S=>{let A=S.data;if(typeof A!="string"){u(A);return}let I;try{I=JSON.parse(A);}catch{u(A);return}if(o){u(A);return}if(I.t===wp){let b=yi(I.heartbeat_interval);y({...typeof I.player_id=="string"?{playerId:I.player_id}:{},...typeof I.match_id=="string"?{matchId:I.match_id}:{},...b===void 0?{}:{heartbeatIntervalMs:b}});return}if(I.t===Sp){w(fi(I.reason));return}u(A);},d=()=>{w(new _("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{w(new _("aborted","the caller aborted during the join exchange"));},u=S=>{o&&n.onMessage?.(S);},p=()=>{t.clearTimeout(a),e.removeEventListener("close",d),n.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=S=>{o=true,p(),n.onMessage===void 0&&g(),r({welcome:S,detach:g});},w=S=>{o||(o=true,p(),g(),i(S));};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:_p,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:gi}:{}}));}catch(S){w(new _("connection_failed",`the join frame could not be sent on the open channel: ${String(S)}`,{cause:S}));}})}var We=1,Bt=2,hi=4,_i=8,xp=2,Ap=1e3,wi="heartbeat timeout",Vt="gem-uu",nr=2,rl="gem_transports";function gt(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!Pp(r)||e.includes(r)||e.push(r);}return e}function Pp(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function Ht(n,e){if(typeof n!="object"||n===null)return null;let t=n[rl];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 rr(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var il=new TextEncoder,ol=new TextDecoder;function Si(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function Ri(n){let e=0;return n?.reliable===false&&(e|=We),n?.ordered===false&&(e|=Bt),e}function ki(n){return {reliable:(n&We)===0,ordered:(n&Bt)===0}}var xi={reliable:true,ordered:true};function al(n){return JSON.stringify({t:"join",credential:n,wire:nr,heartbeat:gi})}function sl(n){let e;try{e=JSON.parse(n);}catch{throw new _("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let t=yi(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"?fi(e.reason):new _("join_refused","the server answered the join out of protocol")}function ir(){return typeof globalThis.WebTransport=="function"&&Ai===null}function or(){return Ai}var Ai=null;var nl="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Ep(n){let e=wn(n);if(e.byteLength!==32)throw new _("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var bi=class{buffered=new Uint8Array(0);push(e){let t=new Uint8Array(this.buffered.byteLength+e.byteLength);t.set(this.buffered,0),t.set(e,this.buffered.byteLength),this.buffered=t;let r=[];for(;!(this.buffered.byteLength<4);){let o=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(o===0||o>1<<20)throw new _("connection_failed",`a control-stream record claims ${o} bytes`);if(this.buffered.byteLength<4+o)break;let s=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:s[0]??0,payload:s.slice(1)});}return r}};function vi(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 Wt(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webTransport;if(t===void 0){let a=globalThis.WebTransport;if(a===void 0)throw new _("connection_failed","this environment has no WebTransport");t=n.certHashBase64===void 0?new a(n.url):new a(n.url,{serverCertificateHashes:[{algorithm:"sha-256",value:Ep(n.certHashBase64)}]});}let r=t,i=a=>{try{r.close();}catch{}throw a},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(Ai=nl,i(new _("connection_failed",`${nl}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,l)=>{setTimeout(()=>l(new _("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,s]);let a=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([a.read(),s]);if(a.releaseLock(),l.done||l.value===void 0)return i(new _("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(vi(hi,il.encode(al(n.credential))));let u=new bi,p=d.readable.getReader(),g;for(;g===void 0;){let y=await Promise.race([p.read(),s]);if(y.done||y.value===void 0)return i(new _("connection_failed","the control stream closed before the join was answered"));for(let w of u.push(y.value)){g=sl(ol.decode(w.payload));break}}return {link:Tp(r,m,p,u,n.log??(y=>console.warn(y)),dl(g,n.clock)),welcome:g}}catch(a){return i(a)}}function Tp(n,e,t,r,i,o){let s,a,l=false,d=y=>{if(!l){l=true,m.stop();try{n.close();}catch{}a?.(y);}},m=Ei(o,()=>d(wi)),u=(y,w)=>{m.heard(),(y&_i)===0&&s!==void 0&&((y&hi)!==0?s(ol.decode(w),xi):s(w,ki(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))u(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 S=await w.read();if(S.done||S.value===void 0)break;let A=S.value;A.byteLength!==0&&u((A[0]??0)|We|Bt,A.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(y){p=void 0,g=void 0,i(`[gem] webtransport datagram lane unusable (${rr(y)}); unreliable sends ride the stream`);}return n.closed.then(y=>d(ll(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,w){if(l)return;if(typeof y=="string"){e.write(vi(hi,il.encode(y))).catch(()=>d("write failed"));return}let S=Ri(w);if((S&We)!==0&&g!==void 0){let A=Si(S,y),I=p?.maxDatagramSize;if(I===void 0||A.byteLength<=I){g.write(A).catch(()=>{});return}}e.write(vi(S,y)).catch(()=>d("write failed"));},onMessage(y){s=y;},onClose(y){a=y;},close(){d("closed");}}}function Pi(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webSocket;if(t===void 0){let i=globalThis.WebSocket;if(i===void 0)return Promise.reject(new _("connection_failed","this environment has no WebSocket"));t=new i(n.url);}let r=t;return r.binaryType="arraybuffer",new Promise((i,o)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),o(new _("timeout","websocket did not come up in time")));},e),l=g=>{s||(s=true,clearTimeout(a),r.close(),o(g));},d=()=>{r.send(al(n.credential));},m=g=>{if(s)return;if(typeof g.data!="string"){l(new _("join_refused","the server sent binary before answering the join"));return}let y;try{y=sl(g.data);}catch(w){l(w);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",u),r.removeEventListener("error",p),i({link:Ip(r,dl(y,n.clock)),welcome:y});},u=()=>{l(new _("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new _("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",m),r.addEventListener("close",u),r.addEventListener("error",p),r.readyState===1&&d();})}function ll(n){return typeof n=="string"&&n.length>0?n:void 0}function dl(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function Ei(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,Ap)*xp,i=t.now(),o=null,s=()=>{o=null;let a=t.now()-i;if(a>=r){e();return}o=t.setTimeout(s,r-a);};return o=t.setTimeout(s,r),{heard:()=>{i=t.now();},stop:()=>{o!==null&&(t.clearTimeout(o),o=null);}}}function Ip(n,e){let t,r,i=false,o=a=>{if(!i){i=true,s.stop();try{n.close();}catch{}r?.(a);}},s=Ei(e,()=>o(wi));return n.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){t?.(a.data,xi);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&_i)===0&&t?.(l.slice(1),ki(d));})),n.addEventListener("close",(a=>o(ll(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!i){if(typeof a=="string"){n.send(a);return}n.send(Si(Ri(l),a));}},onMessage(a){t=a;},onClose(a){r=a;},close(){o("closed");}}}function Ti(n,e,t,r){let i,o,s=false,a=t,l=u=>{if(!s){s=true,d.stop();try{n.close();}catch{}try{e.close();}catch{}o?.(u);}},d=Ei(r,()=>l(wi)),m=(u,p)=>{if(d.heard(),typeof u=="string"){i?.(u,xi);return}let g=new Uint8Array(u);if(g.byteLength===0)return;let y=g[0]??0;(y&_i)===0&&i?.(g.slice(1),ki(y|p));};if(n.addEventListener("message",(u=>m(u.data,0))),n.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let u=e.connectionState;(u==="failed"||u==="closed")&&l(`connection ${u}`);})),a!==void 0){let u=a;u.addEventListener("message",(p=>m(p.data,We|Bt))),u.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(u,p){if(s)return;if(typeof u=="string"){n.send(u);return}let g=Ri(p),y=Si(g,u);if((g&We)!==0&&a!==void 0&&a.readyState==="open"){a.send(y);return}n.send(y);},onMessage(u){i=u;},onClose(u){o=u;},close(){l("closed");}}}function Mi(n){if(typeof n!="object"||n===null)return;let e={};for(let[t,r]of Object.entries(n)){let i=Ii(r);i!==void 0&&(e[t]=i);}return e}function Oi(n){if(Array.isArray(n))return n.map(Cp).filter(e=>!!e)}function Ii(n){if(Ci(n)||Array.isArray(n)&&n.every(Ci))return n}function Ci(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function Cp(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=Ii(e.fixed),r=Ii(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},...yt("description",Mp(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Ci)?{allowed:e.allowed}:{},...yt("min",Kt(e.min)),...yt("max",Kt(e.max)),...yt("minItems",Kt(e.min_items)),...yt("maxItems",Kt(e.max_items)),...yt("maxLength",Kt(e.max_length))}}function Mp(n){return typeof n=="string"&&n.length>0?n:void 0}function Kt(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function yt(n,e){return e===void 0?{}:{[n]:e}}function Ie(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(cl):[];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,...Se("joinCode",Y(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...Se("roomArgs",Mi(e.room_args)),...Se("roomArgsTemplate",Oi(e.room_args_template)),gameChannel:Y(e.game_channel)??"release",...Se("region",Y(e.region)),...Se("clusterTargetId",Y(e.cluster_target_id)),selfHosted:e.self_hosted===true,...Se("matchId",Y(e.match_id)),version:Te(e.version)??0,...Se("templateId",Y(e.template_id)),roomType:Y(e.game_room_type)??"Standard",...Se("transports",gt(e.transports)??void 0),createdAt:Te(e.created_at)??0,updatedAt:Te(e.updated_at)??0,...Se("startedAt",Te(e.started_at))}}function cl(n){let e=n??{};return {...we(e),playerId:Y(e.player_id)??"",isReady:e.is_ready===true,role:Y(e.role)??"member",joinedAt:Te(e.joined_at)??0,...Se("groupId",Y(e.group_id)),...Se("platform",Y(e.platform))}}function ar(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 Se(n,e){return e===void 0?{}:{[n]:e}}var zt=class{constructor(e){this.options=e;}options;list(e){let t=new URLSearchParams;e.status&&t.set("status",e.status),e.templateSlug&&t.set("template_slug",e.templateSlug),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);let r=t.size>0?`?${t.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(i=>({rooms:(i.game_rooms??[]).map(ar),...typeof i.next_cursor=="string"?{nextCursor:i.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(t=>({rooms:(t.game_rooms??[]).map(ar)}))}create(e,t,r){return Op(e.maxPlayers),this.options.client.post(this.baseV2(),{name:e.name,...e.isPublic===void 0?{}:{is_public:e.isPublic},...e.settings===void 0?{}:{settings:e.settings},...e.region===void 0?{}:{region:e.region},...r===void 0?{}:{cluster_target_id:r},...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.partyId===void 0?{}:{party_id:e.partyId},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...e.roomArgs===void 0?{}:{room_args:e.roomArgs},...Jt(t)},e.signal).then(Ie)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(Ie)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...Jt(r)},t.signal).then(Ie)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...Jt(r)},t.signal).then(Ie)}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},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...Jt(t)},e.signal).then(Ie)}createTicket(e,t,r=[]){return Yo(this.generated(),{templates:e.templateSlugs.map(i=>({template_slug:i})),...r.length===0?{}:{cluster_target_ids:[...r]},...e.partyId===void 0?{}:{party_id:e.partyId},...Jt(t)},{...e.signal===void 0?{}:{signal:e.signal}}).then(Nt)}heartbeatTicket(e){return ka(this.generated(),e).then(Nt)}cancelTicket(e,t=false){return t?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(Nt):Ho(this.generated(),e).then(Nt)}leave(e,t,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:t},r,{keepalive:i}).then(()=>{})}asksSelfHosted(e){return e===void 0&&this.options.selfHosted?.()===true}close(e,t){return this.options.client.delete(this.roomV1(e),t).then(()=>{})}update(e,t){return this.options.client.patch(this.roomV2(e),{...t.name===void 0?{}:{name:t.name},...t.maxPlayers===void 0?{}:{max_players:t.maxPlayers},...t.isPublic===void 0?{}:{is_public:t.isPublic},...t.settings===void 0?{}:{settings:t.settings},...t.roomArgs===void 0?{}:{room_args:t.roomArgs}},t.signal).then(Ie)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(Ie)}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(Ie)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function Jt(n){return {platform:n.platform,game_version:n.gameVersion,engine_version:n.engineVersion}}function Op(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 Yt=class{listeners=new Map;retainedMatch=null;on(e,t){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(t),e==="matchReady"&&this.retainedMatch!==null){let i=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(t)&&this.retainedMatch===i&&t(i);});}return ()=>this.off(e,t)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,t){this.listeners.get(e)?.delete(t);}once(e,t){let r=this.on(e,((...i)=>{r(),t(...i);}));return r}emit(e,...t){e==="matchReady"&&(this.retainedMatch=t[0]);let r=this.listeners.get(e);if(r)for(let i of [...r])i(...t);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};function Lp(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var Gp=1e3,Dp=3e3,Fp=6e4,$p=2,ul=new Set(["game_room_closed","game_room_gone"]),qp=12e4,jp=5e3,Np=new Set(["invalid_cluster_target","capacity_unavailable"]),Up=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function Gi(n){return new Li(n)}var Li=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new zt({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Yt;api;room=null;ticketWatch=null;queueing=false;queuedFromRoomId=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("create");let t=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("create",async()=>{let o=await t;return this.api.create(r,this.version("create"),o[0]).catch(async s=>{let a=await this.afterRefusedClusters(s,o);if(a[0]===void 0||a[0]===o[0])throw s;return this.api.create(r,this.version("create"),a[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,t={}){this.assertNotInRoom("join"),this.assertNotQueued("join");let r=await this.attachParty(t),i=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async joinByCode(e,t={}){this.assertNotInRoom("joinByCode"),this.assertNotQueued("joinByCode");let r=await this.attachParty(t),i=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async quickJoin(e){this.assertNotInRoom("quickJoin"),this.assertNotQueued("quickJoin");let t=this.clusterTargets(),r=await this.attachParty(e),i=s=>this.api.quickJoin(r,this.version("quickJoin"),s).catch(a=>this.retryPastStaleMembership(a,r,s)),o=await this.run("quickJoin",async()=>{let s=await t;return i(s).catch(async a=>{let l=await this.afterRefusedClusters(a,s);if(l.length===0||yl(l,s))throw a;return i(l)})});return this.enter(o,"joined"),this.askForLocalServer(o),o}async queueForMatch(e){this.assertNotQueued("queueForMatch"),Vp(e?.templateSlugs),this.queueing=true;try{let t=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("queueForMatch",async()=>{let s=await t;return this.api.createTicket(r,this.version("queueForMatch"),s).catch(async a=>{let l=await this.afterRefusedClusters(a,s);if(l.length===0||yl(l,s))throw a;return this.api.createTicket(r,this.version("queueForMatch"),l)})}),o=new tr({clock:this.options.clock,first:i,heartbeat:s=>this.track(this.api.heartbeatTicket(s)),cancel:(s,a)=>this.track(this.api.cancelTicket(s,a)),seat:s=>this.enterMatchedRoom(s),onSettled:()=>{this.ticketWatch===o&&(this.ticketWatch=null),this.retuneSeatWatch();}});return this.ticketWatch=o,this.retuneSeatWatch(),o.start(),o.ticket}finally{this.queueing=false;}}async enterMatchedRoom(e){let t=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?t:(this.room!==null&&this.room.id!==t.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(t,"joined"),this.room?.id===t.id?this.room:t)}async list(e={}){let t=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",t),t}async myRooms(e){let t=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",t.rooms),t.rooms}async leave(e={}){let t=this.requireRoom("leave"),r=e.keepalive===true,i=()=>this.run("leave",()=>this.api.leave(t.id,e.asGroup!==false,e.signal,r));if(r){let o=i();this.track(this.notifyLeavingMatch({keepalive:true})),await o;}else await this.notifyLeavingMatch(),await i();this.exit(),this.emitter.emit("left");}async leaveAll(e){let t=await this.myRooms(e),r=[];for(let i of t)try{await this.run("leaveAll",()=>this.api.leave(i.id,!0,e)),r.push(i.id),this.room?.id===i.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let t=this.requireRoom("close");await this.run("close",()=>this.api.close(t.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let t=this.room;if(!t)return null;let r;try{r=await this.track(this.api.get(t.id,e));}catch(i){if(i instanceof L&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let s=await this.askWhyEnded(o,e);this.endMatch(o,s??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",i),i}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let t=this.room,r=this.heldMatchId;if(!(t===null||r===null)&&!(t.status==="in_game"&&t.matchId===r)&&!(t.matchId!==void 0&&t.matchId!==r)&&this.settling!==r){this.settling=r;try{let i=await this.askWhyEnded(r,e);i!==null&&this.endMatch(r,i,t.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,t){let r=this.room;if(r===null)return null;let i=this.takeHint(e),o;try{o=await this.track(this.onceGameIdKnown(()=>ui({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...t===void 0?{}:{signal:t}})));}catch(s){return s instanceof L&&s.reason==="not_found"?i??null:(this.reportError("reconcile",s),null)}return o===null?null:o.status==="ready"?(this.seenMatches.add(e),null):o.status==="failed"?(this.settleFailed(o.matchId,o.reason),null):o.reason==="unknown"&&i!==null?i:o.reason}takeHint(e){let t=this.pendingHint;if(t===null||t.matchId!==void 0&&t.matchId!==e||(this.pendingHint=null,t.reason===void 0))return null;let r=$e(t.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let t=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=t,this.track(t)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,t){let r=this.requireRoom("setReady"),i=await this.run("setReady",()=>this.api.setReady(r.id,e,t));return this.apply(i),i}async kick(e,t){let r=this.requireRoom("kick"),i=await this.run("kick",()=>this.api.kick(r.id,e,t));return this.apply(i),i}async transferHost(e,t){let r=this.requireRoom("transferHost"),i=await this.run("transferHost",()=>this.api.transferHost(r.id,e,t));return this.apply(i),i}async update(e){let t=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(t.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,t){let r=this.requireRoom("startMatch");if(!this.isHost)throw new _("misconfigured",`only the host of room ${r.id} can start a match, and this player is not it. Every other member waits for \`matchAllocationStarted\` instead \u2014 that is the whole point of the room carrying the match.`);this.startsInFlight++;try{return await this.startIn(r,e,t)}finally{this.startsInFlight--;}}async startIn(e,t,r){let i=pe(t.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),s=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let a=(m,u)=>di({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...i===void 0?{nextClusterTarget:()=>this.nextCluster(u)}:{},retry:{...t.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),t.retry?.onWaiting?.(p);}},...t.signal===void 0?{}:{signal:t.signal}}),l=()=>a(o,[s]).catch(async m=>{if(i!==void 0||!pl(m))throw m;let u=await this.nextCluster([s],true);if(u===void 0)throw m;return a(u,[s,u])}),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 _("misconfigured","this match is suspended \u2014 the transport dropped and nobody has decided to reconnect yet. Call reconnectToMatch(), or dedicatedServer.connect(), which does it for you.");let t=this.emitter.retained;return t!==null&&this.session.phase==="ready"?t:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let t=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),i=await this.run("pollMatchStatus",()=>this.chase(t.id,r,e));return this.settleOutcome(i)}chase(e,t,r){return ci({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 _("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!ul.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new _("match_ended",`match ${e.matchId} ended: ${e.reason}`);return this.seenMatches.add(e.matchId),this.emitter.retained?.matchId===e.matchId?this.emitter.retain(e):this.emitter.emit("matchReady",e),this.heldMatchId===e.matchId&&this.session.phase!=="connected"&&(this.session={phase:"ready",matchId:e.matchId}),e}settleFailed(e,t){this.heldMatchId===e&&(this.abandonReconnect(e,t),this.emitter.emit("matchFailed",e,t),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,t,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:t,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:t,roomReopened:r}),this.abandonReconnect(e,t));}armReconnect(e,t){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),t==="kicked"){r.abandon(e,t);return}let i={matchId:e,cause:t,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=i,this.track(this.reconnectStep(i));}park(e,t){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),t());}reconnecting(e){return !this.disposed&&!e.done&&this.reconnect===e&&this.session.phase==="suspended"&&this.session.matchId===e.matchId}finishReconnect(){let e=this.reconnect;e!==null&&(e.done=true,e.timer!==null&&(this.options.clock.clearTimeout(e.timer),e.timer=null),e.parked=null,this.reconnect=null);}abandonReconnect(e,t){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,t));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!Ke()){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<Gp){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(Lp(e.attempt,t.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!Ke()){this.park(e,()=>this.reconnectAttempt(e));return}let t=this.options.autoReconnect,r=this.room;if(t===void 0||r===null)return;let i=null;try{i=await this.track(this.onceGameIdKnown(()=>ui({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e.matchId,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e.matchId)})));}catch(o){this.reportError("reconcile",o);}if(this.reconnecting(e)){if(i?.status==="ended"){this.endMatch(i.matchId,i.reason,!ul.has(i.reason)),this.track(this.reconcile().catch(()=>{}));return}if(i?.status==="failed"){this.abandonReconnect(e.matchId,i.reason),this.settleFailed(i.matchId,i.reason);return}if(i?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(i);let o;try{o=await t.redial(e.matchId,e.deadlineAt);}catch(s){this.reportError("reconcile",s),o="failed";}if(e.done||this.reconnect!==e)return;if(o==="closed"){this.finishReconnect();return}if(o==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let t=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):t&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new _("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 _("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 _("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:t},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let t=this.heldMatchId;if(t!==null)try{await this.api.leaveMatch(t,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentTicket(){return this.ticketWatch?.ticket??null}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,t){let r=this.emitter.on(e,t);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}handleRoomEvent(e){if(this.ticketWatch!==null&&e.event!=="version_stale"&&e.roomId!==this.room?.id&&this.ticketWatch.poke(),this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let t=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(t).catch(()=>{}));}handleAutoStartFailed(e,t){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(t);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:t,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let i=new AbortController;this.autoStartRetry=i,this.track(this.requestStart({signal:i.signal},false).then(()=>{},o=>{i.signal.aborted||this.reportError("startMatch",o);}).finally(()=>{this.autoStartRetry===i&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!Np.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)return;let e;try{e=await this.myRooms();}catch{return}let t=new Set;for(let r of e)r.status!=="closed"&&(t.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])t.has(r)||this.reported.delete(r);}async reportSeat(e){let t=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||t===null||!r.members.some(i=>i.playerId===t)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.ticketWatch===null&&this.seatPollMs>0&&Ke())){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(),!!Ke())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of sr)e.addEventListener(r,this.visibilityListener);let t=globalThis.document;typeof t?.addEventListener=="function"&&t.addEventListener("resume",this.visibilityListener);}startPolling(e){this.stopPolling(),!this.disposed&&(this.pinnedIntervalMs=e??null,this.polling=true,this.schedule());}stopPolling(){this.pollHandle!==null&&(this.options.clock.clearTimeout(this.pollHandle),this.pollHandle=null),this.polling=false,this.pollIntervalMs=null;}async settled(){for(let e=0;e<20&&this.inFlight.length>0;e++){let t=this.inFlight;this.inFlight=[],await Promise.allSettled(t);}}dispose(){if(this.disposed=true,this.ticketWatch?.abandon(),this.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 sr)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??jp}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new _("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=Zn(this.options.platformGameVersion?.(),t?.gameVersion);if(r===null)throw new _("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 Qs({...t,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return jt(await this.options.resolveClusterTargets());let e=pe(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,t){return !pl(e)||t.length===0?[]:jt(await this.options.refreshClusterTargets?.(t)??[])}async nextCluster(e,t=false){let r=s=>s.find(a=>!e.includes(a)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!t?o:r(jt(await this.options.refreshClusterTargets?.(i)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let t=this.options.resolveParty;if(t===void 0)return e;let r=await t();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,t,r){if(!(e instanceof L)||e.reason!=="conflict"||!Up.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new L(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let i;try{i=await this.leaveAll(t.signal);}catch{throw new L(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(i.length===0)throw new L(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 _("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}assertNotQueued(e){if(!(this.ticketWatch===null&&!this.queueing))throw new _("misconfigured",`${e} refused: this player is waiting on a matchmaking ticket, which will seat them in a room of its own. Cancel it first \u2014 currentTicket.cancel() \u2014 or wait for its outcome.`)}requireRoom(e){if(this.room===null)throw new _("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 L?{operation:e,code:t.status,reason:t.reason,message:t.message,retryable:t.retryable}:{operation:e,code:0,reason:t instanceof _?t.reason:"unavailable",message:t instanceof Error?t.message:String(t),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let t=this.options.ensureLocalServer;t===void 0||!e.selfHosted||e.status!=="open"||t(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,t){this.room=e,this.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(t,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.abortAutoStartRetry(),this.autoStartRetried=false,this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let t=this.room;if(t===null||t.id!==e.id)return;let r=new Map(t.members.map(a=>[a.playerId,a])),i=new Map(e.members.map(a=>[a.playerId,a])),o=this.playerId();for(let a of i.keys())r.has(a)||this.emitter.emit("memberJoined",a);for(let a of r.keys())if(!i.has(a)){if(a===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",a);}for(let[a,l]of i){let d=r.get(a);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",a,l.isReady);}t.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let s=Bp(t,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),s&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let t=this.heldMatchId;t!==null&&t!==e&&this.endMatch(t,"replaced",true),this.session={phase:"starting",matchId:e},this.autoStartRetried=false,this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,t=this.heldMatchId;if(e===null||t===null||this.followAbort!==null&&this.followingMatchId===t)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=t,this.track(this.onceGameIdKnown(()=>this.chase(e.id,t,{signal:r.signal})).then(i=>{if(!r.signal.aborted)try{this.settleOutcome(i);}catch{}}).catch(i=>{r.signal.aborted||this.reportError("pollMatchStatus",i);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let t=this.heldMatchId;if(t!==null)return Promise.resolve(t);let r=e.timeoutMs??qp;return new Promise((i,o)=>{let s=u=>{a(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),u();},a=this.emitter.on("matchAllocationStarted",u=>s(()=>i(u))),l=this.emitter.on("matchFailed",(u,p)=>s(()=>o(new _("allocation_failed",`match ${u} did not come up: ${p}`)))),d=()=>s(()=>o(new _("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>s(()=>o(new _("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??Dp}pushedInterval(){return this.options.pushedPollIntervalMs??Fp}pushed(){return this.options.clock.now()-this.lastPushAt<$p*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=t=>{if(this.ticketWatch?.abandon(true),t?.persisted!==true&&(this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{})),this.queuedFromRoomId!==null)){let r=this.queuedFromRoomId;this.queuedFromRoomId=null,this.track(this.api.leave(r,true,void 0,true).catch(()=>{}));}},e.addEventListener("pagehide",this.unloadListener));}};function Ke(){let n=globalThis.document;return n?.visibilityState===void 0||n.visibilityState==="visible"}var sr=["visibilitychange","focus","pageshow","online"];function Bp(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||ml(n)!==ml(e)}function ml(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function pl(n){return n instanceof L&&n.code==="invalid_cluster_target"}var gl=8;function Vp(n){if(!(Array.isArray(n)&&n.length>=1&&n.length<=gl&&n.every(t=>typeof t=="string"&&t.length>0)))throw new _("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${gl} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function yl(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Hp=["p2p","dedicated","unknown"],Di=["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 ft=class{constructor(e){this.options=e;}options;async post(e,t){let r=this.options.gameId();if(r===null||r==="")return;let i=Wp(e,this.options.transport,(this.options.now??Date.now)());i.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:i},t);}report(e){this.post(e).catch(()=>{});}};function Wp(n,e,t){let r=Math.floor(t/1e3);return n.filter(i=>Di.includes(i.type)).slice(0,100).map(i=>{let o=Kp(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function Kp(n){if(n!==void 0)return Hp.includes(n)?n:"unknown"}var Xt=class{constructor(e){this.options=e;this.reporter=new ft({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,t,r){let i=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:t},r);return {credential:lr(i.credential)??"",hostFingerprint:lr(i.host_fingerprint)??"",hostEpoch:dr(i.host_epoch)??0,expiresAt:(dr(i.expires_at)??0)*1e3}}async turnLease(e,t,r){let i=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:t},r),o=[];for(let l of Array.isArray(i.ice_servers)?i.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(u=>typeof u=="string"&&u.length>0);m.length!==0&&o.push({urls:m,username:lr(d.username)??"",credential:lr(d.credential)??""});}let s=dr(i.expires_at),a=dr(i.ttl_seconds);return {iceServers:o,expiresAt:s!==void 0?s*1e3:Date.now()+(a??0)*1e3}}async kick(e,t,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:t},r);}async leave(e,t=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:t});}async telemetry(e,t){await this.reporter.post(e,t);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function lr(n){return typeof n=="string"&&n.length>0?n:void 0}function dr(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var Jp=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),G=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="P2pError",this.retryable=Jp.has(t);}reason;retryable};var fl=10240,hl=2048,zp=new TextEncoder;function bl(n){return zp.encode(n).length}function qe(n,e){let t=i=>{throw new _("invalid_sdp",`the ${e} ${i}`)},r=bl(n);r>=fl&&t(`is ${r} bytes, over the ${fl} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),n.startsWith("v=")||t("does not start with 'v=', so it is not SDP"),n.includes("\0")&&t("contains a null byte"),/\r(?!\n)/.test(n)&&t("contains a bare carriage return");for(let i of n.split(/\r\n|\n/)){let o=bl(i);o>hl&&t(`has a ${o}-byte line, over the ${hl} limit`);}}function cr(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 ur=class{listeners=new Map;on(e,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>this.off(e,t)}off(e,t){this.listeners.get(e)?.delete(t);}once(e,t){let r=this.on(e,((...i)=>{r(),t(...i);}));return r}emit(e,...t){let r=this.listeners.get(e);if(r)for(let i of [...r])i(...t);}clear(){this.listeners.clear();}};var Yp=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function ht(n){let e=null;for(let t of n.split(/\r\n|\n/)){if(!t.startsWith("a=fingerprint:"))continue;let r=mr(t.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function mr(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 Yp.test(r)?r:null}function Qt(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 Fi=5e3,Xp=12e4+Fi,Qp=1024,Zp=6e4,eg=1e4,vl=64*1024,_l=5;function $i(n){let e=new Map,t=-1/0,r=null,i=(()=>{let a;try{a=new URL(`${n.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return a.username!==""||a.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:a.href,shown:`${a.protocol}//${a.host}`}})(),o=()=>{let a=n.subtle??globalThis.crypto?.subtle;if(!a)throw new G("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return a},s=async()=>{if(!i.ok)throw new G("keys_unavailable",i.reason);let a=n.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await a(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(eg)});}catch{throw new G("keys_unavailable",`the JWKS endpoint at ${i.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new G("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let p=await l.text();if(p.length>vl)throw new G("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${vl} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof G?p:new G("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>_l)throw new G("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${_l} the platform declares. Refusing rather than verifying against a set of unknown size.`);let u=o();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 u.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(a){let l=e.get(a);if(l)return l;if(!i.ok)throw new G("keys_unavailable",i.reason);if(r)return await r,e.get(a)??null;let d=n.now();if(!Number.isFinite(d))throw new G("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<Zp?null:(t=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var Zt=class{seen=new Map;admit(e,t){for(let[r,i]of this.seen)i<=t&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=Qp){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+Xp),true}};function Sl(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return r}function wl(n){try{let e=new TextDecoder().decode(Sl(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function qi(n,e,t,r,i){let o=F=>{throw new G("peer_unauthenticated",`the peer's join credential is not usable: ${F}`)},s=n.split(".");s.length!==3&&o("it is not a three-part JWT");let[a,l,d]=s,m=wl(a);m===null&&o("its header does not decode"),m.alg!=="RS256"&&o(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let u=m.kid;(typeof u!="string"||u.length===0)&&o("it names no key");let p=await t.key(u);p===null&&o("it was signed by a key this build cannot resolve");let g=i.subtle??globalThis.crypto?.subtle;g||o("this environment has no WebCrypto");let y=new TextEncoder().encode(`${a}.${l}`),w;try{w=Sl(d);}catch{o("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,w,y)||o("its signature does not verify");let A=wl(l);A===null&&o("its payload does not decode");let I=A,b=F=>typeof I[F]=="string"?I[F]:"",R=F=>typeof I[F]=="number"&&Number.isFinite(I[F])?I[F]:NaN;b("iss")!==i.issuer&&o("it was issued by someone else"),b("aud")!==`${i.issuer}/p2p-match`&&o("its audience is not this platform"),b("match_id")!==e.matchId&&o("it is for another match"),b("game_id")!==e.gameId&&o("it is for another game");let E=R("exp")*1e3,T=R("nbf")*1e3;(!Number.isFinite(E)||e.now>E+Fi)&&o("it has expired"),Number.isFinite(T)&&e.now<T-Fi&&o("it is not valid yet");let V=b("role");V!=="host"&&V!=="client"&&o("it names no usable role");let B=R("host_epoch");B!==e.hostEpoch&&o("it names a different host epoch");let K=mr(b("fingerprint"));K===null&&o("its fingerprint claim is malformed"),Qt(K,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let x=mr(b("host_fingerprint"));x===null&&o("its host fingerprint claim is malformed"),Qt(x,e.hostFingerprint)||o("it was issued against a different host certificate");let C=b("jti");C.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(C,e.now)||o("it has already been used");let O=b("sub");return O.length===0&&o("it names no player"),{playerId:O.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:B,role:V,fingerprint:K,hostFingerprint:x,jti:C,expiresAt:E}}function ji(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 Ni(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 Ui(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function Bi(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 Rl(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 kl(n){switch(n){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var en=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 Vi={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}},Le=["reliable","ordered","unreliable"];function Hi(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 tn(){let n=globalThis.RTCPeerConnection;return n?.generateCertificate?n.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var Al=1,og=3e4,Pl=2e3,ag=5e3,El=6e4,sg=8,Ki=class{constructor(e=sg){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;}},lg=new Ki,dg=8,cg=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),rn=class{constructor(e){this.options=e;this.keys=e.keys??$i({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new ur;links=new Map;replays=new Zt;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=Al+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??og;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((a,l)=>{this.ready={resolve:a,reject:l};}),i=pe(this.options.clusterTargetId);if(i!==void 0)try{let a=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=a.iceServers,this.mark("turn leased");}catch(a){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${Wi(a)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let o=this.options.clock.setTimeout(()=>{this.fail(new G("timeout",`no usable P2P connection after ${t}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},t),s=()=>this.fail(new G("aborted","the caller aborted while connecting"));e?.aborted?s():e?.addEventListener("abort",s);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",s),this.ready=null;}}async kick(e){if(!this.isHost)throw new G("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=se(e.playerId),r=se(e.hostPlayerId),i=pr(e.hostEpoch);if(!(t===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=t,this.migration===null&&(this.migration=new en(t,r,i)),!this.helloSeen)){if(this.helloSeen=true,this.isHost){this.mark("host listening"),this.settle(),await this.drainPendingOffers();return}this.pendingOffers.clear(),await this.offerToHost("initial");}}async drainPendingOffers(){if(this.pendingOffers.size===0)return;let e=[...this.pendingOffers.values()];this.pendingOffers.clear(),this.mark("queued offer drained");for(let t of e)try{await this.onOffer(t);}catch(r){this.report_(r);}}async offerToHost(e){let t=this.hostPlayerId,r=this.openLink(t,Al),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new G("invalid_sdp","the browser produced an offer with no SDP");qe(o,"offer"),this.refuseMedia(o,"offer"),this.options.signaling.offer(o,e),this.mark("offer sent"),this.fetchCredential().catch(s=>this.report_(s));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,i=r===void 0?null:ht(r);if(i===null)throw new G("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let o=this.options.credentialPacing??lg,s=()=>this.closed||e!==this.credentialGeneration,a=ag;for(;;){let l=o.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,s))return;o.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,i);if(s())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(s())return;let m=d.status,u;if(m===409)u=Pl;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?u=p*1e3:(u=a,a=Math.min(a*2,El)),u=Math.min(Math.max(u,Pl),El);}else throw d;if(!await this.waitForCredential(u,s))return}}}async waitForCredential(e,t){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!t())}async onOffer(e){let t=se(e.fromPlayerId),r=se(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=dg){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(t,e);return}if(!this.isHost||this.migration.isKicked(t)===true)return;let i=se(e.sessionId);if(i!==null&&this.answeredSessions.get(t)===i)return;qe(r,"offer"),this.refuseMedia(r,"offer");let o=ht(r);if(o===null)throw new G("invalid_sdp",`the offer from ${t} carries no usable fingerprint`);this.mark("offer received"),i!==null&&this.answeredSessions.set(t,i);let s=this.links.get(t);s&&this.dropLink(s,"resignalled",false);let a=this.openLink(t,this.nextPeerId++);a.remoteFingerprint=o,await a.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(a);let l=await a.connection.createAnswer();await a.connection.setLocalDescription(l);let d=a.connection.localDescription?.sdp??l.sdp;if(!d)throw new G("invalid_sdp","the browser produced an answer with no SDP");qe(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(t,d,a.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let t=se(e.fromPlayerId),r=se(e.sdp);if(t===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||t!==this.hostPlayerId)return;qe(r,"answer"),this.refuseMedia(r,"answer");let o=ht(r);if(o===null)throw new G("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),i.remoteFingerprint=o,i.pendingAnswer=r,this.hostVerified(i)&&await this.applyAnswer(i,r);}hostVerified(e){let t=this.credential;return t===null||e.remoteFingerprint===null?false:Qt(t.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new G("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=se(e.fromPlayerId),r=se(e.candidate);if(t===null||r===null)return;let i=this.links.get(t);if(!i)return;let o=se(e.sdpMid),s=pr(e.sdpMLineIndex)??pr(e.sdpMLineIndexAlt),a={candidate:r,...o===null?{}:{sdpMid:o},...s===null?{}:{sdpMLineIndex:s}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(a);return}await i.connection.addIceCandidate(a);}onPeerLeft(e){let t=se(e.playerId);if(t===null)return;let r=se(e.reason)??"left";if(t===this.localPlayerId){this.fail(new G("kicked",`this player was removed from the match (${r})`)),this.close();return}let i=this.links.get(t);i&&this.dropLink(i,r,true);}async onMigration(e){let t=se(e.hostPlayerId),r=pr(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:t,hostEpoch:r,...se(e.reason)===null?{}:{reason:se(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(o=>typeof o=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind!=="duplicate"){if(i.kind==="completed"){this.emitter.emit("hostChanged",t,r);return}if(i.kind==="refused"){this.report_(new G("migration_failed",i.why));return}for(let o of [...this.links.values()])this.dropLink(o,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",t,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new G("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=se(e.reason)??"ended";this.ended=t,this.emitter.emit("matchEnded",t),this.ready!==null&&this.fail(new G("match_ended",`the match ended: ${t}`)),this.close();}onSignalingError(e){let t=se(e.code)??"unknown",r=se(e.message)??"the platform refused a signaling message";this.report_(new G("signaling_failed",`${t}: ${r}`));}openLink(e,t){let i=(this.options.peerConnectionFactory??Hi)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let p of Le){let g=i.createDataChannel(p,Vi[p]);g.binaryType="arraybuffer",o[p]=g;}let s={playerId:e,assignedPeerId:t,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=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(s),d=()=>this.onConnectionState(s),m=p=>{this.onHandshakeMessage(s,p.data).catch(g=>this.report_(g));},u=()=>{this.onReliableOpen(s).catch(p=>this.report_(p));};return i.addEventListener("icecandidate",a),i.addEventListener("iceconnectionstatechange",l),i.addEventListener("connectionstatechange",d),o.reliable.addEventListener("open",u),o.reliable.addEventListener("message",m),s.detachHandshake=()=>{o.reliable.removeEventListener("open",u),o.reliable.removeEventListener("message",m);},s.detachAll=()=>{s.detachHandshake(),i.removeEventListener("icecandidate",a),i.removeEventListener("iceconnectionstatechange",l),i.removeEventListener("connectionstatechange",d);},this.links.set(e,s),s}flushCandidates(e){let t=e.pendingCandidates;e.pendingCandidates=[];for(let r of t)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let t=this.credential;if(t===null)throw new G("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 G("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(ji({jwt:t.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,t){if(!(t instanceof ArrayBuffer))return;let r=Bi(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 G(kl(r.reason),Rl(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,t,r){if(r!==32769){this.refuseLink(e,2,"version_mismatch",`it presented protocol version ${r}, not this SDK's ${32769} \u2014 an engine peer cannot join a browser-hosted match`);return}let i=ht(e.connection.localDescription?.sdp??"");if(i===null||e.remoteFingerprint===null){this.refuseLink(e,1,"fingerprint_unavailable","this connection's DTLS fingerprints could not be read from its SDP, so no credential can be checked against it");return}let o;try{o=await qi(t,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:i,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(s){let a=s instanceof G&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",Wi(s)),a&&this.fail(s);return}if(o.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${o.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(o.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(Ni({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,t,r,i){this.warn(`refused to admit ${e.playerId}: ${i}`);try{e.channels.reliable.send(Ui(t));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){let t=e.connection.iceConnectionState;if(!(t!=="failed"&&t!=="disconnected"&&t!=="closed")){if(this.isHost){(t==="failed"||t==="closed")&&this.dropLink(e,t,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,t);}catch(r){this.report_(r);}}}}onConnectionState(e){let t=e.connection.connectionState;t!=="failed"&&t!=="closed"||this.dropLink(e,t,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(t,r="reliable")=>e.channels[r].send(t)}}dropLink(e,t,r){this.links.delete(e.playerId),e.detachAll();for(let i of Le)Tl(e.channels[i]);Tl(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 G?e:new G("connection_failed",Wi(e),{cause:e}));}count(e){this.counted||!cg.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(cr(e))throw new G("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 se(n){return typeof n=="string"&&n.length>0?n:null}function pr(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function Wi(n){return n instanceof Error?n.message:String(n)}function Tl(n){try{n.close();}catch{}}var ug=100,mg=50,on=class{constructor(e){this.options=e;}options;queue=[];drainHandle=null;dropped=0;closed=false;dropListener=null;onDropped(e){this.dropListener=e;}join(){this.assertUsable(),this.options.bridge.signal("join",this.options.matchId,{});}offer(e,t){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:t});}answer(e,t,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:t,assignedPeerId:r});}candidate(e,t,r,i){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??ug)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:t,...r===void 0?{}:{sdpMid:r},...i===void 0?{}:{sdpMLineIndex:i}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,t){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:t,lastSeenAt:Math.floor(this.options.clock.now()/1e3)}});}discardQueued(){this.queue.length=0;}close(){this.closed=true,this.discardQueued(),this.drainHandle!==null&&(this.options.clock.clearTimeout(this.drainHandle),this.drainHandle=null);}assertUsable(){if(this.closed)throw new G("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new G("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId:t,candidate:r,sdpMid:i,sdpMLineIndex:o}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:t,candidate:r,...i===void 0?{}:{sdpMid:i},...o===void 0?{}:{sdpMLineIndex:o}});}if(this.dropped>0&&this.queue.length===0){let t=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(t),this.dropListener?.(t);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??mg));}};function H(n){return e=>typeof e=="string"&&e.length>0&&e.length<=n?e:void 0}function je(n,e){return t=>typeof t=="number"&&Number.isInteger(t)&&t>=n&&t<=e?t:void 0}function bt(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function Il(n){return typeof n=="boolean"?n:void 0}var be=H(64),an=je(0,2147483647);function Ji(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(e.length>=64)break;let r=be(t);typeof r=="string"&&e.push(r);}return e}function J(n,e,t){return {to:n,from:e,read:t,required:true}}function W(n,e,t){return {to:n,from:e,read:t,required:false}}var yg=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=bt("disconnected","failed","closed")(e.iceState),r=je(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:[J("sdp","sdp",H(10240)),J("signaling_intent","intent",bt("initial","ice_restart","full_reconnect")),W("sdp_hash","sdpHash",H(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[J("peer_id","peerId",be),J("sdp","sdp",H(10240)),J("assigned_peer_id","assignedPeerId",je(0,4294967295)),W("sdp_hash","sdpHash",H(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[J("peer_id","peerId",be),J("candidate","candidate",H(512)),W("sdp_mid","sdpMid",H(64)),W("sdp_mline_index","sdpMLineIndex",je(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[J("host_epoch","hostEpoch",an)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[J("host_epoch","hostEpoch",an),W("evidence","evidence",yg)]}}));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:[J("playerId","player_id",be),J("hostPlayerId","host_player_id",be),J("hostEpoch","host_epoch",an),W("members","members",Ji)],offer:[J("fromPlayerId","from_player_id",be),J("sdp","sdp",H(10240)),W("sessionId","signaling_session_id",H(128)),W("sdpHash","sdp_hash",H(128)),W("iceUfrag","ice_ufrag",H(64)),W("intent","signaling_intent",bt("initial","ice_restart","full_reconnect"))],answer:[J("fromPlayerId","from_player_id",be),J("sdp","sdp",H(10240)),W("sessionId","signaling_session_id",H(128)),W("sdpHash","sdp_hash",H(128)),W("iceUfrag","ice_ufrag",H(64)),W("assignedPeerId","assigned_peer_id",je(0,4294967295))],ice:[J("fromPlayerId","from_player_id",be),J("candidate","candidate",H(512)),W("sdpMid","sdp_mid",H(64)),W("sdpMLineIndex","sdp_m_line_index",je(0,255)),W("sdpMLineIndexAlt","sdp_mline_index",je(0,255))],peerJoined:[J("playerId","player_id",be)],peerLeft:[J("playerId","player_id",be),W("reason","reason",H(64))],migration:[J("hostPlayerId","new_host_player_id",be),J("hostEpoch","host_epoch",an),W("reason","reason",H(64)),W("kickedPlayerIds","kicked_player_ids",Ji),W("migrationComplete","migration_complete",Il)],matchEnded:[W("reason","reason",H(64))],error:[W("code","code",H(64)),W("message","message",H(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 ze="webrtc_p2p";function Ml(n){let e=new Xt({client:n.client,gameId:n.gameId}),t=new Map;return {handleSignalEvent(r,i,o){t.get(r)?.handleSignal(i,o);},session(r){return t.get(r)??null},async connect(r={}){if(n.bridge===null)throw new G("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See docs/p2p-and-parties.md \xA72.");let i=pe(r.clusterTargetId),o=i??pe(await n.resolveClusterTarget?.());n.rooms.isHost&&n.rooms.currentMatch===null&&n.rooms.currentRoom?.matchId===void 0&&await n.rooms.startMatch({...i===void 0?{}:{clusterTargetId:i},...r.signal===void 0?{}:{signal:r.signal}});let s=await n.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(s.protocol!==ze)throw new G("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${ze}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new on({bridge:n.bridge,matchId:s.matchId,clock:n.clock}),l=new rn({api:e,clock:n.clock,matchId:s.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:a,...o===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await tn(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...n.boot===void 0?{}:{boot:n.boot},...n.log===void 0?{}:{log:n.log}});a.onDropped(d=>l.notifyCandidatesDropped(d)),t.set(s.matchId,l),l.on("matchEnded",()=>t.delete(s.matchId));try{await l.start(r.signal);}catch(d){throw t.delete(s.matchId),l.close(),d}return l}}}function Ol(n){let{analytics:e,rooms:t}=n,r=n.target??globalThis,i=n.document??globalThis.document,o=[];if(typeof r.addEventListener=="function"){let a=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",a),o.push(()=>r.removeEventListener?.("pagehide",a));let l=()=>e.setHidden(!Ke());for(let d of sr)r.addEventListener(d,l),o.push(()=>r.removeEventListener?.(d,l));typeof i?.addEventListener=="function"&&(i.addEventListener("resume",l),o.push(()=>i.removeEventListener?.("resume",l))),e.setHidden(!Ke());}let s=new Map;return o.push(t.on("matchReady",a=>{let l=a.protocol===ze?"p2p":"dedicated";s.set(a.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),o.push(t.on("matchEnded",a=>{let l=s.get(a.matchId);l!==void 0&&(s.delete(a.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let a of o.splice(0))try{a();}catch{}s.clear();}}var Ll=["pointerdown","keydown"];function Gl(n,e=globalThis){let t=false,r=false,i=null,o=()=>{if(i!==null){try{e.cancelAnimationFrame?.(i);}catch{}i=null;}},s=()=>{if(!r){r=true,o();for(let g of Ll)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},a=()=>{if(!(t||r)){t=true,s();try{n();}catch{}}};function l(g){g?.isTrusted===true&&a();}let d=()=>{let g;try{g=e.navigator?.getGamepads?.()??[];}catch{return false}return g.some(y=>y?.buttons.some(w=>w.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},u=()=>{if(i=null,!(t||r)){if(d()){a();return}m()&&(i=e.requestAnimationFrame?.(u)??null);}};function p(){i===null&&!t&&!r&&u();}if(typeof e.addEventListener=="function"){for(let g of Ll)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),m()&&(i=e.requestAnimationFrame?.(u)??null);}return {get engaged(){return t},stop:s}}async function gr(n,e,t,r){let i=await t;return n.mark(e)&&r&&r(`[gem] boot: ${n.timeline()}`),i}function zi(n,e){let t=false;return async r=>{let i=await r;return !t&&e&&(t=true,e(`[gem] boot: ${n.timeline()}`)),i}}function Yi(n={}){let e=n.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),t=[],r=new Set;return {marks:t,mark(i,o){return r.has(i)?false:(r.add(i),t.push({name:i,at:o??e()}),true)},timeline(){let i=[...t].sort((o,s)=>o.at-s.at);return i.map((o,s)=>{let a=i[s-1],l=a===void 0?"":` (+${Math.round(o.at-a.at)}ms)`;return `${o.name}@${Math.round(o.at)}ms${l}`}).join(" \u2192 ")}}}var fg="GemWebSdkHandshake";var hg=()=>Date.now();function Dl(n,e,t={}){let r=n[fg];if(r===void 0)return null;let i=t.ttlMs??9500,o=t.now??hg,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,m=false,u=o()-i;for(let p=s.length-1;p>=0;p--){let g=a?.[p];if(g!==void 0&&g<u){d+=1;continue}if(l+=1,e(s[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}var Xi=false;async function jl(n,e,t,r){if(Xi){e.close(),t("busy",true);return}Xi=true;let i=null;try{let o=await vg(n,r);if(typeof o=="string"){e.close(),t(o,bg(o));return}i=o;let a=await(r.encodeRef??(l=>Rg(l,r)))(i);if(i.close(),i=null,a===null){e.close(),t("failed",!0);return}if(a.size>Sg){e.close(),t("too_large",!1);return}e.postMessage(a);}catch(o){e.close(),t("failed",true),console.error("[gem] screenshot capture failed",o);}finally{Xi=false,i?.close();}}function bg(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 vg(n,e){if(e.handler){let o=await e.handler(n);return o===null?"declined":Fl(o,n)}if(!e.useDefaultStrategy)return "not_wired";let t=e.documentRef??globalThis.document;if(!t)return "no_source";let r=wg(t);if(!r)return "no_source";let i=_g(r);if(i!==null)return i;try{return Fl(await createImageBitmap(r),n)}catch(o){if(o instanceof DOMException&&o.name==="SecurityError")return "tainted";throw o}}function _g(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 wg(n){let e=null,t=0;for(let r of Array.from(n.querySelectorAll("canvas"))){let i=r.width*r.height;i<=0||r.clientWidth<=0||r.clientHeight<=0||i>t&&(e=r,t=i);}return e}async function Fl(n,e){let{maxWidth:t,maxHeight:r}=e;if(n.width<=t&&n.height<=r)return n;let i=Math.min(t/n.width,r/n.height),o=Math.max(1,Math.floor(n.width*i)),s=Math.max(1,Math.floor(n.height*i));try{let a=await createImageBitmap(n,{resizeWidth:o,resizeHeight:s,resizeQuality:"high"});return n.close(),a}catch{return n.close(),"too_large"}}var Sg=8*1024*1024,$l="image/webp",ql=.92;async function Rg(n,e){try{if(typeof OffscreenCanvas=="function"){let o=new OffscreenCanvas(n.width,n.height),s=o.getContext("2d");if(s){s.drawImage(n,0,0);let a=await o.convertToBlob({type:$l,quality:ql});if(a&&a.size>0)return a}}}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 i=r.getContext("2d");return !i||(i.drawImage(n,0,0),typeof r.toBlob!="function")?null:await new Promise(o=>{r.toBlob(s=>o(s),$l,ql);})}async function Nl(n,e){if(!e)return;let t;try{t=await kg(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 kg(n){return new Promise((e,t)=>{let r=false,i=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(o=>{r||(r=true,clearTimeout(i),e(o??null));},o=>{r||(r=true,clearTimeout(i),t(o instanceof Error?o:new Error(String(o))));});})}var Ul=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function Bl(n=globalThis){let t=n[Ul];if(t!==void 0)return t;let r=false,i=()=>r,o=[],s=xg(n,i);s!==null&&o.push(s);let a=Ag(n,i);a!==null&&o.push(a);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let u of o)u();}}};return Object.defineProperty(n,Ul,{value:l,configurable:true}),l}function xg(n,e){let t=n.AudioNode?.prototype,r=n.AudioDestinationNode;if(t===void 0||r===void 0)return null;let i=n.OfflineAudioContext,o=t.connect,s=t.disconnect,a=new Map,l=m=>{let u=m.gain,p=m.context.currentTime;u.cancelScheduledValues(p),e()?u.setValueAtTime(0,p):u.setTargetAtTime(1,p,.01);},d=m=>{let u=m.context;if(i!==void 0&&u instanceof i)return null;let p=a.get(u);return p===void 0&&(p=u.createGain(),p.gain.value=e()?0:1,o.call(p,m),a.set(u,p)),p};return t.connect=function(...u){let[p,...g]=u;if(p instanceof r){let y;try{y=d(p);}catch{y=null;}if(y!==null)return o.call(this,y,...g),p}return o.apply(this,u)},t.disconnect=function(...u){let[p,...g]=u;if(p instanceof r){let y=a.get(p.context);if(y!==void 0&&y!==this)try{return s.call(this,y,...g)}catch{}}return s.apply(this,u)},()=>{for(let[m,u]of a){if(m.state==="closed"){a.delete(m);continue}try{l(u);}catch{}}}}function Ag(n,e){let t=n.HTMLMediaElement;if(t===void 0)return null;let r=t.prototype,i=Object.getOwnPropertyDescriptor(r,"muted"),o=i?.get,s=i?.set;if(o===void 0||s===void 0)return null;let a=r.play,l=new WeakMap,d=new WeakSet,m=new Set,u=p=>{l.has(p)||l.set(p,!!o.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),s.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:i?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!o.call(this):p},set(p){l.set(this,!!p),u(this);}}),r.play=function(){try{u(this);}catch{}return a.call(this)},n.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof t)try{u(g);}catch{}},true),()=>{for(let p of m){let g=p.deref();if(g===void 0){m.delete(p);continue}try{s.call(g,(l.get(g)??!1)||e());}catch{}}}}var Pg=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",Eg=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',Tg=`${Pg}${Eg}`,Qi=new WeakSet;function Vl(n=globalThis.document){if(n==null||Qi.has(n))return null;try{let e=n.defaultView?.CSSStyleSheet??globalThis.CSSStyleSheet;if(Array.isArray(n.adoptedStyleSheets)&&typeof e=="function"){let r=new e;if(typeof r.replaceSync=="function")return r.replaceSync(Tg),n.adoptedStyleSheets=[...n.adoptedStyleSheets,r],Qi.add(n),"sheet"}let t=n.documentElement?.style;return t===void 0||typeof t.setProperty!="function"?null:(t.setProperty("-webkit-user-select","none"),t.setProperty("user-select","none"),t.setProperty("-webkit-tap-highlight-color","transparent"),Qi.add(n),"inline")}catch{return null}}function Hl(n){let e=n.windowMs??1e3,t=n.realm??globalThis,r=false,i=false,o=false,s=null,a=null,l=null,d=[],m=()=>r&&!i&&!o,u=()=>{a=null,l=null,d=[];},p=w=>{if(s=null,!m()){u();return}if(l!==null&&d.push(w-l),l=w,a===null)a=w;else {let S=w-a;S>=e&&d.length>0&&(n.report(Ig(d,S)),a=w,d=[]);}g();},g=()=>{let w=t.requestAnimationFrame;typeof w=="function"&&(s=w.call(t,p));},y=()=>{if(m()){s===null&&(u(),g());return}s!==null&&(t.cancelAnimationFrame?.call(t,s),s=null),u();};return {setRequested(w){r=w,y();},setPaused(w){i=w,y();},get running(){return s!==null},dispose(){o=true,y();}}}function Ig(n,e){let t=[...n].sort((i,o)=>i-o),r=Math.max(1,Math.ceil(t.length*.95));return {fps:n.length*1e3/e,frameTimeP95Ms:t[r-1]}}var yr=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function Kl(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function Jl(n,e){n!==null&&(n.style.setProperty(yr.top,`${e.top}px`),n.style.setProperty(yr.right,`${e.right}px`),n.style.setProperty(yr.bottom,`${e.bottom}px`),n.style.setProperty(yr.left,`${e.left}px`));}var Wl=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height"}});function zl(){let n=globalThis,e=n.innerWidth,t=n.innerHeight;return typeof e=="number"&&e>0&&typeof t=="number"&&t>0?{width:e,height:t}:null}function Cg(n,e){let t={tl:{width:0,height:0},tr:{width:0,height:0},bl:{width:0,height:0},br:{width:0,height:0}};for(let r of n){let i=e?r.x+r.width/2<=e.width/2:r.x===0,o=e?r.y+r.height/2<=e.height/2:r.y===0,s=i?r.x+r.width:e?e.width-r.x:r.width,a=o?r.y+r.height:e?e.height-r.y:r.height,l=t[`${o?"t":"b"}${i?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(s)),l.height=Math.max(l.height,Math.ceil(a));}return t}function Yl(n,e,t){if(n===null)return;let r=Cg(e,t);for(let i of ["tl","tr","bl","br"])n.style.setProperty(Wl[i].width,`${r[i].width}px`),n.style.setProperty(Wl[i].height,`${r[i].height}px`);}var Mg=3e4,fr=class extends Error{retryable;reason;constructor(e,t,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=t;}};function Xl(n){let e=n.clock??le,t=n.timeoutMs??Mg,r=new Map,i=new Map,o=0,s=a=>{let l=r.get(a);return l?(r.delete(a),i.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return n.bridge.parentSupports("localHost")},ensure(a){if(!n.bridge.parentSupports("localHost"))return Promise.resolve();let l=i.get(a);if(l)return l;let d=new Promise((m,u)=>{let p=`ls${++o}`,g=e.setTimeout(()=>{r.delete(p),i.delete(a),u(new fr("timeout",true,`the embedder did not answer a local-server request for room ${a} within ${String(t)}ms`));},t);r.set(p,{room:a,resolve:m,reject:u,timer:g}),n.bridge.requestLocalServer(p,a)||(s(p),m());});return i.set(a,d),d.catch(()=>{}),d},accept(a){s(a.requestId)?.resolve();},refuse(a){let l=s(a.requestId);l&&l.reject(new fr(a.reason,a.retryable,a.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 sn={url:"https://downloads.indiegems.games/sdk/v10.1.1/gem-web-sdk.devtools.min.js",integrity:"sha384-CbOy0XkXE8Dpcz3OxKKFeFABWmpTVAwwFTOYscMb369dXSZzd/VuGedsAxcY0lQF"};var _t=null;function Og(){return _t!==null||(_t=new Promise((n,e)=>{let t=document.createElement("script");t.src=sn.url,t.integrity=sn.integrity,t.crossOrigin="anonymous",t.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){_t=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${sn.url} is not a gem-web-sdk devtools build.`));return}n(r);},t.onerror=()=>{_t=null,e(new Error(`gem devtools: could not load ${sn.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);})),_t}function Ql(n,e){let t=null,r=0;async function i(o){if(t!==null)return true;let s=++r;if(!e())return false;let a=await Og();return !e()||s!==r?false:(t!==null||(t=a.mount(n(),{openedBy:o,text:Ue,onDismiss:()=>{t?.unmount(),t=null;}})),true)}return {get isOpen(){return t!==null},close(){r+=1,t?.unmount(),t=null;},open:()=>i("game"),openFrom:i}}var Lg=1e4,Zl={reason:"unavailable",retryable:false};function ed(n){let e=new Map,t=null,r=null,i=0,o=(d,m)=>{m.timer=n.clock.setTimeout(()=>{e.delete(d),m.reject({reason:"timeout",retryable:true});},n.timeoutMs??Lg);},s=(d,m)=>{let u=a(d);u&&m(u);},a=d=>{let m=e.get(d);return m?(e.delete(d),n.clock.clearTimeout(m.timer),m):null},l=new at({clock:n.clock,onStateChange:n.onStateChange,request:d=>new Promise((m,u)=>{let p=n.bridge.currentState;if(p==="refused"||p==="closed"){u(Zl);return}let g=`t${++i}`,y={resolve:m,reject:u,reason:d,timer:null,held:p!=="connected"};e.set(g,y),o(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)){s(d.requestId,u=>u.resolve(m));return}l.accept(m);},onDenied(d){s(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,u]of e)u.held&&(u.held=false,n.clock.clearTimeout(u.timer),o(m,u),n.bridge.requestToken(m,u.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])s(m,u=>u.reject(Zl));},get identity(){return t},get gameVersion(){return r}}}function Gg(n){let e=n.lastIndexOf("@");return (e===-1?n:`***@${n.slice(e+1)}`).slice(0,200)}var Dg=new Set(vn);function Fg(n){if(!n)return {};let e={};for(let[t,r]of Object.entries(n))Dg.has(t.toLowerCase())&&(e[t.toLowerCase()]=r);return e}function hr(n){let e=n.fetch??globalThis.fetch.bind(globalThis);return $o(async(t,r)=>{let i;try{i=new URL(n.baseUrl.replace(/\/+$/,""));}catch{throw new ie("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 o;try{o=new URL(i.href.replace(/\/+$/,"")+t.path);}catch{throw new ie(`${JSON.stringify(typeof t.path=="string"?Gg(t.path):"(a non-string path)")} does not form a valid URL against ${i.protocol}//${i.host}. This is a malformed request, not a server failure.`)}if(o.protocol!==i.protocol||o.host!==i.host)throw new ie(`${JSON.stringify(o.pathname)} resolves to ${o.protocol}//${o.host}, not ${i.protocol}//${i.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(o.username!==""||o.password!==""){let g=i.username!==""||i.password!=="",y=o.username!==i.username||o.password!==i.password,w=g?y?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new ie(`the ${w} puts credentials in the URL, which cannot be fetched (${t.method} ${o.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??{}))o.searchParams.has(g)||o.searchParams.set(g,y);let s=t.bytes,a=t.bytes===void 0?void 0:"application/octet-stream";try{t.body!==void 0&&(s=JSON.stringify(t.body),a="application/json");}catch(g){throw new ie(`the body of ${t.method} ${JSON.stringify(o.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(o.toString(),{method:t.method,headers:{authorization:`Bearer ${r}`,...a===void 0?{}:{"content-type":a},...Fg(t.headers)},body:s,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"),u=$g(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...u===void 0?{}:{retryAfterSeconds:u},...p===null||p===""?{}:{invocationId:p}}},n)}function $g(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 qg=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),eo="embedder_relay_unavailable",jg="embedder_no_relay",Ng=new Set([eo]),to=new Set([jg]),ln=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new Zi(this)}handleEvent(e){let t=this.pending.get(e.matchId);if(t!==void 0){if(e.event==="matchEnded"){t.refuse(new _("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 _("signaling_failed","the parent relayed an answer with no SDP in it"));return}t.settle({sdp:e.sdp});return}t.refuse(Ug(e.code,e.message));}}register(e,t){this.pending.get(e)?.refuse(new _("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 _("signaling_unavailable","this game is not running inside a page that holds the player's notification socket, so there is nothing to carry an offer. Dedicated signaling needs that socket and only the page can hold one \u2014 see docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new _("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See docs/dedicated-server-flow.md \xA72.");return e}};function Ug(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new _(Bg(n),r,{platformCode:n})}function Bg(n){return n===void 0||Ng.has(n)?"signaling_failed":to.has(n)?"offer_refused":qg.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var Zi=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,t){if(this.closed)return Promise.reject(new _("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(i){return Promise.reject(i)}return t?.aborted?Promise.reject(new _("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let s=()=>{a(),o(new _("aborted","the caller aborted the signaling exchange"));},a=()=>{t?.removeEventListener("abort",s),this.hub.release(e.matchId,l),this.teardown===a&&(this.teardown=null);},l={settle:d=>{a(),i(d);},refuse:d=>{a(),o(d);}};this.teardown=a,t?.addEventListener("abort",s),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof _?d:new _("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var td="match_ended:",nd="server_shutdown:",rd="kicked:",Vg=123;function Hg(n){if(typeof n!="string"||n.length===0||n.length>Vg)return {kind:"other"};if(n.startsWith(td)){let e=$e(n.slice(td.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(nd)?{kind:"server_shutdown",cause:n.slice(nd.length)}:n.startsWith(rd)?{kind:"kicked",detail:n.slice(rd.length)}:{kind:"other"}}function no(n,e,t){let r=Hg(t),i=r.kind==="kicked"?"kicked":"link_closed";n.notifyMatchDisconnected(i).catch(()=>{}),r.kind==="match_ended"&&n.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}function ro(){return {exchange(){return Promise.reject(new _("signaling_unavailable","no signaling channel is wired. The exchange rides the notification WebSocket, and POST /v1/ws/ticket accepts only account credentials \u2014 a game frame holds a game-scoped token and cannot mint one \u2014 so it has to be relayed by the page embedding this game. Run inside a parent that advertises `dedicated`, or pass your own `signaling` implementation. See docs/dedicated-server-flow.md \xA72."))},close(){}}}var Wg=3e3,Kg=1e4,Jg=15e3;async function br(n){let e=n.peerConnection;try{od(n,"before the handshake started"),io(n);let t=e.createDataChannel(n.channelLabel??"gem",{ordered:!0});for(let s of n.extraChannels??[]){let a=e.createDataChannel(s.label,{...s.ordered===void 0?{}:{ordered:s.ordered},...s.maxRetransmits===void 0?{}:{maxRetransmits:s.maxRetransmits}});n.onExtraChannel?.(s.label,a);}let r=await e.createOffer();await e.setLocalDescription(r),await Xg(e,n),io(n);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new _("invalid_sdp","the offer carried no SDP");qe(i,"offer"),id(i,"offer");let o=await Yg(n,i);if(io(n),typeof o?.sdp!="string")throw new _("invalid_sdp","the signaling channel answered without an SDP");return qe(o.sdp,"answer"),id(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await Qg(t,n),od(n,"before the channel opened"),t}catch(t){throw e.close(),zg(t)}}function zg(n){return n instanceof _?n:ld(n)?Ye():new _("connection_failed",dd(n),{cause:n})}function id(n,e){if(cr(n))throw new _("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 Yg(n,e){let t=n.exchangeTimeoutMs??Kg,r=sd(n,t),i=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(o=>{throw o instanceof _?o:ld(o)?Ye():new _("signaling_failed",dd(o),{cause:o})});return Zg(i,n,r,()=>r.exhausted?oo("while the offer was in flight"):new _("timeout",`no answer arrived within ${t}ms`))}function Xg(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let i=()=>{t.clearTimeout(s),n.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{n.iceGatheringState==="complete"&&i();},s=t.setTimeout(i,e.gatherTimeoutMs??Wg);n.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function Qg(n,e){if(e.signal?.aborted)return Promise.reject(Ye());if(n.readyState==="open")return Promise.resolve();if(n.readyState!=="connecting")return Promise.reject(new _("connection_failed",`the data channel was already '${n.readyState}' when the answer was applied`));let{clock:t}=e,r=e.openTimeoutMs??Jg,i=sd(e,r);return new Promise((o,s)=>{let a=()=>{t.clearTimeout(p),n.removeEventListener("open",l),n.removeEventListener("close",d),n.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{a(),o();},d=g=>{a(),s(new _("connection_failed","the data channel failed before it opened",ad(g)===void 0?void 0:{cause:ad(g)}));},m=()=>{a(),s(Ye());},u=()=>{a(),s(i.exhausted?oo("while the channel was still opening"):new _("timeout",`the data channel did not open within ${r}ms`));},p=t.setTimeout(u,i.ms);n.addEventListener("open",l),n.addEventListener("close",d),n.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function sd(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 Zg(n,e,t,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(Ye()):new Promise((s,a)=>{let l=u=>{i.clearTimeout(m),o?.removeEventListener("abort",d),u();},d=()=>l(()=>a(Ye())),m=i.setTimeout(()=>l(()=>a(r())),t.ms);o?.addEventListener("abort",d),n.then(u=>l(()=>s(u)),u=>l(()=>a(u)));})}function od(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw oo(`already ${e}`)}function oo(n){return new _("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 Ye()}function Ye(){return new _("aborted","the caller aborted the connection attempt")}function ld(n){return n?.name==="AbortError"}function ad(n){return n?.error}function dd(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:[J("sdp","sdp",H(10240)),W("sessionId","session_id",H(64))],error:[W("code","code",H(64)),W("message","message",H(256))],matchEnded:[W("reason","reason",H(64))]}));function hd(n){let{client:e,clock:t,rooms:r}=n,i=n.signaling??ro,o=n.log??(b=>console.warn(b)),s=new ft({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,l=(b,R)=>{let E=a.get(b)??new Set;E.add(R),a.set(b,E);},d=(b,R)=>{let E=a.get(b);E!==void 0&&(E.delete(R),E.size===0&&a.delete(b));},m=async b=>{if(r.isHost&&!so(r)&&r.currentRoom?.matchId===void 0){let R=pe(b.clusterTargetId);await r.startMatch({...R===void 0?{}:{clusterTargetId:R},...b.retry===void 0?{}:{retry:b.retry},...b.signal===void 0?{}:{signal:b.signal}});}return yd(r.matchConnectionState==="suspended"?await r.reconnectToMatch(ao(b)):await r.awaitMatch(ao(b)))},u=async b=>yd(await r.pollMatchStatus(ao(b))),p=async(b,R)=>{let E=false;try{let T=await m(b),V=r.currentRoom?.transports;if(V!==void 0&&!V.includes("webrtc"))throw new _("misconfigured",`the room template offers (${V.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 B=b.peerConnection??fd();E=!0;let K=await br({peerConnection:B,signaling:R,clock:t,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,...vr(b,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),x=null;if(b.presentCredential!==!1)try{x=await Ut({channel:K,clock:t,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,...vr(b,"onMessage","signal"),...b.welcomeTimeoutMs===void 0?{}:{ceilingMs:b.welcomeTimeoutMs}});}catch(C){throw Re(K),Re(B),C}return ly(r,T,K,B,R,b.reportDisconnect!==!1,b.reportConnected!==!1,x,{remember:l,forget:d},b.onMatchEnded)}catch(T){throw E&&gd(s,T),Re(R),T}},g=async(b,R,E,T,V,B)=>{if(b==="webtransport"){let N=T?.webtransport;if(N===void 0)throw new _("misconfigured","webtransport is not advertised");let q={credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:t};if(typeof N.named_url=="string"&&N.named_url!==""){let Z=Math.max(Math.floor(B/2),1e3);try{return await Wt({url:N.named_url,timeoutMs:Z,log:o,...q})}catch(ge){if(or()!==null)throw ge;return o(`[gem] webtransport named dial failed (${rr(ge)}); retrying the pinned dial`),Wt({url:N.url,certHashBase64:N.cert_sha256_b64,timeoutMs:Z,log:o,...q})}}return Wt({url:N.url,certHashBase64:N.cert_sha256_b64,timeoutMs:B,...q})}if(b==="websocket"){let N=T?.websocket;if(N===void 0)throw new _("misconfigured","websocket is not advertised");return Pi({url:N.url,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:t,timeoutMs:B})}let K=R.peerConnection??fd(),x,C=await br({peerConnection:K,signaling:V,clock:t,matchId:E.matchId,credentialExpiresAt:E.credentialExpiresAt,extraChannels:[{label:Vt,ordered:false,maxRetransmits:0}],onExtraChannel:(N,q)=>{N===Vt&&(x=q);},...vr(R,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...R.exchangeTimeoutMs===void 0&&R.redial===true?{exchangeTimeoutMs:ny}:{}}),O;try{O=await Ut({channel:C,clock:t,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,wire:nr,heartbeat:!0,...vr(R,"signal"),...R.welcomeTimeoutMs===void 0?{}:{ceilingMs:R.welcomeTimeoutMs}});}catch(N){throw Re(C),Re(K),N}let F=O.welcome.heartbeatIntervalMs;return {link:Ti(C,K,x,F===void 0?void 0:{clock:t,intervalMs:F}),welcome:O.welcome,channel:C,peerConnection:K}},y=(b,R,E,T,V)=>{let B=false,K;T.link.onClose(F=>{!B&&b.reportDisconnect!==false&&no(r,R.matchId,F),K?.(F);}),b.reportDisconnect!==false&&b.reportConnected!==false&&r.notifyMatchConnected(R.matchId);let x={transport:T.link.transport,send:(F,N)=>T.link.send(F,N),onMessage:F=>T.link.onMessage(F),onClose:F=>{K=F;},close:()=>T.link.close()},C=()=>{B||(B=true,Re(T.link),Re(V));},O=F=>{if(!B){try{b.onMatchEnded?.(F);}catch{}C();}};return l(R.matchId,O),{matchId:R.matchId,transport:E,link:x,joinCredential:R.joinCredential,credentialExpiresAt:R.credentialExpiresAt,welcome:T.welcome,...T.channel===void 0?{}:{channel:T.channel},...T.peerConnection===void 0?{}:{peerConnection:T.peerConnection},close(){d(R.matchId,O),C();}}},w=async(b,R)=>{let E=r.currentRoom?.id,T=r.gameId,V=()=>({advert:Ht(r.currentRoom?.settings,b),template:r.currentRoom?.transports??null});if(E===void 0||T===null)return V();try{let B=await e.get(`/v2/games/${encodeURIComponent(T)}/game-rooms/${encodeURIComponent(E)}`,R);return {advert:Ht(B.settings,b),template:gt(B.transports)??r.currentRoom?.transports??null}}catch{return V()}},S=(b,R)=>{let E=b??cd;return R.length===0?E:E.filter(T=>R.includes(T))},A=async(b,R,E)=>{try{let T=await m(b),{advert:V,template:B}=await w(T.matchId,b.signal),K=S(B,R),x=K.filter(X=>oy(X,V)),C=or();if(C!==null&&K.includes("webtransport")&&V?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${C} (learned on an earlier dial in this page)`),x.length===0){let X=B===null?`the default order (${cd.join(", ")})`:`the room template's transports (${B.join(", ")||"none"})`;throw new _("misconfigured",`none of ${X}`+(R.length>0?`, narrowed to (${R.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let O=b.transportAttemptTimeoutMs??ty,F=()=>b.deadlineAt===void 0?1/0:b.deadlineAt-t.now(),N=X=>n.signalingReady===void 0||X<=0?Promise.resolve(!0):n.signalingReady(X),q=[],Z=[];for(let X of x){if(F()<md){o(`[gem] ${X} rung not tried: the reconnect budget is spent`);break}Z.length>0&&T.credentialExpiresAt-t.now()<pd&&(T=await u(b)),Z.push(X);let Me=!1,ue=!1,ke={attempts:0,waitedMs:0};for(;;){if(X==="webrtc"&&b.redial===!0){let ne=Math.min(ud,F());await N(ne)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(ne)}ms; offering anyway`);}let Oe=Math.max(Math.min(O,F()),md);try{return y(b,T,X,await g(X,b,T,V,E,Oe),E)}catch(ne){let z=ne instanceof _?ne:new _("connection_failed",ne instanceof Error?ne.message:String(ne),{cause:ne});if(X==="webrtc"&&gd(s,z),(z.reason==="credential_expired"||z.reason==="credential_reused")&&!Me){Me=!0,T=await u(b);continue}if(X==="webrtc"&&z.reason==="signaling_failed"&&z.platformCode===eo&&!ue){ue=!0;let de=Math.min(ud,F());if(o(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(de)}ms for the socket before offering again`),await N(de))continue}if(z.reason==="join_rate_limited"){let de=iy(ke,Math.random,F());if(de!==null){if(ke.attempts+=1,ke.waitedMs+=de,o(`[gem] ${X} rung: the server is rate-limiting this player's joins; waiting ${Math.round(de)}ms before presenting again (retry ${ke.attempts} of ${vd.maxAttempts})`),await Qn(t,de,b.signal),b.signal?.aborted)throw new _("aborted","the caller aborted while waiting out a join rate limit");T.credentialExpiresAt-t.now()<pd&&(T=await u(b));continue}}if(ry.has(z.reason)||z.reason==="credential_expired"||X==="webrtc"&&bd(z)){o(`[gem] ${X} rung failed (${z.reason}): ${rr(z.cause??z)} \u2014 `+(Z.length<x.length?`falling through to ${x[Z.length]}`:"no rungs left")),q.push(z);break}throw o(`[gem] ${X} rung refused the session (${z.reason}): ${z.message}`),z}}}let ge=q[q.length-1];throw ge===void 0?new _("timeout",`the reconnect budget ran out before any transport (${x.join(", ")}) could be tried`):new _(ge.reason,`every transport tried (${Z.join(", ")}) failed; the last said: ${ge.message}`,{cause:q,platformCode:ge.platformCode})}catch(T){throw Re(E),T}};return {listClusterTargets:async(b={})=>mi({client:e,...b}),handleMatchEnded(b,R){let E=a.get(b);if(E!==void 0){a.delete(b);for(let T of E)T(R);}},connect:(async(b={})=>{let R=b.signaling??i();return b.transports===void 0?p(b,R):A(b,b.transports,R)})}}var cd=["webtransport","webrtc","websocket"],ty=1e4,ny=5e3,ud=3e3,md=1e3,pd=1e4,ry=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function bd(n){return n.platformCode!==void 0&&to.has(n.platformCode)}var vd={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function iy(n,e=Math.random,t=1/0){let r=vd;if(n.attempts>=r.maxAttempts)return null;let i=Math.min(r.budgetMs-n.waitedMs,t);if(i<r.initialDelayMs)return null;let o=r.initialDelayMs*r.factor**n.attempts;return Math.min(o+e()*r.jitterMs,i)}function oy(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&ir():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||ay(e.websocket.url)}function ay(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return Pn(e)}function ao(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var sy=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function gd(n,e){e instanceof _&&(!sy.has(e.reason)&&!bd(e)||n.report([{type:"connection_failures_total",value:1}]));}function ly(n,e,t,r,i,o,s,a,l,d){let m=false,u=()=>{m||no(n,e.matchId,void 0);};o&&(t.addEventListener("close",u),s&&n.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,t.removeEventListener("close",u),a?.detach(),Re(t),Re(r),Re(i));},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:a?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function so(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function yd(n){if(n.status==="failed")throw new _("allocation_failed",`match ${n.matchId} did not come up: ${n.reason}`);if(n.status==="ended")throw new _("match_ended",`match ${n.matchId} ended (${n.reason}) before this side connected.`);if(n.protocol!==Xn)throw new _("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${Xn}' 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 _("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 fd(){let n=globalThis.RTCPeerConnection;if(!n)throw new _("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 Re(n){try{n.close();}catch{}}function vr(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var dy=1e4;function _d(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=s=>({token:s.token,expiresAt:s.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,i=new at({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((s,a)=>{let l=e.clock.setTimeout(()=>{r=null,a({reason:"unavailable",retryable:true});},e.timeoutMs??dy);r={resolve:d=>{e.clock.clearTimeout(l),s(d);},reject:a,timer:l};})}),o=n.onServerToken(s=>{let a=t(s),l=r;if(l){r=null,l.resolve(a);return}i.accept(a);});return {source:i,dispose(){o(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var uo={};lc(uo,{acceptTransfer:()=>cy,addEntityProgression:()=>uy,adminAction:()=>my,cancelInventoryTransfer:()=>py,claimEntityProgressionRewards:()=>gy,closeGameRoom:()=>yy,createEntityBatchOrder:()=>fy,createEntityOrder:()=>hy,createSession:()=>by,deleteEntityGameSetting:()=>vy,deleteEntitySave:()=>_y,deleteSession:()=>wy,deleteShowcaseValue:()=>Sy,executeEntityRecipe:()=>Ry,finalizeSaveUpload:()=>ky,getChannelAssignment:()=>xy,getDropRates:()=>Ay,getEntityCurrency:()=>Py,getEntityGameSetting:()=>Ey,getEntityInventory:()=>Ty,getEntityInventoryItem:()=>Iy,getEntityLeaderboard:()=>Cy,getEntityOrder:()=>My,getEntityProgression:()=>Oy,getEntityRecipeAvailability:()=>Ly,getEntityRecipeUsage:()=>Gy,getEntitySave:()=>Dy,getEvent:()=>Fy,getGameRoomV2:()=>$y,getLeaderboard:()=>qy,getPlayerGameProfile:()=>jy,getPurchaseCatalog:()=>Ny,getResolvedTemplate:()=>Uy,getRoomArgs:()=>By,getShowcaseValue:()=>Vy,getTransferDetails:()=>Hy,ingestAnalyticsEvents:()=>co,initiateInventoryTransfer:()=>Wy,invokeFunction:()=>Ky,kickPlayer:()=>Jy,listChallenges:()=>zy,listEntityGameSettings:()=>Yy,listEntityOrders:()=>Xy,listEntityProgressions:()=>Qy,listEntitySaves:()=>Zy,listEvents:()=>ef,listGameRooms:()=>tf,listResolvedTemplates:()=>nf,listTransfers:()=>rf,maxEntityProgression:()=>of,putEntityGameSetting:()=>af,putRoomArgs:()=>sf,putShowcaseValue:()=>lf,rejectTransfer:()=>df,requestSaveUploadUrl:()=>cf,resetEntityProgression:()=>uf,simulateEntityOrder:()=>mf,transferHostV2:()=>pf,updateGameRoomV2:()=>gf});function h(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 cy(n,e,t){let r=`/v1/inventory/transfers/${h(e)}/accept`;return n.client.post(r,void 0,t?.signal)}async function uy(n,e,t,r,i,o){let s=`/v1/inventory/${h(e)}/${h(t)}/progressions/${h(r)}/add`;return n.client.post(s,i,o?.signal)}async function my(n,e,t,r){let i=`/v1/voice/sessions/${h(e)}/admin`;return n.client.post(i,t,r?.signal)}async function py(n,e,t){let r=`/v1/inventory/transfers/${h(e)}/cancel`;return n.client.post(r,void 0,t?.signal)}async function gy(n,e,t,r,i,o){let s=`/v1/inventory/${h(e)}/${h(t)}/progressions/${h(r)}/claim`;return n.client.post(s,i,o?.signal)}async function yy(n,e,t){let r=`/v1/games/${h(n.gameId())}/game-rooms/${h(e)}`;return n.client.delete(r,t?.signal)}async function fy(n,e,t,r,i){let o=`/v1/inventory/${h(e)}/${h(t)}/orders/batch`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function hy(n,e,t,r,i){let o=`/v1/inventory/${h(e)}/${h(t)}/orders`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function by(n,e,t){return n.client.post("/v1/voice/sessions",e,t?.signal)}async function vy(n,e,t,r,i){let o=`/v1/settings/${h(e)}/${h(t)}/${h(r)}`;return n.client.delete(o,i?.signal)}async function _y(n,e,t,r,i){let o=`/v1/saves/${h(e)}/${h(t)}/${h(r)}`;return n.client.delete(o,i?.signal)}async function wy(n,e,t){let r=`/v1/voice/sessions/${h(e)}`;return n.client.delete(r,t?.signal)}async function Sy(n,e,t,r){let i=`/v1/showcase/players/${h(e)}/${h(t)}`;return n.client.delete(i,r?.signal)}async function Ry(n,e,t,r,i){let o=`/v1/inventory/${h(e)}/${h(t)}/recipes/execute`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ky(n,e,t,r,i,o){let s=`/v1/saves/${h(e)}/${h(t)}/${h(r)}/finalize`;return n.client.post(s,i,o?.signal)}async function xy(n,e,t){let r=`/v1/games/${h(n.gameId())}/config/channels/${h(e)}`;return n.client.getWithEtag(r,{...t?.signal===void 0?{}:{signal:t.signal},...t?.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}})}async function Ay(n,e,t){let r=`/v1/inventory/loot-tables/${h(e)}/drop-rates`;return n.client.get(r,t?.signal)}async function Py(n,e,t,r,i){let o=`/v1/inventory/${h(e)}/${h(t)}/currencies/${h(r)}`;return n.client.get(o,i?.signal)}async function Ey(n,e,t,r,i){let o=`/v1/settings/${h(e)}/${h(t)}/${h(r)}`;return n.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Ty(n,e,t,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),s=`/v1/inventory/${h(e)}/${h(t)}`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function Iy(n,e,t,r,i){let o=`/v1/inventory/${h(e)}/${h(t)}/items/${h(r)}`;return n.client.get(o,i?.signal)}async function Cy(n,e,t,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let s=o.toString(),a=`/v1/leaderboards/${h(e)}/${h(t)}/${h(r)}`+(s?`?${s}`:"");return n.client.get(a,i?.signal)}async function My(n,e,t,r,i){let o=`/v1/inventory/${h(e)}/${h(t)}/orders/${h(r)}`;return n.client.get(o,i?.signal)}async function Oy(n,e,t,r,i){let o=`/v1/inventory/${h(e)}/${h(t)}/progressions/${h(r)}`;return n.client.get(o,i?.signal)}async function Ly(n,e,t,r,i,o){let s=`/v1/inventory/${h(e)}/${h(t)}/catalogs/${h(r)}/recipes/${h(i)}/availability`;return n.client.get(s,o?.signal)}async function Gy(n,e,t,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${h(e)}/${h(t)}/recipe-usage`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function Dy(n,e,t,r,i){let o=`/v1/saves/${h(e)}/${h(t)}/${h(r)}`;return n.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Fy(n,e,t){let r=`/v1/events/${h(e)}`;return n.client.get(r,t?.signal)}async function $y(n,e,t){let r=`/v2/games/${h(n.gameId())}/game-rooms/${h(e)}`;return n.client.getWithEtag(r,{...t?.signal===void 0?{}:{signal:t.signal},...t?.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}})}async function qy(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)),t?.periods_back!==void 0&&r.set("periods_back",String(t?.periods_back)),t?.period!==void 0&&r.set("period",String(t?.period)),t?.player_id!==void 0&&r.set("player_id",String(t?.player_id));let i=r.toString(),o=`/v1/leaderboards/${h(e)}`+(i?`?${i}`:"");return n.client.get(o,t?.signal)}async function jy(n,e,t){let r=`/v1/profiles/players/${h(e)}`;return n.client.get(r,t?.signal)}async function Ny(n,e){let t=new URLSearchParams;e?.config_version!==void 0&&t.set("config_version",String(e?.config_version));let r=t.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Uy(n,e,t){let r=`/v1/game-room-templates/${h(e)}`;return n.client.get(r,t?.signal)}async function By(n,e,t){let r=`/v1/games/${h(n.gameId())}/game-rooms/${h(e)}/room-args`;return n.client.get(r,t?.signal)}async function Vy(n,e,t,r){let i=`/v1/showcase/players/${h(e)}/${h(t)}`;return n.client.get(i,r?.signal)}async function Hy(n,e,t){let r=`/v1/inventory/transfers/${h(e)}`;return n.client.get(r,t?.signal)}async function co(n,e,t){let r=`/v1/games/${h(n.gameId())}/analytics/events`;return n.client.post(r,e,t?.signal,{replaySafe:true})}async function Wy(n,e,t){return n.client.post("/v1/inventory/transfers",e,t?.signal)}async function Ky(n,e,t){return n.client.postBytes("/v1/functions/invoke",e,t?.signal)}async function Jy(n,e,t,r){let i=`/v1/games/${h(n.gameId())}/game-rooms/${h(e)}/kick/${h(t)}`;return n.client.post(i,void 0,r?.signal)}async function zy(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(),i="/v1/challenges"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Yy(n,e,t,r){let i=`/v1/settings/${h(e)}/${h(t)}`;return n.client.get(i,r?.signal)}async function Xy(n,e,t,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/inventory/${h(e)}/${h(t)}/orders`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function Qy(n,e,t,r){let i=`/v1/inventory/${h(e)}/${h(t)}/progressions`;return n.client.get(i,r?.signal)}async function Zy(n,e,t,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/saves/${h(e)}/${h(t)}`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function ef(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(),i="/v1/events"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function tf(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(),i=`/v1/games/${h(n.gameId())}/game-rooms`+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function nf(n,e){return n.client.get("/v1/game-room-templates",e?.signal)}async function rf(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(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function of(n,e,t,r,i,o){let s=`/v1/inventory/${h(e)}/${h(t)}/progressions/${h(r)}/max`;return n.client.post(s,i,o?.signal)}async function af(n,e,t,r,i,o){let s=`/v1/settings/${h(e)}/${h(t)}/${h(r)}`;return n.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function sf(n,e,t,r){let i=`/v1/games/${h(n.gameId())}/game-rooms/${h(e)}/room-args`;return n.client.put(i,t,r?.signal)}async function lf(n,e,t,r,i){let o=`/v1/showcase/players/${h(e)}/${h(t)}`;return n.client.put(o,r,i?.signal)}async function df(n,e,t){let r=`/v1/inventory/transfers/${h(e)}/reject`;return n.client.post(r,void 0,t?.signal)}async function cf(n,e,t,r,i,o){let s=`/v1/saves/${h(e)}/${h(t)}/${h(r)}/upload-url`;return n.client.post(s,i,o?.signal,{replaySafe:true})}async function uf(n,e,t,r,i,o){let s=`/v1/inventory/${h(e)}/${h(t)}/progressions/${h(r)}/reset`;return n.client.post(s,i,o?.signal)}async function mf(n,e,t,r,i){let o=`/v1/inventory/${h(e)}/${h(t)}/orders/simulate`;return n.client.post(o,r,i?.signal)}async function pf(n,e,t,r){let i=`/v2/games/${h(n.gameId())}/game-rooms/${h(e)}/transfer/${h(t)}`;return n.client.post(i,void 0,r?.signal)}async function gf(n,e,t,r){let i=`/v2/games/${h(n.gameId())}/game-rooms/${h(e)}`;return n.client.patch(i,t,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var yf=1e4,ff=50,hf=1e3,bf=65536-4*1024,wd=n=>typeof n=="number"?n:0,vf=n=>typeof n=="string"?n:"";function Sd(){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 _f(n){return n?.retryable===true}function wf(n,e){let t=n??{},r=Array.isArray(t.rejected)?t.rejected.map(i=>{let o=i??{};return {index:wd(o.index),code:vf(o.code)}}):[];return {accepted:wd(t.accepted),rejected:r,dropped:e,duplicate:t.duplicate===true}}function Rd(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 kd(n){let e=Math.max(1,Math.floor(n.maxQueue??hf)),t={client:n.client,gameId:()=>n.gameId},r=[],i=0,o=null,s=false,a=false,l=false,d=false,m=w=>{n.log?.(w);},u=()=>{o!==null&&(n.clock.clearTimeout(o),o=null);},p=()=>{o!==null||s||a||(o=n.clock.setTimeout(()=>{o=null,y().catch(()=>{});},yf));},g=()=>{let w=Math.min(r.length,100),S=128;for(let A=0;A<w;A+=1){let I=r[A];if(I===void 0)break;if(S+=JSON.stringify(Rd(I,0)).length+1,S>bf)return Math.max(1,A)}return w};async function y(w){if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};u();let S=r.splice(0,g()),A=i;i=0;let I=Math.round(n.clock.now()),b={batch_id:Sd(),sent_at_ms:I,events:S.map(R=>Rd(R,I))};a=true;try{let R=await co(t,b,w===void 0?void 0:{signal:w}),E=wf(R,A);for(let T of E.rejected)m(`[gem] analytics: an event was refused (${T.code}). See the analytics_events section of your game config.`);return E}catch(R){if(_f(R))for(r=[...S,...r],i+=A;r.length>e;)r.shift(),i+=1;else m(`[gem] analytics: ${S.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(R)}`);throw R}finally{a=false,r.length>0&&p();}}return {track(w,S,A={}){if(s)return;if(typeof w!="string"||w===""){d||(d=true,m(`[gem] analytics: '${S}' 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(S.startsWith(ni)){l||(l=true,m(`[gem] analytics: '${S}' 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 I={},b={};for(let[R,E]of Object.entries(A))typeof E=="string"?I[R]=E:typeof E=="number"&&Number.isFinite(E)&&(b[R]=E);for(;r.length>=e;)r.shift(),i+=1;r.push({uid:Sd(),playerId:w,name:S,atMs:n.clock.now(),dimensions:I,measures:b}),r.length>=ff?y().catch(()=>{}):p();},flush:w=>y(w),get pending(){return r.length},dispose(){s=true,u(),r=[],i=0;}}}function xd(n){return {async list(e){let{playerId:t,periodsBack:r,signal:i}=e??{};if(typeof t!="string"||t==="")throw new TypeError("gem.challenges.list needs { playerId }: a game-server token names no player, so the platform cannot tell whose period you mean. Pass the id from join() or gem.players().");ut(r);let o=await n({player_id:t,...r===void 0?{}:{periods_back:r},...i===void 0?{}:{signal:i}});return Hn(o)}}}function Sf(n){let e={};for(let[t,r]of Object.entries(uo))if(typeof r=="function"){let i=r;e[t]=(...o)=>i(n,...o);}return e}function wt(n,e={}){let t=e.clock??le,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 i=lo(n,{clock:t,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),o=hr({baseUrl:r,tokenSource:i.source,defaultQuery:{game_id:n.gameId,channel:n.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),s=new Ge({transport:o,clock:t}),a={gameId:n.gameId,channel:n.channel,matchId:n.matchId,...n.gameRoomId===void 0?{}:{gameRoomId:n.gameRoomId}},l=Sf({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,m=n.endMatch,u=n.log,p=kd({client:s,clock:t,gameId:a.gameId,...typeof u=="function"?{log:y=>u.call(n,y)}:{}});return {identity:a,client:s,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 Fe(l.invokeFunction),challenges:xd(l.listChallenges),...d===void 0?{}:{room:{get:y=>l.getGameRoomV2(d,y),args:async y=>{let w=await l.getGameRoomV2(d,y?.signal===void 0?{}:{signal:y.signal}),S=w.modified?w.body:void 0;if(S?.room_args==null||S.room_args_template==null)throw new L("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:S.room_args,room_args_template:S.room_args_template}}}},dispose:()=>{p.dispose(),i.dispose();}}}function Xe(n){return n?.reliable!==false?"reliable":n?.ordered!==false?"ordered":"unreliable"}function St(n){return {reliable:n==="reliable",ordered:n!=="unreliable"}}function dn(n){return typeof n=="string"?n:n.slice().buffer}function _r(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 Rf=5e3,Ad=3e4,Pd=2e3,kf=1e4,Ed=1;async function Td(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 i=e.log===void 0?f=>console.info(f):e.log,o=f=>i?.(`[gem host] ${f}`),s=typeof n=="function"?n():n,a=Promise.resolve(),l=true,d=false,m=(f,M)=>{l&&(a=a.then(async()=>{if(!d)try{await M();}catch($){o(`the bundle's ${f} handler threw: ${Qe($)}. Serving continues.`);}}));},u=true,p,g,y,w=f=>{if(!u)return;u=false,m("leave",()=>s.leave?.(r,{cause:f??"left"}));let M=g;M&&queueMicrotask(()=>M(f));},S={send(f,M){if(!u)return;let $=St(Xe(M));m("message",()=>s.message?.(r,f,typeof f=="string",{reliable:$.reliable,ordered:$.ordered}));},onMessage(f){p=f;},onClose(f){g=f;},close(){w("closed");}},A=(f,M)=>{if(!u)return;let $=St(Xe(M));queueMicrotask(()=>{u&&p?.(f,$);});},I=new Map,b=f=>{let M=[];for(let $ of Le){let re=f.channels[$];try{re.binaryType="arraybuffer";}catch{}let _e=St($),tt=j=>{let nt=_r(j?.data);nt!==null&&m("message",()=>s.message?.(f.playerId,nt.data,nt.isText,{reliable:_e.reliable,ordered:_e.ordered}));};re.addEventListener("message",tt),M.push(()=>re.removeEventListener("message",tt));}I.get(f.playerId)?.forEach($=>$()),I.set(f.playerId,M);},R=f=>{I.get(f)?.forEach(M=>M()),I.delete(f);},E=new Set,T=new Map,V=(f,M,$)=>({playerNumber:f.assignedPeerId,transport:"webrtc_p2p",...M?{rejoin:true}:{},...$?{superseded:true}:{}}),B=f=>{let M=I.has(f.playerId),$=E.has(f.playerId);E.add(f.playerId),b(f),M&&m("leave",()=>s.leave?.(f.playerId,{cause:"superseded"})),m("join",()=>s.join?.(f.playerId,V(f,$,M)));},K=new Set,x=(f,M,$)=>{if(f===r){A(M,$);return}let re=t.peer(f);if(re===null){let _e=T.get(f);if(_e!==void 0&&e.clock.now()-_e<Pd)return;K.has(f)||(K.add(f),o(`send to '${f}' dropped: no such connected player`));return}re.send(dn(M),Xe($));},C={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=u?[r]:[];for(let M of t.peers)f.push(M.playerId);return f},profile(f){let M=e.room()?.members.find($=>$.playerId===f);if(!(!M||M.displayName===void 0))return {displayName:Ue.toPlain(M.displayName),...M.displayTag===void 0?{}:{displayTag:Ue.toPlain(M.displayTag)},...M.discriminator===void 0?{}:{discriminator:M.discriminator}}},playerNumber(f){return f===r?Ed:t.peer(f)?.assignedPeerId},send(f,M,$){x(f,M,$);},broadcast(f,M){let $=M?.except;u&&r!==$&&A(f,M);for(let re of t.peers)re.playerId!==$&&re.send(dn(f),Xe(M));},async endMatch(){let f=await Oe();return f.answer!=="ok"&&o(f.cause),f.answer},kick(f,M){if(f===r){w(M??"kicked");return}t.kick(f).catch($=>{o(`kick of '${f}' failed: ${Qe($)}`);});},log(f){o(f);},warn(f){o(`\u26A0 ${f}`);}},O=()=>{},F=new Promise(f=>{O=f;}),N=[],q=null,Z=async(f,M)=>{l=false;let $=a.then(async()=>{try{await s.shutdown(f);}catch(re){o(`the bundle's shutdown threw: ${Qe(re)}`);}});a=$,await $,de();for(let re of N.splice(0))re();for(let re of [...I.keys()])R(re);w(M);},ge=(f,M)=>q||(q=(async()=>{await Z(M,f),t.close(),O();})(),q),X=()=>q||(q=(async()=>{await Z({reason:"signal"},"left"),await t.leave().catch(f=>o(`leaving the match failed: ${Qe(f)}`)),O();})(),q),Me=()=>q||(q=(async()=>{l=false;let f=await Oe();f.answer==="ok"?(await Z({reason:"match_ended",platform_reason:"explicit"},"match ended"),t.close()):(o(`${f.cause}; leaving instead`),await Z({reason:"signal"},"left"),await t.leave().catch(M=>o(`leaving the match failed: ${Qe(M)}`))),O();})(),q),ue=null,ke=()=>(ue??=wt(C,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),ue),Oe=async()=>{try{return await $a({client:ke().client,gameId:()=>C.gameId},C.matchId,{},{signal:AbortSignal.timeout(Rf)}),{answer:"ok"}}catch(f){return f instanceof L&&(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: ${Qe(f)}`}}},ne=null,z=false,de=()=>{z=true,ne!==null&&(e.clock.clearTimeout(ne),ne=null);},gn=async()=>{if(ne=null,!z){try{await ke().client.post(`/v1/games/${encodeURIComponent(C.gameId)}/matches/${encodeURIComponent(C.matchId)}/heartbeat`,void 0,AbortSignal.timeout(kf));}catch(f){if(f instanceof L&&(f.reason==="forbidden"||f.reason==="not_found")){o(`the platform no longer holds this match under this host (${f.reason}); heartbeats stop`),de();return}o(`heartbeat failed: ${Qe(f)}`);}z||(ne=e.clock.setTimeout(()=>{gn();},Ad));}},Rt=()=>{z||ne!==null||(ne=e.clock.setTimeout(()=>{gn();},Ad));};{let f=O;O=()=>{de(),ue?.dispose(),ue=null,f();};}let et=Promise.resolve().then(()=>s.init(C));a=et.then(()=>{},()=>{}),m("join",()=>s.join?.(r,{playerNumber:Ed,transport:"loopback"})),N.push(t.on("peerJoined",B)),N.push(t.on("peerLeft",(f,M)=>{R(f);let $=e.clock.now();for(let[re,_e]of T)$-_e>=Pd&&T.delete(re);T.set(f,$),K.delete(f),m("leave",()=>s.leave?.(f,{cause:M}));})),N.push(t.on("error",f=>{o(`\u26A0 session error: ${f.message}`);})),N.push(t.on("matchEnded",f=>{q||mo(y,f),ge("match ended",{reason:"match_ended",platform_reason:f});})),N.push(t.on("hostChanged",f=>{f!==r&&ge("host migrated",{reason:"host_migrated"});}));for(let f of t.peers)B(f);try{await et,Rt();}catch(f){l=false,de(),d=true;for(let M of N.splice(0))M();for(let M of [...I.keys()])R(M);throw t.leave().catch(()=>{}),O(),f}return {matchId:t.matchId,localLink:S,onMatchEnded(f){y=f;},end:Me,leave:X,stop:f=>ge(f,{reason:"stopped"}),done:F}}function mo(n,e){try{n?.(e);}catch{}}function Qe(n){return n instanceof Error?n.message:String(n)}function po(n,e){let t=async()=>{throw new _("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 Id(n){let e=new Map,t=n.autoReconnect===true,{rooms:r}=n,i=new Map,o=async a=>{r.isHost&&!so(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...a.signal===void 0?{}:{signal:a.signal}});let l={...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},s=a=>({...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0?{}:{clusterTargetId:a.clusterTargetId}});return {async serve(a,l={}){let d=await o(l);if(d.protocol!==ze)return po("dedicated",d.matchId);let m=n.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return po("peer",d.matchId);let u=n.identity();if(u===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(s(l)),g=await Td(a,{session:p,clock:n.clock,gameId:u.gameId,channel:u.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:n.apiBaseUrl(),tokens:n.tokens,room:n.room,localPlayerId:p.playerId!==""?p.playerId:u.playerId,...n.log===void 0?{}:{log:n.log},...n.fetch===void 0?{}:{fetch:n.fetch}});return i.set(d.matchId,g),g.done.then(()=>{i.get(d.matchId)===g&&i.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(a={}){let l=await o(a),d=a.onMatchEnded;if(l.protocol===ze){let g=i.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),Ef(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 tn(),w=async()=>n.p2p.connect({...s(a),certificate:y}),S=await w(),A=If(S,w,d,I=>{r.notifyMatchDisconnected(I).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),t);return t&&(e.set(S.matchId,{redial:A.redial,abandon:A.abandon}),A.onClosed(()=>{e.get(S.matchId)?.abandon===A.abandon&&e.delete(S.matchId);})),A}let m=async(g=null)=>await n.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:a.transports??[]}),u=await m(),p=Tf(u,m,r,t);return t&&(e.set(u.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(u.matchId)?.abandon===p.abandon&&e.delete(u.matchId);})),p},async redialMatch(a,l){let d=e.get(a);return d===void 0?"closed":d.redial(l)},abandonMatch(a,l){e.get(a)?.abandon(l);}}}var Cd="link_closed",xf="host_unreachable",Af=new Set(["failed","closed"]);function Pf(n){return Af.has(n)?Cd:xf}function Ef(n,e,t){let r=e.localLink;e.onMatchEnded(t);let i="connected";r.onClose(()=>{i="closed";});let o;return {matchId:n,protocol:"loopback",get state(){return i},send:(s,a)=>r.send(s,a),onMessage:s=>r.onMessage(s),onClose:s=>{o=s,r.onClose(a=>{i="closed",o?.(a);});},close:()=>r.close()}}function Tf(n,e,t,r){let i=n.matchId,o=n,s="connected",a,l,d=[],m=false,u=false,p=y=>{if(s!=="closed"){s="closed";for(let w of d.splice(0))w();l?.(y);}},g=y=>{y.link.onMessage((w,S)=>a?.(w,S)),y.link.onClose(w=>{if(y!==o||s==="closed")return;if(m||!r){p(w);return}let S=t.matchSession;if(S.phase==="suspended"&&S.matchId===i){s="suspended";return}p(w);});};return g(n),{matchId:i,protocol:"dedicated",get transport(){return o.transport},get state(){return s},send(y,w){s==="connected"&&o.link.send(y,w);},onMessage(y){a=y;},onClose(y){l=y;},close(){if(s!=="closed"){if(m=true,s==="suspended"){p("closed");return}o.close(),p("closed");}},async redial(y){if(s==="closed"||m)return "closed";if(u)return "connected";u=true;let w;try{w=await e(y===void 0?{}:{deadlineAt:y});}finally{u=false;}return m||s==="closed"?(w.close(),"closed"):(o=w,g(w),s="connected",t.notifyMatchConnected(i),"connected")},abandon(y){s!=="closed"&&(s==="connected"&&o.close(),p(y));},onClosed(y){s==="closed"?y():d.push(y);}}}function If(n,e,t,r,i,o=false){let s=n.matchId,a=n,l,d,m=[],u=[],p=[],g=false,y=false,w=false,S=false,A="connected",I=x=>{if(g)return;g=true,A="closed";for(let O of m.splice(0))O();for(let O of u.splice(0))O();for(let O of p.splice(0))O();let C=d;C&&queueMicrotask(()=>C(x));},b=x=>{for(let C of m.splice(0))C();for(let C of Le){let O=x.channels[C];try{O.binaryType="arraybuffer";}catch{}let F=St(C),N=q=>{let Z=_r(q?.data);Z!==null&&l?.(Z.data,F);};O.addEventListener("message",N),m.push(()=>O.removeEventListener("message",N));}},R=()=>a.peer(a.hostPlayerId),E=x=>{if(!(g||a.isHost)&&A!=="suspended"){if(r?.(x),o){A="suspended";return}I(x);}},T=x=>{for(let C of Le){let O=x.channels[C];if(typeof O.addEventListener!="function")continue;let F=()=>{R()===x&&E(Cd);};O.addEventListener("close",F),m.push(()=>O.removeEventListener?.("close",F));}},V=x=>{b(x),T(x),!g&&(A="connected",i?.());},B=x=>{for(let C of u.splice(0))C();u.push(x.on("migrating",()=>{S=true;})),u.push(x.on("hostChanged",C=>{if(S=false,C===x.playerId){I("host_migrated_here");return}let O=R();O!==null&&V(O);})),u.push(x.on("peerJoined",C=>{C.playerId===x.hostPlayerId&&V(C);})),u.push(x.on("matchEnded",C=>{g||mo(t,C),I(C);})),u.push(x.on("peerLeft",(C,O)=>{C===x.hostPlayerId&&E(Pf(O));}));};B(a);let K=R();return K!==null&&V(K),{matchId:s,protocol:"p2p",get state(){return A},send(x,C){A==="connected"&&R()?.send(dn(x),Xe(C));},onMessage(x){l=x;},onClose(x){d=x;},close(){y=true,I("closed"),a.leave().catch(()=>{});},async redial(){if(A==="closed")return "closed";if(A==="connected"||w)return "connected";if(S)throw new G("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 x;try{for(let O of m.splice(0))O();for(let O of u.splice(0))O();a.close(),x=await e();}finally{w=false;}if(g)return y?x.leave().catch(()=>{}):x.close(),"closed";a=x,B(a);let C=R();if(C===null)throw a.close(),new G("connection_failed","this peer rejoined the match but the host never answered with a link");return V(C),"connected"},abandon(x){I(x);},onClosed(x){g?x():p.push(x);}}}function go(n){let e=0,t=new Map;return {resolve(){if(!n.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(i=>{let o={},s=l=>{t.delete(r)&&(n.clock.clearTimeout(o.timer),i(l));};t.set(r,s),o.timer=n.clock.setTimeout(()=>s(void 0),n.timeoutMs??2e3);let a=false;try{a=n.bridge.requestParty(r);}catch{}a||s(void 0);})},settle(r,i){t.get(r)?.(i);}}}var Cf=12e4;function Ze(n,e){return {outcome:n,reason:e}}function Md(n){let e=false,t=new Map;return {api:{request(r){if(!n.bridge.parentSupports("purchases"))return Promise.resolve(Ze("unavailable","error"));if(e)return Promise.resolve(Ze("declined","busy"));let i=`purchase-${Ee()}`;return new Promise(o=>{let s={},a=d=>{t.delete(i)&&(e=false,n.clock.clearTimeout(s.timer),o(d));};e=true,t.set(i,a),s.timer=n.clock.setTimeout(()=>a(Ze("unavailable","error")),n.timeoutMs??Cf);let l=false;try{l=n.bridge.requestPurchase(i,r.kind,r.targetId,r.currencySlug,r.quantity,r.catalogId);}catch{}l||a(Ze("unavailable","error"));})}},settle(r){let i=r.outcome==="ok"||r.outcome==="declined"?r.outcome:"unavailable",o=t.get(r.requestId);if(o===void 0){n.onDropped?.(`gem.purchaseResult (${i}) for an unknown requestId: `+JSON.stringify(r.requestId));return}if(i!=="ok"){o(Ze(i,is(r.reason)));return}let s=r.purchaseId;if(s===void 0){n.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),o(Ze("unavailable","error"));return}(async()=>{let a;try{a=await n.confirm(s);}catch{a="unknown";}if(a==="granted"){o({outcome:"ok",purchaseId:s});return}a==="absent"&&n.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for purchase "+JSON.stringify(s)),o(Ze("unavailable","error"));})();}}}async function Od(n,e){try{return (await _a(n,e)).granted?"granted":"absent"}catch(t){return t instanceof L&&t.reason==="not_found"?"absent":"unknown"}}var Mf=6e5;function Ld(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-${Ee()}`;return e=new Promise(i=>{let o={},s=l=>{t.delete(r)&&(e=null,n.clock.clearTimeout(o.timer),i(l));};t.set(r,s),o.timer=n.clock.setTimeout(()=>{s({outcome:"unavailable"});},n.timeoutMs??Mf);let a=false;try{a=n.bridge.requestSignIn(r);}catch{}a||s({outcome:"unavailable"});}),e}},settle(r){let i=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",o=t.get(r.requestId);if(o===void 0){n.onDropped?.(`gem.signInResult (${i}) for an unknown requestId: `+JSON.stringify(r.requestId));return}o({outcome:i});}}}var Of=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),Lf=["utm_"];function Gd(n){return Of.has(n)||Lf.some(e=>n.startsWith(e))}var Dd=16,Fd=512,Gf=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Df=/[\p{Cc}\p{Cf}]/u,Ff=/\p{Cs}/u,Ce="[gem] gem.share.request:";function $d(n){let{frame:e,log:t}=n,r=false,i=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,o=s=>{t!==null&&(t===void 0?console.warn(s):t(s));};return {get available(){return i()!==null},request(s){let a=i();if(a===null)throw new Error(`${Ce} the arcade does not handle share here \u2014 check gem.share.available first`);if(s!==void 0&&(typeof s!="object"||s===null))throw new TypeError(`${Ce} pass { params }, or nothing`);let l=s?.params===void 0?{}:s.params;if(!$f(l))throw new TypeError(`${Ce} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>Dd)throw new TypeError(`${Ce} at most ${Dd} params; got ${d.length}`);let m=[];for(let[u,p]of d){let g=JSON.stringify(u);if(!Gf.test(u))throw new TypeError(`${Ce} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(Gd(u))throw new TypeError(`${Ce} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Ce} param ${g}: values must be strings`);if(p.length>Fd)throw new TypeError(`${Ce} param ${g}: a value is at most ${Fd} characters`);if(Df.test(p))throw new TypeError(`${Ce} param ${g}: control and format characters are not allowed`);if(Ff.test(p))throw new TypeError(`${Ce} param ${g}: a value must be well-formed text`);m.push({key:u,value:p});}!a.requestShare(m)&&!r&&(r=true,o("[gem] gem.share.request was not sent: more than 6 share requests in a minute. Call it from your Share button's click, not a loop."));}}}function $f(n){if(typeof n!="object"||n===null||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}var Uf="(any-pointer: coarse)";function Bf(n){let e=Array.isArray(n)?n:[n],t=[],r=1e4;for(let i of e){if(typeof i!="number"||!Number.isFinite(i)||i<0)return null;if(t.length===99||r===0)continue;let o=Math.min(Math.trunc(i),1e4,r);t.push(o),r-=o;}return t.length%2===0&&t.pop(),t.every(i=>i===0)?[]:t}function qd(n){let{frame:e,log:t}=n,r=n.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?m=>matchMedia(m):void 0},i=r.navigator,o,s=new Set,a=()=>typeof i?.vibrate!="function"||r.matchMedia===void 0?false:(o??=r.matchMedia(Uf),o.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(m,u)=>{s.has(m)||(s.add(m),t!==null&&(t===void 0?console.warn(u):t(u)));};return {get available(){return a()||l()},vibrate(m){let u=a();if(!u&&!l())return false;let p=Bf(m);if(p===null)return d("pattern","[gem] gem.vibration.vibrate did nothing: a pattern is a number of milliseconds, or an array of them, each finite and not negative."),false;if(i?.userActivation?.hasBeenActive!==true)return d("activation","[gem] gem.vibration.vibrate did nothing: the player has not tapped or pressed a key in your game yet, and browsers allow vibration only after that."),false;if(u)try{return i.vibrate(p)===!0}catch{return false}let g=e.requestVibrate(p);return g||d("rate","[gem] gem.vibration.vibrate was not sent: more than 600 vibrations in a minute. Vibrate on events, not every frame."),g}}}var Vf=/(?:Z|[+-]\d{2}:?\d{2})$/i;function jd(n){if(typeof n!="string"||!Vf.test(n))return;let e=Date.parse(n);return Number.isFinite(e)&&e>0?e:void 0}function cn(){return {declared:false,grantable:false,heldLimitReached:false}}function Nd(n,e){let t=typeof n=="object"&&n!==null?n:{},r=jd(t.resets_at),i=r===void 0?{}:{resetsAt:r};if(t.declared!==true)return {...cn(),...i};let o=t.remaining_today,s=typeof o=="number"&&Number.isFinite(o)&&o>=0?Math.floor(o):void 0,a=t.next_eligible_at,l=jd(a),d=t.held_limit_reached===true,m=a!=null,u=o!=null&&s===void 0;return {declared:true,grantable:t.grantable===true&&e&&s!==0&&!u&&!m&&!d,...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...i}}var Hf=18e4,yo=32,Wf=/^[a-z0-9_-]+$/,Kf="rewarded_requires_user_gesture";function Jf(){let n=globalThis.navigator?.userActivation?.isActive;return typeof n=="boolean"?n:void 0}var zf=1e3;function Yf(){let n=globalThis,e=n.navigator?.getGamepads,t=n.performance?.now;if(typeof e!="function"||typeof t!="function")return;let r=t.call(n.performance),i=e.call(n.navigator);for(let o=0;o<i.length;o+=1){let s=i[o]?.timestamp;if(typeof s=="number"&&r-s>=0&&r-s<=zf)return true}return false}var Ud=1e4;function Xf(n){return n==="interstitial"||n==="rewarded"}function Bd(n){return typeof n=="string"&&n!==""&&n.length<=yo&&Wf.test(n)}function Qf(n){let e=typeof n=="object"&&n!==null?n:{};return [e.name,e.reason,e.status].join()}function wr(n){return typeof n=="string"?JSON.stringify(n):typeof n}function Vd(n){let e=false,t=new Map,r=new Map,i=new Set,o=d=>{try{n.onDropped?.(d);}catch{}},s=false,a=d=>{if(s)return;s=true;let m=n.log;if(m!==null)try{m===void 0?console.warn(`[gem] ${d}`):m(`[gem] ${d}`);}catch{}},l=d=>{let m=n.readAvailability;if(m===void 0)return Promise.resolve(cn());let u=r.get(d);if(u!==void 0)return u;let p=new Promise(g=>{let y={},w=b=>y.done===true?false:(y.done=true,n.clock.clearTimeout(y.timer),g(b),true),S=(b,R)=>{!w(cn())||i.has(b)||(i.add(b),o(`gem.ads.rewardedStatus("${d}") answered not grantable: ${R}. Said once.`));},A=b=>{S(Qf(b),`the read failed (${b instanceof Error?b.message:wr(b)})`);},I;try{I=Promise.resolve(m(d,AbortSignal.timeout(Ud)));}catch(b){I=Promise.reject(b);}y.timer=n.clock.setTimeout(()=>{S("timeout","no answer within 10 s");},Ud),I.then(b=>{try{w(Nd(b,n.bridge.parentSupports("ads")));}catch(R){A(R);}},A);});return r.set(d,p),p.then(()=>{r.get(d)===p&&r.delete(d);}),p};return {api:{rewardedStatus(d){return Bd(d)?l(d):(o(`gem.ads.rewardedStatus(${wr(d)}) answered not grantable: a placement is 1..${String(yo)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(cn()))},requestAd(d){if(!n.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let m=d?.placement,u=d?.format;if(!Bd(m)||!Xf(u))return o(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${wr(m)}, format ${wr(u)}. A placement is 1..${String(yo)} 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"});if(u==="rewarded"){let g;try{g=(n.userActivation??Jf)();}catch{g=void 0;}if(g===false)try{(n.recentGamepadInput??Yf)()===!0&&(g=!0);}catch{}if(g===false){let y=`${Kf}: gem.ads.requestAd("${m}", 'rewarded') answered no_ad without asking: the frame has no user activation and no controller input in the last second. Ask from the button's click, pointerup, touchend or keydown handler, or straight from a controller press, before any await or timer that can outlast the press. On a touchscreen, pointerdown and touchstart run before the tap counts.`;return o(y),a(y),Promise.resolve({outcome:"no_ad"})}}let p=`ad-${Ee()}`;return new Promise(g=>{let y={},w=A=>{t.delete(p)&&(e=false,n.clock.clearTimeout(y.timer),g(A));};e=true,t.set(p,w),y.timer=n.clock.setTimeout(()=>{w({outcome:"unavailable"});},n.timeoutMs??Hf);let S=false;try{S=n.bridge.requestAd(p,m,u);}catch{}S||w({outcome:"no_ad"});})}},settle(d){let m=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",u=t.get(d.requestId);if(u===void 0){n.onDropped?.(`gem.adResult (${m}) for an unknown requestId: `+JSON.stringify(d.requestId));return}u({outcome:m});}}}var fo=16384;function Hd(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:Zf(e)}function Zf(n){let e=0;for(let t=0;t<n.length;t+=1){let r=n.charCodeAt(t);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let i=n.charCodeAt(t+1);i>=56320&&i<=57343?(e+=4,t+=1):e+=3;}else e+=3;}return e}var eh=1e4,th=5e3;function Wd(n){let e=null,t=false,r=[],i=new Map,o=()=>{for(let s of r.splice(0))s();};return {api:{get current(){return e},wait(s=th){return t?Promise.resolve(e):new Promise(a=>{let l=()=>{let u=r.indexOf(d);u>=0&&r.splice(u,1);},d=()=>{n.clock.clearTimeout(m),l(),a(e);},m=n.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!n.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=Hd(s);if(a===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(a>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(s)),d=`device-settings-${Ee()}`;return new Promise(m=>{let u={},p=y=>{i.delete(d)&&(n.clock.clearTimeout(u.timer),y==="stored"&&(e=l,t=true,o()),m(y));};i.set(d,p),u.timer=n.clock.setTimeout(()=>p("unavailable"),n.timeoutMs??eh);let g=false;try{g=n.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(s){let a=s.settings;e=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:null,t=true,o();},settle(s){let a=s.outcome==="stored"||s.outcome==="too_large"?s.outcome:"unavailable",l=i.get(s.requestId);if(l===void 0){n.onDropped?.(`gem.deviceSettings.result (${a}) for an unknown requestId: `+JSON.stringify(s.requestId));return}l(a);}}}var un=class extends Error{constructor(){super("createGem: this game is not framed (window.parent === window), so nothing can hand it a player, saves, config or rooms. Play it in the Gem Arcade or the Gem Editor, or through the Gem dev host on this machine: `npm run dev` (`gemctl serve start . --dev`) while editing, `gemctl serve start .` for a build, signed in to gemctl. Do not open the dev server's own address."),this.name="GemUnframedError";}};var nh=/^[a-z0-9][a-z0-9_-]{0,39}$/;function rh(n){return typeof n=="string"&&nh.test(n)}function Sr(n){if(n===null||rh(n))return n;let e=typeof n=="string"?JSON.stringify(n.length>48?`${n.slice(0,48)}\u2026`:n):`a value of type ${typeof n}`;console.warn(`[gem] showPortraitBorders: ${e} is not a border name, so nothing was sent. A name is 1 to 40 of a-z, 0-9, _ and -, starting with a letter or digit, exactly as your store page declares it under media.portrait_borders. Pass null for no art.`);}function Kd(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function ho(n,e){if(n!==true)return {visible:false};let t=[],r=false;for(let i of Array.isArray(e)?e:[])i==="score"?r=true:typeof i=="string"&&i.length>0&&i.length<=64&&!t.includes(i)&&t.push(i);return !r&&t.length===0?{visible:true}:{visible:true,currencies:t.slice(0,8),score:r}}function Rr(n,e){let t=[];for(let r of Array.isArray(e)?e:[]){if(t.length===4)break;if(typeof r!="object"||r===null)continue;let{id:i,label:o}=r;typeof i!="string"||i.length===0||i.length>32||typeof o!="string"||o.trim().length===0||t.some(s=>s.id===i)||t.push({id:i,label:o.trim().slice(0,40)});}return t.length===0?{settings:n===true}:{settings:n===true,items:t}}function Jd(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function ih(n){let e=n.untrusted,t=he(e.displayName),r=e.displayTag||e.displayHandle,i=r?he(r):void 0,o=n.discriminator||n.displayTag,s=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,a=n.avatarIconUrl||n.avatarUrl,l={displayName:t,displayHandle:i??t,badges:(n.badges??[]).map(p=>({itemId:p.itemId,iconUrl:p.iconUrl}))};n.playerId&&(l.playerId=n.playerId),s&&(l.discriminator=s),i&&(l.displayTag=i),a&&(l.avatarIconUrl=l.avatarUrl=a);let d=n.boost,m=(d?.multipliers??[]).map(p=>({currencyId:p.currencyId,currencySlug:p.currencySlug,multiplier:p.multiplierBp/1e4})),u=m.some(p=>p.multiplier>1);return l.boost=u&&d?.expiresInDays?{active:u,multipliers:m,expiresInDays:d.expiresInDays}:{active:u,multipliers:m},l}var oh=1e4,mn=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??le,this.inbound=new At(this.clock),this.outbound=new At(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(a=>Fr(a,e.origin))||es(e.origin,this.options.selfOrigin)))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),this.state==="waiting"&&this.transition("refused"),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=An["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!Fr(i.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${i.embedder}' but arrived from '${e.origin}'`),false;let o=e.ports?.[0];if(!o)return this.refuse(e,"handshake transferred no MessagePort"),false;let s=ts(kn,i.versions);return s===null?(o.onmessage=null,o.postMessage({gem:U,type:"gem.error",code:"version_mismatch",message:`frame supports v${kn.min}..v${kn.max}`}),o.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=o,this.version=s,o.onmessage=a=>this.receive(a.data,a.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],this.unbidden=i.unbidden===true,o.postMessage({gem:U,type:"gem.handshake.accept",v:s,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:U,type:"gem.ready"});}settled(e=oh){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(t=>{let r=o=>{this.clock.clearTimeout(i),t(o);},i=this.clock.setTimeout(()=>{let o=this.settleWaiters.indexOf(r);o>=0&&this.settleWaiters.splice(o,1),t(this.state);},e);this.settleWaiters.push(r);})}progress(e,t){this.send({gem:U,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:U,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:U,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),true):false}exit(e){this.send(e===void 0?{gem:U,type:"gem.exit"}:{gem:U,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:U,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:U,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:U,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:U,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let t={gem:U,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:Kd(e.origin.x),y:Kd(e.origin.y)}),this.send(t),true}showPortraitBorders(e){let t=Sr(e);return t===void 0||this.state!=="connected"||!this.parentSupports("portraitBorders")?false:this.send(t===null?{gem:U,type:"gem.portraitBorders"}:{gem:U,type:"gem.portraitBorders",name:t})}setWalletVisible(e,t){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:U,type:"gem.walletDisplay",...ho(e,t?.only)})}setMenu(e,t){return this.state!=="connected"||!this.parentSupports("gameMenu")?false:this.send({gem:U,type:"gem.menu",...Rr(e,t)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:U,type:"gem.requestShare",params:e.map(({key:t,value:r})=>({key:t,value:r}))})}requestVibrate(e){return this.state!=="connected"||!this.parentSupports("vibration")?false:this.send({gem:U,type:"gem.vibrate",pattern:[...e]})}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:U,type:"gem.frameStats",fps:Jd(e.fps,1e3),frameTimeP95Ms:Jd(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:U,type:"gem.gameContext",context:e}),true)}signal(e,t,r){this.send({gem:U,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:U,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:U,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,i,o,s){return this.send({gem:U,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...s===void 0?{}:{catalogId:s}})}putDeviceSettings(e,t){return this.send({gem:U,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:U,type:"gem.requestAd",requestId:e,placement:t,format:r})}requestSignIn(e){return this.send({gem:U,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,t,r,i){return this.send({gem:U,type:"gem.requestFriendChallenge",requestId:e,playerId:t,template:r,...i===void 0?{}:{params:i}})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let t of this.settleWaiters.splice(0))t(e);this.options.onStateChange?.(e);}}refuseMalformed(e,t){if(!this.inbound.allow(xn)){this.options.onDropped?.(e,t);return}this.fail(e,t);}dropUnknownType(e){this.inbound.allow(xn)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,t){e.ports?.[0]?.close?.(),this.inbound.allow(xn)&&this.options.onRefused?.(t);}fail(e,t){this.options.onError?.(e,t),this.state==="connected"&&this.port&&this.send({gem:U,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=An[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||zd(t);}}dispatchInbound(e,t){if(this.state!=="connected")return false;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string")return this.refuseMalformed("invalid_message","message has no type"),false;let i=An[r];if(!i)return this.dropUnknownType(r),false;if(!this.inbound.allow(r))return this.fail("rate_limited",`parent exceeded the limit for ${r}`),false;let o=Xa(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let s=i(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(a);break;case "gem.pause":this.options.onPause?.(a);break;case "gem.menuSelect":this.options.onMenuSelect?.(a);break;case "gem.prefs":this.options.onPrefs?.(a);break;case "gem.cohorts":this.options.onCohorts?.(a);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(a);break;case "gem.willTerminate":this.options.onWillTerminate?.(a);break;case "gem.devtools":this.options.onDevtools?.(a.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=t[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:a.maxWidth,maxHeight:a.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return zd(t.slice(1)),this.options.onScreenshot(d,l,(m,u)=>this.screenshotDenied(m,u)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer":this.options.onLocalServer?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{this.options.onPlayer?.(ih(a));break}case "gem.roomEvent":this.options.onRoomEvent?.(a);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(a);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(a);break;case "gem.socketState":this.options.onSocketState?.(a);break;case "gem.signalEvent":this.options.onSignalEvent?.(a);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(a);break;case "gem.clusterTarget":this.options.onClusterTarget?.(a);break;case "gem.partyResult":this.options.onPartyResult?.(a);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(a);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(a);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(a);break;case "gem.adResult":this.options.onAdResult?.(a);break;case "gem.signInResult":this.options.onSignInResult?.(a);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(a);break;case "gem.error":this.options.onError?.(a.code,a.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,t){this.send({gem:U,type:"gem.screenshot.denied",reason:e,retryable:t});}};function zd(n){for(let e of n)try{e?.close?.();}catch{}}var Yd="https://api.gemarcade.com";function bo(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 ah=new Set(["localhost","127.0.0.1","[::1]"]);function Xd(n){let e=bo(n);if(e!==null)return e;let t=new URL(n);return t.protocol==="http:"&&!ah.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 lh=Object.freeze(["https://gemarcade.com","https://meme-games.com","http://gemarcade.localhost","gemarcade://localhost"]),dh=Yd,Qd=8e3,vo=15e3,ch=9e4,uh=1/0,mh=8e3,ph=5e3,gh=5e3;async function yh(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 pn(n){let e=null,t=false,r=[];return {get current(){return e},set(i){e=i;for(let o of r.splice(0))o(i);},release(){t=true;for(let i of r.splice(0))i(e);},wait(i){return e!==null||t?Promise.resolve(e):new Promise(o=>{let s=()=>{let d=r.indexOf(a);d>=0&&r.splice(d,1);},a=d=>{n.clearTimeout(l),s(),o(d);},l=n.setTimeout(()=>{s(),o(e);},i);r.push(a);})}}}function sk(n={}){let e=n.clock??le,t=n.log===void 0?c=>console.info(c):n.log,r=n.baseUrl??void 0;if(r!=null){let c=bo(r);if(c!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${c}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let i=Ps(typeof window>"u"?void 0:window.location?.search),o=Yi();o.mark("sdk created");let s=()=>Zn(ee.gameVersion,n.clientVersion?.gameVersion),a=new qt({client:()=>it,clock:e,gameId:()=>ee.identity?.gameId??null,playerId:()=>ee.identity?.playerId??null,environment:()=>{let c=s();return {sdk_version:Do(),...c===null?{}:{game_version:c}}},...n.analytics===void 0?{}:{options:n.analytics},log:t}),l=Gl(()=>{o.mark("engaged"),a.release(),j.reportEngaged();},typeof window>"u"?{}:window),d=c=>{if(c===false)return null;let k=c?.attempts??uh,D=c?.budgetMs??ch;return !(k>0)||!(D>0)?null:{attempts:k,budgetMs:D,maxDelayMs:c?.maxDelayMs??mh}},m=c=>{c.on("created",()=>{o.mark("room created");}),c.on("joined",()=>{o.mark("room joined");}),c.on("matchAllocationStarted",()=>{o.mark("allocation started");}),c.on("matchReady",()=>{o.mark("match ready");}),c.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.");if(window.parent===window)throw new un;let u=n.allowedEmbedders;if(u!=null&&!Array.isArray(u))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 p=Array.from(u??[]),g=p.filter(c=>typeof c!="string"||!Dr(c));if(g.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${g.length===1?"an entry":"entries"} that ${g.length===1?"is":"are"} not an origin: ${g.map(c=>typeof c=="string"?JSON.stringify(c):String(c)).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 y=Object.freeze([...new Set([...lh,...p])]),w=pn(e),S=pn(e),A=pn(e),I=Os(t),b=pn(e),R=n.manageAudio===false?null:Bl();n.selectableText!==true&&Vl();let E=null,T=()=>{E!==null&&(S.current!==null&&S.current.muted===E||j.reportMuted(E));},V,B,K=-1/0,x=null,C=()=>{if(V===void 0||x!==null||V===B)return;let c=K+1e3-e.now();if(c>0){x=e.setTimeout(()=>{x=null,C();},c);return}j.showPortraitBorders(V)&&(B=V,K=e.now());},O=null,F=null,N=()=>{if(O===null)return false;let c=JSON.stringify(ho(O.visible,O.only));return c===F?j.parentSupports("walletDisplay"):j.setWalletVisible(O.visible,O)?(F=c,true):false},q=null,Z=null,ge=()=>{if(q===null)return false;let c=typeof q.onSettings=="function",k=JSON.stringify(Rr(c,q.items));return k===Z?j.parentSupports("gameMenu"):j.setMenu(c,q.items)?(Z=k,true):false},X=Hl({report:c=>j.reportFrameStats(c)}),Me=false,ue=Ql(()=>Go,()=>Me),ke=c=>{let k=Me&&!c,D=Me!==c;if(Me=c,k&&ue.close(),!!D)try{n.onDevToolsPermissionChange?.(c);}catch(te){t?.(`[gem] onDevToolsPermissionChange threw: ${te instanceof Error?te.message:String(te)}`),queueMicrotask(()=>{throw te});}},Oe=r??dh,ne=r!==void 0,z,de=c=>(t?.(`[gem] token refused: ${c}`),n.onError?.("internal",c),false),gn=(c,k)=>{if(c===void 0)return k!==void 0?de("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 D=Xd(c);return D!==null?de(`the embedder named an API root that cannot be used: ${D}. Its value is withheld here rather than written to logs.`):z!==void 0&&z!==c?de("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."):(z=c,ne||(Oe=c),true)},Rt=window.location?.origin,et=null,f=-1/0,M=2e3,$=new Set,re=c=>et!==false?Promise.resolve(true):new Promise(k=>{let D=e.setTimeout(()=>{$.delete(te),k(false);},c),te=()=>{e.clearTimeout(D),$.delete(te),k(true);};$.add(te);}),_e=()=>{},tt=null,j=new mn({allowedEmbedders:y,...typeof Rt=="string"&&Rt!==""?{selfOrigin:Rt}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","portraitBorders","earnAllowance","share","vibration","frameStats","walletDisplay","gameMenu","engagement","reservedAreas","viewport","purchases","deviceSettings","ads","signIn","friendChallenges",...n.onFeedbackContext!==void 0?["feedbackContext"]:[]],onRefused:c=>{tt=c,n.onRefused?.(c);},...n.onError===void 0?{}:{onError:n.onError},onStateChange:c=>{ee.onBridgeState(c),c!=="connected"&&X.setRequested(false),F=null,Z=null,B=void 0,c==="refused"&&(console.error("[gem] this game refused the page that framed it"+(tt===null?"":` (${tt})`)+", so it has no player, saves, config or rooms. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders."),_e()),c==="connected"&&(o.mark("bridge connected"),nc(),T(),C(),N(),ge(),j.unbiddenLaunch&&!l.engaged&&a.hold(),a.startSession(),l.engaged&&j.reportEngaged()),n.onStateChange?.(c);},onPlayer:c=>{w.set(c),n.onPlayer?.(c);},onPrefs:c=>{let k={reducedMotion:c.reducedMotion,muted:c.muted,locale:c.locale,showFrameStats:c.showFrameStats===true,recommended:c.recommended===void 0?null:Object.freeze({volume:c.recommended.volume,batterySaver:c.recommended.batterySaver,keyboardLayout:c.recommended.keyboardLayout,gamepadConfirm:c.recommended.gamepadConfirm,vibration:c.recommended.vibration})};S.set(k),R?.setMuted(k.muted),X.setRequested(k.showFrameStats&&j.parentSupports("frameStats")),n.onPrefs?.(k);},onCohorts:c=>{let k=Object.freeze(c.cohorts.map(D=>Object.freeze({experimentId:D.experimentId,variantKey:D.variantKey})));A.set(k),n.onCohorts?.(k);},onEarnAllowanceChanged:()=>I.emit(),onViewport:c=>{let k=Object.freeze({insets:Object.freeze({top:c.insets.top,right:c.insets.right,bottom:c.insets.bottom,left:c.insets.left}),reserved:Object.freeze((c.reserved??[]).map(te=>Object.freeze({x:te.x,y:te.y,width:te.width,height:te.height})))});b.set(k);let D=Kl();Jl(D,k.insets),Yl(D,k.reserved,zl()),n.onViewport?.(k);},onPause:c=>{a.setPaused(c.paused),X.setPaused(c.paused),n.onPause?.(c.paused);},onMenuSelect:c=>{if(q===null)return;if(c.entry==="settings"){q.onSettings?.();return}(Rr(false,q.items).items??[]).some(D=>D.id===c.id)&&q.items?.find(D=>D.id===c.id)?.onSelect?.();},onWillTerminate:c=>{a.endSession(c.reason),n.onWillTerminate?.({reason:c.reason,graceMs:c.graceMs});},onToken:c=>{let k=c.garden;if(ke(c.allowDevTools===true),!gn(c.apiBaseUrl,k))return;let D=c;ee.onToken(D);let te=ee.identity;te&&(kr.set(te),wo||(wo=true,me.reconcileSeats().catch(()=>{}))),So.push({token:D.token,expiresAt:D.expiresAt});},onTokenDenied:c=>{ke(false),ee.onDenied(c);},onScreenshot:(c,k,D)=>{jl(c,k,D,{...n.onScreenshot===void 0?{}:{handler:n.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{Nl(j,n.onFeedbackContext);},onDevtools:c=>{c==="close"?ue.close():c==="open"?ue.openFrom("platform").catch(()=>{}):ue.isOpen?ue.close():ue.openFrom("platform").catch(()=>{});},onRoomEvent:c=>me.handleRoomEvent({event:c.event,roomId:c.roomId,...c.matchId===void 0?{}:{matchId:c.matchId},...c.version===void 0?{}:{version:c.version},...c.reason===void 0?{}:{reason:c.reason},...c.platform===void 0?{}:{platform:c.platform}}),onSeatedEvent:c=>me.handleSeated(c.roomId),onAutoStartFailedEvent:c=>me.handleAutoStartFailed(c.roomId,c.code),onSocketState:c=>{let k=et;if(et=c.connected,c.connected)for(let te of [...$])te();if(!c.connected||k===true)return;let D=e.now();D-f<M||(f=D,me.reconcile().catch(()=>{}));},onSignalEvent:c=>{let k=typeof c.data=="object"&&c.data!==null&&!Array.isArray(c.data)?c.data:{};ot.handleSignalEvent(c.matchId,c.event,k),c.event==="matchEnded"&&me.reconcile({matchId:c.matchId,...typeof k.reason=="string"?{reason:k.reason}:{}}).catch(()=>{});},onDedicatedEvent:c=>{c.event==="matchEnded"&&(kt.handleMatchEnded(c.matchId,c.reason),me.reconcile({matchId:c.matchId,...c.reason===void 0?{}:{reason:c.reason}}).catch(()=>{})),nt.handleEvent(c);},onClusterTarget:c=>hn.accept(c.clusterTargetId,c.clusterTargetIds),onLocalServer:c=>bn.accept(c),onLocalServerDenied:c=>bn.refuse(c),onPartyResult:c=>ko.settle(c.requestId,c.partyId),onPurchaseResult:c=>Ao.settle(c),onDeviceSettings:c=>{fn.receive(c),n.onDeviceSettings?.(fn.api.current);},onDeviceSettingsResult:c=>fn.settle(c),onAdResult:c=>Eo.settle(c),onSignInResult:c=>To.settle(c),onFriendChallengeResult:c=>Io.settle(c)}),nt=new ln({bridge:j}),kr=pn(e);_e=()=>{kr.release(),w.release(),A.release();},j.currentState==="refused"&&_e();let wo=false,xr=new Set,yn,So={current:()=>yn,subscribe:c=>(xr.add(c),yn!==void 0&&c(yn),()=>xr.delete(c)),push:c=>{yn=c;for(let k of [...xr])try{k(c);}catch(D){t?.(`[gem] a server-token listener threw: ${D instanceof Error?D.message:String(D)}`);}}},ee=ed({bridge:j,clock:e,onStateChange:(c,k)=>{if(c==="ready"){if(o.mark("token ready")){let D=o.marks.find(te=>te.name==="token ready")?.at;a.trackPlatform("gem_boot_ready",D===void 0?{}:{boot_ms:Math.max(0,Math.round(D))});}}else c==="lost"&&(o.mark("token lost"),a.trackPlatform("gem_auth_lost"));n.onAuthStateChange?.(c,k);}}),Ro=()=>{let c=ee.identity;return !c||ee.source.currentState==="lost"?null:`${c.playerId}\0${c.gameId}\0${c.channel}`},nc=()=>{o.mark("token requested"),ee.source.get().catch(()=>{});},ko=go({bridge:j,clock:e}),xo={},Ao=Md({bridge:j,clock:e,onDropped:c=>n.onError?.("internal",c),confirm:async c=>xo.confirm?.(c)??"unknown"}),fn=Wd({bridge:j,clock:e,onDropped:c=>n.onError?.("internal",c)}),Po={},Eo=Vd({bridge:j,clock:e,onDropped:c=>n.onError?.("internal",c),readAvailability:(c,k)=>Po.read?.(c,k)??Promise.reject(new Error("the gem-api client is not built yet")),log:n.log}),To=Ld({bridge:j,clock:e,onDropped:c=>n.onError?.("internal",c)}),Io=Ms({bridge:j,clock:e,onDropped:c=>n.onError?.("internal",c)}),hn=Us({bridge:j,clock:e}),bn=Xl({bridge:j,clock:e}),Ar=c=>{let k=j.handleWindowMessage({data:c.data,origin:c.origin,source:c.source,ports:c.ports});return k&&window.removeEventListener("message",Ar),k};window.addEventListener("message",Ar);let rt=Dl(window,Ar),rc=rt?.capture,Pr=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Pr?.domInteractive!==void 0&&Pr.domInteractive>0&&o.mark("document parsed",Pr.domInteractive),rc?.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 Er=n.handshakeWarningMs;Er!==null&&t&&e.setTimeout(()=>{let c=rt===null?"no capture script ran":`capture: ${rt.delivered} offer(s) delivered, ${rt.stale} stale, ${rt.capture.dropped} evicted${rt.capture.late?", installed late":""}`;if(j.currentState==="connected"){t(`[gem] handshake connected. boot: ${o.timeline()} \xB7 ${c}`);return}t(`[gem] no completed handshake after ${Er??Qd}ms (bridge state: ${j.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 `+c);},Er??Qd);let ic=hr({get baseUrl(){return Oe},tokenSource:ee.source,get defaultQuery(){let c=ee.identity;return c?{game_id:c.gameId,channel:c.channel}:{}}}),it=new Ge({transport:ic,clock:e}),fe={client:it,gameId:()=>ee.identity?.gameId??""};xo.confirm=c=>Od(fe,c),Po.read=(c,k)=>Ua(fe,"players","me",c,{signal:k});let oc=()=>ee.identity?.channel??"release",Co=new Vn(fe,oc),Mo=async c=>(await Co.load())?.currency(c)?.id??void 0,Oo=$n(fe,Kr,{identity:Ro,resolveCurrencyId:Mo}),Tr=async c=>{let k=await kr.wait(c);if(k)return k;throw j.currentState==="refused"?new oe("unavailable","the page that framed this game is not one it accepts, so no play token will ever arrive. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders (see onRefused for the reason)."):new oe("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=d(n.autoReconnect),me=Gi({client:it,clock:e,gameId:()=>ee.identity?.gameId??null,playerId:()=>ee.identity?.playerId??null,awaitGameId:async()=>(await Tr(vo)).gameId,resolveParty:ko.resolve,resolveClusterTargets:hn.resolveList,refreshClusterTargets:hn.refresh,ensureLocalServer:bn.ensure,localHostAvailable:bn.available,...n.clientVersion===void 0?{}:{clientVersion:n.clientVersion},platformGameVersion:()=>ee.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:(c,k)=>Cr.redialMatch(c,k),abandon:(c,k)=>Cr.abandonMatch(c,k)}}});m(me),Ol({analytics:a,rooms:me});let ot=Ml({client:it,clock:e,rooms:me,bridge:j,gameId:()=>ee.identity?.gameId??"",baseUrl:()=>Oe,resolveClusterTarget:hn.resolve,boot:o,...n.log===void 0?{}:{log:n.log}}),Lo=zi(o,t),kt=hd({client:it,clock:e,rooms:me,signaling:()=>nt.channel(),signalingReady:re,log:t??(()=>{})}),Cr=Id({rooms:me,p2p:{connect:c=>Lo(ot.connect(c)),session:c=>ot.session(c)},dedicated:{connect:(c=>gr(o,"welcome",kt.connect(c),t))},clock:e,identity:()=>ee.identity,apiBaseUrl:()=>Oe,tokens:So,room:()=>me.currentRoom,autoReconnect:Ir!==null,...n.log===void 0?{}:{log:n.log}}),ac=async()=>(await Tr(vo)).playerId,Go={client:it,boot:o,get identity(){return ee.identity},awaitIdentity:(c=vo)=>Tr(c),awaitBridge:c=>j.settled(c),get player(){return w.current},awaitPlayer:(c=ph)=>w.wait(c),me:Oo,characters:new jn(fe,void 0,Ro,Mo),transfers:new Un(fe,Kr,Oo.inventory),gameConfig:Co,purchases:Ao.api,deviceSettings:fn.api,ads:Eo.api,account:To.api,share:$d({frame:j,log:n.log}),vibration:qd({frame:j,log:n.log}),analytics:a,leaderboards:new Mt(fe),challenges:new Tt(fe),showcase:new Ot(fe,ac),friends:new Lt(fe,{challenge:Io.challenge,...i===void 0?{}:{launchedChallengeId:i}}),platform:new Dt(fe,I,t),profiles:new Ft(fe),functions:new Fe((c,k)=>Ea(fe,c,k)),get prefs(){return S.current},get cohorts(){return A.current},get viewport(){return b.current},awaitCohorts:(c=gh)=>A.wait(c),reportMuted:c=>{E=!!c,T();},showPortraitBorders:c=>{let k=Sr(c);k!==void 0&&(V=k,C());},cueReward:c=>j.cueReward(c),setWalletVisible:(c,k)=>{let D=Array.isArray(k?.only)?[...k.only]:void 0;return O=D===void 0?{visible:c===true}:{visible:c===true,only:D},N()},setMenu:c=>(q={...typeof c?.onSettings=="function"?{onSettings:c.onSettings}:{},...Array.isArray(c?.items)?{items:c.items.map(k=>({...k}))}:{}},ge()),exit:c=>yh(me,j,c,a),frame:j,devtools:ue,rooms:me,dedicatedServer:{listClusterTargets:c=>kt.listClusterTargets(c),connect:(c=>gr(o,"welcome",kt.connect(c),t)),handleMatchEnded:(c,k)=>kt.handleMatchEnded(c,k)},p2p:{handleSignalEvent:(c,k,D)=>ot.handleSignalEvent(c,k,D),session:c=>ot.session(c),connect:c=>Lo(ot.connect(c))},match:Cr};return Go}var Zd="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 _o(n,e={}){let t=e.clock??le,r=()=>{let a=n();if(a===null)throw new Error(Zd);return a},i=null,o=()=>{if(i===null)throw new Error(Zd);return i};return {server:{get identity(){return o().identity},get client(){return o().client},get api(){return o().api},get match(){return o().match},get analytics(){return o().analytics},get functions(){return o().functions},get challenges(){return o().challenges},get room(){return o().room},dispose(){i?.dispose();},get sizeClass(){return r().sizeClass},get roomArgs(){return r().roomArgs},get roster(){return r().roster},players(){return r().players()},profile(a){let d=r().profile?.(a);if(!d)return null;let m=d.displayName;return typeof m!="string"||m===""?null:{displayName:he(m),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:he(d.displayTag)}:{},...typeof d.discriminator=="string"?{discriminator:d.discriminator}:{}}},playerNumber(a){return r().playerNumber?.(a)},send(a,l,d){d===void 0?r().send(a,l):r().send(a,l,d);},broadcast(a,l){l===void 0?r().broadcast(a):r().broadcast(a,l);},kick(a,l){l===void 0?r().kick(a):r().kick(a,l);},log(a){r().log(a);},warn(a){r().warn(a);}},attach:()=>{i=wt(r(),{...e,clock:t});}}}function ec(n,e={}){let{server:t,attach:r}=_o(()=>n,e);return r(),t}function fh(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:$e(e)}}}function tc(n,e={}){return ()=>{let t=null,{server:r,attach:i}=_o(()=>t,e),o=n(r),s={async init(a){t=a,i(),await o.init?.();},async shutdown(a){let l=fh(a);try{await o.shutdown?.(l);}finally{r.dispose();}}};return o.join&&(s.join=(a,l)=>o.join?.(a,l)),o.leave&&(s.leave=(a,l)=>o.leave?.(a,l)),o.message&&(s.message=(a,l,d,m)=>o.message?.(a,l,d,m)),s}}
2
- export{lh as ARCADE_EMBEDDERS,qt as AnalyticsApi,oe as AuthError,vn as CONDITIONAL_HEADERS,Tt as ChallengesApi,fo as DEVICE_SETTINGS_MAX_BYTES,_ as DedicatedServerError,He as FriendChallengeError,Lt as FriendsApi,Fe as FunctionsApi,L as GemApiError,Ge as GemClient,ce as GemConfigError,mn as GemFrame,$t as GemFunctionError,ae as GemSaveError,un as GemUnframedError,Mt as LeaderboardsApi,fs as MAX_PERIODS_BACK,Ym as PLATFORM_EVENTS,Dt as PlatformApi,zn as PlatformCurrenciesApi,Yn as PlatformEarnAllowanceApi,ye as PlayerText,Ft as ProfilesApi,De as PurchaseRefusal,Ot as ShowcaseApi,ie as TransportRefusal,Vt as UNRELIABLE_CHANNEL_LABEL,he as asPlayerText,Yi as createBootTimeline,sk as createGem,wt as createGemServer,_d as createHostTokenSource,ec as createMatchServer,tc as defineServer,yh as leaveAndExit,we as mapIdentity,gr as markOnResolve,Sm as platformIconUrl,Ut as presentJoinCredential,gt as readTemplateTransports,Ht as readTransportAdvert,zi as reportOnResolve,le as systemClock,Ue as text,_n as toBase64,ir as webTransportAvailable};//# sourceMappingURL=gem-web-sdk.sdk.js.map
1
+ var sc=Object.defineProperty;var lc=(n,e)=>{for(var t in e)sc(n,t,{get:e[t],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:10.2.0]";function Di(){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 dc(n,e){return e!==void 0?!e:n==="chain_exhausted"}var at=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 ie(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 ie("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 ie("internal","token arrived for a superseded generation");return this.grant=o,this.rejected=false,this.enter("ready"),o.token}).catch(o=>{let i=cc(o),s=o?.retryable;throw t===this.generation&&this.enter(dc(i,typeof s=="boolean"?s:void 0)?"lost":"degraded",i),o instanceof ie?o:new ie(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)}},ie=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 cc(n){if(n instanceof ie)return n.reason;let e=n?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var oe=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}},vn=["if-match","if-none-match"],Fi=4096;function uc(n){if(!n)return;let e={};for(let[t,r]of Object.entries(n)){let o=t.toLowerCase();if(!vn.includes(o)||r===void 0)continue;let i=typeof r=="string"?mc(r):r;if(typeof i!="string"||i.length>Fi||!pc(i))throw new oe(`the ${o} header value cannot be sent \u2014 it is not a string, is longer than ${Fi} 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 mc(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 pc(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 gc(n){let{bytes:e}=n;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new oe("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 oe("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 $i(n,e){let t=e.replayUnauthorizedOnce??true;return {async request(r){let o={...r},i=uc(o.headers),s=gc(o),a=Object.freeze({...o,headers:i,...s===void 0?{}:{bytes:s}}),l=await e.tokenSource.get(),d=await n(a,l);if(d.status!==401||!t)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),u=await n(a,m);if(u.status===401)throw e.tokenSource.close("unavailable"),new ie("unavailable","the server refused a freshly minted token");return u}}}function _n(n){let e=typeof n=="string"?new TextEncoder().encode(n):n;return btoa(yc(e))}function wn(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 Mr(n){return new TextDecoder().decode(wn(n))}function yc(n){let t="";for(let r=0;r<n.length;r+=32768)t+=String.fromCharCode(...n.subarray(r,r+32768));return t}var O=class extends Error{constructor(t,r,o,i,s){super(`${t} (${r}): ${o}`);this.reason=t;this.status=r;this.detail=o;this.retryAfterSeconds=i;this.code=s;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},ji=new WeakMap;function Ni(n){return ji.get(n)??{}}var hc=new Set([408,429,500,502,503,504]),fc=6e4;function bc(n){if(n===void 0)return 2;if(!Number.isInteger(n)||n<0||n>10)throw new oe(`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 Ge=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,...xt(o)},o.replaySafe===true)}async post(e,t,r,o={}){return this.send({method:"POST",path:e,body:t,signal:r,...xt(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,...xt(o)},o.replaySafe===true);return {bytes:vc(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,...xt(o)},o.replaySafe===true)}async delete(e,t,r={}){return this.send({method:"DELETE",path:e,signal:t,...xt(r)},r.replaySafe===true)}async send(e,t){return (await this.sendRaw(e,t)).body}async sendRaw(e,t){let r=t?bc(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw qi(e.signal);for(let i=0;i<r;i++){if(i>0&&await this.backoff(i,o,e.signal),e.signal?.aborted)throw qi(e.signal);let s;try{s=await this.options.transport.request(e);}catch(l){if(ie.isAuthError(l)||oe.isRefusal(l)||e.signal?.aborted||_c(l))throw l;o=new O("unavailable",0,String(l));continue}if(s.status>=200&&s.status<300||s.status===304)return s;let a=wc(s);if(!hc.has(s.status))throw a;o=a;}throw o??new O("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,s=2**(e-1)*250,a=Math.min(Math.max(i,s),fc);return new Promise(l=>{let d=this.options.clock,m=false,u=false,p,g=()=>{m||(m=true,u&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,a),u=true,m&&d.clearTimeout(p);})}};function vc(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 xt(n){return {...n.keepalive===void 0?{}:{keepalive:n.keepalive},...n.ifMatch===void 0?{}:{headers:{"if-match":n.ifMatch}}}}function qi(n){return n.reason!==void 0?n.reason:new DOMException("The operation was aborted.","AbortError")}function _c(n){let e=n?.name;return e==="AbortError"||e==="TimeoutError"}function wc(n){let e=Rc(n),t=xc(n.body),r={...t===void 0?{}:{details:t},...n.invocationId===void 0?{}:{invocationId:n.invocationId}};return Object.keys(r).length>0&&ji.set(e,r),e}var Sc=new Map([["insufficient_funds","insufficient_funds"]]);function Rc(n){let{status:e,body:t}=n,r=kc(t),o=n.retryAfterSeconds??Pc(t),i=Ac(t),s=i===void 0?void 0:Sc.get(i);if(s!==void 0)return new O(s,e,r,void 0,i);switch(e){case 304:return new O("not_modified",e,r);case 400:case 422:return new O("invalid",e,r,void 0,i);case 403:return new O("forbidden",e,r,void 0,i);case 404:return new O("not_found",e,r,void 0,i);case 402:return new O("insufficient_funds",e,r,void 0,i);case 409:return new O("conflict",e,r,void 0,i);case 412:return new O("precondition_failed",e,r,void 0,i);case 413:return new O("too_large",e,r,void 0,i);case 429:return new O("rate_limited",e,r,o,i);default:return new O("unavailable",e,r,o,i)}}function kc(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 xc(n){let t=n?.error?.details;return t===null?void 0:t}function Ac(n){let t=n?.error?.code;return typeof t=="string"&&t.length>0?t:void 0}function Pc(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 Ui(n,e,t){let r=`/v1/inventory/transfers/${_(e)}/accept`;return n.client.post(r,void 0,t?.signal)}async function Bi(n,e,t,r,o,i){let s=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/add`;return n.client.post(s,o,i?.signal)}async function Hi(n,e,t){let r=`/v1/inventory/transfers/${_(e)}/cancel`;return n.client.post(r,void 0,t?.signal)}async function Vi(n,e,t){let r=`/v1/games/${_(n.gameId())}/matchmaking/tickets/${_(e)}`;return n.client.delete(r,t?.signal)}async function Wi(n,e,t,r,o,i){let s=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/claim`;return n.client.post(s,o,i?.signal)}async function Ki(n,e,t){return n.client.post("/v1/characters",e,t?.signal)}async function Ji(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 zi(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 Yi(n,e,t){let r=`/v1/games/${_(n.gameId())}/matchmaking/tickets`;return n.client.post(r,e,t?.signal)}async function Xi(n,e,t,r,o){let i=`/v1/settings/${_(e)}/${_(t)}/${_(r)}`;return n.client.delete(i,o?.signal)}async function Qi(n,e,t,r,o){let i=`/v1/saves/${_(e)}/${_(t)}/${_(r)}`;return n.client.delete(i,o?.signal)}async function Zi(n,e,t,r){let o=`/v1/showcase/players/${_(e)}/${_(t)}`;return n.client.delete(o,r?.signal)}async function ea(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 ta(n,e,t,r,o,i){let s=`/v1/saves/${_(e)}/${_(t)}/${_(r)}/finalize`;return n.client.post(s,o,i?.signal)}async function na(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 ra(n,e,t){let r=`/v1/characters/${_(e)}`;return n.client.get(r,t?.signal)}async function oa(n,e,t){let r=`/v1/inventory/loot-tables/${_(e)}/drop-rates`;return n.client.get(r,t?.signal)}async function ia(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 aa(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(),s=`/v1/inventory/${_(e)}/${_(t)}`+(i?`?${i}`:"");return n.client.get(s,r?.signal)}async function sa(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/items/${_(r)}`;return n.client.get(i,o?.signal)}async function la(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)),o?.periods_back!==void 0&&i.set("periods_back",String(o?.periods_back)),o?.period!==void 0&&i.set("period",String(o?.period)),o?.player_id!==void 0&&i.set("player_id",String(o?.player_id));let s=i.toString(),a=`/v1/leaderboards/${_(e)}/${_(t)}/${_(r)}`+(s?`?${s}`:"");return n.client.get(a,o?.signal)}async function da(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/orders/${_(r)}`;return n.client.get(i,o?.signal)}async function ca(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}`;return n.client.get(i,o?.signal)}async function ua(n,e,t,r,o,i){let s=`/v1/inventory/${_(e)}/${_(t)}/catalogs/${_(r)}/recipes/${_(o)}/availability`;return n.client.get(s,i?.signal)}async function ma(n,e,t,r){let o=new URLSearchParams;o.set("limit",String(r?.limit));let i=o.toString(),s=`/v1/inventory/${_(e)}/${_(t)}/recipe-usage`+(i?`?${i}`:"");return n.client.get(s,r?.signal)}async function Or(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 pa(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)),t?.periods_back!==void 0&&r.set("periods_back",String(t?.periods_back)),t?.period!==void 0&&r.set("period",String(t?.period)),t?.player_id!==void 0&&r.set("player_id",String(t?.player_id));let o=r.toString(),i=`/v1/leaderboards/${_(e)}/friends`+(o?`?${o}`:"");return n.client.get(i,t?.signal)}async function ga(n,e,t){let r=`/v1/showcase/friends/${_(e)}`;return n.client.get(r,t?.signal)}async function ya(n,e,t){let r=`/v1/inbox/friend-challenges/${_(e)}`;return n.client.get(r,t?.signal)}async function ha(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)),t?.periods_back!==void 0&&r.set("periods_back",String(t?.periods_back)),t?.period!==void 0&&r.set("period",String(t?.period)),t?.player_id!==void 0&&r.set("player_id",String(t?.player_id));let o=r.toString(),i=`/v1/leaderboards/${_(e)}`+(o?`?${o}`:"");return n.client.get(i,t?.signal)}async function fa(n,e){let t=`/v1/games/${_(n.gameId())}/players/me/earn-allowance`;return n.client.get(t,e?.signal)}async function Sn(n,e){return n.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function ba(n,e,t){let r=`/v1/profiles/players/${_(e)}`;return n.client.get(r,t?.signal)}async function va(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 _a(n,e,t){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${_(e)}`;return n.client.get(r,t?.signal)}async function wa(n,e,t,r){let o=`/v1/showcase/players/${_(e)}/${_(t)}`;return n.client.get(o,r?.signal)}async function Sa(n,e){return n.client.get("/v1/characters/slots",e?.signal)}async function Ra(n,e,t){let r=`/v1/inventory/transfers/${_(e)}`;return n.client.get(r,t?.signal)}async function ka(n,e,t){let r=`/v1/games/${_(n.gameId())}/matchmaking/tickets/${_(e)}/heartbeat`;return n.client.post(r,void 0,t?.signal)}async function xa(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 Aa(n,e,t){return n.client.post("/v1/inventory/transfers",e,t?.signal)}async function Pa(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 Ea(n,e,t){return n.client.postBytes("/v1/functions/invoke",e,t?.signal)}async function Ta(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 Ia(n,e){return n.client.get("/v1/characters",e?.signal)}async function Ca(n,e,t,r){let o=`/v1/settings/${_(e)}/${_(t)}`;return n.client.get(o,r?.signal)}async function Ma(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(),s=`/v1/inventory/${_(e)}/${_(t)}/orders`+(i?`?${i}`:"");return n.client.get(s,r?.signal)}async function Oa(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(),s=`/v1/saves/${_(e)}/${_(t)}`+(i?`?${i}`:"");return n.client.get(s,r?.signal)}async function La(n,e){let t=new URLSearchParams;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/inbox/friend-challenges"+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function Ga(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 Da(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 Fa(n,e,t){let r=`/v1/inbox/friend-challenges/${_(e)}/answered`;return n.client.post(r,void 0,t?.signal)}async function $a(n,e,t,r){let o=`/v1/games/${_(n.gameId())}/matches/${_(e)}/end`;return n.client.post(o,t,r?.signal)}async function qa(n,e,t,r,o,i){let s=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/max`;return n.client.post(s,o,i?.signal)}async function ja(n,e,t,r,o,i){let s=`/v1/settings/${_(e)}/${_(t)}/${_(r)}`;return n.client.put(s,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Na(n,e,t,r,o){let i=`/v1/showcase/players/${_(e)}/${_(t)}`;return n.client.put(i,r,o?.signal)}async function Ua(n,e,t,r,o){let i=`/v1/inventory/${_(e)}/${_(t)}/rewarded-placements/${_(r)}/availability`;return n.client.get(i,o?.signal)}async function Ba(n,e,t){let r=`/v1/inventory/transfers/${_(e)}/reject`;return n.client.post(r,void 0,t?.signal)}async function Ha(n,e,t,r){let o=`/v1/characters/${_(e)}`;return n.client.patch(o,t,r?.signal)}async function Va(n,e,t,r,o,i){let s=`/v1/saves/${_(e)}/${_(t)}/${_(r)}/upload-url`;return n.client.post(s,o,i?.signal,{replaySafe:true})}async function Wa(n,e,t,r,o,i){let s=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/reset`;return n.client.post(s,o,i?.signal)}async function Ka(n,e,t){let r=`/v1/characters/${_(e)}`;return n.client.delete(r,t?.signal)}var U="gem-web-bridge",kn={min:1,max:1},st=65536,Ja=8,Rn=5e3,za=1024;function Gr(n){return Object.freeze(Object.assign(Object.create(null),n))}var Ya=Gr({"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.earnAllowanceChanged":30,"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.engaged":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.walletDisplay":60,"gem.menu":60,"gem.menuSelect":60,"gem.requestShare":6,"gem.requestAvatarPicker":6,"gem.vibrate":600,"gem.frameStats":120,"gem.portraitBorders":60,"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,"gem.requestFriendChallenge":12,"gem.friendChallengeResult":30,__malformed:60}),xn="__malformed";var Ec=Gr({"gem.requestAd":"ads","gem.adResult":"ads","gem.requestSignIn":"signIn","gem.signInResult":"signIn","gem.requestPurchase":"purchases","gem.purchaseResult":"purchases","gem.requestFriendChallenge":"friendChallenges","gem.friendChallengeResult":"friendChallenges","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.portraitBorders":"portraitBorders","gem.engaged":"engagement","gem.viewport":"viewport","gem.walletDisplay":"walletDisplay","gem.requestLocalServer":"localHost","gem.localServer":"localHost","gem.localServer.denied":"localHost","gem.cohorts":"cohorts","gem.earnAllowanceChanged":"earnAllowance","gem.deviceSettings":"deviceSettings","gem.deviceSettings.put":"deviceSettings","gem.deviceSettings.result":"deviceSettings","gem.requestShare":"share","gem.requestAvatarPicker":"avatarPicker","gem.vibrate":"vibration","gem.menu":"gameMenu","gem.menuSelect":"gameMenu"}),Tc=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"]]);function Xa(n){let e=Ec[n];if(e!==void 0)return e;for(let[t,r]of Tc)if(n.startsWith(t))return r}function Dr(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 Ic(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 Cc(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function Mc(n){return /^[a-z_]+$/.test(n)}function Lr(n,e,t){if(e>Ja)return `nesting deeper than ${Ja}`;if(++t.nodes>Rn)return `more than ${Rn} values`;if(t.bytes>st)return `over the ${st} 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>za)return `an array of ${n.length} entries, over the ${za} limit`;t.bytes+=2;for(let a of n){let l=Lr(a,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 s=n;for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;if(++t.nodes>Rn)return `more than ${Rn} values`;if(t.bytes+=a.length*3+4,t.bytes>st)return `over the ${st} byte limit`;let l=Lr(s[a],e+1,t);if(l)return l}return null}function Oc(n){let e={nodes:0,bytes:0,seen:new Set},t=Lr(n,0,e);return t?`message contains ${t}`:e.bytes>st?`message is over the ${st} byte limit`:null}var Lc={origin:[Dr,"not a well-formed origin"],url:[Ic,"not a safe absolute http(s) URL"],bcp47:[Cc,"not a well-formed BCP 47 tag"],code:[Mc,"not a code of lower-case letters and underscores"]};function Qa(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 s=Za(i,r,o);if(s)return s}return null}function Za(n,e,t){switch(e.k){case "s":{if(typeof n!="string")return `${t}: expected string`;if(n.length>e.max)return `${t}: exceeds ${e.max} characters`;if(e.f){let[r,o]=Lc[e.f];if(!r(n))return `${t}: ${o}`}return null}case "i":return typeof n!="number"||!Number.isInteger(n)?`${t}: expected integer`:n<e.lo||n>e.hi?`${t}: out of range ${e.lo}..${e.hi}`:null;case "b":return typeof n=="boolean"?null:`${t}: expected boolean`;case "e":{let r=e.v;return r.includes(n)?null:`${t}: not one of ${r.join("|")}`}case "o":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected object`:Qa(n,e.fs,t);case "j":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected a plain object`:null;case "a":{if(!Array.isArray(n))return `${t}: expected array`;if(n.length>e.max)return `${t}: exceeds ${e.max} items`;let r=e.it,o=`${t}[]`;for(let i of n){if(i==null){if(r.o)continue;return `${o}: required`}let s=Za(i,r,o);if(s)return s}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}function P(n,e){return t=>{let r=Oc(t);if(r)return r;if(typeof t!="object"||t===null||Array.isArray(t))return "message: expected object";let o=t;return o.gem!==U?"gem: wrong protocol marker":o.type!==n?`type: expected ${n}`:Qa(o,e,"")}}var Gc=P("gem.handshake",[{n:"versions",k:"o",fs:[{n:"min",k:"i",lo:1,hi:1e3},{n:"max",k:"i",lo:1,hi:1e3}]},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}},{n:"embedder",k:"s",max:2048,f:"origin"},{n:"unbidden",k:"b",o:1}]),Dc=P("gem.handshake.accept",[{n:"v",k:"i",lo:1,hi:1e3},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}}]),Fc=P("gem.token",[{n:"token",k:"s",max:4096},{n:"requestId",k:"s",o:1,max:64},{n:"generation",k:"i",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"s",o:1,max:512,f:"url"},{n:"playerId",k:"s",max:64},{n:"gameId",k:"s",max:64},{n:"channel",k:"e",v:["dev","test","release"]},{n:"gameVersion",k:"s",o:1,max:64},{n:"expiresAt",k:"i",lo:0,hi:4102444800},{n:"chainEndsAt",k:"i",lo:0,hi:4102444800},{n:"allowDevTools",k:"b",o:1}]),$c=P("gem.token.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:36e5},{n:"reason",k:"e",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"s",max:64}]),qc=P("gem.player",[{n:"untrusted",k:"o",fs:[{n:"displayName",k:"s",max:64},{n:"displayTag",k:"s",o:1,max:80},{n:"displayHandle",k:"s",max:80}]},{n:"playerId",k:"s",o:1,max:64},{n:"discriminator",k:"s",o:1,max:8},{n:"avatarIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatarIconId",k:"s",o:1,max:64},{n:"badges",k:"a",o:1,max:2,it:{n:"",k:"o",fs:[{n:"itemId",k:"s",max:64},{n:"iconUrl",k:"s",max:2048,f:"url"}]}},{n:"displayTag",k:"s",max:8},{n:"avatarUrl",k:"s",o:1,max:2048,f:"url"},{n:"boost",k:"o",o:1,fs:[{n:"multipliers",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"currencyId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"multiplierBp",k:"i",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"i",o:1,lo:1,hi:7}]}]),jc=P("gem.pause",[{n:"paused",k:"b"}]),Nc=P("gem.prefs",[{n:"reducedMotion",k:"b"},{n:"muted",k:"b"},{n:"showFrameStats",k:"b",o:1},{n:"locale",k:"s",max:35,f:"bcp47"},{n:"recommended",k:"o",o:1,fs:[{n:"volume",k:"i",lo:0,hi:100},{n:"batterySaver",k:"b"},{n:"keyboardLayout",k:"e",v:["wasd","arrows"]},{n:"gamepadConfirm",k:"e",v:["south","east"]},{n:"vibration",k:"b"}]}]),Uc=P("gem.cohorts",[{n:"cohorts",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"experimentId",k:"s",max:36},{n:"variantKey",k:"s",max:32}]}}]),Bc=P("gem.earnAllowanceChanged",[]),Hc=P("gem.viewport",[{n:"insets",k:"o",fs:[{n:"top",k:"i",lo:0,hi:4096},{n:"right",k:"i",lo:0,hi:4096},{n:"bottom",k:"i",lo:0,hi:4096},{n:"left",k:"i",lo:0,hi:4096}]},{n:"reserved",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384},{n:"width",k:"i",lo:0,hi:16384},{n:"height",k:"i",lo:0,hi:16384}]}}]),Vc=P("gem.deviceSettings",[{n:"settings",k:"j",o:1}]),Wc=P("gem.willTerminate",[{n:"reason",k:"e",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"i",lo:0,hi:6e4}]),Kc=P("gem.roomEvent",[{n:"event",k:"e",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"s",max:64},{n:"matchId",k:"s",o:1,max:64},{n:"version",k:"i",o:1,lo:0,hi:2147483647},{n:"reason",k:"s",o:1,max:64},{n:"platform",k:"e",o:1,v:["universal","mobile"]}]),Jc=P("gem.socketState",[{n:"connected",k:"b"},{n:"reason",k:"e",o:1,v:["connecting","dropped","watchdog","terminal"]}]),zc=P("gem.seatedEvent",[{n:"roomId",k:"s",max:64}]),Yc=P("gem.autoStartFailedEvent",[{n:"roomId",k:"s",max:64},{n:"code",k:"s",max:64}]),Xc=P("gem.signalEvent",[{n:"event",k:"e",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}]),Qc=P("gem.dedicatedEvent",[{n:"event",k:"e",v:["answer","error","matchEnded"]},{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",o:1,max:10240},{n:"sessionId",k:"s",o:1,max:64},{n:"code",k:"s",o:1,max:64},{n:"message",k:"s",o:1,max:256},{n:"reason",k:"s",o:1,max:64}]),Zc=P("gem.partyResult",[{n:"requestId",k:"s",max:64},{n:"partyId",k:"s",o:1,max:64}]),eu=P("gem.clusterTarget",[{n:"clusterTargetId",k:"s",max:64},{n:"clusterTargetIds",k:"a",o:1,max:3,it:{n:"",k:"s",max:64}}]),tu=P("gem.devtools",[{n:"action",k:"e",v:["open","close","toggle"]}]),nu=P("gem.screenshot",[{n:"maxWidth",k:"i",lo:1,hi:7680},{n:"maxHeight",k:"i",lo:1,hi:4320}]),ru=P("gem.screenshot.denied",[{n:"reason",k:"e",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"b"}]),ou=P("gem.requestContext",[]),iu=P("gem.gameContext",[{n:"context",k:"j"}]),au=P("gem.signal",[{n:"signal",k:"e",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}]),su=P("gem.dedicatedOffer",[{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",max:10240},{n:"intent",k:"e",v:["initial","ice_restart","full_reconnect"]}]),lu=P("gem.partyRequest",[{n:"requestId",k:"s",max:64}]),du=P("gem.ready",[]),cu=P("gem.engaged",[]),uu=P("gem.progress",[{n:"loaded",k:"i",lo:0,hi:1099511627776},{n:"total",k:"i",lo:0,hi:1099511627776}]),mu=P("gem.requestToken",[{n:"requestId",k:"s",max:64},{n:"reason",k:"e",v:["initial","expiring","rejected"]}]),pu=P("gem.requestLocalServer",[{n:"requestId",k:"s",max:64},{n:"gameRoomId",k:"s",max:64}]),gu=P("gem.localServer",[{n:"requestId",k:"s",max:64},{n:"serverId",k:"s",o:1,max:128}]),yu=P("gem.localServer.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"reason",k:"e",v:["refused","unavailable"]}]),hu=P("gem.exit",[{n:"reason",k:"s",o:1,max:64}]),fu=P("gem.openExternal",[{n:"url",k:"s",max:2048,f:"url"}]),bu=P("gem.requestFullscreen",[{n:"enabled",k:"b"}]),vu=P("gem.audioState",[{n:"muted",k:"b"}]),_u=P("gem.rewardCue",[{n:"currencySlug",k:"s",max:32},{n:"expected",k:"i",o:1,lo:1,hi:1e9},{n:"origin",k:"o",o:1,fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384}]}]),wu=P("gem.walletDisplay",[{n:"visible",k:"b"},{n:"currencies",k:"a",o:1,max:8,it:{n:"",k:"s",max:64}},{n:"score",k:"b",o:1}]),Su=P("gem.menu",[{n:"settings",k:"b"},{n:"items",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"id",k:"s",max:32},{n:"label",k:"s",max:40}]}}]),Ru=P("gem.menuSelect",[{n:"entry",k:"e",v:["settings","item"]},{n:"id",k:"s",o:1,max:32}]),ku=P("gem.requestShare",[{n:"params",k:"a",max:16,it:{n:"",k:"o",fs:[{n:"key",k:"s",max:64},{n:"value",k:"s",max:512}]}}]),xu=P("gem.requestAvatarPicker",[]),Au=P("gem.vibrate",[{n:"pattern",k:"a",max:99,it:{n:"",k:"i",lo:0,hi:1e4}}]),Pu=P("gem.frameStats",[{n:"fps",k:"i",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"i",lo:0,hi:1e5}]),Eu=P("gem.portraitBorders",[{n:"name",k:"s",o:1,max:40}]),Tu=P("gem.error",[{n:"code",k:"e",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"s",o:1,max:256}]),Iu=P("gem.requestPurchase",[{n:"requestId",k:"s",max:64},{n:"purchaseKind",k:"e",v:["item","recipe"]},{n:"targetId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"quantity",k:"i",o:1,lo:1,hi:10},{n:"catalogId",k:"s",o:1,max:64}]),Cu=P("gem.purchaseResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["ok","declined","unavailable"]},{n:"reason",k:"s",o:1,max:64,f:"code"},{n:"purchaseId",k:"s",o:1,max:64}]),Mu=P("gem.deviceSettings.put",[{n:"requestId",k:"s",max:64},{n:"settings",k:"j"}]),Ou=P("gem.deviceSettings.result",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["stored","too_large","unavailable"]}]),Lu=P("gem.requestAd",[{n:"requestId",k:"s",max:64},{n:"placement",k:"s",max:32},{n:"format",k:"e",v:["interstitial","rewarded"]}]),Gu=P("gem.adResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["shown","no_ad","unavailable"]}]),Du=P("gem.requestSignIn",[{n:"requestId",k:"s",max:64}]),Fu=P("gem.signInResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["signed_in","declined","unavailable"]}]),$u=P("gem.requestFriendChallenge",[{n:"requestId",k:"s",max:64},{n:"playerId",k:"s",max:64},{n:"template",k:"s",max:64},{n:"params",k:"j",o:1}]),qu=P("gem.friendChallengeResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"s",o:1,max:64},{n:"param",k:"s",o:1,max:64},{n:"channel",k:"s",o:1,max:16},{n:"configVersion",k:"i",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:864e5},{n:"detail",k:"s",o:1,max:300}]),An=Gr({"gem.handshake":Gc,"gem.handshake.accept":Dc,"gem.token":Fc,"gem.token.denied":$c,"gem.player":qc,"gem.pause":jc,"gem.prefs":Nc,"gem.cohorts":Uc,"gem.earnAllowanceChanged":Bc,"gem.viewport":Hc,"gem.deviceSettings":Vc,"gem.willTerminate":Wc,"gem.roomEvent":Kc,"gem.socketState":Jc,"gem.seatedEvent":zc,"gem.autoStartFailedEvent":Yc,"gem.signalEvent":Xc,"gem.dedicatedEvent":Qc,"gem.partyResult":Zc,"gem.clusterTarget":eu,"gem.devtools":tu,"gem.screenshot":nu,"gem.screenshot.denied":ru,"gem.requestContext":ou,"gem.gameContext":iu,"gem.signal":au,"gem.dedicatedOffer":su,"gem.partyRequest":lu,"gem.ready":du,"gem.engaged":cu,"gem.progress":uu,"gem.requestToken":mu,"gem.requestLocalServer":pu,"gem.localServer":gu,"gem.localServer.denied":yu,"gem.exit":hu,"gem.openExternal":fu,"gem.requestFullscreen":bu,"gem.audioState":vu,"gem.rewardCue":_u,"gem.walletDisplay":wu,"gem.menu":Su,"gem.menuSelect":Ru,"gem.requestShare":ku,"gem.requestAvatarPicker":xu,"gem.vibrate":Au,"gem.frameStats":Pu,"gem.portraitBorders":Eu,"gem.error":Tu,"gem.requestPurchase":Iu,"gem.purchaseResult":Cu,"gem.deviceSettings.put":Mu,"gem.deviceSettings.result":Ou,"gem.requestAd":Lu,"gem.adResult":Gu,"gem.requestSignIn":Du,"gem.signInResult":Fu,"gem.requestFriendChallenge":$u,"gem.friendChallengeResult":qu});var le={now:()=>Date.now(),setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n)},At=class{constructor(e=le){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let t=Ya[e];if(t===void 0)return false;let r=this.clock.now(),o=this.lastRefill.get(e)??r,i=this.tokens.get(e)??t,s=Math.max(0,r-o),a=Math.min(t,i+s*t/6e4);return a<1?(this.tokens.set(e,a),this.lastRefill.set(e,r),false):(this.tokens.set(e,a-1),this.lastRefill.set(e,r),true)}};function Fr(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 es(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 ts(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 En=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(a=>a.currencyId===e),s;return !i&&this.resolveCurrencyId&&(s=await this.resolveCurrencyId(e).catch(()=>{}),s!==void 0&&(i=o.find(a=>a.currencyId===s))),{currencyId:i?i.currencyId:s??e,total:i?i.total:null,...i?.buckets===void 0?{}:{buckets:i.buckets}}}};function qr(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 ns="inventory",lt=n=>typeof n=="number"?n:0,Pt=n=>typeof n=="string"?n:"";function $r(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 rs(n){let e=n??{};return {itemDefinitionId:Pt(e.item_definition_id),instanceId:Pt(e.instance_id),quantity:lt(e.quantity),acquiredAt:lt(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function ju(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0;return {currencies:$r(e.currencies,r=>{let o=r??{},i=Array.isArray(o.buckets)?o.buckets.map(s=>{let a=s??{};return {bucket:Pt(a.bucket),balance:lt(a.balance)}}):void 0;return {currencyId:Pt(o.currency_id),total:lt(o.total),...i===void 0?{}:{buckets:i}}}),items:$r(e.items,rs),progressions:$r(e.progressions,r=>{let o=r??{};return {progressionDefinitionId:Pt(o.progression_definition_id),currentValue:lt(o.current_value),completionCount:lt(o.completion_count),isCompleted:o.is_completed===true,...qr(o)}}),...t===void 0?{}:{etag:t}}}var Tn=class{constructor(e,t,r){this.api=e;this.entity=t;this.cache=r;}api;entity;cache;snapshot(e={}){let t=e.buckets?`${ns}#buckets`:ns;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(s=>s.itemDefinitionId===e);if(i.length>0)return i}let o=await sa(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return Array.isArray(o)?o.map(rs):[]}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 aa(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 ju(t)}};var Nu={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},Uu=new Set(Object.keys(Nu));function os(n){return typeof n=="string"&&Uu.has(n)?n:"error"}var De=class extends RangeError{constructor(t,r){super(r);this.code=t;this.name="PurchaseRefusal";}code;retryable=false};var Q=n=>typeof n=="string"?n:"",Bu=n=>typeof n=="string"?n:Q(n&&typeof n=="object"?n.type:void 0),xe=n=>typeof n=="number"?n:0;function Hu(n){let e=n??{};return {prerequisiteType:Q(e.prerequisite_type),referenceId:Q(e.reference_id),required:xe(e.required),current:xe(e.current)}}function Et(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0;return {orderId:Q(e.order_id),status:Q(e.status),...t===void 0?{}:{etag:t}}}function In(){return crypto.randomUUID()}var Vu="recipe-usage",is=100;function Cn(n){let e=n??{};switch(e.type){case "currency":return {kind:"currency",currencyId:Q(e.currency_id),bucket:Q(e.bucket),delta:xe(e.delta),balanceAfter:xe(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:Q(e.item_definition_id),instanceId:Q(e.instance_id),delta:xe(e.delta),quantityAfter:xe(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:Q(e.progression_definition_id),delta:xe(e.delta),valueAfter:xe(e.value_after),completed:e.completed===true};default:return {kind:"other",type:Q(e.type)}}}function Wu(n){let e=n??{},t=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:Q(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(Cn):[]}}function Ku(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(Wu):void 0;return {orderId:Q(e.order_id),status:Q(e.status),...t===void 0?{}:{etag:t},granted:Array.isArray(e.granted)?e.granted.map(Cn):[],consumed:Array.isArray(e.consumed)?e.consumed.map(Cn):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(Cn):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function Ju(n){let e=n??{},t=e.price??{};return {payment:"platform_currency",orderId:Q(e.target_order_id)||Q(e.source_order_id),status:Q(e.status),purchaseId:Q(e.purchase_id),sourceOrderId:Q(e.source_order_id),price:{currencyId:Q(t.platform_currency_id),amount:xe(t.price)}}}function zu(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:Q(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 as(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 Mn=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(()=>zi(this.api,this.entity.type,this.entity.id,{operations:e.map(as),source:t.source??"play",nonce:In()},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}));return Et(r)}async createMany(e,t={}){return this.write(()=>Ji(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(as),nonce:In()})),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 ua(this.api,this.entity.type,this.entity.id,e,t,r===void 0?{}:{signal:r})??{},s=typeof i.uses_remaining=="number"?i.uses_remaining:void 0,a=typeof i.cooldown_expires_at=="string"?i.cooldown_expires_at:void 0,l=Array.isArray(i.lock_reasons)?i.lock_reasons.map(Hu):[];return {canExecute:i.can_execute===true,locked:i.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(i.reasons)?i.reasons.map(d=>Bu(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(Vu,[],async()=>{let t=await ma(this.api,this.entity.type,this.entity.id,{limit:is})??{},r=Array.isArray(t.usages)?t.usages:[];return {usages:r.map(zu),truncated:r.length>=is}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,t={}){if(e.payment.kind==="configured"){let u=e,p=await this.write(()=>ea(this.api,this.entity.type,this.entity.id,{catalog_id:u.catalogId,recipe_id:u.targetId,game_id:this.api.gameId(),nonce:In()},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}));return {payment:"configured",...Ku(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([va(this.api,t.signal===void 0?{}:{signal:t.signal}),Sn(this.api,t.signal===void 0?{}:{signal:t.signal})]),i=e.payment.currencySlug.toLowerCase(),s=o.currencies.find(u=>u.currency_id.toLowerCase()===i||u.slug.toLowerCase()===i);if(s===void 0){let u=o.currencies.map(p=>p.slug);throw new De("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${u.length===0?"none":u.join(", ")}`)}let a=e.kind==="item"?r.items.find(u=>u.item_id===e.targetId):r.recipes.find(u=>u.recipe_id===e.targetId&&u.catalog_id===e.catalogId);if(a===void 0)throw new De("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=a.platform_prices.find(u=>u.platform_currency_id===s.currency_id);if(l===void 0){let u=g=>o.currencies.find(y=>y.currency_id===g)?.slug??g,p=a.platform_prices.map(g=>`${u(g.platform_currency_id)} ${g.price}`);throw new De("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${s.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 De("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>Pa(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:s.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:In(),confirmation:"none"},t.signal===void 0?{}:{signal:t.signal}));return Ju(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(()=>Bi(this.api,this.entity.type,this.entity.id,e,{amount:t,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Et(o)}async maxProgression(e,t,r){let o=await this.write(()=>qa(this.api,this.entity.type,this.entity.id,e,{value:t,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Et(o)}async claimProgression(e,t){let r=await this.write(()=>Wi(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},t===void 0?{}:{signal:t}));return Et(r)}async resetProgression(e,t){let r=await this.write(()=>Wa(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},t===void 0?{}:{signal:t}));return Et(r)}async write(e){return this.cache.invalidate(),e()}};var jr=n=>typeof n=="string"?n:"",Yu=n=>typeof n=="number"?n:0;function ss(n){let e=n??{};return {orderId:jr(e.order_id),status:jr(e.status),source:jr(e.source),createdAt:Yu(e.created_at)}}var On=class{constructor(e,t){this.api=e;this.entity=t;}api;entity;async list(e={}){let r=await Ma(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(ss):[],...o===void 0?{}:{nextCursor:o}}}async get(e,t){let r=await da(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return ss(r)}};var ls=n=>typeof n=="number"?n:0,Xu=n=>typeof n=="string"?n:"";function Qu(n){let e=n??{};return {progressionDefinitionId:Xu(e.progression_definition_id),currentValue:ls(e.current_value),completionCount:ls(e.completion_count),isCompleted:e.is_completed===true,...qr(e)}}var Ln=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 ca(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return Qu(i)}catch{return o??null}}};var Gn=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,s=i?e:e+"\0"+t.join("\0"),a=this.slots.get(s);if(a){let u=a.filledAt;if(u!==void 0&&(o===void 0||this.clock.now()-u<=o))return Promise.resolve(a.value);if(a.inFlight)return a.inFlight}let l=a??{};this.slots.set(s,l);let d=this.generation,m=r().then(u=>(i&&this.generation===d&&(l.value=u,l.filledAt=this.clock.now()),u)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(s)===l&&this.slots.delete(s));});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 Nr(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 Ur(n){try{let e=Nr(await n.text());return e?`Storage said: ${e}`:""}catch{return ""}}var ae=class extends Error{constructor(t,r){super(r);this.reason=t;this.name="GemSaveError";}reason},Zu=3e4,ds="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",em=/^[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(!em.test(n)||n.startsWith("_"))throw new TypeError(`${JSON.stringify(n)} is not a usable save key: ${e}.`);return n}function cs(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 tm=new Set(["x-ms-blob-type"]),nm=/^[ -~]+$/;function rm(n,e){if(n==null)return {};if(typeof n!="object"||Array.isArray(n))throw new ae("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(!tm.has(i))throw new ae("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"||!nm.test(o))throw new ae("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 ae("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(i)} twice.`);t[i]=o;}return t}function Hr(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 Vr(n){return n?.reason==="not_found"}var Dn=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 ae("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 ae("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),s=cs(r.signal,i);try{let a=await Va(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:s.signal});if(typeof a.upload_url!="string"||typeof a.session_id!="string")throw new ae("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=rm(a.upload_headers,e),d,m=this.options.fetch??globalThis.fetch.bind(globalThis);try{d=await m(a.upload_url,{method:"PUT",headers:{"content-type":o,...l},body:t,credentials:"omit",signal:s.signal});}catch(u){throw Br(s.signal,r.signal)?this.timeout("upload",i):new ae("upload_failed",`${ds} for PUT. Underlying error: ${u}`)}if(!d.ok){let u=await Ur(d);throw new ae("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. "+u:`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. ":"")+u)}return Hr(await ta(this.api,this.entity.type,this.entity.id,Ae(e),{session_id:a.session_id},{signal:s.signal}))}catch(a){throw this.rethrow(a,r.signal,s.signal,"save",i)}finally{s.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 ae("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=cs(t.signal,r);try{let i;try{let l=await Or(this.api,this.entity.type,this.entity.id,Ae(e),{signal:o.signal});if(!l.modified)return null;i=l.body;}catch(l){if(Vr(l))return null;throw l}if(typeof i.download_url!="string")throw new ae("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let s=this.options.fetch??globalThis.fetch.bind(globalThis),a;try{a=await s(i.download_url,{credentials:"omit",signal:o.signal});}catch(l){throw Br(o.signal,t.signal)?this.timeout("download",r):new ae("download_failed",`${ds} for GET. Underlying error: ${l}`)}if(!a.ok){let l=await Ur(a);throw new ae("download_failed",`the save download answered ${a.status}. `+(a.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 a.arrayBuffer())}catch(i){throw this.rethrow(i,t.signal,o.signal,"load",r)}finally{o.release();}}async describe(e,t={}){try{let r=await Or(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?Hr(r.body):null}catch(r){if(Vr(r))return null;throw r}}async list(e={}){let t=await Oa(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(Hr),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,t){try{await Qi(this.api,this.entity.type,this.entity.id,Ae(e),{...t===void 0?{}:{signal:t}});}catch(r){if(!Vr(r))throw r}}budget(e){return e??this.options.timeoutMs??Zu}timeout(e,t){return new ae("save_timeout",`the save ${e} did not finish within ${t}ms`)}rethrow(e,t,r,o,i){return e instanceof ae?e:Br(r,t)?this.timeout(o,i):e}};function om(n){try{return Mr(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"?om(t.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof t.updated_at=="number"?t.updated_at:0}}var Fn=class{constructor(e,t){this.api=e;this.entity=t;}api;entity;async list(e){let r=(await Ca(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 ia(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(us(r))return null;throw r}}async put(e,t,r={}){let o=await ja(this.api,this.entity.type,this.entity.id,e,{value:_n(t)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return Wr(o)}async delete(e,t){try{await Xi(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});}catch(r){if(!us(r))throw r}}};function us(n){return n?.reason==="not_found"}function $n(n,e,t={}){let r=new Gn(le,t.identity);t.onInventoryChanged&&r.onInvalidate(t.onInventoryChanged);let o=new Tn(n,e,r);return {settings:new Fn(n,e),inventory:o,saves:new Dn(n,e,t.saves??{}),currencies:new En(o,t.resolveCurrencyId),mutations:new Mn(n,e,r),orders:new On(n,e),progressions:new Ln(n,e,o)}}var Kr={type:"players",id:"me"};var Ne=n=>typeof n=="string"?n:"",dt=n=>typeof n=="number"?n:0;function qn(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:dt(t.slot_index),isActive:t.is_active!==false,createdAt:Ne(t.created_at),updatedAt:Ne(t.updated_at)}}var jn=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=$n(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 Ia(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(o=>qn(this.scope,o)):[]}async get(e,t){let r=await ra(this.api,e,t===void 0?{}:{signal:t});return qn(this.scope,r)}async create(e){let t=await Ki(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return qn(this.scope,t)}async update(e,t,r){let o=await Ha(this.api,e,{name:t},r===void 0?{}:{signal:r});return qn(this.scope,o)}async delete(e,t){await Ka(this.api,e,t===void 0?{}:{signal:t});}async slots(e){let r=await Sa(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:dt(r?.total_slots),availableSlots:dt(r?.available_slots),activeCharacterCount:dt(r?.active_character_count),defaultMaxSlots:dt(r?.default_max_slots),purchasedExtraSlots:dt(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var ye=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 fe(n){return new ye(n)}var Ue={toPlain(n){return ye.unwrap(n)},compare(n,e,t){let r=n instanceof ye?ye.unwrap(n):n,o=e instanceof ye?ye.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 ye?ye.unwrap(n):n,r=e instanceof ye?ye.unwrap(e):e;return t.normalize("NFC")===r.normalize("NFC")}};var ct=n=>typeof n=="string"?n:"";function Nn(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:ct(e.transfer_id),status:ct(e.status),sourceEntityId:ct(e.source_entity_id),targetEntityId:ct(e.target_entity_id),...t===void 0?{}:{message:fe(t)},createdAt:ct(e.created_at),expiresAt:ct(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function im(){return crypto.randomUUID()}var Un=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 Aa(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:im()},e.signal===void 0?{}:{signal:e.signal});return Nn(t)}async list(e={}){let r=await Da(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(Nn):[],...o===void 0?{}:{nextCursor:o}}}async get(e,t){let r=await Ra(this.api,e,t===void 0?{}:{signal:t});return Nn(r)}async accept(e,t){return this.resolve(()=>Ui(this.api,e,t===void 0?{}:{signal:t}))}async reject(e,t){return this.resolve(()=>Ba(this.api,e,t===void 0?{}:{signal:t}))}async cancel(e,t){return this.resolve(()=>Hi(this.api,e,t===void 0?{}:{signal:t}))}async resolve(e){return this.inventory.invalidate(),Nn(await e())}};var am=n=>typeof n=="string"?n:"",sm=n=>typeof n=="string"&&n?n:void 0,lm=n=>typeof n=="number"?n:void 0;function ms(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 dm(n){if(typeof n!="object"||n===null||Array.isArray(n))throw new ce("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 ce("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=lm(e.version);if(r===void 0)throw new ce("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let o=(l,d,m)=>{let u=am(l.id);if(!u)throw new ce("config_malformed",`${d}[${m}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return u},i=t("items");i.forEach((l,d)=>o(l??{},"items",d));let s=t("currencies");s.forEach((l,d)=>o(l??{},"currencies",d));let a=n;return {...a,version:r,hash:typeof a.hash=="string"?a.hash:"",items:i,currencies:s,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 a.kv=="object"&&a.kv!==null&&!Array.isArray(a.kv)?a.kv:{},item:ms(i),currency:ms(s)}}var ce=class extends Error{constructor(t,r){super(r);this.reason=t;this.name="GemConfigError";}reason},ps=10*1024*1024,gs=15e3,ys=new Set(["dev","test","release"]);function cm(n){if(!ys.has(n))throw new ce("config_channel_unknown",`the play token names channel "${n}", which is not one of ${[...ys].join(", ")}. gem-api would reject the assignment read.`);return n}var Bn=n=>typeof n=="number"?n:0,Jr=n=>typeof n=="string"?n:"";function um(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:Jr(o.entry_id),weight:Bn(o.weight),dropRate:Bn(o.drop_rate),...i===void 0?{}:{rarityTier:i}}}):[];return {lootTableId:Jr(e.loot_table_id),name:Jr(e.name),rollCount:Bn(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Bn(e.total_weight),entries:t}}var Hn=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 ce("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 s=(async()=>{let a=await oa(this.api,e,t===void 0?{}:{signal:t});return um(a)})().catch(a=>{throw o?.get(e)===s&&o.delete(e),a});return o.set(e,s),s}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??gs),t;try{let l=await na(this.api,cm(this.channel()),{signal:e});if(!l.modified)throw new ce("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");t=l.body;}catch(l){if(l instanceof ce)throw l;if(l?.reason==="not_found")return null;throw l}let r=sm(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 ce("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??gs}ms`):new ce("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=>Nr(d)).catch(()=>"");throw new ce("config_unreachable",`the config document answered ${i.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let s=await i.text();if(s.length>ps)throw new ce("config_too_large",`the config document is ${s.length} bytes, over the ${ps} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new ce("config_malformed",`config document is not JSON: ${String(l)}`)}return dm(a)}};var hs=400,Pe=n=>typeof n=="string"?n:"",mm=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Be(n){let e=Pe(n);if(!mm.test(e))return 0;let t=Date.parse(e);return Number.isFinite(t)?Math.floor(t/1e3):0}var pm=/^[0-9a-f]{1,64}$/,gm=/^[0-9a-f]{16}$/,ym=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,hm=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function zr(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])],s=new Date(Date.UTC(r,o-1,i));return s.getUTCFullYear()===r&&s.getUTCMonth()===o-1&&s.getUTCDate()===i?e:void 0}var fm=4096,bm=new TextEncoder;function vm(n){let e=Pe(n.challenge_data),t=Pe(n.challenge_data_hash);return e===""||!gm.test(t)?{}:bm.encode(e).length>fm?{}:{data:e,dataHash:t}}function _m(n){let e=n??{},t=Be(e.period_start_at),r=Be(e.period_ends_at);if(t===0||r===0)return;let o=Pe(e.slug),i=Pe(e.seed),s=zr(e.period_local_date),a=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,...s===void 0?{}:{periodLocalDate:s},boundary:ym.test(a)?a:"",resetTime:hm.test(l)?l:"",seed:pm.test(i)?i:"",...vm(e)}}function ut(n){if(n!==void 0&&(!Number.isInteger(n)||n<0||n>400))throw new TypeError(`periodsBack must be an integer between 0 and 400, got ${String(n)}`)}function Vn(n){let e=n??{};return Array.isArray(e.challenges)?e.challenges.map(_m).filter(t=>t!==void 0):[]}var Tt=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:t}=e;ut(t);let r=await Ta(this.#e,{...t===void 0?{}:{periods_back:t},...e.signal===void 0?{}:{signal:e.signal}});return Vn(r)}};function He(n){return typeof n=="string"&&n!==""?n:void 0}var fs=new Set(["localhost","127.0.0.1","[::1]"]);function Yr(n){let e=He(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:"&&fs.has(t.hostname)))return e}function wm(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=t??{},o=He(r.item_id),i=Yr(r.icon_url);o!==void 0&&i!==void 0&&e.push({itemId:o,iconUrl:i});}return e}function we(n){let e=n??{},t=He(e.player_id),r=He(e.display_name),o=He(e.discriminator),i=He(e.display_tag),s=He(e.avatar_icon_id),a=Yr(e.avatar_icon_url);return {...t===void 0?{}:{playerId:t},...r===void 0?{}:{displayName:fe(r)},...o===void 0?{}:{discriminator:o},...i===void 0?{}:{displayTag:fe(i)},...s===void 0?{}:{avatarIconId:s},...a===void 0?{}:{avatarIconUrl:a},badges:wm(e.badges)}}var Sm=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Rm(n){if(n===void 0)return;let e=Yr(n);if(e===void 0)return;let t=new URL(e);return fs.has(t.hostname)||Sm.has(t.origin)?e:void 0}var bs=100,ws=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function Xr(n){let{periodsBack:e,period:t,playerId:r}=n;if(ut(e),e!==void 0&&t!==void 0)throw new TypeError("pass periodsBack or period, not both");if(t!==void 0&&(typeof t!="string"||!ws.test(t)))throw new TypeError(`period must be a period id such as 2026-10-02 (a result's period.id), got ${String(t)}`);if(r!==void 0&&(typeof r!="string"||r===""))throw new TypeError("playerId must be a player id");return {...e===void 0?{}:{periods_back:e},...t===void 0?{}:{period:t},...r===void 0?{}:{player_id:r}}}function Ss(n){let e=typeof n.period_id=="string"?n.period_id:"";if(!ws.test(e))return;let t=zr(n.period_local_date),r=Be(n.period_start_at),o=Be(n.period_ends_at),i=r>0&&o>0;return {id:e,...t===void 0?{}:{localDate:t},...i?{startAt:r,endsAt:o}:{},opensAt:Be(n.opens_at),closesAt:Be(n.closes_at),final:n.final===true}}var It=n=>typeof n=="string"?n:"",mt=n=>typeof n=="number"?n:0,Ct=n=>typeof n=="string"?n:void 0,km=n=>typeof n=="number"?n:void 0,Rs={player:"players",character:"characters"};function xm(n,e){let t=n??{},r=Ct(t.entity_id),o=typeof t.entity_type=="string"&&Object.hasOwn(Rs,t.entity_type)?t.entity_type:void 0,i=ks(t.stats),s=t.properties!==null&&typeof t.properties=="object"?t.properties:void 0,a=e?t.is_viewer===true:void 0;return {...we(t),rank:mt(t.rank),occurredAt:mt(t.occurred_at),...a===void 0?{}:{isViewer:a},...r===void 0?{}:{entityId:r},...o===void 0?{}:{entityType:o},...i===void 0?{}:{stats:i},...s===void 0?{}:{properties:s}}}function vs(n,e){let t=n??{},r=Ct(t.bucket_1),o=Ct(t.bucket_2),i=km(t.update_frequency_seconds),s=Ss(t);return {leaderboardType:It(t.leaderboard_type),runType:It(t.run_type),...r===void 0?{}:{bucket1:r},...o===void 0?{}:{bucket2:o},entries:Array.isArray(t.entries)?t.entries.map(a=>xm(a,e)):[],generatedAt:mt(t.generated_at),...i===void 0?{}:{updateFrequencySeconds:i},...s===void 0?{}:{period:s}}}function _s(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:mt(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 Am(n,e,t){let r=n??{},o=Ct(r.bucket_1),i=Ct(r.bucket_2),s=Ss(r);return {leaderboardType:It(r.leaderboard_type),runType:It(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(_s).filter(a=>a!==void 0):[],personalBest:_s(r.personal_best)??null,totalRuns:mt(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:mt(r.generated_at),...s===void 0?{}:{period:s}}}var Mt=class{#e;constructor(e){this.#e=e;}async get(e,t={}){let r=Xr(t),o=await ha(this.#e,e,{...r,...t.bucket1===void 0?{}:{bucket_1:t.bucket1},...t.bucket2===void 0?{}:{bucket_2:t.bucket2},...t.signal===void 0?{}:{signal:t.signal}});return vs(o,false)}async friends(e,t={}){let r=Xr(t),o=await pa(this.#e,e,{...r,...t.bucket1===void 0?{}:{bucket_1:t.bucket1},...t.bucket2===void 0?{}:{bucket_2:t.bucket2},...t.signal===void 0?{}:{signal:t.signal}});return vs(o,true)}async mine(e,t={}){return this.#n(e,"player","me",t)}async character(e,t,r={}){return this.#n(e,"character",t,r)}async#n(e,t,r,o){if(o.limit!==void 0){let{limit:l}=o;if(!Number.isInteger(l)||l<1||l>bs)throw new TypeError(`limit must be an integer between 1 and ${bs}, got ${String(l)}`)}let i=Xr(o),s=await la(this.#e,e,Rs[t],r,{...i,...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"&&It((s??{}).entity_id)||r;return Am(s,t,a)}};var Wn=n=>typeof n=="string"?n:"",Qr=n=>typeof n=="number"?n:0;function xs(n){let e=n??{};return {playerId:Wn(e.player_id),key:Wn(e.key),value:e.value,updatedAt:Qr(e.updated_at)}}function Pm(n){let e=n??{};return {...we(e),playerId:Wn(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:Qr(e.updated_at)}}function Em(n){return n?.reason==="not_found"}var Ot=class{constructor(e,t){this.api=e;this.selfPlayerId=t;}api;selfPlayerId;async friends(e,t={}){let o=await ga(this.api,Ae(e),{...t.signal===void 0?{}:{signal:t.signal}})??{};return {key:Wn(o.key),entries:Array.isArray(o.entries)?o.entries.map(Pm):[],generatedAt:Qr(o.generated_at)}}async of(e,t,r={}){try{return xs(await wa(this.api,e,Ae(t),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(o){if(Em(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 Na(this.api,o,e,{value:t},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,t={}){let r=await this.selfPlayerId();await Zi(this.api,r,Ae(e),{...t.signal===void 0?{}:{signal:t.signal}});}};var Tm="gemChallenge",As=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ps(n){if(!(typeof n!="string"||n===""))try{return new URLSearchParams(n).get(Tm)??void 0}catch{return}}var Ve=class extends O{constructor(e,t={}){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="FriendChallengeError";for(let[r,o]of Object.entries(t))o!==void 0&&Object.assign(this,{[r]:o});}},Kn=n=>typeof n=="string"?n:void 0;function Es(n){let e=n??{};return {...we(e),playerId:Kn(e.player_id)??""}}function Ts(n){let e=n.has_more===true?Kn(n.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function Im(n){let e=n??{};return {friends:Array.isArray(e.data)?e.data.map(Es):[],...Ts(e)}}var Zr=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0;function Cm(n){return typeof n!="object"||n===null||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).filter(e=>typeof e[1]=="string"||typeof e[1]=="number"&&Number.isFinite(e[1])))}function Is(n){let e=n??{},t=Zr(e.opened_at),r=Zr(e.answered_at);return {id:Kn(e.item_id)??"",from:Es(e.sender),template:Kn(e.template)??"",params:Cm(e.params),createdAt:Zr(e.created_at)??0,...t===void 0?{}:{openedAt:t},...r===void 0?{}:{answeredAt:r}}}function Mm(n){let e=n??{};return {challenges:Array.isArray(e.data)?e.data.map(Is):[],...Ts(e)}}function Om(n){let e=n;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var Lt=class{#e;#n;#i;constructor(e,t={}){this.#e=e,this.#n=t.challenge,this.#i=t.launchedChallengeId;}async list(e={}){let t=await Ga(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Im(t)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let t=await La(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Mm(t)}async launchedChallenge(e={}){let t=this.#i;if(t===void 0||!As.test(t))return null;try{return Is(await ya(this.#e,t,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(Om(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!As.test(e))throw new O("invalid",400,"id must be a FriendChallenge.id, as gem.friends.launchedChallenge() or inbox() returned it",void 0,"bad_request");await Fa(this.#e,e);}};var Lm=0;function Ee(){try{return crypto.randomUUID()}catch{let n=Math.random().toString(36).slice(2,10);return `local-${String(++Lm)}-${String(Date.now())}-${n}`}}var Gm=12e4,Cs=8,Dm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Fm=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Gt(n,e,t={}){return new Ve(new O("invalid",400,e,void 0,n),t)}function $m(n){if(typeof n!="object"||n===null||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function qm(n){let{playerId:e,template:t,params:r}=n??{};if(typeof e!="string"||!Dm.test(e))return {error:Gt("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof t!="string"||!Fm.test(t))return {error:Gt("unknown_template","template must be a friend_challenge_templates key from this game's config")};if(r===void 0)return {playerId:e,template:t,params:void 0};if(!$m(r))return {error:Gt("param_invalid","params must be a plain object of strings and integers")};let o={},i=Object.keys(r);for(let s of i){let a=r[s];if(typeof a=="string"||typeof a=="number"&&Number.isSafeInteger(a)){Object.defineProperty(o,s,{value:a,enumerable:true,writable:true,configurable:true});continue}return {error:Gt("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return i.length>Cs?{error:Gt("param_undeclared",`params has ${String(i.length)} keys; a template declares at most ${String(Cs)}`)}:{playerId:e,template:t,params:o}}function jm(n){switch(n.outcome){case "accepted":case "cancelled":case "refused":case "unavailable":return {outcome:{outcome:n.outcome}};case "rate_limited":{let e=n.retryAfterMs,t=typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.ceil(e/1e3):void 0;return {error:new Ve(new O("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",t,"rate_limited"))}}case "invalid":{let e=typeof n.code=="string"?n.code:void 0,t=typeof n.detail=="string"&&n.detail!==""?n.detail:e??"the friend challenge request was refused as invalid";return {error:new Ve(new O("invalid",400,t,void 0,e),{...typeof n.param=="string"?{param:n.param}:{},...typeof n.channel=="string"?{channel:n.channel}:{},...typeof n.configVersion=="number"?{configVersion:n.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function Nm(n){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(n.outcome)?n.outcome:"unknown"}function Ms(n){let e=new Map;return {challenge(t){if(!n.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=qm(t);if("error"in r)return Promise.reject(r.error);let o=`challenge-${Ee()}`;return new Promise((i,s)=>{let a={},l=m=>{e.delete(o)&&(n.clock.clearTimeout(a.timer),"error"in m?s(m.error):i(m.outcome));};e.set(o,l),a.timer=n.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},n.timeoutMs??Gm);let d=false;try{d=n.bridge.requestFriendChallenge(o,r.playerId,r.template,r.params);}catch{}d||l({outcome:{outcome:"unavailable"}});})},settle(t){let r=e.get(t.requestId);if(r===void 0){n.onDropped?.(`gem.friendChallengeResult (${Nm(t)}) for an unknown requestId: `+JSON.stringify(t.requestId));return}r(jm(t));}}}var Jn=n=>typeof n=="string"?n:void 0;function Um(n){let e=n??{},t=Jn(e.currency_id);if(t===void 0||t==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Jn(e.slug)??"",currencyId:t,balance:r,access:e.access==="spend"?"spend":"read"}}var zn=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 s=Um(i);s!==void 0&&o.push(s);}return o}},eo=n=>typeof n=="number"&&Number.isFinite(n)&&n>=0?Math.floor(n):0;function Bm(n){let e=n??{},t=Jn(e.currency_id);if(t===void 0||t==="")return;let r=eo(e.limit),o=Math.min(eo(e.earned),r),i=Math.min(eo(e.remaining),r-o),s=e.period_days,a=typeof s=="number"&&Number.isInteger(s)&&s>=1?s:1,l=e.resets_at,d=typeof l=="number"&&Number.isFinite(l)&&l>0?Math.round(l*1e3):void 0;return {currencySlug:Jn(e.currency_slug)??"",currencyId:t,limit:r,earned:o,remaining:i,period:e.period==="day"?"day":"window",periodDays:a,...d===void 0?{}:{resetsAt:d}}}function Os(n){let e=new Set,t=r=>{n?.(`[gem] an earnAllowance 'changed' listener threw: ${r instanceof Error?r.message:String(r)}`);};return {on(r){return e.add(r),()=>{e.delete(r);}},emit(){for(let r of [...e])try{let o=r();typeof o?.then=="function"&&o.then(void 0,t);}catch(o){t(o);}}}}var Yn=class{#e;#n;#i;constructor(e,t,r){this.#e=e,this.#n=t,this.#i=r;}async get(e={}){let r=(await fa(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let s=Bm(i);s!==void 0&&o.push(s);}return o}on(e,t){return e!=="changed"?(this.#i?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#n?.on(t)??(()=>{})}},Dt=class{currencies;earnAllowance;constructor(e,t,r){this.currencies=new zn(e),this.earnAllowance=new Yn(e,t,r);}};var to=n=>typeof n=="string"?n:"",Ls=n=>typeof n=="number"?n:0;function Hm(n){let e=n??{};return {key:to(e.key),visibility:to(e.visibility),value:e.value,updatedAt:Ls(e.updated_at)}}function Vm(n){let e=n??{};return {...we(e),playerId:to(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Hm):[],generatedAt:Ls(e.generated_at)}}function Wm(n){return n?.reason==="not_found"}var Ft=class{#e;constructor(e){this.#e=e;}async of(e,t={}){try{return Vm(await ba(this.#e,e,{...t.signal===void 0?{}:{signal:t.signal}}))}catch(r){if(Wm(r))return null;throw r}}};var Km=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]]),$t=class extends O{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:Km.get(this.code))??super.retryable}},Fe=class{#e;constructor(e){this.#e=e;}async invoke(e,t={}){let r=Jm(e),o;try{o=await this.#e(r,t.signal===void 0?{}:{signal:t.signal});}catch(i){throw i instanceof O?Ym(i):i}return zm(o)}};function Jm(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 oe(`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 oe(`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 zm(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 Ym(n){let{details:e,invocationId:t}=Ni(n),o=e?.untrusted?.message,i=e?.reason;return new $t(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 Xm=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],no="gem_";function Gs(n){return n.startsWith(no)}var Ds=1e4,Fs=50,Qm=500,Zm=65536-4*1024,ep=24*1024;function $s(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 qs=n=>typeof n=="number"?n:0,tp=n=>typeof n=="string"?n:"";function ro(n=0){return {accepted:0,rejected:[],dropped:n,duplicate:false}}function np(n,e){let t=n??{},r=Array.isArray(t.rejected)?t.rejected.map(o=>{let i=o??{};return {index:qs(i.index),code:tp(i.code)}}):[];return {accepted:qs(t.accepted),rejected:r,dropped:e,duplicate:t.duplicate===true}}function oo(){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 rp(n){return n?.retryable===true}var qt=class{#e;#n;#i;#y;#t=[];#h={};#a=0;#s=null;#f=false;#b=false;#v=false;#r=false;#_=null;#l=null;#d=false;#o=false;#m=false;#w=false;#S=false;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#i=Math.max(Ds,e.options?.flushIntervalMs??Ds),this.#y=Math.max(1,Math.floor(e.options?.maxQueue??Qm));}track(e,t={}){if(!(!this.#n||this.#r)){if(Gs(e)){this.#S||(this.#S=true,this.#g(`[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.#R(e,$s({...this.#h,...t}));}}setContext(e){this.#h={...this.#h,...e};}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#o)return ro();let t=this.#E();if(t===null||t==="")return this.#t.length>0&&!this.#w&&(this.#w=true,this.#g("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),ro();if(this.#k(),this.#t.length===0)return ro();let r=e.keepalive===true;this.#u();let o=this.#t.splice(0,this.#A(r)),i=this.#a;this.#a=0;let s=Math.round(this.#e.clock.now()),a={batch_id:oo(),sent_at_ms:s,events:o.map(d=>js(d,s))},l={client:this.#e.client(),gameId:()=>t};this.#v=true;try{let d=await xa(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=np(d,i);return this.#P(m),m}catch(d){throw rp(d)?this.#x(o,i):this.#g(`[gem] analytics: ${o.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#v=false,this.#t.length>0&&this.#c();}}trackPlatform(e,t={}){this.#r||this.#o&&(e==="gem_pause"||e==="gem_resume")||this.#R(e,$s(t));}hold(){this.#r||this.#l!==null||(this.#o=true,this.#u());}release(){if(!this.#o||this.#r)return;this.#o=false;let e=this.#e.clock.now(),t=this.#t.map(r=>({...r,atMs:e}));this.#t=t,this.#m&&(this.#m=false,this.#l=e,this.#d=false,this.#t.unshift({uid:oo(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=Fs?this.#p():this.#t.length>0&&this.#c();}get held(){return this.#o}startSession(){if(!(this.#r||this.#l!==null)){if(this.#o){this.#m=true;return}this.#l=this.#e.clock.now(),this.#d=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#d)return;if(this.#d=true,this.#o){this.#m=false,this.#t=[],this.#a=0;return}let t=this.#l;this.trackPlatform("gem_session_end",{reason:e,...t===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-t))}}),this.#p({keepalive:true});}setPaused(e){this.#r||e===this.#f||(this.#f=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#t.length>0&&this.#c());}setHidden(e){this.#r||e===this.#b||(this.#b=e,e?this.#u():this.#t.length>0&&this.#c());}dispose(){this.#r=true,this.#u(),this.#t=[],this.#a=0;}get pending(){return this.#t.length}#R(e,t){let{dimensions:r,measures:o}=t;for(this.#k();this.#t.length>=this.#y;)this.#t.shift(),this.#a+=1;this.#t.push({uid:oo(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:o}),this.#t.length>=Fs?this.#p():this.#c();}#p(e={}){this.flush(e).catch(()=>{});}#x(e,t){for(this.#t=[...e,...this.#t],this.#a+=t;this.#t.length>this.#y;)this.#t.shift(),this.#a+=1;}#A(e){let t=e?ep:Zm,r=Math.min(this.#t.length,100),o=128;for(let i=0;i<r;i+=1){let s=this.#t[i];if(s===void 0)break;if(o+=JSON.stringify(js(s,0)).length+1,o>t)return Math.max(1,i)}return r}#c(){this.#s!==null||this.#f||this.#b||this.#o||this.#r||this.#v||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#p();},this.#i));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#k(){let e=this.#T();e===null||e===""||(this.#_!==null&&this.#_!==e&&(this.#t=[],this.#a=0,this.#l=null,this.#d=false),this.#_=e);}#P(e){for(let t of e.rejected)this.#g(`[gem] analytics: an event was refused (${t.code}). `+op(t.code));}#g(e){let t=this.#e.log;t!==null&&(t===void 0?console.warn(e):t(e));}#E(){try{return this.#e.gameId()}catch{return null}}#T(){try{return this.#e.playerId()}catch{return null}}};function js(n,e){return {event_uid:n.uid,name:n.name,offset_ms:Math.round(n.atMs)-e,dimensions:n.dimensions,measures:n.measures}}function op(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 jt(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 ip=2e3,ap=5e3;function Us(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 s,a=new Promise(l=>{let d=false,m=null;s=u=>{d||(d=true,r=null,n.clock.clearTimeout(m),l(u));},m=n.clock.setTimeout(()=>{t=true,s([]);},n.timeoutMs??ip);});return r={promise:a,settle:s},a};return {resolveList:i,resolve(){return e.length>0||t||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):i().then(s=>s[0])},refresh(s){return !Ns(e,s)||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=m=>{o.delete(d)&&(n.clock.clearTimeout(l),a(m));};o.set(d,s),l=n.clock.setTimeout(()=>d(e),n.refreshTimeoutMs??ap);})},accept(s,a){let l=jt(a),d=pe(s),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[u,p]of [...o])Ns(m,p)||u(m);}}}}function Ns(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var sp=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),w=class extends Error{constructor(t,r,o){super(`${t}: ${r}`,o);this.reason=t;this.name="DedicatedServerError",this.retryable=sp.has(t),this.platformCode=o?.platformCode;}reason;retryable;platformCode};var Bs=["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"],lp=new Set(Bs);function $e(n){return typeof n=="string"&&lp.has(n)?n:"unknown"}var Xn="webrtc_dedicated",lo=["universal","mobile","web"];var dp="p2p_unavailable",cp="capacity_unavailable",up=2,Hs=3e4,Vs=1e3,Ws=2e4;async function co(n){let e=pe(n.clusterTargetId),t=n.nextClusterTarget,r=0,o=n.clock??le,i=n.retry??{},s=i.budgetMs??Hs,a=i.maxDelayMs??Ws,l=i.initialDelayMs??Vs,d=o.now(),m=d+s,u=0;for(;;){u++;try{let p=await go(n.signal,"while allocating",()=>n.client.post(`${zs(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!mp(p)||s<=0)throw p;if(p.status===503&&p.code===dp)throw new w("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===cp?r+1:0,t!==void 0&&r>=up){let x=t;t=void 0;let I=pe(await x());I!==void 0&&(e=I,r=0);}let g=Math.min(a,l*2**(u-1)),y=Math.min(a,(p.retryAfterSeconds??0)*1e3),S=Math.max(g/2,y)+Math.random()*(g/2);if(o.now()+S>m)throw pp(n,p,u,o.now()-d,s);if(i.onWaiting?.({attempt:u,elapsedMs:o.now()-d,budgetMs:s,nextAttemptInMs:S,status:p.status,message:p.message}),await Qn(o,S,n.signal),n.signal?.aborted)throw so("while waiting to allocate")}}}function mp(n){return n instanceof O?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function pp(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 w("start_rate_limited",`the platform was still limiting match starts for room ${n.roomId} after ${i}: ${e.message}`,{cause:e}):new w("no_server_ready",`the platform had no server ready for room ${n.roomId} after ${i}: ${e.message}`,{cause:e})}var gp=12e4,yp=1e3;async function uo(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??yp,o=n.timeoutMs??gp,i=e.now()+o,s=Ks(n),a={seen:n.knownToExist===true};for(;;){let l=await Js(n,s,a);if(l.outcome!==null)return l.outcome;if(e.now()+r>i)throw new w("timeout",`match ${t} was still ${l.status} after ${o}ms`);await Qn(e,r,n.signal);}}async function mo(n){return (await Js(n,Ks(n),{seen:n.knownToExist===true})).outcome}function Ks(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${zs(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function Js(n,e,t){let{matchId:r}=n,o=n.clock.now(),i;try{i=await go(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(s){if(s instanceof O&&s.reason==="not_found")return {status:"not_found",outcome:t.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(t.seen=true,i.status==="ready")return {status:"ready",outcome:hp(r,i,o)};if(i.status==="failed"){let s=i.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:$e(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:i.failure_reason??"unknown"}}}return {status:i.status,outcome:null}}async function po(n){let e=await go(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 go(n,e,t){if(n?.aborted)throw so(e);try{return await t()}catch(r){throw n?.aborted?so(e,r):r}}function so(n,e){return new w("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function hp(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 zs(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function Qn(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 Ys(n){return typeof n=="string"&&n.trim()!==""}function Zn(n,e){return Ys(n)?n.trim():Ys(e)?e:null}var er="0.1.0-beta",Xs="0-beta",pt="web",fp=/^(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 bp(n){let e=fp.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function Qs(n,e){let t=vp(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:er};let o=bp(r);if(o===null)throw new w("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 '${er}' for it.`);if(o!==Xs)throw new w("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${o}', and '${Xs}' 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 '${er}' for it.`);return {...n,platform:t,engineVersion:r}}function vp(n,e){if(n===void 0||n===pt)return pt;if(!lo.includes(n))throw new w("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${lo.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${pt}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${pt}' 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.`),pt}function Nt(n){let e=n??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let t=e.heartbeat_interval_seconds;return {id:e.ticket_id,status:typeof e.status=="string"?e.status:"queued",...typeof e.reason=="string"?{reason:e.reason}:{},...typeof e.game_room_id=="string"?{roomId:e.game_room_id}:{},partySize:typeof e.party_size=="number"?e.party_size:1,queuedAt:Zs(e.queued_at),expiresAt:Zs(e.expires_at),heartbeatIntervalSeconds:typeof t=="number"&&t>0?t:0}}function Zs(n){if(typeof n!="string")return 0;let e=Date.parse(n);return Number.isFinite(e)?Math.floor(e/1e3):0}var _p=3,el=1e3,tr=class{constructor(e){this.options=e;this.snapshot=e.first;let t=new Promise((i,s)=>{this.resolve=i,this.reject=s;});t.catch(()=>{});let r=()=>this.snapshot,o=()=>this.status;this.ticket={get id(){return r().id},get status(){return o()},get partySize(){return r().partySize},get queuedAt(){return r().queuedAt},get expiresAt(){return r().expiresAt},outcome:t,cancel:()=>(this.requestCancel(),t)};}options;ticket;snapshot;status="queued";timer=null;busy=false;again=false;cancelRequested=false;soon=false;misses=0;settled=false;resolve;reject;start(){this.apply(this.snapshot);}poke(){this.settled||(this.soon=true,!this.busy&&(this.clearTimer(),this.tick()));}abandon(e=false){this.settled||(this.options.cancel(this.snapshot.id,e).catch(()=>{}),this.settle({status:"cancelled",reason:"requested"}));}requestCancel(){this.settled||(this.cancelRequested=true,this.trigger());}trigger(){if(this.busy){this.again=true;return}this.clearTimer(),this.tick();}schedule(e=false){if(this.settled)return;this.clearTimer();let t=e?el:Math.max(el,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},t);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,t=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){t=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(t);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof O&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<_p){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let t=e instanceof O&&e.code==="matchmaking_unavailable";this.settle({status:t?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let t=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:t});}catch(t){this.busy=false,this.fail(t);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};var wp="join",Sp="welcome",Rp="rejected",tl=25e3,kp=1e3,yo=1;function ho(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var xp={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 fo(n){let e=typeof n=="string"?n:"unknown";return new w(xp[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function Ut(n){let{channel:e,clock:t}=n;return new Promise((r,o)=>{let i=false,s=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??tl),a=t.setTimeout(()=>v(new w("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(s,kp)),l=S=>{let x=S.data;if(typeof x!="string"){u(x);return}let I;try{I=JSON.parse(x);}catch{u(x);return}if(i){u(x);return}if(I.t===Sp){let b=ho(I.heartbeat_interval);y({...typeof I.player_id=="string"?{playerId:I.player_id}:{},...typeof I.match_id=="string"?{matchId:I.match_id}:{},...b===void 0?{}:{heartbeatIntervalMs:b}});return}if(I.t===Rp){v(fo(I.reason));return}u(x);},d=()=>{v(new w("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{v(new w("aborted","the caller aborted during the join exchange"));},u=S=>{i&&n.onMessage?.(S);},p=()=>{t.clearTimeout(a),e.removeEventListener("close",d),n.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=S=>{i=true,p(),n.onMessage===void 0&&g(),r({welcome:S,detach:g});},v=S=>{i||(i=true,p(),g(),o(S));};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:wp,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:yo}:{}}));}catch(S){v(new w("connection_failed",`the join frame could not be sent on the open channel: ${String(S)}`,{cause:S}));}})}var We=1,Bt=2,bo=4,wo=8,Ap=2,Pp=1e3,So="heartbeat timeout",Ht="gem-uu",nr=2,rl="gem_transports";function gt(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!Ep(r)||e.includes(r)||e.push(r);}return e}function Ep(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function Vt(n,e){if(typeof n!="object"||n===null)return null;let t=n[rl];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 rr(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var ol=new TextEncoder,il=new TextDecoder;function Ro(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function ko(n){let e=0;return n?.reliable===false&&(e|=We),n?.ordered===false&&(e|=Bt),e}function xo(n){return {reliable:(n&We)===0,ordered:(n&Bt)===0}}var Ao={reliable:true,ordered:true};function al(n){return JSON.stringify({t:"join",credential:n,wire:nr,heartbeat:yo})}function sl(n){let e;try{e=JSON.parse(n);}catch{throw new w("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let t=ho(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"?fo(e.reason):new w("join_refused","the server answered the join out of protocol")}function or(){return typeof globalThis.WebTransport=="function"&&Po===null}function ir(){return Po}var Po=null;var nl="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Tp(n){let e=wn(n);if(e.byteLength!==32)throw new w("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var vo=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 w("connection_failed",`a control-stream record claims ${i} bytes`);if(this.buffered.byteLength<4+i)break;let s=this.buffered.slice(4,4+i);this.buffered=this.buffered.slice(4+i),r.push({flags:s[0]??0,payload:s.slice(1)});}return r}};function _o(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 Wt(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webTransport;if(t===void 0){let a=globalThis.WebTransport;if(a===void 0)throw new w("connection_failed","this environment has no WebTransport");t=n.certHashBase64===void 0?new a(n.url):new a(n.url,{serverCertificateHashes:[{algorithm:"sha-256",value:Tp(n.certHashBase64)}]});}let r=t,o=a=>{try{r.close();}catch{}throw a},i=r.datagrams;(i?.readable===void 0||i.writable===void 0)&&(Po=nl,o(new w("connection_failed",`${nl}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,l)=>{setTimeout(()=>l(new w("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,s]);let a=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([a.read(),s]);if(a.releaseLock(),l.done||l.value===void 0)return o(new w("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(_o(bo,ol.encode(al(n.credential))));let u=new vo,p=d.readable.getReader(),g;for(;g===void 0;){let y=await Promise.race([p.read(),s]);if(y.done||y.value===void 0)return o(new w("connection_failed","the control stream closed before the join was answered"));for(let v of u.push(y.value)){g=sl(il.decode(v.payload));break}}return {link:Ip(r,m,p,u,n.log??(y=>console.warn(y)),dl(g,n.clock)),welcome:g}}catch(a){return o(a)}}function Ip(n,e,t,r,o,i){let s,a,l=false,d=y=>{if(!l){l=true,m.stop();try{n.close();}catch{}a?.(y);}},m=To(i,()=>d(So)),u=(y,v)=>{m.heard(),(y&wo)===0&&s!==void 0&&((y&bo)!==0?s(il.decode(v),Ao):s(v,xo(y)));};(async()=>{try{for(;;){let y=await t.read();if(y.done||y.value===void 0)break;for(let v of r.push(y.value))u(v.flags,v.payload);}}catch{}d("stream closed");})();let p,g;try{let y=n.datagrams;if(y?.readable!==void 0&&y.writable!==void 0){let v=y.readable.getReader();g=y.writable.getWriter(),p=y,(async()=>{try{for(;;){let S=await v.read();if(S.done||S.value===void 0)break;let x=S.value;x.byteLength!==0&&u((x[0]??0)|We|Bt,x.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 (${rr(y)}); unreliable sends ride the stream`);}return n.closed.then(y=>d(ll(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,v){if(l)return;if(typeof y=="string"){e.write(_o(bo,ol.encode(y))).catch(()=>d("write failed"));return}let S=ko(v);if((S&We)!==0&&g!==void 0){let x=Ro(S,y),I=p?.maxDatagramSize;if(I===void 0||x.byteLength<=I){g.write(x).catch(()=>{});return}}e.write(_o(S,y)).catch(()=>d("write failed"));},onMessage(y){s=y;},onClose(y){a=y;},close(){d("closed");}}}function Eo(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 w("connection_failed","this environment has no WebSocket"));t=new o(n.url);}let r=t;return r.binaryType="arraybuffer",new Promise((o,i)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),i(new w("timeout","websocket did not come up in time")));},e),l=g=>{s||(s=true,clearTimeout(a),r.close(),i(g));},d=()=>{r.send(al(n.credential));},m=g=>{if(s)return;if(typeof g.data!="string"){l(new w("join_refused","the server sent binary before answering the join"));return}let y;try{y=sl(g.data);}catch(v){l(v);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",u),r.removeEventListener("error",p),o({link:Cp(r,dl(y,n.clock)),welcome:y});},u=()=>{l(new w("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new w("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",m),r.addEventListener("close",u),r.addEventListener("error",p),r.readyState===1&&d();})}function ll(n){return typeof n=="string"&&n.length>0?n:void 0}function dl(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function To(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,Pp)*Ap,o=t.now(),i=null,s=()=>{i=null;let a=t.now()-o;if(a>=r){e();return}i=t.setTimeout(s,r-a);};return i=t.setTimeout(s,r),{heard:()=>{o=t.now();},stop:()=>{i!==null&&(t.clearTimeout(i),i=null);}}}function Cp(n,e){let t,r,o=false,i=a=>{if(!o){o=true,s.stop();try{n.close();}catch{}r?.(a);}},s=To(e,()=>i(So));return n.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){t?.(a.data,Ao);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&wo)===0&&t?.(l.slice(1),xo(d));})),n.addEventListener("close",(a=>i(ll(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!o){if(typeof a=="string"){n.send(a);return}n.send(Ro(ko(l),a));}},onMessage(a){t=a;},onClose(a){r=a;},close(){i("closed");}}}function Io(n,e,t,r){let o,i,s=false,a=t,l=u=>{if(!s){s=true,d.stop();try{n.close();}catch{}try{e.close();}catch{}i?.(u);}},d=To(r,()=>l(So)),m=(u,p)=>{if(d.heard(),typeof u=="string"){o?.(u,Ao);return}let g=new Uint8Array(u);if(g.byteLength===0)return;let y=g[0]??0;(y&wo)===0&&o?.(g.slice(1),xo(y|p));};if(n.addEventListener("message",(u=>m(u.data,0))),n.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let u=e.connectionState;(u==="failed"||u==="closed")&&l(`connection ${u}`);})),a!==void 0){let u=a;u.addEventListener("message",(p=>m(p.data,We|Bt))),u.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(u,p){if(s)return;if(typeof u=="string"){n.send(u);return}let g=ko(p),y=Ro(g,u);if((g&We)!==0&&a!==void 0&&a.readyState==="open"){a.send(y);return}n.send(y);},onMessage(u){o=u;},onClose(u){i=u;},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=Co(r);o!==void 0&&(e[t]=o);}return e}function Lo(n){if(Array.isArray(n))return n.map(Mp).filter(e=>!!e)}function Co(n){if(Mo(n)||Array.isArray(n)&&n.every(Mo))return n}function Mo(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function Mp(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=Co(e.fixed),r=Co(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},...yt("description",Op(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Mo)?{allowed:e.allowed}:{},...yt("min",Kt(e.min)),...yt("max",Kt(e.max)),...yt("minItems",Kt(e.min_items)),...yt("maxItems",Kt(e.max_items)),...yt("maxLength",Kt(e.max_length))}}function Op(n){return typeof n=="string"&&n.length>0?n:void 0}function Kt(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function yt(n,e){return e===void 0?{}:{[n]:e}}function Ie(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(cl):[];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,...Se("joinCode",Y(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...Se("roomArgs",Oo(e.room_args)),...Se("roomArgsTemplate",Lo(e.room_args_template)),gameChannel:Y(e.game_channel)??"release",...Se("region",Y(e.region)),...Se("clusterTargetId",Y(e.cluster_target_id)),selfHosted:e.self_hosted===true,...Se("matchId",Y(e.match_id)),version:Te(e.version)??0,...Se("templateId",Y(e.template_id)),roomType:Y(e.game_room_type)??"Standard",...Se("transports",gt(e.transports)??void 0),createdAt:Te(e.created_at)??0,updatedAt:Te(e.updated_at)??0,...Se("startedAt",Te(e.started_at))}}function cl(n){let e=n??{};return {...we(e),playerId:Y(e.player_id)??"",isReady:e.is_ready===true,role:Y(e.role)??"member",joinedAt:Te(e.joined_at)??0,...Se("groupId",Y(e.group_id)),...Se("platform",Y(e.platform))}}function ar(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 Se(n,e){return e===void 0?{}:{[n]:e}}var zt=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(ar),...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(ar)}))}create(e,t,r){return Lp(e.maxPlayers),this.options.client.post(this.baseV2(),{name:e.name,...e.isPublic===void 0?{}:{is_public:e.isPublic},...e.settings===void 0?{}:{settings:e.settings},...e.region===void 0?{}:{region:e.region},...r===void 0?{}:{cluster_target_id:r},...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.partyId===void 0?{}:{party_id:e.partyId},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...e.roomArgs===void 0?{}:{room_args:e.roomArgs},...Jt(t)},e.signal).then(Ie)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(Ie)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...Jt(r)},t.signal).then(Ie)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...Jt(r)},t.signal).then(Ie)}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},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...Jt(t)},e.signal).then(Ie)}createTicket(e,t,r=[]){return Yi(this.generated(),{templates:e.templateSlugs.map(o=>({template_slug:o})),...r.length===0?{}:{cluster_target_ids:[...r]},...e.partyId===void 0?{}:{party_id:e.partyId},...Jt(t)},{...e.signal===void 0?{}:{signal:e.signal}}).then(Nt)}heartbeatTicket(e){return ka(this.generated(),e).then(Nt)}cancelTicket(e,t=false){return t?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(Nt):Vi(this.generated(),e).then(Nt)}leave(e,t,r,o=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:t},r,{keepalive:o}).then(()=>{})}asksSelfHosted(e){return e===void 0&&this.options.selfHosted?.()===true}close(e,t){return this.options.client.delete(this.roomV1(e),t).then(()=>{})}update(e,t){return this.options.client.patch(this.roomV2(e),{...t.name===void 0?{}:{name:t.name},...t.maxPlayers===void 0?{}:{max_players:t.maxPlayers},...t.isPublic===void 0?{}:{is_public:t.isPublic},...t.settings===void 0?{}:{settings:t.settings},...t.roomArgs===void 0?{}:{room_args:t.roomArgs}},t.signal).then(Ie)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(Ie)}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(Ie)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function Jt(n){return {platform:n.platform,game_version:n.gameVersion,engine_version:n.engineVersion}}function Lp(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 Yt=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 Gp(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var Dp=1e3,Fp=3e3,$p=6e4,qp=2,ul=new Set(["game_room_closed","game_room_gone"]),jp=12e4,Np=5e3,Up=new Set(["invalid_cluster_target","capacity_unavailable"]),Bp=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function Do(n){return new Go(n)}var Go=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new zt({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Yt;api;room=null;ticketWatch=null;queueing=false;queuedFromRoomId=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("create");let t=this.clusterTargets(),r=await this.attachParty(e),o=await this.run("create",async()=>{let i=await t;return this.api.create(r,this.version("create"),i[0]).catch(async s=>{let a=await this.afterRefusedClusters(s,i);if(a[0]===void 0||a[0]===i[0])throw s;return this.api.create(r,this.version("create"),a[0])})});return this.enter(o,"created"),this.askForLocalServer(o),o}async join(e,t={}){this.assertNotInRoom("join"),this.assertNotQueued("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"),this.askForLocalServer(o),o}async joinByCode(e,t={}){this.assertNotInRoom("joinByCode"),this.assertNotQueued("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"),this.askForLocalServer(o),o}async quickJoin(e){this.assertNotInRoom("quickJoin"),this.assertNotQueued("quickJoin");let t=this.clusterTargets(),r=await this.attachParty(e),o=s=>this.api.quickJoin(r,this.version("quickJoin"),s).catch(a=>this.retryPastStaleMembership(a,r,s)),i=await this.run("quickJoin",async()=>{let s=await t;return o(s).catch(async a=>{let l=await this.afterRefusedClusters(a,s);if(l.length===0||yl(l,s))throw a;return o(l)})});return this.enter(i,"joined"),this.askForLocalServer(i),i}async queueForMatch(e){this.assertNotQueued("queueForMatch"),Vp(e?.templateSlugs),this.queueing=true;try{let t=this.clusterTargets(),r=await this.attachParty(e),o=await this.run("queueForMatch",async()=>{let s=await t;return this.api.createTicket(r,this.version("queueForMatch"),s).catch(async a=>{let l=await this.afterRefusedClusters(a,s);if(l.length===0||yl(l,s))throw a;return this.api.createTicket(r,this.version("queueForMatch"),l)})}),i=new tr({clock:this.options.clock,first:o,heartbeat:s=>this.track(this.api.heartbeatTicket(s)),cancel:(s,a)=>this.track(this.api.cancelTicket(s,a)),seat:s=>this.enterMatchedRoom(s),onSettled:()=>{this.ticketWatch===i&&(this.ticketWatch=null),this.retuneSeatWatch();}});return this.ticketWatch=i,this.retuneSeatWatch(),i.start(),i.ticket}finally{this.queueing=false;}}async enterMatchedRoom(e){let t=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?t:(this.room!==null&&this.room.id!==t.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(t,"joined"),this.room?.id===t.id?this.room:t)}async list(e={}){let t=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",t),t}async myRooms(e){let t=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",t.rooms),t.rooms}async leave(e={}){let t=this.requireRoom("leave"),r=e.keepalive===true,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 O&&o.reason==="not_found"){let i=this.heldMatchId;if(i!==null){let s=await this.askWhyEnded(i,e);this.endMatch(i,s??"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(()=>mo({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...t===void 0?{}:{signal:t}})));}catch(s){return s instanceof O&&s.reason==="not_found"?o??null:(this.reportError("reconcile",s),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=$e(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 w("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),s=i??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let a=(m,u)=>co({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(u)}:{},retry:{...t.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),t.retry?.onWaiting?.(p);}},...t.signal===void 0?{}:{signal:t.signal}}),l=()=>a(i,[s]).catch(async m=>{if(o!==void 0||!pl(m))throw m;let u=await this.nextCluster([s],true);if(u===void 0)throw m;return a(u,[s,u])}),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 w("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 uo({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 w("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!ul.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new w("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(!Ke()){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<Dp){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(Gp(e.attempt,t.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!Ke()){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(()=>mo({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,!ul.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(s){this.reportError("reconcile",s),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 w("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 w("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 w("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:t},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let t=this.heldMatchId;if(t!==null)try{await this.api.leaveMatch(t,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentTicket(){return this.ticketWatch?.ticket??null}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,t){let r=this.emitter.on(e,t);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}handleRoomEvent(e){if(this.ticketWatch!==null&&e.event!=="version_stale"&&e.roomId!==this.room?.id&&this.ticketWatch.poke(),this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let t=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(t).catch(()=>{}));}handleAutoStartFailed(e,t){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(t);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:t,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let 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||!Up.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)return;let e;try{e=await this.myRooms();}catch{return}let t=new Set;for(let r of e)r.status!=="closed"&&(t.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])t.has(r)||this.reported.delete(r);}async reportSeat(e){let t=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||t===null||!r.members.some(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.ticketWatch===null&&this.seatPollMs>0&&Ke())){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(),!!Ke())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of sr)e.addEventListener(r,this.visibilityListener);let t=globalThis.document;typeof t?.addEventListener=="function"&&t.addEventListener("resume",this.visibilityListener);}startPolling(e){this.stopPolling(),!this.disposed&&(this.pinnedIntervalMs=e??null,this.polling=true,this.schedule());}stopPolling(){this.pollHandle!==null&&(this.options.clock.clearTimeout(this.pollHandle),this.pollHandle=null),this.polling=false,this.pollIntervalMs=null;}async settled(){for(let e=0;e<20&&this.inFlight.length>0;e++){let t=this.inFlight;this.inFlight=[],await Promise.allSettled(t);}}dispose(){if(this.disposed=true,this.ticketWatch?.abandon(),this.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 sr)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??Np}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new w("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=Zn(this.options.platformGameVersion?.(),t?.gameVersion);if(r===null)throw new w("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 Qs({...t,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return jt(await this.options.resolveClusterTargets());let e=pe(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,t){return !pl(e)||t.length===0?[]:jt(await this.options.refreshClusterTargets?.(t)??[])}async nextCluster(e,t=false){let r=s=>s.find(a=>!e.includes(a)),o=await this.clusterTargets(),i=r(o);return i!==void 0||!t?i:r(jt(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 O)||e.reason!=="conflict"||!Bp.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new O(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 O(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 O(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 w("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}assertNotQueued(e){if(!(this.ticketWatch===null&&!this.queueing))throw new w("misconfigured",`${e} refused: this player is waiting on a matchmaking ticket, which will seat them in a room of its own. Cancel it first \u2014 currentTicket.cancel() \u2014 or wait for its outcome.`)}requireRoom(e){if(this.room===null)throw new w("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 O?{operation:e,code:t.status,reason:t.reason,message:t.message,retryable:t.retryable}:{operation:e,code:0,reason:t instanceof w?t.reason:"unavailable",message:t instanceof Error?t.message:String(t),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let t=this.options.ensureLocalServer;t===void 0||!e.selfHosted||e.status!=="open"||t(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,t){this.room=e,this.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(t,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.abortAutoStartRetry(),this.autoStartRetried=false,this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let t=this.room;if(t===null||t.id!==e.id)return;let r=new Map(t.members.map(a=>[a.playerId,a])),o=new Map(e.members.map(a=>[a.playerId,a])),i=this.playerId();for(let a of o.keys())r.has(a)||this.emitter.emit("memberJoined",a);for(let a of r.keys())if(!o.has(a)){if(a===i){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",a);}for(let[a,l]of o){let d=r.get(a);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",a,l.isReady);}t.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let s=Hp(t,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),s&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let t=this.heldMatchId;t!==null&&t!==e&&this.endMatch(t,"replaced",true),this.session={phase:"starting",matchId:e},this.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??jp;return new Promise((o,i)=>{let s=u=>{a(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),u();},a=this.emitter.on("matchAllocationStarted",u=>s(()=>o(u))),l=this.emitter.on("matchFailed",(u,p)=>s(()=>i(new w("allocation_failed",`match ${u} did not come up: ${p}`)))),d=()=>s(()=>i(new w("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>s(()=>i(new w("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??Fp}pushedInterval(){return this.options.pushedPollIntervalMs??$p}pushed(){return this.options.clock.now()-this.lastPushAt<qp*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=t=>{if(this.ticketWatch?.abandon(true),t?.persisted!==true&&(this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{})),this.queuedFromRoomId!==null)){let r=this.queuedFromRoomId;this.queuedFromRoomId=null,this.track(this.api.leave(r,true,void 0,true).catch(()=>{}));}},e.addEventListener("pagehide",this.unloadListener));}};function Ke(){let n=globalThis.document;return n?.visibilityState===void 0||n.visibilityState==="visible"}var sr=["visibilitychange","focus","pageshow","online"];function Hp(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||ml(n)!==ml(e)}function ml(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function pl(n){return n instanceof O&&n.code==="invalid_cluster_target"}var gl=8;function Vp(n){if(!(Array.isArray(n)&&n.length>=1&&n.length<=gl&&n.every(t=>typeof t=="string"&&t.length>0)))throw new w("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${gl} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function yl(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Wp=["p2p","dedicated","unknown"],Fo=["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 ht=class{constructor(e){this.options=e;}options;async post(e,t){let r=this.options.gameId();if(r===null||r==="")return;let o=Kp(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 Kp(n,e,t){let r=Math.floor(t/1e3);return n.filter(o=>Fo.includes(o.type)).slice(0,100).map(o=>{let i=Jp(o.transport??e);return {event_type:o.type,timestamp:r,...i===void 0?{}:{transport:i},data:o.value===void 0?{}:{value:o.value}}})}function Jp(n){if(n!==void 0)return Wp.includes(n)?n:"unknown"}var Xt=class{constructor(e){this.options=e;this.reporter=new ht({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:lr(o.credential)??"",hostFingerprint:lr(o.host_fingerprint)??"",hostEpoch:dr(o.host_epoch)??0,expiresAt:(dr(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(u=>typeof u=="string"&&u.length>0);m.length!==0&&i.push({urls:m,username:lr(d.username)??"",credential:lr(d.credential)??""});}let s=dr(o.expires_at),a=dr(o.ttl_seconds);return {iceServers:i,expiresAt:s!==void 0?s*1e3:Date.now()+(a??0)*1e3}}async kick(e,t,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:t},r);}async leave(e,t=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:t});}async telemetry(e,t){await this.reporter.post(e,t);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function lr(n){return typeof n=="string"&&n.length>0?n:void 0}function dr(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var zp=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),G=class extends Error{constructor(t,r,o){super(`${t}: ${r}`,o);this.reason=t;this.name="P2pError",this.retryable=zp.has(t);}reason;retryable};var hl=10240,fl=2048,Yp=new TextEncoder;function bl(n){return Yp.encode(n).length}function qe(n,e){let t=o=>{throw new w("invalid_sdp",`the ${e} ${o}`)},r=bl(n);r>=hl&&t(`is ${r} bytes, over the ${hl} 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=bl(o);i>fl&&t(`has a ${i}-byte line, over the ${fl} limit`);}}function cr(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 ur=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 Xp=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function ft(n){let e=null;for(let t of n.split(/\r\n|\n/)){if(!t.startsWith("a=fingerprint:"))continue;let r=mr(t.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function mr(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 Xp.test(r)?r:null}function Qt(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 $o=5e3,Qp=12e4+$o,Zp=1024,eg=6e4,tg=1e4,vl=64*1024,_l=5;function qo(n){let e=new Map,t=-1/0,r=null,o=(()=>{let a;try{a=new URL(`${n.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return a.username!==""||a.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:a.href,shown:`${a.protocol}//${a.host}`}})(),i=()=>{let a=n.subtle??globalThis.crypto?.subtle;if(!a)throw new G("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return a},s=async()=>{if(!o.ok)throw new G("keys_unavailable",o.reason);let a=n.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await a(o.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(tg)});}catch{throw new G("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 G("keys_unavailable",`the JWKS endpoint answered ${o.shown} with an error`);let d;try{let p=await l.text();if(p.length>vl)throw new G("keys_unavailable",`the JWKS endpoint at ${o.shown} answered with more than ${vl} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof G?p:new G("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>_l)throw new G("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${_l} the platform declares. Refusing rather than verifying against a set of unknown size.`);let u=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 u.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(a){let l=e.get(a);if(l)return l;if(!o.ok)throw new G("keys_unavailable",o.reason);if(r)return await r,e.get(a)??null;let d=n.now();if(!Number.isFinite(d))throw new G("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<eg?null:(t=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var Zt=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>=Zp){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+Qp),true}};function Sl(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 wl(n){try{let e=new TextDecoder().decode(Sl(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function jo(n,e,t,r,o){let i=F=>{throw new G("peer_unauthenticated",`the peer's join credential is not usable: ${F}`)},s=n.split(".");s.length!==3&&i("it is not a three-part JWT");let[a,l,d]=s,m=wl(a);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 u=m.kid;(typeof u!="string"||u.length===0)&&i("it names no key");let p=await t.key(u);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(`${a}.${l}`),v;try{v=Sl(d);}catch{i("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,v,y)||i("its signature does not verify");let x=wl(l);x===null&&i("its payload does not decode");let I=x,b=F=>typeof I[F]=="string"?I[F]:"",R=F=>typeof I[F]=="number"&&Number.isFinite(I[F])?I[F]:NaN;b("iss")!==o.issuer&&i("it was issued by someone else"),b("aud")!==`${o.issuer}/p2p-match`&&i("its audience is not this platform"),b("match_id")!==e.matchId&&i("it is for another match"),b("game_id")!==e.gameId&&i("it is for another game");let E=R("exp")*1e3,T=R("nbf")*1e3;(!Number.isFinite(E)||e.now>E+$o)&&i("it has expired"),Number.isFinite(T)&&e.now<T-$o&&i("it is not valid yet");let H=b("role");H!=="host"&&H!=="client"&&i("it names no usable role");let B=R("host_epoch");B!==e.hostEpoch&&i("it names a different host epoch");let K=mr(b("fingerprint"));K===null&&i("its fingerprint claim is malformed"),Qt(K,e.peerFingerprint)||i("it was issued for a different certificate than this connection used");let A=mr(b("host_fingerprint"));A===null&&i("its host fingerprint claim is malformed"),Qt(A,e.hostFingerprint)||i("it was issued against a different host certificate");let C=b("jti");C.length===0&&i("it carries no jti, so replay cannot be detected"),r.admit(C,e.now)||i("it has already been used");let L=b("sub");return L.length===0&&i("it names no player"),{playerId:L.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:B,role:H,fingerprint:K,hostFingerprint:A,jti:C,expiresAt:E}}function No(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 Uo(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 Bo(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function Ho(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 Rl(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 kl(n){switch(n){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var en=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 Vo={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}},Le=["reliable","ordered","unreliable"];function Wo(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 tn(){let n=globalThis.RTCPeerConnection;return n?.generateCertificate?n.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var Al=1,ag=3e4,Pl=2e3,sg=5e3,El=6e4,lg=8,Jo=class{constructor(e=lg){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;}},dg=new Jo,cg=8,ug=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),rn=class{constructor(e){this.options=e;this.keys=e.keys??qo({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new ur;links=new Map;replays=new Zt;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=Al+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??ag;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((a,l)=>{this.ready={resolve:a,reject:l};}),o=pe(this.options.clusterTargetId);if(o!==void 0)try{let a=await this.options.api.turnLease(this.options.matchId,o,e);this.iceServers=a.iceServers,this.mark("turn leased");}catch(a){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${Ko(a)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let i=this.options.clock.setTimeout(()=>{this.fail(new G("timeout",`no usable P2P connection after ${t}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},t),s=()=>this.fail(new G("aborted","the caller aborted while connecting"));e?.aborted?s():e?.addEventListener("abort",s);try{await r;}finally{this.options.clock.clearTimeout(i),e?.removeEventListener("abort",s),this.ready=null;}}async kick(e){if(!this.isHost)throw new G("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=se(e.playerId),r=se(e.hostPlayerId),o=pr(e.hostEpoch);if(!(t===null||r===null||o===null)&&(this.mark("signaling hello"),this.localPlayerId=t,this.migration===null&&(this.migration=new en(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,Al),o=await r.connection.createOffer();await r.connection.setLocalDescription(o);let i=r.connection.localDescription?.sdp??o.sdp;if(!i)throw new G("invalid_sdp","the browser produced an offer with no SDP");qe(i,"offer"),this.refuseMedia(i,"offer"),this.options.signaling.offer(i,e),this.mark("offer sent"),this.fetchCredential().catch(s=>this.report_(s));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,o=r===void 0?null:ft(r);if(o===null)throw new G("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??dg,s=()=>this.closed||e!==this.credentialGeneration,a=sg;for(;;){let l=i.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,s))return;i.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,o);if(s())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(s())return;let m=d.status,u;if(m===409)u=Pl;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?u=p*1e3:(u=a,a=Math.min(a*2,El)),u=Math.min(Math.max(u,Pl),El);}else throw d;if(!await this.waitForCredential(u,s))return}}}async waitForCredential(e,t){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!t())}async onOffer(e){let t=se(e.fromPlayerId),r=se(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=cg){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=se(e.sessionId);if(o!==null&&this.answeredSessions.get(t)===o)return;qe(r,"offer"),this.refuseMedia(r,"offer");let i=ft(r);if(i===null)throw new G("invalid_sdp",`the offer from ${t} carries no usable fingerprint`);this.mark("offer received"),o!==null&&this.answeredSessions.set(t,o);let s=this.links.get(t);s&&this.dropLink(s,"resignalled",false);let a=this.openLink(t,this.nextPeerId++);a.remoteFingerprint=i,await a.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(a);let l=await a.connection.createAnswer();await a.connection.setLocalDescription(l);let d=a.connection.localDescription?.sdp??l.sdp;if(!d)throw new G("invalid_sdp","the browser produced an answer with no SDP");qe(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(t,d,a.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let t=se(e.fromPlayerId),r=se(e.sdp);if(t===null||r===null)return;let o=this.links.get(this.hostPlayerId);if(!o||t!==this.hostPlayerId)return;qe(r,"answer"),this.refuseMedia(r,"answer");let i=ft(r);if(i===null)throw new G("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:Qt(t.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new G("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=se(e.fromPlayerId),r=se(e.candidate);if(t===null||r===null)return;let o=this.links.get(t);if(!o)return;let i=se(e.sdpMid),s=pr(e.sdpMLineIndex)??pr(e.sdpMLineIndexAlt),a={candidate:r,...i===null?{}:{sdpMid:i},...s===null?{}:{sdpMLineIndex:s}};if(o.connection.remoteDescription===null){o.pendingCandidates.length<64&&o.pendingCandidates.push(a);return}await o.connection.addIceCandidate(a);}onPeerLeft(e){let t=se(e.playerId);if(t===null)return;let r=se(e.reason)??"left";if(t===this.localPlayerId){this.fail(new G("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=se(e.hostPlayerId),r=pr(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let o=this.migration.apply({hostPlayerId:t,hostEpoch:r,...se(e.reason)===null?{}:{reason:se(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 G("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 G("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=se(e.reason)??"ended";this.ended=t,this.emitter.emit("matchEnded",t),this.ready!==null&&this.fail(new G("match_ended",`the match ended: ${t}`)),this.close();}onSignalingError(e){let t=se(e.code)??"unknown",r=se(e.message)??"the platform refused a signaling message";this.report_(new G("signaling_failed",`${t}: ${r}`));}openLink(e,t){let o=(this.options.peerConnectionFactory??Wo)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),i={};for(let p of Le){let g=o.createDataChannel(p,Vo[p]);g.binaryType="arraybuffer",i[p]=g;}let s={playerId:e,assignedPeerId:t,connection:o,channels:i,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=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(s),d=()=>this.onConnectionState(s),m=p=>{this.onHandshakeMessage(s,p.data).catch(g=>this.report_(g));},u=()=>{this.onReliableOpen(s).catch(p=>this.report_(p));};return o.addEventListener("icecandidate",a),o.addEventListener("iceconnectionstatechange",l),o.addEventListener("connectionstatechange",d),i.reliable.addEventListener("open",u),i.reliable.addEventListener("message",m),s.detachHandshake=()=>{i.reliable.removeEventListener("open",u),i.reliable.removeEventListener("message",m);},s.detachAll=()=>{s.detachHandshake(),o.removeEventListener("icecandidate",a),o.removeEventListener("iceconnectionstatechange",l),o.removeEventListener("connectionstatechange",d);},this.links.set(e,s),s}flushCandidates(e){let t=e.pendingCandidates;e.pendingCandidates=[];for(let r of t)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let t=this.credential;if(t===null)throw new G("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 G("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(No({jwt:t.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,t){if(!(t instanceof ArrayBuffer))return;let r=Ho(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 G(kl(r.reason),Rl(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=ft(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 jo(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(s){let a=s instanceof G&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",Ko(s)),a&&this.fail(s);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(Uo({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(Bo(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 Le)Tl(e.channels[o]);Tl(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 G?e:new G("connection_failed",Ko(e),{cause:e}));}count(e){this.counted||!ug.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(cr(e))throw new G("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 se(n){return typeof n=="string"&&n.length>0?n:null}function pr(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function Ko(n){return n instanceof Error?n.message:String(n)}function Tl(n){try{n.close();}catch{}}var mg=100,pg=50,on=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??mg)){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 G("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new G("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId:t,candidate:r,sdpMid: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??pg));}};function V(n){return e=>typeof e=="string"&&e.length>0&&e.length<=n?e:void 0}function je(n,e){return t=>typeof t=="number"&&Number.isInteger(t)&&t>=n&&t<=e?t:void 0}function bt(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function Il(n){return typeof n=="boolean"?n:void 0}var be=V(64),an=je(0,2147483647);function zo(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(e.length>=64)break;let r=be(t);typeof r=="string"&&e.push(r);}return e}function J(n,e,t){return {to:n,from:e,read:t,required:true}}function W(n,e,t){return {to:n,from:e,read:t,required:false}}var hg=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=bt("disconnected","failed","closed")(e.iceState),r=je(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:[J("sdp","sdp",V(10240)),J("signaling_intent","intent",bt("initial","ice_restart","full_reconnect")),W("sdp_hash","sdpHash",V(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[J("peer_id","peerId",be),J("sdp","sdp",V(10240)),J("assigned_peer_id","assignedPeerId",je(0,4294967295)),W("sdp_hash","sdpHash",V(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[J("peer_id","peerId",be),J("candidate","candidate",V(512)),W("sdp_mid","sdpMid",V(64)),W("sdp_mline_index","sdpMLineIndex",je(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[J("host_epoch","hostEpoch",an)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[J("host_epoch","hostEpoch",an),W("evidence","evidence",hg)]}}));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:[J("playerId","player_id",be),J("hostPlayerId","host_player_id",be),J("hostEpoch","host_epoch",an),W("members","members",zo)],offer:[J("fromPlayerId","from_player_id",be),J("sdp","sdp",V(10240)),W("sessionId","signaling_session_id",V(128)),W("sdpHash","sdp_hash",V(128)),W("iceUfrag","ice_ufrag",V(64)),W("intent","signaling_intent",bt("initial","ice_restart","full_reconnect"))],answer:[J("fromPlayerId","from_player_id",be),J("sdp","sdp",V(10240)),W("sessionId","signaling_session_id",V(128)),W("sdpHash","sdp_hash",V(128)),W("iceUfrag","ice_ufrag",V(64)),W("assignedPeerId","assigned_peer_id",je(0,4294967295))],ice:[J("fromPlayerId","from_player_id",be),J("candidate","candidate",V(512)),W("sdpMid","sdp_mid",V(64)),W("sdpMLineIndex","sdp_m_line_index",je(0,255)),W("sdpMLineIndexAlt","sdp_mline_index",je(0,255))],peerJoined:[J("playerId","player_id",be)],peerLeft:[J("playerId","player_id",be),W("reason","reason",V(64))],migration:[J("hostPlayerId","new_host_player_id",be),J("hostEpoch","host_epoch",an),W("reason","reason",V(64)),W("kickedPlayerIds","kicked_player_ids",zo),W("migrationComplete","migration_complete",Il)],matchEnded:[W("reason","reason",V(64))],error:[W("code","code",V(64)),W("message","message",V(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 ze="webrtc_p2p";function Ml(n){let e=new Xt({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 G("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See docs/p2p-and-parties.md \xA72.");let 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 s=await n.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(s.protocol!==ze)throw new G("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${ze}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new on({bridge:n.bridge,matchId:s.matchId,clock:n.clock}),l=new rn({api:e,clock:n.clock,matchId:s.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:a,...i===void 0?{}:{clusterTargetId:i},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await tn(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...n.boot===void 0?{}:{boot:n.boot},...n.log===void 0?{}:{log:n.log}});a.onDropped(d=>l.notifyCandidatesDropped(d)),t.set(s.matchId,l),l.on("matchEnded",()=>t.delete(s.matchId));try{await l.start(r.signal);}catch(d){throw t.delete(s.matchId),l.close(),d}return l}}}function Ol(n){let{analytics:e,rooms:t}=n,r=n.target??globalThis,o=n.document??globalThis.document,i=[];if(typeof r.addEventListener=="function"){let a=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",a),i.push(()=>r.removeEventListener?.("pagehide",a));let l=()=>e.setHidden(!Ke());for(let d of sr)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(!Ke());}let s=new Map;return i.push(t.on("matchReady",a=>{let l=a.protocol===ze?"p2p":"dedicated";s.set(a.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),i.push(t.on("matchEnded",a=>{let l=s.get(a.matchId);l!==void 0&&(s.delete(a.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let a of i.splice(0))try{a();}catch{}s.clear();}}var Ll=["pointerdown","keydown"];function Gl(n,e=globalThis){let t=false,r=false,o=null,i=()=>{if(o!==null){try{e.cancelAnimationFrame?.(o);}catch{}o=null;}},s=()=>{if(!r){r=true,i();for(let g of Ll)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},a=()=>{if(!(t||r)){t=true,s();try{n();}catch{}}};function l(g){g?.isTrusted===true&&a();}let d=()=>{let g;try{g=e.navigator?.getGamepads?.()??[];}catch{return false}return g.some(y=>y?.buttons.some(v=>v.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},u=()=>{if(o=null,!(t||r)){if(d()){a();return}m()&&(o=e.requestAnimationFrame?.(u)??null);}};function p(){o===null&&!t&&!r&&u();}if(typeof e.addEventListener=="function"){for(let g of Ll)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),m()&&(o=e.requestAnimationFrame?.(u)??null);}return {get engaged(){return t},stop:s}}async function gr(n,e,t,r){let o=await t;return n.mark(e)&&r&&r(`[gem] boot: ${n.timeline()}`),o}function Yo(n,e){let t=false;return async r=>{let o=await r;return !t&&e&&(t=true,e(`[gem] boot: ${n.timeline()}`)),o}}function Xo(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,s)=>i.at-s.at);return o.map((i,s)=>{let a=o[s-1],l=a===void 0?"":` (+${Math.round(i.at-a.at)}ms)`;return `${i.name}@${Math.round(i.at)}ms${l}`}).join(" \u2192 ")}}}var fg="GemWebSdkHandshake";var bg=()=>Date.now();function Dl(n,e,t={}){let r=n[fg];if(r===void 0)return null;let o=t.ttlMs??9500,i=t.now??bg,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,m=false,u=i()-o;for(let p=s.length-1;p>=0;p--){let g=a?.[p];if(g!==void 0&&g<u){d+=1;continue}if(l+=1,e(s[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}var Qo=false;async function jl(n,e,t,r){if(Qo){e.close(),t("busy",true);return}Qo=true;let o=null;try{let i=await _g(n,r);if(typeof i=="string"){e.close(),t(i,vg(i));return}o=i;let a=await(r.encodeRef??(l=>kg(l,r)))(o);if(o.close(),o=null,a===null){e.close(),t("failed",!0);return}if(a.size>Rg){e.close(),t("too_large",!1);return}e.postMessage(a);}catch(i){e.close(),t("failed",true),console.error("[gem] screenshot capture failed",i);}finally{Qo=false,o?.close();}}function vg(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 _g(n,e){if(e.handler){let i=await e.handler(n);return i===null?"declined":Fl(i,n)}if(!e.useDefaultStrategy)return "not_wired";let t=e.documentRef??globalThis.document;if(!t)return "no_source";let r=Sg(t);if(!r)return "no_source";let o=wg(r);if(o!==null)return o;try{return Fl(await createImageBitmap(r),n)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}function wg(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 Sg(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 Fl(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)),s=Math.max(1,Math.floor(n.height*o));try{let a=await createImageBitmap(n,{resizeWidth:i,resizeHeight:s,resizeQuality:"high"});return n.close(),a}catch{return n.close(),"too_large"}}var Rg=8*1024*1024,$l="image/webp",ql=.92;async function kg(n,e){try{if(typeof OffscreenCanvas=="function"){let i=new OffscreenCanvas(n.width,n.height),s=i.getContext("2d");if(s){s.drawImage(n,0,0);let a=await i.convertToBlob({type:$l,quality:ql});if(a&&a.size>0)return a}}}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(s=>i(s),$l,ql);})}async function Nl(n,e){if(!e)return;let t;try{t=await xg(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 xg(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 Ul=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function Bl(n=globalThis){let t=n[Ul];if(t!==void 0)return t;let r=false,o=()=>r,i=[],s=Ag(n,o);s!==null&&i.push(s);let a=Pg(n,o);a!==null&&i.push(a);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let u of i)u();}}};return Object.defineProperty(n,Ul,{value:l,configurable:true}),l}function Ag(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,s=t.disconnect,a=new Map,l=m=>{let u=m.gain,p=m.context.currentTime;u.cancelScheduledValues(p),e()?u.setValueAtTime(0,p):u.setTargetAtTime(1,p,.01);},d=m=>{let u=m.context;if(o!==void 0&&u instanceof o)return null;let p=a.get(u);return p===void 0&&(p=u.createGain(),p.gain.value=e()?0:1,i.call(p,m),a.set(u,p)),p};return t.connect=function(...u){let[p,...g]=u;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,u)},t.disconnect=function(...u){let[p,...g]=u;if(p instanceof r){let y=a.get(p.context);if(y!==void 0&&y!==this)try{return s.call(this,y,...g)}catch{}}return s.apply(this,u)},()=>{for(let[m,u]of a){if(m.state==="closed"){a.delete(m);continue}try{l(u);}catch{}}}}function Pg(n,e){let t=n.HTMLMediaElement;if(t===void 0)return null;let r=t.prototype,o=Object.getOwnPropertyDescriptor(r,"muted"),i=o?.get,s=o?.set;if(i===void 0||s===void 0)return null;let a=r.play,l=new WeakMap,d=new WeakSet,m=new Set,u=p=>{l.has(p)||l.set(p,!!i.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),s.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),u(this);}}),r.play=function(){try{u(this);}catch{}return a.call(this)},n.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof t)try{u(g);}catch{}},true),()=>{for(let p of m){let g=p.deref();if(g===void 0){m.delete(p);continue}try{s.call(g,(l.get(g)??!1)||e());}catch{}}}}var Eg=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",Tg=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',Ig=`${Eg}${Tg}`,Zo=new WeakSet;function Hl(n=globalThis.document){if(n==null||Zo.has(n))return null;try{let e=n.defaultView?.CSSStyleSheet??globalThis.CSSStyleSheet;if(Array.isArray(n.adoptedStyleSheets)&&typeof e=="function"){let r=new e;if(typeof r.replaceSync=="function")return r.replaceSync(Ig),n.adoptedStyleSheets=[...n.adoptedStyleSheets,r],Zo.add(n),"sheet"}let t=n.documentElement?.style;return t===void 0||typeof t.setProperty!="function"?null:(t.setProperty("-webkit-user-select","none"),t.setProperty("user-select","none"),t.setProperty("-webkit-tap-highlight-color","transparent"),Zo.add(n),"inline")}catch{return null}}function Vl(n){let e=n.windowMs??1e3,t=n.realm??globalThis,r=false,o=false,i=false,s=null,a=null,l=null,d=[],m=()=>r&&!o&&!i,u=()=>{a=null,l=null,d=[];},p=v=>{if(s=null,!m()){u();return}if(l!==null&&d.push(v-l),l=v,a===null)a=v;else {let S=v-a;S>=e&&d.length>0&&(n.report(Cg(d,S)),a=v,d=[]);}g();},g=()=>{let v=t.requestAnimationFrame;typeof v=="function"&&(s=v.call(t,p));},y=()=>{if(m()){s===null&&(u(),g());return}s!==null&&(t.cancelAnimationFrame?.call(t,s),s=null),u();};return {setRequested(v){r=v,y();},setPaused(v){o=v,y();},get running(){return s!==null},dispose(){i=true,y();}}}function Cg(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 yr=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function Kl(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function Jl(n,e){n!==null&&(n.style.setProperty(yr.top,`${e.top}px`),n.style.setProperty(yr.right,`${e.right}px`),n.style.setProperty(yr.bottom,`${e.bottom}px`),n.style.setProperty(yr.left,`${e.left}px`));}var Wl=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height"}});function zl(){let n=globalThis,e=n.innerWidth,t=n.innerHeight;return typeof e=="number"&&e>0&&typeof t=="number"&&t>0?{width:e,height:t}:null}function Mg(n,e){let t={tl:{width:0,height:0},tr:{width:0,height:0},bl:{width:0,height:0},br:{width:0,height:0}};for(let r of n){let o=e?r.x+r.width/2<=e.width/2:r.x===0,i=e?r.y+r.height/2<=e.height/2:r.y===0,s=o?r.x+r.width:e?e.width-r.x:r.width,a=i?r.y+r.height:e?e.height-r.y:r.height,l=t[`${i?"t":"b"}${o?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(s)),l.height=Math.max(l.height,Math.ceil(a));}return t}function Yl(n,e,t){if(n===null)return;let r=Mg(e,t);for(let o of ["tl","tr","bl","br"])n.style.setProperty(Wl[o].width,`${r[o].width}px`),n.style.setProperty(Wl[o].height,`${r[o].height}px`);}var Og=3e4,hr=class extends Error{retryable;reason;constructor(e,t,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=t;}};function Xl(n){let e=n.clock??le,t=n.timeoutMs??Og,r=new Map,o=new Map,i=0,s=a=>{let l=r.get(a);return l?(r.delete(a),o.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return n.bridge.parentSupports("localHost")},ensure(a){if(!n.bridge.parentSupports("localHost"))return Promise.resolve();let l=o.get(a);if(l)return l;let d=new Promise((m,u)=>{let p=`ls${++i}`,g=e.setTimeout(()=>{r.delete(p),o.delete(a),u(new hr("timeout",true,`the embedder did not answer a local-server request for room ${a} within ${String(t)}ms`));},t);r.set(p,{room:a,resolve:m,reject:u,timer:g}),n.bridge.requestLocalServer(p,a)||(s(p),m());});return o.set(a,d),d.catch(()=>{}),d},accept(a){s(a.requestId)?.resolve();},refuse(a){let l=s(a.requestId);l&&l.reject(new hr(a.reason,a.retryable,a.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 sn={url:"https://downloads.indiegems.games/sdk/v10.2.0/gem-web-sdk.devtools.min.js",integrity:"sha384-/j1nybTaY/CozqKhvl7VK4tIetrdsLAQ8jidYOilaPW2Hf2HhLMQBpiHCKjBZrfR"};var _t=null;function Lg(){return _t!==null||(_t=new Promise((n,e)=>{let t=document.createElement("script");t.src=sn.url,t.integrity=sn.integrity,t.crossOrigin="anonymous",t.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){_t=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${sn.url} is not a gem-web-sdk devtools build.`));return}n(r);},t.onerror=()=>{_t=null,e(new Error(`gem devtools: could not load ${sn.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);})),_t}function Ql(n,e){let t=null,r=0;async function o(i){if(t!==null)return true;let s=++r;if(!e())return false;let a=await Lg();return !e()||s!==r?false:(t!==null||(t=a.mount(n(),{openedBy:i,text:Ue,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 Gg=1e4,Zl={reason:"unavailable",retryable:false};function ed(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??Gg);},s=(d,m)=>{let u=a(d);u&&m(u);},a=d=>{let m=e.get(d);return m?(e.delete(d),n.clock.clearTimeout(m.timer),m):null},l=new at({clock:n.clock,onStateChange:n.onStateChange,request:d=>new Promise((m,u)=>{let p=n.bridge.currentState;if(p==="refused"||p==="closed"){u(Zl);return}let g=`t${++o}`,y={resolve:m,reject:u,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)){s(d.requestId,u=>u.resolve(m));return}l.accept(m);},onDenied(d){s(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,u]of e)u.held&&(u.held=false,n.clock.clearTimeout(u.timer),i(m,u),n.bridge.requestToken(m,u.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])s(m,u=>u.reject(Zl));},get identity(){return t},get gameVersion(){return r}}}function Dg(n){let e=n.lastIndexOf("@");return (e===-1?n:`***@${n.slice(e+1)}`).slice(0,200)}var Fg=new Set(vn);function $g(n){if(!n)return {};let e={};for(let[t,r]of Object.entries(n))Fg.has(t.toLowerCase())&&(e[t.toLowerCase()]=r);return e}function fr(n){let e=n.fetch??globalThis.fetch.bind(globalThis);return $i(async(t,r)=>{let o;try{o=new URL(n.baseUrl.replace(/\/+$/,""));}catch{throw new oe("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 oe(`${JSON.stringify(typeof t.path=="string"?Dg(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 oe(`${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,v=g?y?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new oe(`the ${v} 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 s=t.bytes,a=t.bytes===void 0?void 0:"application/octet-stream";try{t.body!==void 0&&(s=JSON.stringify(t.body),a="application/json");}catch(g){throw new oe(`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}`,...a===void 0?{}:{"content-type":a},...$g(t.headers)},body:s,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"),u=qg(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...u===void 0?{}:{retryAfterSeconds:u},...p===null||p===""?{}:{invocationId:p}}},n)}function qg(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 jg=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),ti="embedder_relay_unavailable",Ng="embedder_no_relay",Ug=new Set([ti]),ni=new Set([Ng]),ln=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new ei(this)}handleEvent(e){let t=this.pending.get(e.matchId);if(t!==void 0){if(e.event==="matchEnded"){t.refuse(new w("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 w("signaling_failed","the parent relayed an answer with no SDP in it"));return}t.settle({sdp:e.sdp});return}t.refuse(Bg(e.code,e.message));}}register(e,t){this.pending.get(e)?.refuse(new w("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 w("signaling_unavailable","this game is not running inside a page that holds the player's notification socket, so there is nothing to carry an offer. Dedicated signaling needs that socket and only the page can hold one \u2014 see docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new w("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See docs/dedicated-server-flow.md \xA72.");return e}};function Bg(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new w(Hg(n),r,{platformCode:n})}function Hg(n){return n===void 0||Ug.has(n)?"signaling_failed":ni.has(n)?"offer_refused":jg.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var ei=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,t){if(this.closed)return Promise.reject(new w("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 w("aborted","the caller aborted before the offer was sent")):new Promise((o,i)=>{let s=()=>{a(),i(new w("aborted","the caller aborted the signaling exchange"));},a=()=>{t?.removeEventListener("abort",s),this.hub.release(e.matchId,l),this.teardown===a&&(this.teardown=null);},l={settle:d=>{a(),o(d);},refuse:d=>{a(),i(d);}};this.teardown=a,t?.addEventListener("abort",s),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof w?d:new w("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var td="match_ended:",nd="server_shutdown:",rd="kicked:",Vg=123;function Wg(n){if(typeof n!="string"||n.length===0||n.length>Vg)return {kind:"other"};if(n.startsWith(td)){let e=$e(n.slice(td.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(nd)?{kind:"server_shutdown",cause:n.slice(nd.length)}:n.startsWith(rd)?{kind:"kicked",detail:n.slice(rd.length)}:{kind:"other"}}function ri(n,e,t){let r=Wg(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 oi(){return {exchange(){return Promise.reject(new w("signaling_unavailable","no signaling channel is wired. The exchange rides the notification WebSocket, and POST /v1/ws/ticket accepts only account credentials \u2014 a game frame holds a game-scoped token and cannot mint one \u2014 so it has to be relayed by the page embedding this game. Run inside a parent that advertises `dedicated`, or pass your own `signaling` implementation. See docs/dedicated-server-flow.md \xA72."))},close(){}}}var Kg=3e3,Jg=1e4,zg=15e3;async function br(n){let e=n.peerConnection;try{id(n,"before the handshake started"),ii(n);let t=e.createDataChannel(n.channelLabel??"gem",{ordered:!0});for(let s of n.extraChannels??[]){let a=e.createDataChannel(s.label,{...s.ordered===void 0?{}:{ordered:s.ordered},...s.maxRetransmits===void 0?{}:{maxRetransmits:s.maxRetransmits}});n.onExtraChannel?.(s.label,a);}let r=await e.createOffer();await e.setLocalDescription(r),await Qg(e,n),ii(n);let o=e.localDescription?.sdp??r.sdp;if(!o)throw new w("invalid_sdp","the offer carried no SDP");qe(o,"offer"),od(o,"offer");let i=await Xg(n,o);if(ii(n),typeof i?.sdp!="string")throw new w("invalid_sdp","the signaling channel answered without an SDP");return qe(i.sdp,"answer"),od(i.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:i.sdp}),await Zg(t,n),id(n,"before the channel opened"),t}catch(t){throw e.close(),Yg(t)}}function Yg(n){return n instanceof w?n:ld(n)?Ye():new w("connection_failed",dd(n),{cause:n})}function od(n,e){if(cr(n))throw new w("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 Xg(n,e){let t=n.exchangeTimeoutMs??Jg,r=sd(n,t),o=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(i=>{throw i instanceof w?i:ld(i)?Ye():new w("signaling_failed",dd(i),{cause:i})});return ey(o,n,r,()=>r.exhausted?ai("while the offer was in flight"):new w("timeout",`no answer arrived within ${t}ms`))}function Qg(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let o=()=>{t.clearTimeout(s),n.removeEventListener("icegatheringstatechange",i),e.signal?.removeEventListener("abort",o),r();},i=()=>{n.iceGatheringState==="complete"&&o();},s=t.setTimeout(o,e.gatherTimeoutMs??Kg);n.addEventListener("icegatheringstatechange",i),e.signal?.addEventListener("abort",o);})}function Zg(n,e){if(e.signal?.aborted)return Promise.reject(Ye());if(n.readyState==="open")return Promise.resolve();if(n.readyState!=="connecting")return Promise.reject(new w("connection_failed",`the data channel was already '${n.readyState}' when the answer was applied`));let{clock:t}=e,r=e.openTimeoutMs??zg,o=sd(e,r);return new Promise((i,s)=>{let a=()=>{t.clearTimeout(p),n.removeEventListener("open",l),n.removeEventListener("close",d),n.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{a(),i();},d=g=>{a(),s(new w("connection_failed","the data channel failed before it opened",ad(g)===void 0?void 0:{cause:ad(g)}));},m=()=>{a(),s(Ye());},u=()=>{a(),s(o.exhausted?ai("while the channel was still opening"):new w("timeout",`the data channel did not open within ${r}ms`));},p=t.setTimeout(u,o.ms);n.addEventListener("open",l),n.addEventListener("close",d),n.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function sd(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 ey(n,e,t,r){let{clock:o,signal:i}=e;return i?.aborted?Promise.reject(Ye()):new Promise((s,a)=>{let l=u=>{o.clearTimeout(m),i?.removeEventListener("abort",d),u();},d=()=>l(()=>a(Ye())),m=o.setTimeout(()=>l(()=>a(r())),t.ms);i?.addEventListener("abort",d),n.then(u=>l(()=>s(u)),u=>l(()=>a(u)));})}function id(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw ai(`already ${e}`)}function ai(n){return new w("credential_expired",`the join credential ran out ${n} \u2014 poll match status again for a fresh one`)}function ii(n){if(n.signal?.aborted)throw Ye()}function Ye(){return new w("aborted","the caller aborted the connection attempt")}function ld(n){return n?.name==="AbortError"}function ad(n){return n?.error}function dd(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:[J("sdp","sdp",V(10240)),W("sessionId","session_id",V(64))],error:[W("code","code",V(64)),W("message","message",V(256))],matchEnded:[W("reason","reason",V(64))]}));function fd(n){let{client:e,clock:t,rooms:r}=n,o=n.signaling??oi,i=n.log??(b=>console.warn(b)),s=new ht({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,l=(b,R)=>{let E=a.get(b)??new Set;E.add(R),a.set(b,E);},d=(b,R)=>{let E=a.get(b);E!==void 0&&(E.delete(R),E.size===0&&a.delete(b));},m=async b=>{if(r.isHost&&!li(r)&&r.currentRoom?.matchId===void 0){let R=pe(b.clusterTargetId);await r.startMatch({...R===void 0?{}:{clusterTargetId:R},...b.retry===void 0?{}:{retry:b.retry},...b.signal===void 0?{}:{signal:b.signal}});}return yd(r.matchConnectionState==="suspended"?await r.reconnectToMatch(si(b)):await r.awaitMatch(si(b)))},u=async b=>yd(await r.pollMatchStatus(si(b))),p=async(b,R)=>{let E=false;try{let T=await m(b),H=r.currentRoom?.transports;if(H!==void 0&&!H.includes("webrtc"))throw new w("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 B=b.peerConnection??hd();E=!0;let K=await br({peerConnection:B,signaling:R,clock:t,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,...vr(b,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),A=null;if(b.presentCredential!==!1)try{A=await Ut({channel:K,clock:t,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,...vr(b,"onMessage","signal"),...b.welcomeTimeoutMs===void 0?{}:{ceilingMs:b.welcomeTimeoutMs}});}catch(C){throw Re(K),Re(B),C}return dy(r,T,K,B,R,b.reportDisconnect!==!1,b.reportConnected!==!1,A,{remember:l,forget:d},b.onMatchEnded)}catch(T){throw E&&gd(s,T),Re(R),T}},g=async(b,R,E,T,H,B)=>{if(b==="webtransport"){let N=T?.webtransport;if(N===void 0)throw new w("misconfigured","webtransport is not advertised");let j={credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:t};if(typeof N.named_url=="string"&&N.named_url!==""){let Z=Math.max(Math.floor(B/2),1e3);try{return await Wt({url:N.named_url,timeoutMs:Z,log:i,...j})}catch(ge){if(ir()!==null)throw ge;return i(`[gem] webtransport named dial failed (${rr(ge)}); retrying the pinned dial`),Wt({url:N.url,certHashBase64:N.cert_sha256_b64,timeoutMs:Z,log:i,...j})}}return Wt({url:N.url,certHashBase64:N.cert_sha256_b64,timeoutMs:B,...j})}if(b==="websocket"){let N=T?.websocket;if(N===void 0)throw new w("misconfigured","websocket is not advertised");return Eo({url:N.url,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:t,timeoutMs:B})}let K=R.peerConnection??hd(),A,C=await br({peerConnection:K,signaling:H,clock:t,matchId:E.matchId,credentialExpiresAt:E.credentialExpiresAt,extraChannels:[{label:Ht,ordered:false,maxRetransmits:0}],onExtraChannel:(N,j)=>{N===Ht&&(A=j);},...vr(R,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...R.exchangeTimeoutMs===void 0&&R.redial===true?{exchangeTimeoutMs:ry}:{}}),L;try{L=await Ut({channel:C,clock:t,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,wire:nr,heartbeat:!0,...vr(R,"signal"),...R.welcomeTimeoutMs===void 0?{}:{ceilingMs:R.welcomeTimeoutMs}});}catch(N){throw Re(C),Re(K),N}let F=L.welcome.heartbeatIntervalMs;return {link:Io(C,K,A,F===void 0?void 0:{clock:t,intervalMs:F}),welcome:L.welcome,channel:C,peerConnection:K}},y=(b,R,E,T,H)=>{let B=false,K;T.link.onClose(F=>{!B&&b.reportDisconnect!==false&&ri(r,R.matchId,F),K?.(F);}),b.reportDisconnect!==false&&b.reportConnected!==false&&r.notifyMatchConnected(R.matchId);let A={transport:T.link.transport,send:(F,N)=>T.link.send(F,N),onMessage:F=>T.link.onMessage(F),onClose:F=>{K=F;},close:()=>T.link.close()},C=()=>{B||(B=true,Re(T.link),Re(H));},L=F=>{if(!B){try{b.onMatchEnded?.(F);}catch{}C();}};return l(R.matchId,L),{matchId:R.matchId,transport:E,link:A,joinCredential:R.joinCredential,credentialExpiresAt:R.credentialExpiresAt,welcome:T.welcome,...T.channel===void 0?{}:{channel:T.channel},...T.peerConnection===void 0?{}:{peerConnection:T.peerConnection},close(){d(R.matchId,L),C();}}},v=async(b,R)=>{let E=r.currentRoom?.id,T=r.gameId,H=()=>({advert:Vt(r.currentRoom?.settings,b),template:r.currentRoom?.transports??null});if(E===void 0||T===null)return H();try{let B=await e.get(`/v2/games/${encodeURIComponent(T)}/game-rooms/${encodeURIComponent(E)}`,R);return {advert:Vt(B.settings,b),template:gt(B.transports)??r.currentRoom?.transports??null}}catch{return H()}},S=(b,R)=>{let E=b??cd;return R.length===0?E:E.filter(T=>R.includes(T))},x=async(b,R,E)=>{try{let T=await m(b),{advert:H,template:B}=await v(T.matchId,b.signal),K=S(B,R),A=K.filter(X=>ay(X,H)),C=ir();if(C!==null&&K.includes("webtransport")&&H?.webtransport!==void 0&&i(`[gem] webtransport skipped: ${C} (learned on an earlier dial in this page)`),A.length===0){let X=B===null?`the default order (${cd.join(", ")})`:`the room template's transports (${B.join(", ")||"none"})`;throw new w("misconfigured",`none of ${X}`+(R.length>0?`, narrowed to (${R.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let L=b.transportAttemptTimeoutMs??ny,F=()=>b.deadlineAt===void 0?1/0:b.deadlineAt-t.now(),N=X=>n.signalingReady===void 0||X<=0?Promise.resolve(!0):n.signalingReady(X),j=[],Z=[];for(let X of A){if(F()<md){i(`[gem] ${X} rung not tried: the reconnect budget is spent`);break}Z.length>0&&T.credentialExpiresAt-t.now()<pd&&(T=await u(b)),Z.push(X);let Me=!1,ue=!1,ke={attempts:0,waitedMs:0};for(;;){if(X==="webrtc"&&b.redial===!0){let ne=Math.min(ud,F());await N(ne)||i(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(ne)}ms; offering anyway`);}let Oe=Math.max(Math.min(L,F()),md);try{return y(b,T,X,await g(X,b,T,H,E,Oe),E)}catch(ne){let z=ne instanceof w?ne:new w("connection_failed",ne instanceof Error?ne.message:String(ne),{cause:ne});if(X==="webrtc"&&gd(s,z),(z.reason==="credential_expired"||z.reason==="credential_reused")&&!Me){Me=!0,T=await u(b);continue}if(X==="webrtc"&&z.reason==="signaling_failed"&&z.platformCode===ti&&!ue){ue=!0;let de=Math.min(ud,F());if(i(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(de)}ms for the socket before offering again`),await N(de))continue}if(z.reason==="join_rate_limited"){let de=iy(ke,Math.random,F());if(de!==null){if(ke.attempts+=1,ke.waitedMs+=de,i(`[gem] ${X} rung: the server is rate-limiting this player's joins; waiting ${Math.round(de)}ms before presenting again (retry ${ke.attempts} of ${vd.maxAttempts})`),await Qn(t,de,b.signal),b.signal?.aborted)throw new w("aborted","the caller aborted while waiting out a join rate limit");T.credentialExpiresAt-t.now()<pd&&(T=await u(b));continue}}if(oy.has(z.reason)||z.reason==="credential_expired"||X==="webrtc"&&bd(z)){i(`[gem] ${X} rung failed (${z.reason}): ${rr(z.cause??z)} \u2014 `+(Z.length<A.length?`falling through to ${A[Z.length]}`:"no rungs left")),j.push(z);break}throw i(`[gem] ${X} rung refused the session (${z.reason}): ${z.message}`),z}}}let ge=j[j.length-1];throw ge===void 0?new w("timeout",`the reconnect budget ran out before any transport (${A.join(", ")}) could be tried`):new w(ge.reason,`every transport tried (${Z.join(", ")}) failed; the last said: ${ge.message}`,{cause:j,platformCode:ge.platformCode})}catch(T){throw Re(E),T}};return {listClusterTargets:async(b={})=>po({client:e,...b}),handleMatchEnded(b,R){let E=a.get(b);if(E!==void 0){a.delete(b);for(let T of E)T(R);}},connect:(async(b={})=>{let R=b.signaling??o();return b.transports===void 0?p(b,R):x(b,b.transports,R)})}}var cd=["webtransport","webrtc","websocket"],ny=1e4,ry=5e3,ud=3e3,md=1e3,pd=1e4,oy=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function bd(n){return n.platformCode!==void 0&&ni.has(n.platformCode)}var vd={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function iy(n,e=Math.random,t=1/0){let r=vd;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 ay(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&or():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||sy(e.websocket.url)}function sy(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return Pn(e)}function si(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var ly=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function gd(n,e){e instanceof w&&(!ly.has(e.reason)&&!bd(e)||n.report([{type:"connection_failures_total",value:1}]));}function dy(n,e,t,r,o,i,s,a,l,d){let m=false,u=()=>{m||ri(n,e.matchId,void 0);};i&&(t.addEventListener("close",u),s&&n.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,t.removeEventListener("close",u),a?.detach(),Re(t),Re(r),Re(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:a?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function li(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function yd(n){if(n.status==="failed")throw new w("allocation_failed",`match ${n.matchId} did not come up: ${n.reason}`);if(n.status==="ended")throw new w("match_ended",`match ${n.matchId} ended (${n.reason}) before this side connected.`);if(n.protocol!==Xn)throw new w("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${Xn}' 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 w("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 hd(){let n=globalThis.RTCPeerConnection;if(!n)throw new w("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 Re(n){try{n.close();}catch{}}function vr(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var cy=1e4;function _d(n,e){return di(n,e)}function di(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=s=>({token:s.token,expiresAt:s.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,o=new at({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((s,a)=>{let l=e.clock.setTimeout(()=>{r=null,a({reason:"unavailable",retryable:true});},e.timeoutMs??cy);r={resolve:d=>{e.clock.clearTimeout(l),s(d);},reject:a,timer:l};})}),i=n.onServerToken(s=>{let a=t(s),l=r;if(l){r=null,l.resolve(a);return}o.accept(a);});return {source:o,dispose(){i(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var ui={};lc(ui,{acceptTransfer:()=>uy,addEntityProgression:()=>my,adminAction:()=>py,cancelInventoryTransfer:()=>gy,claimEntityProgressionRewards:()=>yy,closeGameRoom:()=>hy,createEntityBatchOrder:()=>fy,createEntityOrder:()=>by,createSession:()=>vy,deleteEntityGameSetting:()=>_y,deleteEntitySave:()=>wy,deleteSession:()=>Sy,deleteShowcaseValue:()=>Ry,executeEntityRecipe:()=>ky,finalizeSaveUpload:()=>xy,getChannelAssignment:()=>Ay,getDropRates:()=>Py,getEntityCurrency:()=>Ey,getEntityGameSetting:()=>Ty,getEntityInventory:()=>Iy,getEntityInventoryItem:()=>Cy,getEntityLeaderboard:()=>My,getEntityOrder:()=>Oy,getEntityProgression:()=>Ly,getEntityRecipeAvailability:()=>Gy,getEntityRecipeUsage:()=>Dy,getEntitySave:()=>Fy,getEvent:()=>$y,getGameRoomV2:()=>qy,getLeaderboard:()=>jy,getPlayerGameProfile:()=>Ny,getPurchaseCatalog:()=>Uy,getResolvedTemplate:()=>By,getRoomArgs:()=>Hy,getShowcaseValue:()=>Vy,getTransferDetails:()=>Wy,ingestAnalyticsEvents:()=>ci,initiateInventoryTransfer:()=>Ky,invokeFunction:()=>Jy,kickPlayer:()=>zy,listChallenges:()=>Yy,listEntityGameSettings:()=>Xy,listEntityOrders:()=>Qy,listEntityProgressions:()=>Zy,listEntitySaves:()=>eh,listEvents:()=>th,listGameRooms:()=>nh,listResolvedTemplates:()=>rh,listTransfers:()=>oh,maxEntityProgression:()=>ih,putEntityGameSetting:()=>ah,putRoomArgs:()=>sh,putShowcaseValue:()=>lh,rejectTransfer:()=>dh,reportMatchPlayers:()=>ch,requestSaveUploadUrl:()=>uh,resetEntityProgression:()=>mh,setMatchBackfill:()=>ph,simulateEntityOrder:()=>gh,transferHostV2:()=>yh,updateGameRoomV2:()=>hh});function f(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 uy(n,e,t){let r=`/v1/inventory/transfers/${f(e)}/accept`;return n.client.post(r,void 0,t?.signal)}async function my(n,e,t,r,o,i){let s=`/v1/inventory/${f(e)}/${f(t)}/progressions/${f(r)}/add`;return n.client.post(s,o,i?.signal)}async function py(n,e,t,r){let o=`/v1/voice/sessions/${f(e)}/admin`;return n.client.post(o,t,r?.signal)}async function gy(n,e,t){let r=`/v1/inventory/transfers/${f(e)}/cancel`;return n.client.post(r,void 0,t?.signal)}async function yy(n,e,t,r,o,i){let s=`/v1/inventory/${f(e)}/${f(t)}/progressions/${f(r)}/claim`;return n.client.post(s,o,i?.signal)}async function hy(n,e,t){let r=`/v1/games/${f(n.gameId())}/game-rooms/${f(e)}`;return n.client.delete(r,t?.signal)}async function fy(n,e,t,r,o){let i=`/v1/inventory/${f(e)}/${f(t)}/orders/batch`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function by(n,e,t,r,o){let i=`/v1/inventory/${f(e)}/${f(t)}/orders`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function vy(n,e,t){return n.client.post("/v1/voice/sessions",e,t?.signal)}async function _y(n,e,t,r,o){let i=`/v1/settings/${f(e)}/${f(t)}/${f(r)}`;return n.client.delete(i,o?.signal)}async function wy(n,e,t,r,o){let i=`/v1/saves/${f(e)}/${f(t)}/${f(r)}`;return n.client.delete(i,o?.signal)}async function Sy(n,e,t){let r=`/v1/voice/sessions/${f(e)}`;return n.client.delete(r,t?.signal)}async function Ry(n,e,t,r){let o=`/v1/showcase/players/${f(e)}/${f(t)}`;return n.client.delete(o,r?.signal)}async function ky(n,e,t,r,o){let i=`/v1/inventory/${f(e)}/${f(t)}/recipes/execute`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function xy(n,e,t,r,o,i){let s=`/v1/saves/${f(e)}/${f(t)}/${f(r)}/finalize`;return n.client.post(s,o,i?.signal)}async function Ay(n,e,t){let r=`/v1/games/${f(n.gameId())}/config/channels/${f(e)}`;return n.client.getWithEtag(r,{...t?.signal===void 0?{}:{signal:t.signal},...t?.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}})}async function Py(n,e,t){let r=`/v1/inventory/loot-tables/${f(e)}/drop-rates`;return n.client.get(r,t?.signal)}async function Ey(n,e,t,r,o){let i=`/v1/inventory/${f(e)}/${f(t)}/currencies/${f(r)}`;return n.client.get(i,o?.signal)}async function Ty(n,e,t,r,o){let i=`/v1/settings/${f(e)}/${f(t)}/${f(r)}`;return n.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Iy(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(),s=`/v1/inventory/${f(e)}/${f(t)}`+(i?`?${i}`:"");return n.client.get(s,r?.signal)}async function Cy(n,e,t,r,o){let i=`/v1/inventory/${f(e)}/${f(t)}/items/${f(r)}`;return n.client.get(i,o?.signal)}async function My(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)),o?.periods_back!==void 0&&i.set("periods_back",String(o?.periods_back)),o?.period!==void 0&&i.set("period",String(o?.period)),o?.player_id!==void 0&&i.set("player_id",String(o?.player_id));let s=i.toString(),a=`/v1/leaderboards/${f(e)}/${f(t)}/${f(r)}`+(s?`?${s}`:"");return n.client.get(a,o?.signal)}async function Oy(n,e,t,r,o){let i=`/v1/inventory/${f(e)}/${f(t)}/orders/${f(r)}`;return n.client.get(i,o?.signal)}async function Ly(n,e,t,r,o){let i=`/v1/inventory/${f(e)}/${f(t)}/progressions/${f(r)}`;return n.client.get(i,o?.signal)}async function Gy(n,e,t,r,o,i){let s=`/v1/inventory/${f(e)}/${f(t)}/catalogs/${f(r)}/recipes/${f(o)}/availability`;return n.client.get(s,i?.signal)}async function Dy(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit));let i=o.toString(),s=`/v1/inventory/${f(e)}/${f(t)}/recipe-usage`+(i?`?${i}`:"");return n.client.get(s,r?.signal)}async function Fy(n,e,t,r,o){let i=`/v1/saves/${f(e)}/${f(t)}/${f(r)}`;return n.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function $y(n,e,t){let r=`/v1/events/${f(e)}`;return n.client.get(r,t?.signal)}async function qy(n,e,t){let r=`/v2/games/${f(n.gameId())}/game-rooms/${f(e)}`;return n.client.getWithEtag(r,{...t?.signal===void 0?{}:{signal:t.signal},...t?.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}})}async function jy(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)),t?.periods_back!==void 0&&r.set("periods_back",String(t?.periods_back)),t?.period!==void 0&&r.set("period",String(t?.period)),t?.player_id!==void 0&&r.set("player_id",String(t?.player_id));let o=r.toString(),i=`/v1/leaderboards/${f(e)}`+(o?`?${o}`:"");return n.client.get(i,t?.signal)}async function Ny(n,e,t){let r=`/v1/profiles/players/${f(e)}`;return n.client.get(r,t?.signal)}async function Uy(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 By(n,e,t){let r=`/v1/game-room-templates/${f(e)}`;return n.client.get(r,t?.signal)}async function Hy(n,e,t){let r=`/v1/games/${f(n.gameId())}/game-rooms/${f(e)}/room-args`;return n.client.get(r,t?.signal)}async function Vy(n,e,t,r){let o=`/v1/showcase/players/${f(e)}/${f(t)}`;return n.client.get(o,r?.signal)}async function Wy(n,e,t){let r=`/v1/inventory/transfers/${f(e)}`;return n.client.get(r,t?.signal)}async function ci(n,e,t){let r=`/v1/games/${f(n.gameId())}/analytics/events`;return n.client.post(r,e,t?.signal,{replaySafe:true})}async function Ky(n,e,t){return n.client.post("/v1/inventory/transfers",e,t?.signal)}async function Jy(n,e,t){return n.client.postBytes("/v1/functions/invoke",e,t?.signal)}async function zy(n,e,t,r){let o=`/v1/games/${f(n.gameId())}/game-rooms/${f(e)}/kick/${f(t)}`;return n.client.post(o,void 0,r?.signal)}async function Yy(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 Xy(n,e,t,r){let o=`/v1/settings/${f(e)}/${f(t)}`;return n.client.get(o,r?.signal)}async function Qy(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(),s=`/v1/inventory/${f(e)}/${f(t)}/orders`+(i?`?${i}`:"");return n.client.get(s,r?.signal)}async function Zy(n,e,t,r){let o=`/v1/inventory/${f(e)}/${f(t)}/progressions`;return n.client.get(o,r?.signal)}async function eh(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(),s=`/v1/saves/${f(e)}/${f(t)}`+(i?`?${i}`:"");return n.client.get(s,r?.signal)}async function th(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 nh(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/${f(n.gameId())}/game-rooms`+(r?`?${r}`:"");return n.client.get(o,e?.signal)}async function rh(n,e){return n.client.get("/v1/game-room-templates",e?.signal)}async function oh(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 ih(n,e,t,r,o,i){let s=`/v1/inventory/${f(e)}/${f(t)}/progressions/${f(r)}/max`;return n.client.post(s,o,i?.signal)}async function ah(n,e,t,r,o,i){let s=`/v1/settings/${f(e)}/${f(t)}/${f(r)}`;return n.client.put(s,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function sh(n,e,t,r){let o=`/v1/games/${f(n.gameId())}/game-rooms/${f(e)}/room-args`;return n.client.put(o,t,r?.signal)}async function lh(n,e,t,r,o){let i=`/v1/showcase/players/${f(e)}/${f(t)}`;return n.client.put(i,r,o?.signal)}async function dh(n,e,t){let r=`/v1/inventory/transfers/${f(e)}/reject`;return n.client.post(r,void 0,t?.signal)}async function ch(n,e,t,r){let o=`/v1/games/${f(n.gameId())}/matches/${f(e)}/players/report`;return n.client.post(o,t,r?.signal)}async function uh(n,e,t,r,o,i){let s=`/v1/saves/${f(e)}/${f(t)}/${f(r)}/upload-url`;return n.client.post(s,o,i?.signal,{replaySafe:true})}async function mh(n,e,t,r,o,i){let s=`/v1/inventory/${f(e)}/${f(t)}/progressions/${f(r)}/reset`;return n.client.post(s,o,i?.signal)}async function ph(n,e,t,r){let o=`/v1/games/${f(n.gameId())}/matches/${f(e)}/backfill`;return n.client.put(o,t,r?.signal)}async function gh(n,e,t,r,o){let i=`/v1/inventory/${f(e)}/${f(t)}/orders/simulate`;return n.client.post(i,r,o?.signal)}async function yh(n,e,t,r){let o=`/v2/games/${f(n.gameId())}/game-rooms/${f(e)}/transfer/${f(t)}`;return n.client.post(o,void 0,r?.signal)}async function hh(n,e,t,r){let o=`/v2/games/${f(n.gameId())}/game-rooms/${f(e)}`;return n.client.patch(o,t,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var fh=1e4,bh=50,vh=1e3,_h=65536-4*1024,wd=n=>typeof n=="number"?n:0,wh=n=>typeof n=="string"?n:"";function Sd(){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 Sh(n){return n?.retryable===true}function Rh(n,e){let t=n??{},r=Array.isArray(t.rejected)?t.rejected.map(o=>{let i=o??{};return {index:wd(i.index),code:wh(i.code)}}):[];return {accepted:wd(t.accepted),rejected:r,dropped:e,duplicate:t.duplicate===true}}function Rd(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 kd(n){let e=Math.max(1,Math.floor(n.maxQueue??vh)),t={client:n.client,gameId:()=>n.gameId},r=[],o=0,i=null,s=false,a=false,l=false,d=false,m=v=>{n.log?.(v);},u=()=>{i!==null&&(n.clock.clearTimeout(i),i=null);},p=()=>{i!==null||s||a||(i=n.clock.setTimeout(()=>{i=null,y().catch(()=>{});},fh));},g=()=>{let v=Math.min(r.length,100),S=128;for(let x=0;x<v;x+=1){let I=r[x];if(I===void 0)break;if(S+=JSON.stringify(Rd(I,0)).length+1,S>_h)return Math.max(1,x)}return v};async function y(v){if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};u();let S=r.splice(0,g()),x=o;o=0;let I=Math.round(n.clock.now()),b={batch_id:Sd(),sent_at_ms:I,events:S.map(R=>Rd(R,I))};a=true;try{let R=await ci(t,b,v===void 0?void 0:{signal:v}),E=Rh(R,x);for(let T of E.rejected)m(`[gem] analytics: an event was refused (${T.code}). See the analytics_events section of your game config.`);return E}catch(R){if(Sh(R))for(r=[...S,...r],o+=x;r.length>e;)r.shift(),o+=1;else m(`[gem] analytics: ${S.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(R)}`);throw R}finally{a=false,r.length>0&&p();}}return {track(v,S,x={}){if(s)return;if(typeof v!="string"||v===""){d||(d=true,m(`[gem] analytics: '${S}' 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(S.startsWith(no)){l||(l=true,m(`[gem] analytics: '${S}' 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 I={},b={};for(let[R,E]of Object.entries(x))typeof E=="string"?I[R]=E:typeof E=="number"&&Number.isFinite(E)&&(b[R]=E);for(;r.length>=e;)r.shift(),o+=1;r.push({uid:Sd(),playerId:v,name:S,atMs:n.clock.now(),dimensions:I,measures:b}),r.length>=bh?y().catch(()=>{}):p();},flush:v=>y(v),get pending(){return r.length},dispose(){s=true,u(),r=[],o=0;}}}function xd(n){return {async list(e){let{playerId:t,periodsBack:r,signal:o}=e??{};if(typeof t!="string"||t==="")throw new TypeError("gem.challenges.list needs { playerId }: a game-server token names no player, so the platform cannot tell whose period you mean. Pass the id from join() or gem.players().");ut(r);let i=await n({player_id:t,...r===void 0?{}:{periods_back:r},...o===void 0?{}:{signal:o}});return Vn(i)}}}function kh(n){let e={};for(let[t,r]of Object.entries(ui))if(typeof r=="function"){let o=r;e[t]=(...i)=>o(n,...i);}return e}function wt(n,e={}){let t=e.clock??le,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=di(n,{clock:t,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),i=fr({baseUrl:r,tokenSource:o.source,defaultQuery:{game_id:n.gameId,channel:n.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),s=new Ge({transport:i,clock:t}),a={gameId:n.gameId,channel:n.channel,matchId:n.matchId,...n.gameRoomId===void 0?{}:{gameRoomId:n.gameRoomId}},l=kh({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,m=n.endMatch,u=n.log,p=kd({client:s,clock:t,gameId:a.gameId,...typeof u=="function"?{log:y=>u.call(n,y)}:{}});return {identity:a,client:s,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);},setBackfill:async(y,v)=>{let S=await l.setMatchBackfill(a.matchId,{open:y.open,...y.seats===void 0?{}:{seats:y.seats}},v===void 0?{}:{signal:v});return {open:S.open,seats:S.seats??null}},reportPlayers:async(y,v)=>(await l.reportMatchPlayers(a.matchId,{players:y.map(x=>({player_id:x.playerId,state:x.state}))},v===void 0?{}:{signal:v})).players.map(x=>({playerId:x.player_id,outcome:x.outcome}))},analytics:p,functions:new Fe(l.invokeFunction),challenges:xd(l.listChallenges),...d===void 0?{}:{room:{get:y=>l.getGameRoomV2(d,y),args:async y=>{let v=await l.getGameRoomV2(d,y?.signal===void 0?{}:{signal:y.signal}),S=v.modified?v.body:void 0;if(S?.room_args==null||S.room_args_template==null)throw new O("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:S.room_args,room_args_template:S.room_args_template}}}},dispose:()=>{p.dispose(),o.dispose();}}}function Xe(n){return n?.reliable!==false?"reliable":n?.ordered!==false?"ordered":"unreliable"}function St(n){return {reliable:n==="reliable",ordered:n!=="unreliable"}}function dn(n){return typeof n=="string"?n:n.slice().buffer}function _r(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 xh=5e3,Ad=3e4,Pd=2e3,Ah=1e4,Ed=1;async function Td(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?h=>console.info(h):e.log,i=h=>o?.(`[gem host] ${h}`),s=typeof n=="function"?n():n,a=Promise.resolve(),l=true,d=false,m=(h,M)=>{l&&(a=a.then(async()=>{if(!d)try{await M();}catch(q){i(`the bundle's ${h} handler threw: ${Qe(q)}. Serving continues.`);}}));},u=true,p,g,y,v=h=>{if(!u)return;u=false,m("leave",()=>s.leave?.(r,{cause:h??"left"}));let M=g;M&&queueMicrotask(()=>M(h));},S={send(h,M){if(!u)return;let q=St(Xe(M));m("message",()=>s.message?.(r,h,typeof h=="string",{reliable:q.reliable,ordered:q.ordered}));},onMessage(h){p=h;},onClose(h){g=h;},close(){v("closed");}},x=(h,M)=>{if(!u)return;let q=St(Xe(M));queueMicrotask(()=>{u&&p?.(h,q);});},I=new Map,b=h=>{let M=[];for(let q of Le){let re=h.channels[q];try{re.binaryType="arraybuffer";}catch{}let _e=St(q),tt=$=>{let nt=_r($?.data);nt!==null&&m("message",()=>s.message?.(h.playerId,nt.data,nt.isText,{reliable:_e.reliable,ordered:_e.ordered}));};re.addEventListener("message",tt),M.push(()=>re.removeEventListener("message",tt));}I.get(h.playerId)?.forEach(q=>q()),I.set(h.playerId,M);},R=h=>{I.get(h)?.forEach(M=>M()),I.delete(h);},E=new Set,T=new Map,H=(h,M,q)=>({playerNumber:h.assignedPeerId,transport:"webrtc_p2p",...M?{rejoin:true}:{},...q?{superseded:true}:{}}),B=h=>{let M=I.has(h.playerId),q=E.has(h.playerId);E.add(h.playerId),b(h),M&&m("leave",()=>s.leave?.(h.playerId,{cause:"superseded"})),m("join",()=>s.join?.(h.playerId,H(h,q,M)));},K=new Set,A=(h,M,q)=>{if(h===r){x(M,q);return}let re=t.peer(h);if(re===null){let _e=T.get(h);if(_e!==void 0&&e.clock.now()-_e<Pd)return;K.has(h)||(K.add(h),i(`send to '${h}' dropped: no such connected player`));return}re.send(dn(M),Xe(q));},C={matchId:t.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:h=>e.tokens.subscribe(h),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(h=>h.playerId)??[],players(){let h=u?[r]:[];for(let M of t.peers)h.push(M.playerId);return h},profile(h){let M=e.room()?.members.find(q=>q.playerId===h);if(!(!M||M.displayName===void 0))return {displayName:Ue.toPlain(M.displayName),...M.displayTag===void 0?{}:{displayTag:Ue.toPlain(M.displayTag)},...M.discriminator===void 0?{}:{discriminator:M.discriminator}}},playerNumber(h){return h===r?Ed:t.peer(h)?.assignedPeerId},send(h,M,q){A(h,M,q);},broadcast(h,M){let q=M?.except;u&&r!==q&&x(h,M);for(let re of t.peers)re.playerId!==q&&re.send(dn(h),Xe(M));},async endMatch(){let h=await Oe();return h.answer!=="ok"&&i(h.cause),h.answer},kick(h,M){if(h===r){v(M??"kicked");return}t.kick(h).catch(q=>{i(`kick of '${h}' failed: ${Qe(q)}`);});},log(h){i(h);},warn(h){i(`\u26A0 ${h}`);}},L=()=>{},F=new Promise(h=>{L=h;}),N=[],j=null,Z=async(h,M)=>{l=false;let q=a.then(async()=>{try{await s.shutdown(h);}catch(re){i(`the bundle's shutdown threw: ${Qe(re)}`);}});a=q,await q,de();for(let re of N.splice(0))re();for(let re of [...I.keys()])R(re);v(M);},ge=(h,M)=>j||(j=(async()=>{await Z(M,h),t.close(),L();})(),j),X=()=>j||(j=(async()=>{await Z({reason:"signal"},"left"),await t.leave().catch(h=>i(`leaving the match failed: ${Qe(h)}`)),L();})(),j),Me=()=>j||(j=(async()=>{l=false;let h=await Oe();h.answer==="ok"?(await Z({reason:"match_ended",platform_reason:"explicit"},"match ended"),t.close()):(i(`${h.cause}; leaving instead`),await Z({reason:"signal"},"left"),await t.leave().catch(M=>i(`leaving the match failed: ${Qe(M)}`))),L();})(),j),ue=null,ke=()=>(ue??=wt(C,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),ue),Oe=async()=>{try{return await $a({client:ke().client,gameId:()=>C.gameId},C.matchId,{},{signal:AbortSignal.timeout(xh)}),{answer:"ok"}}catch(h){return h instanceof O&&(h.reason==="forbidden"||h.reason==="not_found")?{answer:h.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${h.reason})`}:{answer:"failed",cause:`ending the match failed: ${Qe(h)}`}}},ne=null,z=false,de=()=>{z=true,ne!==null&&(e.clock.clearTimeout(ne),ne=null);},gn=async()=>{if(ne=null,!z){try{await ke().client.post(`/v1/games/${encodeURIComponent(C.gameId)}/matches/${encodeURIComponent(C.matchId)}/heartbeat`,void 0,AbortSignal.timeout(Ah));}catch(h){if(h instanceof O&&(h.reason==="forbidden"||h.reason==="not_found")){i(`the platform no longer holds this match under this host (${h.reason}); heartbeats stop`),de();return}i(`heartbeat failed: ${Qe(h)}`);}z||(ne=e.clock.setTimeout(()=>{gn();},Ad));}},Rt=()=>{z||ne!==null||(ne=e.clock.setTimeout(()=>{gn();},Ad));};{let h=L;L=()=>{de(),ue?.dispose(),ue=null,h();};}let et=Promise.resolve().then(()=>s.init(C));a=et.then(()=>{},()=>{}),m("join",()=>s.join?.(r,{playerNumber:Ed,transport:"loopback"})),N.push(t.on("peerJoined",B)),N.push(t.on("peerLeft",(h,M)=>{R(h);let q=e.clock.now();for(let[re,_e]of T)q-_e>=Pd&&T.delete(re);T.set(h,q),K.delete(h),m("leave",()=>s.leave?.(h,{cause:M}));})),N.push(t.on("error",h=>{i(`\u26A0 session error: ${h.message}`);})),N.push(t.on("matchEnded",h=>{j||mi(y,h),ge("match ended",{reason:"match_ended",platform_reason:h});})),N.push(t.on("hostChanged",h=>{h!==r&&ge("host migrated",{reason:"host_migrated"});}));for(let h of t.peers)B(h);try{await et,Rt();}catch(h){l=false,de(),d=true;for(let M of N.splice(0))M();for(let M of [...I.keys()])R(M);throw t.leave().catch(()=>{}),L(),h}return {matchId:t.matchId,localLink:S,onMatchEnded(h){y=h;},end:Me,leave:X,stop:h=>ge(h,{reason:"stopped"}),done:F}}function mi(n,e){try{n?.(e);}catch{}}function Qe(n){return n instanceof Error?n.message:String(n)}function pi(n,e){let t=async()=>{throw new w("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 Id(n){let e=new Map,t=n.autoReconnect===true,{rooms:r}=n,o=new Map,i=async a=>{r.isHost&&!li(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...a.signal===void 0?{}:{signal:a.signal}});let l={...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},s=a=>({...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0?{}:{clusterTargetId:a.clusterTargetId}});return {async serve(a,l={}){let d=await i(l);if(d.protocol!==ze)return pi("dedicated",d.matchId);let m=n.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return pi("peer",d.matchId);let u=n.identity();if(u===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(s(l)),g=await Td(a,{session:p,clock:n.clock,gameId:u.gameId,channel:u.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:n.apiBaseUrl(),tokens:n.tokens,room:n.room,localPlayerId:p.playerId!==""?p.playerId:u.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(a={}){let l=await i(a),d=a.onMatchEnded;if(l.protocol===ze){let g=o.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),Ih(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 tn(),v=async()=>n.p2p.connect({...s(a),certificate:y}),S=await v(),x=Mh(S,v,d,I=>{r.notifyMatchDisconnected(I).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),t);return t&&(e.set(S.matchId,{redial:x.redial,abandon:x.abandon}),x.onClosed(()=>{e.get(S.matchId)?.abandon===x.abandon&&e.delete(S.matchId);})),x}let m=async(g=null)=>await n.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:a.transports??[]}),u=await m(),p=Ch(u,m,r,t);return t&&(e.set(u.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(u.matchId)?.abandon===p.abandon&&e.delete(u.matchId);})),p},async redialMatch(a,l){let d=e.get(a);return d===void 0?"closed":d.redial(l)},abandonMatch(a,l){e.get(a)?.abandon(l);}}}var Cd="link_closed",Ph="host_unreachable",Eh=new Set(["failed","closed"]);function Th(n){return Eh.has(n)?Cd:Ph}function Ih(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:(s,a)=>r.send(s,a),onMessage:s=>r.onMessage(s),onClose:s=>{i=s,r.onClose(a=>{o="closed",i?.(a);});},close:()=>r.close()}}function Ch(n,e,t,r){let o=n.matchId,i=n,s="connected",a,l,d=[],m=false,u=false,p=y=>{if(s!=="closed"){s="closed";for(let v of d.splice(0))v();l?.(y);}},g=y=>{y.link.onMessage((v,S)=>a?.(v,S)),y.link.onClose(v=>{if(y!==i||s==="closed")return;if(m||!r){p(v);return}let S=t.matchSession;if(S.phase==="suspended"&&S.matchId===o){s="suspended";return}p(v);});};return g(n),{matchId:o,protocol:"dedicated",get transport(){return i.transport},get state(){return s},send(y,v){s==="connected"&&i.link.send(y,v);},onMessage(y){a=y;},onClose(y){l=y;},close(){if(s!=="closed"){if(m=true,s==="suspended"){p("closed");return}i.close(),p("closed");}},async redial(y){if(s==="closed"||m)return "closed";if(u)return "connected";u=true;let v;try{v=await e(y===void 0?{}:{deadlineAt:y});}finally{u=false;}return m||s==="closed"?(v.close(),"closed"):(i=v,g(v),s="connected",t.notifyMatchConnected(o),"connected")},abandon(y){s!=="closed"&&(s==="connected"&&i.close(),p(y));},onClosed(y){s==="closed"?y():d.push(y);}}}function Mh(n,e,t,r,o,i=false){let s=n.matchId,a=n,l,d,m=[],u=[],p=[],g=false,y=false,v=false,S=false,x="connected",I=A=>{if(g)return;g=true,x="closed";for(let L of m.splice(0))L();for(let L of u.splice(0))L();for(let L of p.splice(0))L();let C=d;C&&queueMicrotask(()=>C(A));},b=A=>{for(let C of m.splice(0))C();for(let C of Le){let L=A.channels[C];try{L.binaryType="arraybuffer";}catch{}let F=St(C),N=j=>{let Z=_r(j?.data);Z!==null&&l?.(Z.data,F);};L.addEventListener("message",N),m.push(()=>L.removeEventListener("message",N));}},R=()=>a.peer(a.hostPlayerId),E=A=>{if(!(g||a.isHost)&&x!=="suspended"){if(r?.(A),i){x="suspended";return}I(A);}},T=A=>{for(let C of Le){let L=A.channels[C];if(typeof L.addEventListener!="function")continue;let F=()=>{R()===A&&E(Cd);};L.addEventListener("close",F),m.push(()=>L.removeEventListener?.("close",F));}},H=A=>{b(A),T(A),!g&&(x="connected",o?.());},B=A=>{for(let C of u.splice(0))C();u.push(A.on("migrating",()=>{S=true;})),u.push(A.on("hostChanged",C=>{if(S=false,C===A.playerId){I("host_migrated_here");return}let L=R();L!==null&&H(L);})),u.push(A.on("peerJoined",C=>{C.playerId===A.hostPlayerId&&H(C);})),u.push(A.on("matchEnded",C=>{g||mi(t,C),I(C);})),u.push(A.on("peerLeft",(C,L)=>{C===A.hostPlayerId&&E(Th(L));}));};B(a);let K=R();return K!==null&&H(K),{matchId:s,protocol:"p2p",get state(){return x},send(A,C){x==="connected"&&R()?.send(dn(A),Xe(C));},onMessage(A){l=A;},onClose(A){d=A;},close(){y=true,I("closed"),a.leave().catch(()=>{});},async redial(){if(x==="closed")return "closed";if(x==="connected"||v)return "connected";if(S)throw new G("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");v=true;let A;try{for(let L of m.splice(0))L();for(let L of u.splice(0))L();a.close(),A=await e();}finally{v=false;}if(g)return y?A.leave().catch(()=>{}):A.close(),"closed";a=A,B(a);let C=R();if(C===null)throw a.close(),new G("connection_failed","this peer rejoined the match but the host never answered with a link");return H(C),"connected"},abandon(A){I(A);},onClosed(A){g?A():p.push(A);}}}function gi(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={},s=l=>{t.delete(r)&&(n.clock.clearTimeout(i.timer),o(l));};t.set(r,s),i.timer=n.clock.setTimeout(()=>s(void 0),n.timeoutMs??2e3);let a=false;try{a=n.bridge.requestParty(r);}catch{}a||s(void 0);})},settle(r,o){t.get(r)?.(o);}}}var Oh=12e4;function Ze(n,e){return {outcome:n,reason:e}}function Md(n){let e=false,t=new Map;return {api:{request(r){if(!n.bridge.parentSupports("purchases"))return Promise.resolve(Ze("unavailable","error"));if(e)return Promise.resolve(Ze("declined","busy"));let o=`purchase-${Ee()}`;return new Promise(i=>{let s={},a=d=>{t.delete(o)&&(e=false,n.clock.clearTimeout(s.timer),i(d));};e=true,t.set(o,a),s.timer=n.clock.setTimeout(()=>a(Ze("unavailable","error")),n.timeoutMs??Oh);let l=false;try{l=n.bridge.requestPurchase(o,r.kind,r.targetId,r.currencySlug,r.quantity,r.catalogId);}catch{}l||a(Ze("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(Ze(o,os(r.reason)));return}let s=r.purchaseId;if(s===void 0){n.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),i(Ze("unavailable","error"));return}(async()=>{let a;try{a=await n.confirm(s);}catch{a="unknown";}if(a==="granted"){i({outcome:"ok",purchaseId:s});return}a==="absent"&&n.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for purchase "+JSON.stringify(s)),i(Ze("unavailable","error"));})();}}}async function Od(n,e){try{return (await _a(n,e)).granted?"granted":"absent"}catch(t){return t instanceof O&&t.reason==="not_found"?"absent":"unknown"}}var Lh=6e5;function Ld(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-${Ee()}`;return e=new Promise(o=>{let i={},s=l=>{t.delete(r)&&(e=null,n.clock.clearTimeout(i.timer),o(l));};t.set(r,s),i.timer=n.clock.setTimeout(()=>{s({outcome:"unavailable"});},n.timeoutMs??Lh);let a=false;try{a=n.bridge.requestSignIn(r);}catch{}a||s({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 Gh=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),Dh=["utm_"];function Gd(n){return Gh.has(n)||Dh.some(e=>n.startsWith(e))}var Dd=16,Fd=512,Fh=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,$h=/[\p{Cc}\p{Cf}]/u,qh=/\p{Cs}/u,Ce="[gem] gem.share.request:";function $d(n){let{frame:e,log:t}=n,r=false,o=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,i=s=>{t!==null&&(t===void 0?console.warn(s):t(s));};return {get available(){return o()!==null},request(s){let a=o();if(a===null)throw new Error(`${Ce} the arcade does not handle share here \u2014 check gem.share.available first`);if(s!==void 0&&(typeof s!="object"||s===null))throw new TypeError(`${Ce} pass { params }, or nothing`);let l=s?.params===void 0?{}:s.params;if(!jh(l))throw new TypeError(`${Ce} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>Dd)throw new TypeError(`${Ce} at most ${Dd} params; got ${d.length}`);let m=[];for(let[u,p]of d){let g=JSON.stringify(u);if(!Fh.test(u))throw new TypeError(`${Ce} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(Gd(u))throw new TypeError(`${Ce} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Ce} param ${g}: values must be strings`);if(p.length>Fd)throw new TypeError(`${Ce} param ${g}: a value is at most ${Fd} characters`);if($h.test(p))throw new TypeError(`${Ce} param ${g}: control and format characters are not allowed`);if(qh.test(p))throw new TypeError(`${Ce} param ${g}: a value must be well-formed text`);m.push({key:u,value:p});}!a.requestShare(m)&&!r&&(r=true,i("[gem] gem.share.request was not sent: more than 6 share requests in a minute. Call it from your Share button's click, not a loop."));}}}function jh(n){if(typeof n!="object"||n===null||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}var Hh="(any-pointer: coarse)";function Vh(n){let e=Array.isArray(n)?n:[n],t=[],r=1e4;for(let o of e){if(typeof o!="number"||!Number.isFinite(o)||o<0)return null;if(t.length===99||r===0)continue;let i=Math.min(Math.trunc(o),1e4,r);t.push(i),r-=i;}return t.length%2===0&&t.pop(),t.every(o=>o===0)?[]:t}function qd(n){let{frame:e,log:t}=n,r=n.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?m=>matchMedia(m):void 0},o=r.navigator,i,s=new Set,a=()=>typeof o?.vibrate!="function"||r.matchMedia===void 0?false:(i??=r.matchMedia(Hh),i.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(m,u)=>{s.has(m)||(s.add(m),t!==null&&(t===void 0?console.warn(u):t(u)));};return {get available(){return a()||l()},vibrate(m){let u=a();if(!u&&!l())return false;let p=Vh(m);if(p===null)return d("pattern","[gem] gem.vibration.vibrate did nothing: a pattern is a number of milliseconds, or an array of them, each finite and not negative."),false;if(o?.userActivation?.hasBeenActive!==true)return d("activation","[gem] gem.vibration.vibrate did nothing: the player has not tapped or pressed a key in your game yet, and browsers allow vibration only after that."),false;if(u)try{return o.vibrate(p)===!0}catch{return false}let g=e.requestVibrate(p);return g||d("rate","[gem] gem.vibration.vibrate was not sent: more than 600 vibrations in a minute. Vibrate on events, not every frame."),g}}}var Wh=/(?:Z|[+-]\d{2}:?\d{2})$/i;function jd(n){if(typeof n!="string"||!Wh.test(n))return;let e=Date.parse(n);return Number.isFinite(e)&&e>0?e:void 0}function cn(){return {declared:false,grantable:false,heldLimitReached:false}}function Nd(n,e){let t=typeof n=="object"&&n!==null?n:{},r=jd(t.resets_at),o=r===void 0?{}:{resetsAt:r};if(t.declared!==true)return {...cn(),...o};let i=t.remaining_today,s=typeof i=="number"&&Number.isFinite(i)&&i>=0?Math.floor(i):void 0,a=t.next_eligible_at,l=jd(a),d=t.held_limit_reached===true,m=a!=null,u=i!=null&&s===void 0;return {declared:true,grantable:t.grantable===true&&e&&s!==0&&!u&&!m&&!d,...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...o}}var Kh=18e4,yi=32,Jh=/^[a-z0-9_-]+$/,zh="rewarded_requires_user_gesture";function Yh(){let n=globalThis.navigator?.userActivation?.isActive;return typeof n=="boolean"?n:void 0}var Xh=1e3;function Qh(){let n=globalThis,e=n.navigator?.getGamepads,t=n.performance?.now;if(typeof e!="function"||typeof t!="function")return;let r=t.call(n.performance),o=e.call(n.navigator);for(let i=0;i<o.length;i+=1){let s=o[i]?.timestamp;if(typeof s=="number"&&r-s>=0&&r-s<=Xh)return true}return false}var Ud=1e4;function Zh(n){return n==="interstitial"||n==="rewarded"}function Bd(n){return typeof n=="string"&&n!==""&&n.length<=yi&&Jh.test(n)}function ef(n){let e=typeof n=="object"&&n!==null?n:{};return [e.name,e.reason,e.status].join()}function wr(n){return typeof n=="string"?JSON.stringify(n):typeof n}function Hd(n){let e=false,t=new Map,r=new Map,o=new Set,i=d=>{try{n.onDropped?.(d);}catch{}},s=false,a=d=>{if(s)return;s=true;let m=n.log;if(m!==null)try{m===void 0?console.warn(`[gem] ${d}`):m(`[gem] ${d}`);}catch{}},l=d=>{let m=n.readAvailability;if(m===void 0)return Promise.resolve(cn());let u=r.get(d);if(u!==void 0)return u;let p=new Promise(g=>{let y={},v=b=>y.done===true?false:(y.done=true,n.clock.clearTimeout(y.timer),g(b),true),S=(b,R)=>{!v(cn())||o.has(b)||(o.add(b),i(`gem.ads.rewardedStatus("${d}") answered not grantable: ${R}. Said once.`));},x=b=>{S(ef(b),`the read failed (${b instanceof Error?b.message:wr(b)})`);},I;try{I=Promise.resolve(m(d,AbortSignal.timeout(Ud)));}catch(b){I=Promise.reject(b);}y.timer=n.clock.setTimeout(()=>{S("timeout","no answer within 10 s");},Ud),I.then(b=>{try{v(Nd(b,n.bridge.parentSupports("ads")));}catch(R){x(R);}},x);});return r.set(d,p),p.then(()=>{r.get(d)===p&&r.delete(d);}),p};return {api:{rewardedStatus(d){return Bd(d)?l(d):(i(`gem.ads.rewardedStatus(${wr(d)}) answered not grantable: a placement is 1..${String(yi)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(cn()))},requestAd(d){if(!n.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let m=d?.placement,u=d?.format;if(!Bd(m)||!Zh(u))return i(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${wr(m)}, format ${wr(u)}. A placement is 1..${String(yi)} 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"});if(u==="rewarded"){let g;try{g=(n.userActivation??Yh)();}catch{g=void 0;}if(g===false)try{(n.recentGamepadInput??Qh)()===!0&&(g=!0);}catch{}if(g===false){let y=`${zh}: gem.ads.requestAd("${m}", 'rewarded') answered no_ad without asking: the frame has no user activation and no controller input in the last second. Ask from the button's click, pointerup, touchend or keydown handler, or straight from a controller press, before any await or timer that can outlast the press. On a touchscreen, pointerdown and touchstart run before the tap counts.`;return i(y),a(y),Promise.resolve({outcome:"no_ad"})}}let p=`ad-${Ee()}`;return new Promise(g=>{let y={},v=x=>{t.delete(p)&&(e=false,n.clock.clearTimeout(y.timer),g(x));};e=true,t.set(p,v),y.timer=n.clock.setTimeout(()=>{v({outcome:"unavailable"});},n.timeoutMs??Kh);let S=false;try{S=n.bridge.requestAd(p,m,u);}catch{}S||v({outcome:"no_ad"});})}},settle(d){let m=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",u=t.get(d.requestId);if(u===void 0){n.onDropped?.(`gem.adResult (${m}) for an unknown requestId: `+JSON.stringify(d.requestId));return}u({outcome:m});}}}var hi=16384;function Vd(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:tf(e)}function tf(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 nf=1e4,rf=5e3;function Wd(n){let e=null,t=false,r=[],o=new Map,i=()=>{for(let s of r.splice(0))s();};return {api:{get current(){return e},wait(s=rf){return t?Promise.resolve(e):new Promise(a=>{let l=()=>{let u=r.indexOf(d);u>=0&&r.splice(u,1);},d=()=>{n.clock.clearTimeout(m),l(),a(e);},m=n.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!n.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=Vd(s);if(a===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(a>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(s)),d=`device-settings-${Ee()}`;return new Promise(m=>{let u={},p=y=>{o.delete(d)&&(n.clock.clearTimeout(u.timer),y==="stored"&&(e=l,t=true,i()),m(y));};o.set(d,p),u.timer=n.clock.setTimeout(()=>p("unavailable"),n.timeoutMs??nf);let g=false;try{g=n.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(s){let a=s.settings;e=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:null,t=true,i();},settle(s){let a=s.outcome==="stored"||s.outcome==="too_large"?s.outcome:"unavailable",l=o.get(s.requestId);if(l===void 0){n.onDropped?.(`gem.deviceSettings.result (${a}) for an unknown requestId: `+JSON.stringify(s.requestId));return}l(a);}}}var un=class extends Error{constructor(){super("createGem: this game is not framed (window.parent === window), so nothing can hand it a player, saves, config or rooms. Play it in the Gem Arcade or the Gem Editor, or through the Gem dev host on this machine: `npm run dev` (`gemctl serve start . --dev`) while editing, `gemctl serve start .` for a build, signed in to gemctl. Do not open the dev server's own address."),this.name="GemUnframedError";}};var of=/^[a-z0-9][a-z0-9_-]{0,39}$/;function af(n){return typeof n=="string"&&of.test(n)}function Sr(n){if(n===null||af(n))return n;let e=typeof n=="string"?JSON.stringify(n.length>48?`${n.slice(0,48)}\u2026`:n):`a value of type ${typeof n}`;console.warn(`[gem] showPortraitBorders: ${e} is not a border name, so nothing was sent. A name is 1 to 40 of a-z, 0-9, _ and -, starting with a letter or digit, exactly as your store page declares it under media.portrait_borders. Pass null for no art.`);}function Kd(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function fi(n,e){if(n!==true)return {visible:false};let t=[],r=false;for(let o of Array.isArray(e)?e:[])o==="score"?r=true:typeof o=="string"&&o.length>0&&o.length<=64&&!t.includes(o)&&t.push(o);return !r&&t.length===0?{visible:true}:{visible:true,currencies:t.slice(0,8),score:r}}function Rr(n,e){let t=[];for(let r of Array.isArray(e)?e:[]){if(t.length===4)break;if(typeof r!="object"||r===null)continue;let{id:o,label:i}=r;typeof o!="string"||o.length===0||o.length>32||typeof i!="string"||i.trim().length===0||t.some(s=>s.id===o)||t.push({id:o,label:i.trim().slice(0,40)});}return t.length===0?{settings:n===true}:{settings:n===true,items:t}}function Jd(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function sf(n){let e=n.untrusted,t=fe(e.displayName),r=e.displayTag||e.displayHandle,o=r?fe(r):void 0,i=n.discriminator||n.displayTag,s=i&&/^[0-9]{1,8}$/.test(i)?i:void 0,a=n.avatarIconUrl||n.avatarUrl,l=n.avatarIconId,d={displayName:t,displayHandle:o??t,badges:(n.badges??[]).map(g=>({itemId:g.itemId,iconUrl:g.iconUrl}))};n.playerId&&(d.playerId=n.playerId),s&&(d.discriminator=s),o&&(d.displayTag=o),a&&(d.avatarIconUrl=d.avatarUrl=a),l&&/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i.test(l)&&(d.avatarIconId=l);let m=n.boost,u=(m?.multipliers??[]).map(g=>({currencyId:g.currencyId,currencySlug:g.currencySlug,multiplier:g.multiplierBp/1e4})),p=u.some(g=>g.multiplier>1);return d.boost=p&&m?.expiresInDays?{active:p,multipliers:u,expiresInDays:m.expiresInDays}:{active:p,multipliers:u},d}var lf=1e4,mn=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??le,this.inbound=new At(this.clock),this.outbound=new At(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(a=>Fr(a,e.origin))||es(e.origin,this.options.selfOrigin)))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),this.state==="waiting"&&this.transition("refused"),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=An["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let o=e.data;if(!Fr(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 s=ts(kn,o.versions);return s===null?(i.onmessage=null,i.postMessage({gem:U,type:"gem.error",code:"version_mismatch",message:`frame supports v${kn.min}..v${kn.max}`}),i.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=i,this.version=s,i.onmessage=a=>this.receive(a.data,a.ports??[]),i.start?.(),this.peerCapabilities=o.capabilities??[],this.unbidden=o.unbidden===true,i.postMessage({gem:U,type:"gem.handshake.accept",v:s,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:U,type:"gem.ready"});}settled(e=lf){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:U,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:U,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:U,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),true):false}exit(e){this.send(e===void 0?{gem:U,type:"gem.exit"}:{gem:U,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:U,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:U,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:U,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:U,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let t={gem:U,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:Kd(e.origin.x),y:Kd(e.origin.y)}),this.send(t),true}showPortraitBorders(e){let t=Sr(e);return t===void 0||this.state!=="connected"||!this.parentSupports("portraitBorders")?false:this.send(t===null?{gem:U,type:"gem.portraitBorders"}:{gem:U,type:"gem.portraitBorders",name:t})}setWalletVisible(e,t){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:U,type:"gem.walletDisplay",...fi(e,t?.only)})}setMenu(e,t){return this.state!=="connected"||!this.parentSupports("gameMenu")?false:this.send({gem:U,type:"gem.menu",...Rr(e,t)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:U,type:"gem.requestShare",params:e.map(({key:t,value:r})=>({key:t,value:r}))})}requestAvatarPicker(){return this.state!=="connected"||!this.parentSupports("avatarPicker")?false:this.send({gem:U,type:"gem.requestAvatarPicker"})}requestVibrate(e){return this.state!=="connected"||!this.parentSupports("vibration")?false:this.send({gem:U,type:"gem.vibrate",pattern:[...e]})}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:U,type:"gem.frameStats",fps:Jd(e.fps,1e3),frameTimeP95Ms:Jd(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:U,type:"gem.gameContext",context:e}),true)}signal(e,t,r){this.send({gem:U,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:U,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:U,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,o,i,s){return this.send({gem:U,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:o,...i===void 0?{}:{quantity:i},...s===void 0?{}:{catalogId:s}})}putDeviceSettings(e,t){return this.send({gem:U,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:U,type:"gem.requestAd",requestId:e,placement:t,format:r})}requestSignIn(e){return this.send({gem:U,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,t,r,o){return this.send({gem:U,type:"gem.requestFriendChallenge",requestId:e,playerId:t,template:r,...o===void 0?{}:{params:o}})}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(xn)){this.options.onDropped?.(e,t);return}this.fail(e,t);}dropUnknownType(e){this.inbound.allow(xn)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,t){e.ports?.[0]?.close?.(),this.inbound.allow(xn)&&this.options.onRefused?.(t);}fail(e,t){this.options.onError?.(e,t),this.state==="connected"&&this.port&&this.send({gem:U,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=An[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||zd(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=An[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=Xa(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 s=o(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(a);break;case "gem.pause":this.options.onPause?.(a);break;case "gem.menuSelect":this.options.onMenuSelect?.(a);break;case "gem.prefs":this.options.onPrefs?.(a);break;case "gem.cohorts":this.options.onCohorts?.(a);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(a);break;case "gem.willTerminate":this.options.onWillTerminate?.(a);break;case "gem.devtools":this.options.onDevtools?.(a.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=t[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:a.maxWidth,maxHeight:a.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return zd(t.slice(1)),this.options.onScreenshot(d,l,(m,u)=>this.screenshotDenied(m,u)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer":this.options.onLocalServer?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{this.options.onPlayer?.(sf(a));break}case "gem.roomEvent":this.options.onRoomEvent?.(a);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(a);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(a);break;case "gem.socketState":this.options.onSocketState?.(a);break;case "gem.signalEvent":this.options.onSignalEvent?.(a);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(a);break;case "gem.clusterTarget":this.options.onClusterTarget?.(a);break;case "gem.partyResult":this.options.onPartyResult?.(a);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(a);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(a);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(a);break;case "gem.adResult":this.options.onAdResult?.(a);break;case "gem.signInResult":this.options.onSignInResult?.(a);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(a);break;case "gem.error":this.options.onError?.(a.code,a.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,t){this.send({gem:U,type:"gem.screenshot.denied",reason:e,retryable:t});}};function zd(n){for(let e of n)try{e?.close?.();}catch{}}var Yd="https://api.gemarcade.com";function bi(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 df=new Set(["localhost","127.0.0.1","[::1]"]);function Xd(n){let e=bi(n);if(e!==null)return e;let t=new URL(n);return t.protocol==="http:"&&!df.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 uf=Object.freeze(["https://gemarcade.com","https://meme-games.com","http://gemarcade.localhost","gemarcade://localhost"]),mf=Yd,Qd=8e3,vi=15e3,pf=9e4,gf=1/0,yf=8e3,hf=5e3,ff=5e3;async function bf(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 pn(n){let e=null,t=false,r=[];return {get current(){return e},set(o){e=o;for(let i of r.splice(0))i(o);},release(){t=true;for(let o of r.splice(0))o(e);},wait(o){return e!==null||t?Promise.resolve(e):new Promise(i=>{let s=()=>{let d=r.indexOf(a);d>=0&&r.splice(d,1);},a=d=>{n.clearTimeout(l),s(),i(d);},l=n.setTimeout(()=>{s(),i(e);},o);r.push(a);})}}}function mk(n={}){let e=n.clock??le,t=n.log===void 0?c=>console.info(c):n.log,r=n.baseUrl??void 0;if(r!=null){let c=bi(r);if(c!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${c}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let o=Ps(typeof window>"u"?void 0:window.location?.search),i=Xo();i.mark("sdk created");let s=()=>Zn(ee.gameVersion,n.clientVersion?.gameVersion),a=new qt({client:()=>ot,clock:e,gameId:()=>ee.identity?.gameId??null,playerId:()=>ee.identity?.playerId??null,environment:()=>{let c=s();return {sdk_version:Di(),...c===null?{}:{game_version:c}}},...n.analytics===void 0?{}:{options:n.analytics},log:t}),l=Gl(()=>{i.mark("engaged"),a.release(),$.reportEngaged();},typeof window>"u"?{}:window),d=c=>{if(c===false)return null;let k=c?.attempts??gf,D=c?.budgetMs??pf;return !(k>0)||!(D>0)?null:{attempts:k,budgetMs:D,maxDelayMs:c?.maxDelayMs??yf}},m=c=>{c.on("created",()=>{i.mark("room created");}),c.on("joined",()=>{i.mark("room joined");}),c.on("matchAllocationStarted",()=>{i.mark("allocation started");}),c.on("matchReady",()=>{i.mark("match ready");}),c.on("matchFailed",()=>{i.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.");if(window.parent===window)throw new un;let u=n.allowedEmbedders;if(u!=null&&!Array.isArray(u))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 p=Array.from(u??[]),g=p.filter(c=>typeof c!="string"||!Dr(c));if(g.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${g.length===1?"an entry":"entries"} that ${g.length===1?"is":"are"} not an origin: ${g.map(c=>typeof c=="string"?JSON.stringify(c):String(c)).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 y=Object.freeze([...new Set([...uf,...p])]),v=pn(e),S=pn(e),x=pn(e),I=Os(t),b=pn(e),R=n.manageAudio===false?null:Bl();n.selectableText!==true&&Hl();let E=null,T=()=>{E!==null&&(S.current!==null&&S.current.muted===E||$.reportMuted(E));},H,B,K=-1/0,A=null,C=()=>{if(H===void 0||A!==null||H===B)return;let c=K+1e3-e.now();if(c>0){A=e.setTimeout(()=>{A=null,C();},c);return}$.showPortraitBorders(H)&&(B=H,K=e.now());},L=null,F=null,N=()=>{if(L===null)return false;let c=JSON.stringify(fi(L.visible,L.only));return c===F?$.parentSupports("walletDisplay"):$.setWalletVisible(L.visible,L)?(F=c,true):false},j=null,Z=null,ge=()=>{if(j===null)return false;let c=typeof j.onSettings=="function",k=JSON.stringify(Rr(c,j.items));return k===Z?$.parentSupports("gameMenu"):$.setMenu(c,j.items)?(Z=k,true):false},X=Vl({report:c=>$.reportFrameStats(c)}),Me=false,ue=Ql(()=>Gi,()=>Me),ke=c=>{let k=Me&&!c,D=Me!==c;if(Me=c,k&&ue.close(),!!D)try{n.onDevToolsPermissionChange?.(c);}catch(te){t?.(`[gem] onDevToolsPermissionChange threw: ${te instanceof Error?te.message:String(te)}`),queueMicrotask(()=>{throw te});}},Oe=r??mf,ne=r!==void 0,z,de=c=>(t?.(`[gem] token refused: ${c}`),n.onError?.("internal",c),false),gn=(c,k)=>{if(c===void 0)return k!==void 0?de("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 D=Xd(c);return D!==null?de(`the embedder named an API root that cannot be used: ${D}. Its value is withheld here rather than written to logs.`):z!==void 0&&z!==c?de("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."):(z=c,ne||(Oe=c),true)},Rt=window.location?.origin,et=null,h=-1/0,M=2e3,q=new Set,re=c=>et!==false?Promise.resolve(true):new Promise(k=>{let D=e.setTimeout(()=>{q.delete(te),k(false);},c),te=()=>{e.clearTimeout(D),q.delete(te),k(true);};q.add(te);}),_e=()=>{},tt=null,$=new mn({allowedEmbedders:y,...typeof Rt=="string"&&Rt!==""?{selfOrigin:Rt}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","portraitBorders","earnAllowance","share","avatarPicker","vibration","frameStats","walletDisplay","gameMenu","engagement","reservedAreas","viewport","purchases","deviceSettings","ads","signIn","friendChallenges",...n.onFeedbackContext!==void 0?["feedbackContext"]:[]],onRefused:c=>{tt=c,n.onRefused?.(c);},...n.onError===void 0?{}:{onError:n.onError},onStateChange:c=>{ee.onBridgeState(c),c!=="connected"&&X.setRequested(false),F=null,Z=null,B=void 0,c==="refused"&&(console.error("[gem] this game refused the page that framed it"+(tt===null?"":` (${tt})`)+", so it has no player, saves, config or rooms. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders."),_e()),c==="connected"&&(i.mark("bridge connected"),nc(),T(),C(),N(),ge(),$.unbiddenLaunch&&!l.engaged&&a.hold(),a.startSession(),l.engaged&&$.reportEngaged()),n.onStateChange?.(c);},onPlayer:c=>{v.set(c),n.onPlayer?.(c);},onPrefs:c=>{let k={reducedMotion:c.reducedMotion,muted:c.muted,locale:c.locale,showFrameStats:c.showFrameStats===true,recommended:c.recommended===void 0?null:Object.freeze({volume:c.recommended.volume,batterySaver:c.recommended.batterySaver,keyboardLayout:c.recommended.keyboardLayout,gamepadConfirm:c.recommended.gamepadConfirm,vibration:c.recommended.vibration})};S.set(k),R?.setMuted(k.muted),X.setRequested(k.showFrameStats&&$.parentSupports("frameStats")),n.onPrefs?.(k);},onCohorts:c=>{let k=Object.freeze(c.cohorts.map(D=>Object.freeze({experimentId:D.experimentId,variantKey:D.variantKey})));x.set(k),n.onCohorts?.(k);},onEarnAllowanceChanged:()=>I.emit(),onViewport:c=>{let k=Object.freeze({insets:Object.freeze({top:c.insets.top,right:c.insets.right,bottom:c.insets.bottom,left:c.insets.left}),reserved:Object.freeze((c.reserved??[]).map(te=>Object.freeze({x:te.x,y:te.y,width:te.width,height:te.height})))});b.set(k);let D=Kl();Jl(D,k.insets),Yl(D,k.reserved,zl()),n.onViewport?.(k);},onPause:c=>{a.setPaused(c.paused),X.setPaused(c.paused),n.onPause?.(c.paused);},onMenuSelect:c=>{if(j===null)return;if(c.entry==="settings"){j.onSettings?.();return}(Rr(false,j.items).items??[]).some(D=>D.id===c.id)&&j.items?.find(D=>D.id===c.id)?.onSelect?.();},onWillTerminate:c=>{a.endSession(c.reason),n.onWillTerminate?.({reason:c.reason,graceMs:c.graceMs});},onToken:c=>{let k=c.garden;if(ke(c.allowDevTools===true),!gn(c.apiBaseUrl,k))return;let D=c;ee.onToken(D);let te=ee.identity;te&&(kr.set(te),wi||(wi=true,me.reconcileSeats().catch(()=>{}))),Si.push({token:D.token,expiresAt:D.expiresAt});},onTokenDenied:c=>{ke(false),ee.onDenied(c);},onScreenshot:(c,k,D)=>{jl(c,k,D,{...n.onScreenshot===void 0?{}:{handler:n.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{Nl($,n.onFeedbackContext);},onDevtools:c=>{c==="close"?ue.close():c==="open"?ue.openFrom("platform").catch(()=>{}):ue.isOpen?ue.close():ue.openFrom("platform").catch(()=>{});},onRoomEvent:c=>me.handleRoomEvent({event:c.event,roomId:c.roomId,...c.matchId===void 0?{}:{matchId:c.matchId},...c.version===void 0?{}:{version:c.version},...c.reason===void 0?{}:{reason:c.reason},...c.platform===void 0?{}:{platform:c.platform}}),onSeatedEvent:c=>me.handleSeated(c.roomId),onAutoStartFailedEvent:c=>me.handleAutoStartFailed(c.roomId,c.code),onSocketState:c=>{let k=et;if(et=c.connected,c.connected)for(let te of [...q])te();if(!c.connected||k===true)return;let D=e.now();D-h<M||(h=D,me.reconcile().catch(()=>{}));},onSignalEvent:c=>{let k=typeof c.data=="object"&&c.data!==null&&!Array.isArray(c.data)?c.data:{};it.handleSignalEvent(c.matchId,c.event,k),c.event==="matchEnded"&&me.reconcile({matchId:c.matchId,...typeof k.reason=="string"?{reason:k.reason}:{}}).catch(()=>{});},onDedicatedEvent:c=>{c.event==="matchEnded"&&(kt.handleMatchEnded(c.matchId,c.reason),me.reconcile({matchId:c.matchId,...c.reason===void 0?{}:{reason:c.reason}}).catch(()=>{})),nt.handleEvent(c);},onClusterTarget:c=>fn.accept(c.clusterTargetId,c.clusterTargetIds),onLocalServer:c=>bn.accept(c),onLocalServerDenied:c=>bn.refuse(c),onPartyResult:c=>ki.settle(c.requestId,c.partyId),onPurchaseResult:c=>Ai.settle(c),onDeviceSettings:c=>{hn.receive(c),n.onDeviceSettings?.(hn.api.current);},onDeviceSettingsResult:c=>hn.settle(c),onAdResult:c=>Ei.settle(c),onSignInResult:c=>Ti.settle(c),onFriendChallengeResult:c=>Ii.settle(c)}),nt=new ln({bridge:$}),kr=pn(e);_e=()=>{kr.release(),v.release(),x.release();},$.currentState==="refused"&&_e();let wi=false,xr=new Set,yn,Si={current:()=>yn,subscribe:c=>(xr.add(c),yn!==void 0&&c(yn),()=>xr.delete(c)),push:c=>{yn=c;for(let k of [...xr])try{k(c);}catch(D){t?.(`[gem] a server-token listener threw: ${D instanceof Error?D.message:String(D)}`);}}},ee=ed({bridge:$,clock:e,onStateChange:(c,k)=>{if(c==="ready"){if(i.mark("token ready")){let D=i.marks.find(te=>te.name==="token ready")?.at;a.trackPlatform("gem_boot_ready",D===void 0?{}:{boot_ms:Math.max(0,Math.round(D))});}}else c==="lost"&&(i.mark("token lost"),a.trackPlatform("gem_auth_lost"));n.onAuthStateChange?.(c,k);}}),Ri=()=>{let c=ee.identity;return !c||ee.source.currentState==="lost"?null:`${c.playerId}\0${c.gameId}\0${c.channel}`},nc=()=>{i.mark("token requested"),ee.source.get().catch(()=>{});},ki=gi({bridge:$,clock:e}),xi={},Ai=Md({bridge:$,clock:e,onDropped:c=>n.onError?.("internal",c),confirm:async c=>xi.confirm?.(c)??"unknown"}),hn=Wd({bridge:$,clock:e,onDropped:c=>n.onError?.("internal",c)}),Pi={},Ei=Hd({bridge:$,clock:e,onDropped:c=>n.onError?.("internal",c),readAvailability:(c,k)=>Pi.read?.(c,k)??Promise.reject(new Error("the gem-api client is not built yet")),log:n.log}),Ti=Ld({bridge:$,clock:e,onDropped:c=>n.onError?.("internal",c)}),Ii=Ms({bridge:$,clock:e,onDropped:c=>n.onError?.("internal",c)}),fn=Us({bridge:$,clock:e}),bn=Xl({bridge:$,clock:e}),Ar=c=>{let k=$.handleWindowMessage({data:c.data,origin:c.origin,source:c.source,ports:c.ports});return k&&window.removeEventListener("message",Ar),k};window.addEventListener("message",Ar);let rt=Dl(window,Ar),rc=rt?.capture,Pr=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Pr?.domInteractive!==void 0&&Pr.domInteractive>0&&i.mark("document parsed",Pr.domInteractive),rc?.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 Er=n.handshakeWarningMs;Er!==null&&t&&e.setTimeout(()=>{let c=rt===null?"no capture script ran":`capture: ${rt.delivered} offer(s) delivered, ${rt.stale} stale, ${rt.capture.dropped} evicted${rt.capture.late?", installed late":""}`;if($.currentState==="connected"){t(`[gem] handshake connected. boot: ${i.timeline()} \xB7 ${c}`);return}t(`[gem] no completed handshake after ${Er??Qd}ms (bridge state: ${$.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: ${i.timeline()} \xB7 `+c);},Er??Qd);let oc=fr({get baseUrl(){return Oe},tokenSource:ee.source,get defaultQuery(){let c=ee.identity;return c?{game_id:c.gameId,channel:c.channel}:{}}}),ot=new Ge({transport:oc,clock:e}),he={client:ot,gameId:()=>ee.identity?.gameId??""};xi.confirm=c=>Od(he,c),Pi.read=(c,k)=>Ua(he,"players","me",c,{signal:k});let ic=()=>ee.identity?.channel??"release",Ci=new Hn(he,ic),Mi=async c=>(await Ci.load())?.currency(c)?.id??void 0,Oi=$n(he,Kr,{identity:Ri,resolveCurrencyId:Mi}),Tr=async c=>{let k=await kr.wait(c);if(k)return k;throw $.currentState==="refused"?new ie("unavailable","the page that framed this game is not one it accepts, so no play token will ever arrive. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders (see onRefused for the reason)."):new ie("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=d(n.autoReconnect),me=Do({client:ot,clock:e,gameId:()=>ee.identity?.gameId??null,playerId:()=>ee.identity?.playerId??null,awaitGameId:async()=>(await Tr(vi)).gameId,resolveParty:ki.resolve,resolveClusterTargets:fn.resolveList,refreshClusterTargets:fn.refresh,ensureLocalServer:bn.ensure,localHostAvailable:bn.available,...n.clientVersion===void 0?{}:{clientVersion:n.clientVersion},platformGameVersion:()=>ee.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:(c,k)=>Cr.redialMatch(c,k),abandon:(c,k)=>Cr.abandonMatch(c,k)}}});m(me),Ol({analytics:a,rooms:me});let it=Ml({client:ot,clock:e,rooms:me,bridge:$,gameId:()=>ee.identity?.gameId??"",baseUrl:()=>Oe,resolveClusterTarget:fn.resolve,boot:i,...n.log===void 0?{}:{log:n.log}}),Li=Yo(i,t),kt=fd({client:ot,clock:e,rooms:me,signaling:()=>nt.channel(),signalingReady:re,log:t??(()=>{})}),Cr=Id({rooms:me,p2p:{connect:c=>Li(it.connect(c)),session:c=>it.session(c)},dedicated:{connect:(c=>gr(i,"welcome",kt.connect(c),t))},clock:e,identity:()=>ee.identity,apiBaseUrl:()=>Oe,tokens:Si,room:()=>me.currentRoom,autoReconnect:Ir!==null,...n.log===void 0?{}:{log:n.log}}),ac=async()=>(await Tr(vi)).playerId,Gi={client:ot,boot:i,get identity(){return ee.identity},awaitIdentity:(c=vi)=>Tr(c),awaitBridge:c=>$.settled(c),get player(){return v.current},awaitPlayer:(c=hf)=>v.wait(c),me:Oi,characters:new jn(he,void 0,Ri,Mi),transfers:new Un(he,Kr,Oi.inventory),gameConfig:Ci,purchases:Ai.api,deviceSettings:hn.api,ads:Ei.api,account:Ti.api,share:$d({frame:$,log:n.log}),vibration:qd({frame:$,log:n.log}),get avatarPickerAvailable(){return $.currentState==="connected"&&$.parentSupports("avatarPicker")},openAvatarPicker:()=>$.requestAvatarPicker(),analytics:a,leaderboards:new Mt(he),challenges:new Tt(he),showcase:new Ot(he,ac),friends:new Lt(he,{challenge:Ii.challenge,...o===void 0?{}:{launchedChallengeId:o}}),platform:new Dt(he,I,t),profiles:new Ft(he),functions:new Fe((c,k)=>Ea(he,c,k)),get prefs(){return S.current},get cohorts(){return x.current},get viewport(){return b.current},awaitCohorts:(c=ff)=>x.wait(c),reportMuted:c=>{E=!!c,T();},showPortraitBorders:c=>{let k=Sr(c);k!==void 0&&(H=k,C());},cueReward:c=>$.cueReward(c),setWalletVisible:(c,k)=>{let D=Array.isArray(k?.only)?[...k.only]:void 0;return L=D===void 0?{visible:c===true}:{visible:c===true,only:D},N()},setMenu:c=>(j={...typeof c?.onSettings=="function"?{onSettings:c.onSettings}:{},...Array.isArray(c?.items)?{items:c.items.map(k=>({...k}))}:{}},ge()),exit:c=>bf(me,$,c,a),frame:$,devtools:ue,rooms:me,dedicatedServer:{listClusterTargets:c=>kt.listClusterTargets(c),connect:(c=>gr(i,"welcome",kt.connect(c),t)),handleMatchEnded:(c,k)=>kt.handleMatchEnded(c,k)},p2p:{handleSignalEvent:(c,k,D)=>it.handleSignalEvent(c,k,D),session:c=>it.session(c),connect:c=>Li(it.connect(c))},match:Cr};return Gi}var Zd="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 _i(n,e={}){let t=e.clock??le,r=()=>{let a=n();if(a===null)throw new Error(Zd);return a},o=null,i=()=>{if(o===null)throw new Error(Zd);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 challenges(){return i().challenges},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(a){let d=r().profile?.(a);if(!d)return null;let m=d.displayName;return typeof m!="string"||m===""?null:{displayName:fe(m),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:fe(d.displayTag)}:{},...typeof d.discriminator=="string"?{discriminator:d.discriminator}:{}}},playerNumber(a){return r().playerNumber?.(a)},send(a,l,d){d===void 0?r().send(a,l):r().send(a,l,d);},broadcast(a,l){l===void 0?r().broadcast(a):r().broadcast(a,l);},kick(a,l){l===void 0?r().kick(a):r().kick(a,l);},log(a){r().log(a);},warn(a){r().warn(a);}},attach:()=>{o=wt(r(),{...e,clock:t});}}}function ec(n,e={}){let{server:t,attach:r}=_i(()=>n,e);return r(),t}function vf(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:$e(e)}}}var _f=1e4;function wf(n){let e=false;return t=>{if(e)return;let r;try{r=n.match.reportPlayers([{playerId:t,state:"connected"}],AbortSignal.timeout(_f));}catch{return}r.catch(o=>{o instanceof O&&o.status>=400&&o.status<500&&(e=o.status!==429);});}}function tc(n,e={}){return ()=>{let t=null,{server:r,attach:o}=_i(()=>t,e),i=n(r),s={async init(l){t=l,o(),await i.init?.();},async shutdown(l){let d=vf(l);try{await i.shutdown?.(d);}finally{r.dispose();}}},a=wf(r);return s.join=(l,d)=>(a(l),i.join?.(l,d)),i.leave&&(s.leave=(l,d)=>i.leave?.(l,d)),i.message&&(s.message=(l,d,m,u)=>i.message?.(l,d,m,u)),s}}
2
+ export{uf as ARCADE_EMBEDDERS,qt as AnalyticsApi,ie as AuthError,vn as CONDITIONAL_HEADERS,Tt as ChallengesApi,hi as DEVICE_SETTINGS_MAX_BYTES,w as DedicatedServerError,Ve as FriendChallengeError,Lt as FriendsApi,Fe as FunctionsApi,O as GemApiError,Ge as GemClient,ce as GemConfigError,mn as GemFrame,$t as GemFunctionError,ae as GemSaveError,un as GemUnframedError,Mt as LeaderboardsApi,hs as MAX_PERIODS_BACK,Xm as PLATFORM_EVENTS,Dt as PlatformApi,zn as PlatformCurrenciesApi,Yn as PlatformEarnAllowanceApi,ye as PlayerText,Ft as ProfilesApi,De as PurchaseRefusal,Ot as ShowcaseApi,oe as TransportRefusal,Ht as UNRELIABLE_CHANNEL_LABEL,fe as asPlayerText,Xo as createBootTimeline,mk as createGem,wt as createGemServer,_d as createHostTokenSource,ec as createMatchServer,tc as defineServer,bf as leaveAndExit,we as mapIdentity,gr as markOnResolve,Rm as platformIconUrl,Ut as presentJoinCredential,gt as readTemplateTransports,Vt as readTransportAdvert,Yo as reportOnResolve,le as systemClock,Ue as text,_n as toBase64,or as webTransportAvailable};//# sourceMappingURL=gem-web-sdk.sdk.js.map
3
3
  //# sourceMappingURL=gem-web-sdk.sdk.js.map